diff --git a/.github/workflows/dart.yml b/.github/workflows/dart.yml index fdd3143a..588860f5 100644 --- a/.github/workflows/dart.yml +++ b/.github/workflows/dart.yml @@ -38,23 +38,23 @@ jobs: - name: mono_repo self validate run: dart pub global run mono_repo generate --validate job_002: - name: "analyze_and_format; linux; Dart 3.7.0-39.0.dev; PKGS: pkgs/_analyzer_cfe_macros, pkgs/_analyzer_macros, pkgs/_cfe_macros, pkgs/_macro_builder, pkgs/_macro_client, pkgs/_macro_host, pkgs/_macro_runner, pkgs/_macro_server, pkgs/_macro_tool, pkgs/_test_macros, pkgs/dart_model, pkgs/macro, pkgs/macro_service, tool/benchmark_generator, tool/dart_model_generator; `dart analyze --fatal-infos .`" + name: "analyze_and_format; linux; Dart 3.7.0-123.0.dev; PKGS: pkgs/_analyzer_cfe_macros, pkgs/_analyzer_macros, pkgs/_cfe_macros, pkgs/_macro_builder, pkgs/_macro_client, pkgs/_macro_host, pkgs/_macro_runner, pkgs/_macro_server, pkgs/_macro_tool, pkgs/_test_macros, pkgs/dart_model, pkgs/macro, pkgs/macro_service, tool/benchmark_generator, tool/dart_model_generator; `dart analyze --fatal-infos .`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_analyzer_cfe_macros-pkgs/_analyzer_macros-pkgs/_cfe_macros-pkgs/_macro_builder-pkgs/_macro_client-pkgs/_macro_host-pkgs/_macro_runner-pkgs/_macro_server-pkgs/_macro_tool-pkgs/_test_macros-pkgs/dart_model-pkgs/macro-pkgs/macro_service-tool/benchmark_generator-tool/dart_model_generator;commands:analyze" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_analyzer_cfe_macros-pkgs/_analyzer_macros-pkgs/_cfe_macros-pkgs/_macro_builder-pkgs/_macro_client-pkgs/_macro_host-pkgs/_macro_runner-pkgs/_macro_server-pkgs/_macro_tool-pkgs/_test_macros-pkgs/dart_model-pkgs/macro-pkgs/macro_service-tool/benchmark_generator-tool/dart_model_generator;commands:analyze" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_analyzer_cfe_macros-pkgs/_analyzer_macros-pkgs/_cfe_macros-pkgs/_macro_builder-pkgs/_macro_client-pkgs/_macro_host-pkgs/_macro_runner-pkgs/_macro_server-pkgs/_macro_tool-pkgs/_test_macros-pkgs/dart_model-pkgs/macro-pkgs/macro_service-tool/benchmark_generator-tool/dart_model_generator - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_analyzer_cfe_macros-pkgs/_analyzer_macros-pkgs/_cfe_macros-pkgs/_macro_builder-pkgs/_macro_client-pkgs/_macro_host-pkgs/_macro_runner-pkgs/_macro_server-pkgs/_macro_tool-pkgs/_test_macros-pkgs/dart_model-pkgs/macro-pkgs/macro_service-tool/benchmark_generator-tool/dart_model_generator + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -488,23 +488,23 @@ jobs: if: "always() && steps.tool_dart_model_generator_pub_upgrade.conclusion == 'success'" working-directory: tool/dart_model_generator job_005: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: goldens/foo; `../../tool/run_e2e_tests.sh`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: goldens/foo; `../../tool/run_e2e_tests.sh`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:goldens/foo;commands:command_0" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:goldens/foo;commands:command_0" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:goldens/foo - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:goldens/foo + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -523,23 +523,23 @@ jobs: - job_003 - job_004 job_006: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: pkgs/_analyzer_cfe_macros; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: pkgs/_analyzer_cfe_macros; `dart test --test-randomize-ordering-seed=random`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_analyzer_cfe_macros;commands:test_0" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_analyzer_cfe_macros;commands:test_0" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_analyzer_cfe_macros - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_analyzer_cfe_macros + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -558,23 +558,23 @@ jobs: - job_003 - job_004 job_007: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: pkgs/_analyzer_macros; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: pkgs/_analyzer_macros; `dart test --test-randomize-ordering-seed=random`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_analyzer_macros;commands:test_0" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_analyzer_macros;commands:test_0" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_analyzer_macros - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_analyzer_macros + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -593,23 +593,23 @@ jobs: - job_003 - job_004 job_008: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: pkgs/_cfe_macros; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: pkgs/_cfe_macros; `dart test --test-randomize-ordering-seed=random`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_cfe_macros;commands:test_0" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_cfe_macros;commands:test_0" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_cfe_macros - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_cfe_macros + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -628,23 +628,23 @@ jobs: - job_003 - job_004 job_009: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: pkgs/_macro_builder; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: pkgs/_macro_builder; `dart test --test-randomize-ordering-seed=random`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_macro_builder;commands:test_0" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_macro_builder;commands:test_0" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_macro_builder - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_macro_builder + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -663,23 +663,23 @@ jobs: - job_003 - job_004 job_010: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: pkgs/_macro_client; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: pkgs/_macro_client; `dart test --test-randomize-ordering-seed=random`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_macro_client;commands:test_0" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_macro_client;commands:test_0" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_macro_client - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_macro_client + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -698,23 +698,23 @@ jobs: - job_003 - job_004 job_011: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: pkgs/_macro_host; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: pkgs/_macro_host; `dart test --test-randomize-ordering-seed=random`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_macro_host;commands:test_0" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_macro_host;commands:test_0" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_macro_host - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_macro_host + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -733,23 +733,23 @@ jobs: - job_003 - job_004 job_012: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: pkgs/_macro_runner; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: pkgs/_macro_runner; `dart test --test-randomize-ordering-seed=random`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_macro_runner;commands:test_0" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_macro_runner;commands:test_0" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_macro_runner - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_macro_runner + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -768,23 +768,23 @@ jobs: - job_003 - job_004 job_013: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: pkgs/_macro_server; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: pkgs/_macro_server; `dart test --test-randomize-ordering-seed=random`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_macro_server;commands:test_0" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_macro_server;commands:test_0" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_macro_server - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_macro_server + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -803,23 +803,23 @@ jobs: - job_003 - job_004 job_014: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: pkgs/macro_service; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: pkgs/macro_service; `dart test --test-randomize-ordering-seed=random`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/macro_service;commands:test_0" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/macro_service;commands:test_0" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/macro_service - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/macro_service + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -838,23 +838,23 @@ jobs: - job_003 - job_004 job_015: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: tool/dart_model_generator; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: tool/dart_model_generator; `dart test --test-randomize-ordering-seed=random`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:tool/dart_model_generator;commands:test_0" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:tool/dart_model_generator;commands:test_0" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:tool/dart_model_generator - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:tool/dart_model_generator + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -873,23 +873,23 @@ jobs: - job_003 - job_004 job_016: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: pkgs/_macro_tool; `dart test --test-randomize-ordering-seed=random --concurrency=1`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: pkgs/_macro_tool; `dart test --test-randomize-ordering-seed=random --concurrency=1`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_macro_tool;commands:test_1" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_macro_tool;commands:test_1" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/_macro_tool - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/_macro_tool + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -908,23 +908,23 @@ jobs: - job_003 - job_004 job_017: - name: "unit_test; linux; Dart 3.7.0-39.0.dev; PKG: pkgs/dart_model; `dart -Ddebug_json_buffer=true test --test-randomize-ordering-seed=random -c source`" + name: "unit_test; linux; Dart 3.7.0-123.0.dev; PKG: pkgs/dart_model; `dart -Ddebug_json_buffer=true test --test-randomize-ordering-seed=random -c source`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/dart_model;commands:command_1" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/dart_model;commands:command_1" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev;packages:pkgs/dart_model - os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-39.0.dev + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev;packages:pkgs/dart_model + os:ubuntu-latest;pub-cache-hosted;sdk:3.7.0-123.0.dev os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1328,13 +1328,13 @@ jobs: - job_003 - job_004 job_029: - name: "unit_test; windows; Dart 3.7.0-39.0.dev; PKG: pkgs/_analyzer_cfe_macros; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; windows; Dart 3.7.0-123.0.dev; PKG: pkgs/_analyzer_cfe_macros; `dart test --test-randomize-ordering-seed=random`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1353,13 +1353,13 @@ jobs: - job_003 - job_004 job_030: - name: "unit_test; windows; Dart 3.7.0-39.0.dev; PKG: pkgs/_analyzer_macros; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; windows; Dart 3.7.0-123.0.dev; PKG: pkgs/_analyzer_macros; `dart test --test-randomize-ordering-seed=random`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1378,13 +1378,13 @@ jobs: - job_003 - job_004 job_031: - name: "unit_test; windows; Dart 3.7.0-39.0.dev; PKG: pkgs/_cfe_macros; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; windows; Dart 3.7.0-123.0.dev; PKG: pkgs/_cfe_macros; `dart test --test-randomize-ordering-seed=random`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1403,13 +1403,13 @@ jobs: - job_003 - job_004 job_032: - name: "unit_test; windows; Dart 3.7.0-39.0.dev; PKG: pkgs/_macro_builder; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; windows; Dart 3.7.0-123.0.dev; PKG: pkgs/_macro_builder; `dart test --test-randomize-ordering-seed=random`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1428,13 +1428,13 @@ jobs: - job_003 - job_004 job_033: - name: "unit_test; windows; Dart 3.7.0-39.0.dev; PKG: pkgs/_macro_client; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; windows; Dart 3.7.0-123.0.dev; PKG: pkgs/_macro_client; `dart test --test-randomize-ordering-seed=random`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1453,13 +1453,13 @@ jobs: - job_003 - job_004 job_034: - name: "unit_test; windows; Dart 3.7.0-39.0.dev; PKG: pkgs/_macro_host; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; windows; Dart 3.7.0-123.0.dev; PKG: pkgs/_macro_host; `dart test --test-randomize-ordering-seed=random`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1478,13 +1478,13 @@ jobs: - job_003 - job_004 job_035: - name: "unit_test; windows; Dart 3.7.0-39.0.dev; PKG: pkgs/_macro_runner; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; windows; Dart 3.7.0-123.0.dev; PKG: pkgs/_macro_runner; `dart test --test-randomize-ordering-seed=random`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1503,13 +1503,13 @@ jobs: - job_003 - job_004 job_036: - name: "unit_test; windows; Dart 3.7.0-39.0.dev; PKG: pkgs/_macro_server; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; windows; Dart 3.7.0-123.0.dev; PKG: pkgs/_macro_server; `dart test --test-randomize-ordering-seed=random`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1528,13 +1528,13 @@ jobs: - job_003 - job_004 job_037: - name: "unit_test; windows; Dart 3.7.0-39.0.dev; PKG: pkgs/macro_service; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; windows; Dart 3.7.0-123.0.dev; PKG: pkgs/macro_service; `dart test --test-randomize-ordering-seed=random`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1553,13 +1553,13 @@ jobs: - job_003 - job_004 job_038: - name: "unit_test; windows; Dart 3.7.0-39.0.dev; PKG: tool/dart_model_generator; `dart test --test-randomize-ordering-seed=random`" + name: "unit_test; windows; Dart 3.7.0-123.0.dev; PKG: tool/dart_model_generator; `dart test --test-randomize-ordering-seed=random`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1578,13 +1578,13 @@ jobs: - job_003 - job_004 job_039: - name: "unit_test; windows; Dart 3.7.0-39.0.dev; PKG: pkgs/_macro_tool; `dart test --test-randomize-ordering-seed=random --concurrency=1`" + name: "unit_test; windows; Dart 3.7.0-123.0.dev; PKG: pkgs/_macro_tool; `dart test --test-randomize-ordering-seed=random --concurrency=1`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -1603,13 +1603,13 @@ jobs: - job_003 - job_004 job_040: - name: "unit_test; windows; Dart 3.7.0-39.0.dev; PKG: pkgs/dart_model; `dart -Ddebug_json_buffer=true test --test-randomize-ordering-seed=random -c source`" + name: "unit_test; windows; Dart 3.7.0-123.0.dev; PKG: pkgs/dart_model; `dart -Ddebug_json_buffer=true test --test-randomize-ordering-seed=random -c source`" runs-on: windows-latest steps: - name: Setup Dart SDK uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672 with: - sdk: "3.7.0-39.0.dev" + sdk: "3.7.0-123.0.dev" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 diff --git a/goldens/foo/lib/json_codable_test.dart b/goldens/foo/lib/json_codable_test.dart index 9675ccae..4e8ae833 100644 --- a/goldens/foo/lib/json_codable_test.dart +++ b/goldens/foo/lib/json_codable_test.dart @@ -21,7 +21,7 @@ void main() { {'x': 2}, ], 'mapOfSerializableField': { - 'c': {'x': 3} + 'c': {'x': 3}, }, }; @@ -107,10 +107,7 @@ void main() { }); test('class hierarchies', () { - var json = { - 'x': 1, - 'y': 'z', - }; + var json = {'x': 1, 'y': 'z'}; var d = D.fromJson(json); expect(d.x, 1); expect(d.y, 'z'); @@ -123,34 +120,25 @@ void main() { 'listOfNullableInts': [null, 1], 'listOfNullableSerializables': [ {'x': 1}, - null + null, ], 'listOfNullableMapsOfNullableInts': [ null, {'a': 1, 'b': null}, ], - 'setOfNullableInts': [ - null, - 2, - ], + 'setOfNullableInts': [null, 2], 'setOfNullableSerializables': [ {'x': 2}, null, ], 'setOfNullableMapsOfNullableInts': [ null, - { - 'a': 2, - 'b': null, - }, + {'a': 2, 'b': null}, ], - 'mapOfNullableInts': { - 'a': 3, - 'b': null, - }, + 'mapOfNullableInts': {'a': 3, 'b': null}, 'mapOfNullableSerializables': { 'a': {'x': 3}, - 'b': null + 'b': null, }, 'mapOfNullableSetsOfNullableInts': { 'a': [null, 3], @@ -163,29 +151,23 @@ void main() { expect(e.listOfNullableSerializables.first!.x, 1); expect(e.listOfNullableSerializables[1], null); expect( - e.listOfNullableMapsOfNullableInts, - equals([ - null, - {'a': 1, 'b': null}, - ])); + e.listOfNullableMapsOfNullableInts, + equals([ + null, + {'a': 1, 'b': null}, + ]), + ); expect(e.setOfNullableInts, equals({null, 2})); expect(e.setOfNullableSerializables.first!.x, 2); expect(e.setOfNullableSerializables.elementAt(1), null); expect( - e.setOfNullableMapsOfNullableInts, - equals({ - null, - { - 'a': 2, - 'b': null, - }, - })); - expect( - e.mapOfNullableInts, - equals({ - 'a': 3, - 'b': null, - })); + e.setOfNullableMapsOfNullableInts, + equals({ + null, + {'a': 2, 'b': null}, + }), + ); + expect(e.mapOfNullableInts, equals({'a': 3, 'b': null})); expect(e.mapOfNullableSerializables['a']!.x, 3); expect(e.mapOfNullableSerializables.containsKey('b'), true); expect(e.mapOfNullableSerializables['b'], null); @@ -198,9 +180,7 @@ void main() { }); test(r'field with dollar sign $', () { - var json = { - r'fieldWithDollarSign$': 1, - }; + var json = {r'fieldWithDollarSign$': 1}; var f = F.fromJson(json); expect(f.fieldWithDollarSign$, 1); diff --git a/goldens/foo/lib/literal_params.dart b/goldens/foo/lib/literal_params.dart index 5cf2b853..c7d15235 100644 --- a/goldens/foo/lib/literal_params.dart +++ b/goldens/foo/lib/literal_params.dart @@ -14,10 +14,7 @@ import 'package:_test_macros/literal_params.dart'; nums: [13.0, 14], doubles: [15.0, 16], strings: ['17', 'eighteen'], - objects: [ - 19, - Bar(a: true, b: false), - ], + objects: [19, Bar(a: true, b: false)], ) class Foo {} diff --git a/goldens/foo/pubspec.yaml b/goldens/foo/pubspec.yaml index 2dfbfa1f..e6e4e434 100644 --- a/goldens/foo/pubspec.yaml +++ b/goldens/foo/pubspec.yaml @@ -3,7 +3,7 @@ publish-to: none resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: _test_macros: any diff --git a/pkgs/_analyzer_cfe_macros/lib/metadata_converter.dart b/pkgs/_analyzer_cfe_macros/lib/metadata_converter.dart index 94960963..f7173f15 100644 --- a/pkgs/_analyzer_cfe_macros/lib/metadata_converter.dart +++ b/pkgs/_analyzer_cfe_macros/lib/metadata_converter.dart @@ -11,416 +11,514 @@ import 'package:dart_model/src/macro_metadata.g.dart' as dart_model; // TODO(davidmorgan): determine how this will be maintained. dart_model.Argument? convertToArgument(Object? object) => switch (object) { - front_end.PositionalArgument o => dart_model.Argument.positionalArgument( - convert(o)!), - front_end.NamedArgument o => dart_model.Argument.namedArgument( - convert(o)!), - null => null, - _ => throw ArgumentError(object), - }; + front_end.PositionalArgument o => dart_model.Argument.positionalArgument( + convert(o)!, + ), + front_end.NamedArgument o => dart_model.Argument.namedArgument( + convert(o)!, + ), + null => null, + _ => throw ArgumentError(object), +}; dart_model.Element? convertToElement(Object? object) => switch (object) { - front_end.ExpressionElement o => dart_model.Element.expressionElement( - convert(o)!), - front_end.MapEntryElement o => dart_model.Element.mapEntryElement( - convert(o)!), - front_end.SpreadElement o => - dart_model.Element.spreadElement(convert(o)!), - front_end.IfElement o => - dart_model.Element.ifElement(convert(o)!), - null => null, - _ => throw ArgumentError(object), - }; + front_end.ExpressionElement o => dart_model.Element.expressionElement( + convert(o)!, + ), + front_end.MapEntryElement o => dart_model.Element.mapEntryElement( + convert(o)!, + ), + front_end.SpreadElement o => dart_model.Element.spreadElement( + convert(o)!, + ), + front_end.IfElement o => dart_model.Element.ifElement( + convert(o)!, + ), + null => null, + _ => throw ArgumentError(object), +}; dart_model.Expression? convertToExpression(Object? object) => switch (object) { - front_end.InvalidExpression o => dart_model.Expression.invalidExpression( - convert(o)!), - front_end.StaticGet o => - dart_model.Expression.staticGet(convert(o)!), - front_end.FunctionTearOff o => dart_model.Expression.functionTearOff( - convert(o)!), - front_end.ConstructorTearOff o => - dart_model.Expression.constructorTearOff( - convert(o)!), - front_end.ConstructorInvocation o => - dart_model.Expression.constructorInvocation( - convert(o)!), - front_end.IntegerLiteral o => dart_model.Expression.integerLiteral( - convert(o)!), - front_end.DoubleLiteral o => dart_model.Expression.doubleLiteral( - convert(o)!), - front_end.BooleanLiteral o => dart_model.Expression.booleanLiteral( - convert(o)!), - front_end.NullLiteral o => - dart_model.Expression.nullLiteral(convert(o)!), - front_end.SymbolLiteral o => dart_model.Expression.symbolLiteral( - convert(o)!), - front_end.StringLiteral o => dart_model.Expression.stringLiteral( - convert(o)!), - front_end.AdjacentStringLiterals o => - dart_model.Expression.adjacentStringLiterals( - convert(o)!), - front_end.ImplicitInvocation o => - dart_model.Expression.implicitInvocation( - convert(o)!), - front_end.StaticInvocation o => dart_model.Expression.staticInvocation( - convert(o)!), - front_end.Instantiation o => dart_model.Expression.instantiation( - convert(o)!), - front_end.MethodInvocation o => dart_model.Expression.methodInvocation( - convert(o)!), - front_end.PropertyGet o => - dart_model.Expression.propertyGet(convert(o)!), - front_end.NullAwarePropertyGet o => - dart_model.Expression.nullAwarePropertyGet( - convert(o)!), - front_end.TypeLiteral o => - dart_model.Expression.typeLiteral(convert(o)!), - front_end.ParenthesizedExpression o => - dart_model.Expression.parenthesizedExpression( - convert(o)!), - front_end.ConditionalExpression o => - dart_model.Expression.conditionalExpression( - convert(o)!), - front_end.ListLiteral o => - dart_model.Expression.listLiteral(convert(o)!), - front_end.SetOrMapLiteral o => dart_model.Expression.setOrMapLiteral( - convert(o)!), - front_end.RecordLiteral o => dart_model.Expression.recordLiteral( - convert(o)!), - front_end.IfNull o => - dart_model.Expression.ifNull(convert(o)!), - front_end.LogicalExpression o => dart_model.Expression.logicalExpression( - convert(o)!), - front_end.EqualityExpression o => - dart_model.Expression.equalityExpression( - convert(o)!), - front_end.BinaryExpression o => dart_model.Expression.binaryExpression( - convert(o)!), - front_end.UnaryExpression o => dart_model.Expression.unaryExpression( - convert(o)!), - front_end.IsTest o => - dart_model.Expression.isTest(convert(o)!), - front_end.AsExpression o => dart_model.Expression.asExpression( - convert(o)!), - front_end.NullCheck o => - dart_model.Expression.nullCheck(convert(o)!), - front_end.UnresolvedExpression o => - dart_model.Expression.unresolvedExpression( - convert(o)!), - null => null, - _ => throw ArgumentError(object), - }; + front_end.InvalidExpression o => dart_model.Expression.invalidExpression( + convert(o)!, + ), + front_end.StaticGet o => dart_model.Expression.staticGet( + convert(o)!, + ), + front_end.FunctionTearOff o => dart_model.Expression.functionTearOff( + convert(o)!, + ), + front_end.ConstructorTearOff o => dart_model.Expression.constructorTearOff( + convert(o)!, + ), + front_end.ConstructorInvocation o => dart_model + .Expression.constructorInvocation( + convert(o)!, + ), + front_end.IntegerLiteral o => dart_model.Expression.integerLiteral( + convert(o)!, + ), + front_end.DoubleLiteral o => dart_model.Expression.doubleLiteral( + convert(o)!, + ), + front_end.BooleanLiteral o => dart_model.Expression.booleanLiteral( + convert(o)!, + ), + front_end.NullLiteral o => dart_model.Expression.nullLiteral( + convert(o)!, + ), + front_end.SymbolLiteral o => dart_model.Expression.symbolLiteral( + convert(o)!, + ), + front_end.StringLiteral o => dart_model.Expression.stringLiteral( + convert(o)!, + ), + front_end.AdjacentStringLiterals o => dart_model + .Expression.adjacentStringLiterals( + convert(o)!, + ), + front_end.ImplicitInvocation o => dart_model.Expression.implicitInvocation( + convert(o)!, + ), + front_end.StaticInvocation o => dart_model.Expression.staticInvocation( + convert(o)!, + ), + front_end.Instantiation o => dart_model.Expression.instantiation( + convert(o)!, + ), + front_end.MethodInvocation o => dart_model.Expression.methodInvocation( + convert(o)!, + ), + front_end.PropertyGet o => dart_model.Expression.propertyGet( + convert(o)!, + ), + front_end.NullAwarePropertyGet o => dart_model + .Expression.nullAwarePropertyGet( + convert(o)!, + ), + front_end.TypeLiteral o => dart_model.Expression.typeLiteral( + convert(o)!, + ), + front_end.ParenthesizedExpression o => dart_model + .Expression.parenthesizedExpression( + convert(o)!, + ), + front_end.ConditionalExpression o => dart_model + .Expression.conditionalExpression( + convert(o)!, + ), + front_end.ListLiteral o => dart_model.Expression.listLiteral( + convert(o)!, + ), + front_end.SetOrMapLiteral o => dart_model.Expression.setOrMapLiteral( + convert(o)!, + ), + front_end.RecordLiteral o => dart_model.Expression.recordLiteral( + convert(o)!, + ), + front_end.IfNull o => dart_model.Expression.ifNull( + convert(o)!, + ), + front_end.LogicalExpression o => dart_model.Expression.logicalExpression( + convert(o)!, + ), + front_end.EqualityExpression o => dart_model.Expression.equalityExpression( + convert(o)!, + ), + front_end.BinaryExpression o => dart_model.Expression.binaryExpression( + convert(o)!, + ), + front_end.UnaryExpression o => dart_model.Expression.unaryExpression( + convert(o)!, + ), + front_end.IsTest o => dart_model.Expression.isTest( + convert(o)!, + ), + front_end.AsExpression o => dart_model.Expression.asExpression( + convert(o)!, + ), + front_end.NullCheck o => dart_model.Expression.nullCheck( + convert(o)!, + ), + front_end.UnresolvedExpression o => dart_model + .Expression.unresolvedExpression( + convert(o)!, + ), + null => null, + _ => throw ArgumentError(object), +}; dart_model.RecordField? convertToRecordField(Object? object) => switch (object) { front_end.RecordNamedField o => dart_model.RecordField.recordNamedField( - convert(o)!), - front_end.RecordPositionalField o => - dart_model.RecordField.recordPositionalField( - convert(o)!), + convert(o)!, + ), + front_end.RecordPositionalField o => dart_model + .RecordField.recordPositionalField( + convert(o)!, + ), null => null, _ => throw ArgumentError(object), }; dart_model.Reference? convertToReference(Object? object) => switch (object) { - front_end.FieldReference o => dart_model.Reference.fieldReference( - convert(o)!), - front_end.FunctionReference o => dart_model.Reference.functionReference( - convert(o)!), - front_end.ConstructorReference o => - dart_model.Reference.constructorReference( - convert(o)!), - front_end.TypeReference o => dart_model.Reference.typeReference( - convert(o)!), - front_end.ClassReference o => dart_model.Reference.classReference( - convert(o)!), - front_end.TypedefReference o => dart_model.Reference.typedefReference( - convert(o)!), - front_end.ExtensionReference o => dart_model.Reference.extensionReference( - convert(o)!), - front_end.ExtensionTypeReference o => - dart_model.Reference.extensionTypeReference( - convert(o)!), - front_end.EnumReference o => dart_model.Reference.enumReference( - convert(o)!), - front_end.FunctionTypeParameterReference o => - dart_model.Reference.functionTypeParameterReference( - convert(o)!), - null => null, - _ => throw ArgumentError(object), - }; + front_end.FieldReference o => dart_model.Reference.fieldReference( + convert(o)!, + ), + front_end.FunctionReference o => dart_model.Reference.functionReference( + convert(o)!, + ), + front_end.ConstructorReference o => dart_model.Reference.constructorReference( + convert(o)!, + ), + front_end.TypeReference o => dart_model.Reference.typeReference( + convert(o)!, + ), + front_end.ClassReference o => dart_model.Reference.classReference( + convert(o)!, + ), + front_end.TypedefReference o => dart_model.Reference.typedefReference( + convert(o)!, + ), + front_end.ExtensionReference o => dart_model.Reference.extensionReference( + convert(o)!, + ), + front_end.ExtensionTypeReference o => dart_model + .Reference.extensionTypeReference( + convert(o)!, + ), + front_end.EnumReference o => dart_model.Reference.enumReference( + convert(o)!, + ), + front_end.FunctionTypeParameterReference o => dart_model + .Reference.functionTypeParameterReference( + convert(o)!, + ), + null => null, + _ => throw ArgumentError(object), +}; dart_model.StringLiteralPart? convertToStringLiteralPart(Object? object) => switch (object) { front_end.StringPart o => dart_model.StringLiteralPart.stringPart( - convert(o)!), - front_end.InterpolationPart o => - dart_model.StringLiteralPart.interpolationPart( - convert(o)!), + convert(o)!, + ), + front_end.InterpolationPart o => dart_model + .StringLiteralPart.interpolationPart( + convert(o)!, + ), null => null, _ => throw ArgumentError(object), }; dart_model.TypeAnnotation? convertToTypeAnnotation(Object? object) => switch (object) { - front_end.NamedTypeAnnotation o => - dart_model.TypeAnnotation.namedTypeAnnotation( - convert(o)!), - front_end.NullableTypeAnnotation o => - dart_model.TypeAnnotation.nullableTypeAnnotation( - convert(o)!), - front_end.VoidTypeAnnotation o => - dart_model.TypeAnnotation.voidTypeAnnotation( - convert(o)!), - front_end.DynamicTypeAnnotation o => - dart_model.TypeAnnotation.dynamicTypeAnnotation( - convert(o)!), - front_end.InvalidTypeAnnotation o => - dart_model.TypeAnnotation.invalidTypeAnnotation( - convert(o)!), - front_end.UnresolvedTypeAnnotation o => - dart_model.TypeAnnotation.unresolvedTypeAnnotation( - convert(o)!), - front_end.FunctionTypeAnnotation o => - dart_model.TypeAnnotation.functionTypeAnnotation( - convert(o)!), - front_end.FunctionTypeParameterType o => - dart_model.TypeAnnotation.functionTypeParameterType( - convert(o)!), - front_end.RecordTypeAnnotation o => - dart_model.TypeAnnotation.recordTypeAnnotation( - convert(o)!), + front_end.NamedTypeAnnotation o => dart_model + .TypeAnnotation.namedTypeAnnotation( + convert(o)!, + ), + front_end.NullableTypeAnnotation o => dart_model + .TypeAnnotation.nullableTypeAnnotation( + convert(o)!, + ), + front_end.VoidTypeAnnotation o => dart_model + .TypeAnnotation.voidTypeAnnotation( + convert(o)!, + ), + front_end.DynamicTypeAnnotation o => dart_model + .TypeAnnotation.dynamicTypeAnnotation( + convert(o)!, + ), + front_end.InvalidTypeAnnotation o => dart_model + .TypeAnnotation.invalidTypeAnnotation( + convert(o)!, + ), + front_end.UnresolvedTypeAnnotation o => dart_model + .TypeAnnotation.unresolvedTypeAnnotation( + convert(o)!, + ), + front_end.FunctionTypeAnnotation o => dart_model + .TypeAnnotation.functionTypeAnnotation( + convert(o)!, + ), + front_end.FunctionTypeParameterType o => dart_model + .TypeAnnotation.functionTypeParameterType( + convert(o)!, + ), + front_end.RecordTypeAnnotation o => dart_model + .TypeAnnotation.recordTypeAnnotation( + convert(o)!, + ), null => null, _ => throw ArgumentError(object), }; T? convert(Object? object) => switch (object) { - front_end.BinaryOperator o => o.name as T, - front_end.LogicalOperator o => o.name as T, - front_end.UnaryOperator o => o.name as T, - front_end.AsExpression o => dart_model.AsExpression( + front_end.BinaryOperator o => o.name as T, + front_end.LogicalOperator o => o.name as T, + front_end.UnaryOperator o => o.name as T, + front_end.AsExpression o => + dart_model.AsExpression( expression: convertToExpression(o.expression), type: convert(o.type), - ) as T, - front_end.BinaryExpression o => dart_model.BinaryExpression( + ) + as T, + front_end.BinaryExpression o => + dart_model.BinaryExpression( left: convertToExpression(o.left), operator: convert(o.operator), right: convertToExpression(o.right), - ) as T, - front_end.BooleanLiteral o => dart_model.BooleanLiteral( - text: convert(o.text), - ) as T, - front_end.ClassReference o => dart_model.ClassReference() as T, - front_end.ConditionalExpression o => dart_model.ConditionalExpression( + ) + as T, + front_end.BooleanLiteral o => + dart_model.BooleanLiteral(text: convert(o.value.toString())) as T, + front_end.ClassReference o => dart_model.ClassReference() as T, + front_end.ConditionalExpression o => + dart_model.ConditionalExpression( condition: convertToExpression(o.condition), then: convertToExpression(o.then), otherwise: convertToExpression(o.otherwise), - ) as T, - front_end.ConstructorInvocation o => dart_model.ConstructorInvocation( + ) + as T, + front_end.ConstructorInvocation o => + dart_model.ConstructorInvocation( type: convert(o.type), constructor: convertToReference(o.constructor), arguments: convert(o.arguments), - ) as T, - front_end.ConstructorReference o => - dart_model.ConstructorReference() as T, - front_end.ConstructorTearOff o => dart_model.ConstructorTearOff( + ) + as T, + front_end.ConstructorReference o => dart_model.ConstructorReference() as T, + front_end.ConstructorTearOff o => + dart_model.ConstructorTearOff( type: convert(o.type), reference: convert(o.reference), - ) as T, - front_end.DoubleLiteral o => dart_model.DoubleLiteral( - text: convert(o.text), - ) as T, - front_end.DynamicTypeAnnotation o => dart_model.DynamicTypeAnnotation( - reference: convertToReference(o.reference), - ) as T, - front_end.EnumReference o => dart_model.EnumReference() as T, - front_end.EqualityExpression o => dart_model.EqualityExpression( + ) + as T, + front_end.DoubleLiteral o => + dart_model.DoubleLiteral(text: convert(o.text)) as T, + front_end.DynamicTypeAnnotation o => + dart_model.DynamicTypeAnnotation(reference: convertToReference(o.reference)) + as T, + front_end.EnumReference o => dart_model.EnumReference() as T, + front_end.EqualityExpression o => + dart_model.EqualityExpression( left: convertToExpression(o.left), right: convertToExpression(o.right), isNotEquals: convert(o.isNotEquals), - ) as T, - front_end.ExpressionElement o => dart_model.ExpressionElement( + ) + as T, + front_end.ExpressionElement o => + dart_model.ExpressionElement( expression: convertToExpression(o.expression), isNullAware: convert(o.isNullAware), - ) as T, - front_end.ExtensionReference o => dart_model.ExtensionReference() as T, - front_end.ExtensionTypeReference o => - dart_model.ExtensionTypeReference() as T, - front_end.FieldReference o => dart_model.FieldReference() as T, - front_end.FormalParameter o => dart_model.FormalParameter() as T, - front_end.FormalParameterGroup o => - dart_model.FormalParameterGroup() as T, - front_end.FunctionReference o => dart_model.FunctionReference() as T, - front_end.FunctionTearOff o => dart_model.FunctionTearOff( - reference: convert(o.reference), - ) as T, - front_end.FunctionTypeAnnotation o => dart_model.FunctionTypeAnnotation( + ) + as T, + front_end.ExtensionReference o => dart_model.ExtensionReference() as T, + front_end.ExtensionTypeReference o => + dart_model.ExtensionTypeReference() as T, + front_end.FieldReference o => dart_model.FieldReference() as T, + front_end.FormalParameter o => dart_model.FormalParameter() as T, + front_end.FormalParameterGroup o => dart_model.FormalParameterGroup() as T, + front_end.FunctionReference o => dart_model.FunctionReference() as T, + front_end.FunctionTearOff o => + dart_model.FunctionTearOff(reference: convert(o.reference)) as T, + front_end.FunctionTypeAnnotation o => + dart_model.FunctionTypeAnnotation( returnType: convert(o.returnType), typeParameters: convert(o.typeParameters), formalParameters: convert(o.formalParameters), - ) as T, - front_end.FunctionTypeParameter o => - dart_model.FunctionTypeParameter() as T, - front_end.FunctionTypeParameterReference o => - dart_model.FunctionTypeParameterReference() as T, - front_end.FunctionTypeParameterType o => - dart_model.FunctionTypeParameterType( + ) + as T, + front_end.FunctionTypeParameter o => dart_model.FunctionTypeParameter() as T, + front_end.FunctionTypeParameterReference o => + dart_model.FunctionTypeParameterReference() as T, + front_end.FunctionTypeParameterType o => + dart_model.FunctionTypeParameterType( functionTypeParameter: convert(o.functionTypeParameter), - ) as T, - front_end.IfElement o => dart_model.IfElement( + ) + as T, + front_end.IfElement o => + dart_model.IfElement( condition: convertToExpression(o.condition), then: convertToElement(o.then), otherwise: convert(o.otherwise), - ) as T, - front_end.IfNull o => dart_model.IfNull( + ) + as T, + front_end.IfNull o => + dart_model.IfNull( left: convertToExpression(o.left), right: convertToExpression(o.right), - ) as T, - front_end.ImplicitInvocation o => dart_model.ImplicitInvocation( + ) + as T, + front_end.ImplicitInvocation o => + dart_model.ImplicitInvocation( receiver: convertToExpression(o.receiver), typeArguments: convert(o.typeArguments), arguments: convert(o.arguments), - ) as T, - front_end.Instantiation o => dart_model.Instantiation( + ) + as T, + front_end.Instantiation o => + dart_model.Instantiation( receiver: convertToExpression(o.receiver), typeArguments: convert(o.typeArguments), - ) as T, - front_end.IntegerLiteral o => dart_model.IntegerLiteral( - text: convert(o.text), - ) as T, - front_end.InterpolationPart o => dart_model.InterpolationPart( - expression: convertToExpression(o.expression), - ) as T, - front_end.InvalidExpression o => dart_model.InvalidExpression() as T, - front_end.InvalidTypeAnnotation o => - dart_model.InvalidTypeAnnotation() as T, - front_end.IsTest o => dart_model.IsTest( + ) + as T, + front_end.IntegerLiteral o => + dart_model.IntegerLiteral(text: convert(o.text)) as T, + front_end.InterpolationPart o => + dart_model.InterpolationPart(expression: convertToExpression(o.expression)) + as T, + front_end.InvalidExpression o => dart_model.InvalidExpression() as T, + front_end.InvalidTypeAnnotation o => dart_model.InvalidTypeAnnotation() as T, + front_end.IsTest o => + dart_model.IsTest( expression: convertToExpression(o.expression), type: convert(o.type), isNot: convert(o.isNot), - ) as T, - front_end.ListLiteral o => dart_model.ListLiteral( + ) + as T, + front_end.ListLiteral o => + dart_model.ListLiteral( typeArguments: convert(o.typeArguments), elements: convert(o.elements), - ) as T, - front_end.LogicalExpression o => dart_model.LogicalExpression( + ) + as T, + front_end.LogicalExpression o => + dart_model.LogicalExpression( left: convertToExpression(o.left), operator: convert(o.operator), right: convertToExpression(o.right), - ) as T, - front_end.MapEntryElement o => dart_model.MapEntryElement( + ) + as T, + front_end.MapEntryElement o => + dart_model.MapEntryElement( key: convertToExpression(o.key), value: convertToExpression(o.value), isNullAwareKey: convert(o.isNullAwareKey), isNullAwareValue: convert(o.isNullAwareValue), - ) as T, - front_end.MethodInvocation o => dart_model.MethodInvocation( + ) + as T, + front_end.MethodInvocation o => + dart_model.MethodInvocation( receiver: convertToExpression(o.receiver), name: convert(o.name), typeArguments: convert(o.typeArguments), arguments: convert(o.arguments), - ) as T, - front_end.NamedArgument o => dart_model.NamedArgument( + ) + as T, + front_end.NamedArgument o => + dart_model.NamedArgument( name: convert(o.name), expression: convertToExpression(o.expression), - ) as T, - front_end.NamedTypeAnnotation o => dart_model.NamedTypeAnnotation( + ) + as T, + front_end.NamedTypeAnnotation o => + dart_model.NamedTypeAnnotation( reference: convertToReference(o.reference), typeArguments: convert(o.typeArguments), - ) as T, - front_end.NullableTypeAnnotation o => dart_model.NullableTypeAnnotation( - typeAnnotation: convert(o.typeAnnotation), - ) as T, - front_end.NullAwarePropertyGet o => dart_model.NullAwarePropertyGet( + ) + as T, + front_end.NullableTypeAnnotation o => + dart_model.NullableTypeAnnotation(typeAnnotation: convert(o.typeAnnotation)) + as T, + front_end.NullAwarePropertyGet o => + dart_model.NullAwarePropertyGet( receiver: convertToExpression(o.receiver), name: convert(o.name), - ) as T, - front_end.NullCheck o => dart_model.NullCheck( - expression: convertToExpression(o.expression), - ) as T, - front_end.NullLiteral o => dart_model.NullLiteral() as T, - front_end.ParenthesizedExpression o => dart_model.ParenthesizedExpression( - expression: convertToExpression(o.expression), - ) as T, - front_end.PositionalArgument o => dart_model.PositionalArgument( + ) + as T, + front_end.NullCheck o => + dart_model.NullCheck(expression: convertToExpression(o.expression)) as T, + front_end.NullLiteral o => dart_model.NullLiteral() as T, + front_end.ParenthesizedExpression o => + dart_model.ParenthesizedExpression( expression: convertToExpression(o.expression), - ) as T, - front_end.PropertyGet o => dart_model.PropertyGet( + ) + as T, + front_end.PositionalArgument o => + dart_model.PositionalArgument(expression: convertToExpression(o.expression)) + as T, + front_end.PropertyGet o => + dart_model.PropertyGet( receiver: convertToExpression(o.receiver), name: convert(o.name), - ) as T, - front_end.RecordLiteral o => dart_model.RecordLiteral( - fields: convert(o.fields), - ) as T, - front_end.RecordNamedField o => dart_model.RecordNamedField( + ) + as T, + front_end.RecordLiteral o => + dart_model.RecordLiteral(fields: convert(o.fields)) as T, + front_end.RecordNamedField o => + dart_model.RecordNamedField( name: convert(o.name), expression: convertToExpression(o.expression), - ) as T, - front_end.RecordPositionalField o => dart_model.RecordPositionalField( + ) + as T, + front_end.RecordPositionalField o => + dart_model.RecordPositionalField( expression: convertToExpression(o.expression), - ) as T, - front_end.RecordTypeAnnotation o => dart_model.RecordTypeAnnotation( + ) + as T, + front_end.RecordTypeAnnotation o => + dart_model.RecordTypeAnnotation( positional: convert(o.positional), named: convert(o.named), - ) as T, - front_end.RecordTypeEntry o => dart_model.RecordTypeEntry() as T, - front_end.References o => dart_model.References() as T, - front_end.SetOrMapLiteral o => dart_model.SetOrMapLiteral( + ) + as T, + front_end.RecordTypeEntry o => dart_model.RecordTypeEntry() as T, + front_end.References o => dart_model.References() as T, + front_end.SetOrMapLiteral o => + dart_model.SetOrMapLiteral( typeArguments: convert(o.typeArguments), elements: convert(o.elements), - ) as T, - front_end.SpreadElement o => dart_model.SpreadElement( + ) + as T, + front_end.SpreadElement o => + dart_model.SpreadElement( expression: convertToExpression(o.expression), isNullAware: convert(o.isNullAware), - ) as T, - front_end.StaticGet o => dart_model.StaticGet( - reference: convert(o.reference), - ) as T, - front_end.StaticInvocation o => dart_model.StaticInvocation( + ) + as T, + front_end.StaticGet o => + dart_model.StaticGet(reference: convert(o.reference)) as T, + front_end.StaticInvocation o => + dart_model.StaticInvocation( function: convert(o.function), typeArguments: convert(o.typeArguments), arguments: convert(o.arguments), - ) as T, - front_end.AdjacentStringLiterals o => dart_model.AdjacentStringLiterals( - expressions: convert(o.expressions), - ) as T, - front_end.StringLiteral o => dart_model.StringLiteral( - parts: convert(o.parts), - ) as T, - front_end.StringPart o => dart_model.StringPart( - text: convert(o.text), - ) as T, - front_end.SymbolLiteral o => dart_model.SymbolLiteral( - parts: convert(o.parts), - ) as T, - front_end.TypedefReference o => dart_model.TypedefReference() as T, - front_end.TypeLiteral o => dart_model.TypeLiteral( - typeAnnotation: convert(o.typeAnnotation), - ) as T, - front_end.TypeReference o => dart_model.TypeReference() as T, - front_end.UnaryExpression o => dart_model.UnaryExpression( + ) + as T, + front_end.AdjacentStringLiterals o => + dart_model.AdjacentStringLiterals(expressions: convert(o.expressions)) as T, + front_end.StringLiteral o => + dart_model.StringLiteral(parts: convert(o.parts)) as T, + front_end.StringPart o => dart_model.StringPart(text: convert(o.text)) as T, + front_end.SymbolLiteral o => + dart_model.SymbolLiteral(parts: convert(o.parts)) as T, + front_end.TypedefReference o => dart_model.TypedefReference() as T, + front_end.TypeLiteral o => + dart_model.TypeLiteral(typeAnnotation: convert(o.typeAnnotation)) as T, + front_end.TypeReference o => dart_model.TypeReference() as T, + front_end.UnaryExpression o => + dart_model.UnaryExpression( operator: convert(o.operator), expression: convertToExpression(o.expression), - ) as T, - front_end.UnresolvedExpression o => - dart_model.UnresolvedExpression() as T, - front_end.UnresolvedTypeAnnotation o => - dart_model.UnresolvedTypeAnnotation() as T, - front_end.VoidTypeAnnotation o => dart_model.VoidTypeAnnotation( - reference: convertToReference(o.reference), - ) as T, - String o => o as T, - int o => o as T, - bool o => o as T, - double o => o as T, - // Manually added converters for lists of union types. - List o => - o.map((i) => convertToArgument(i)!).toList() as T, - List o => - o.map((i) => convertToElement(i)!).toList() as T, - List o => - o.map((i) => convertToExpression(i)!).toList() as T, - List o => - o.map((i) => convertToRecordField(i)!).toList() as T, - List o => - o.map((i) => convertToStringLiteralPart(i)!).toList() as T, - List o => - o.map((i) => convertToTypeAnnotation(i)!).toList() as T, - List o => o.map((i) => convert>(i)!).toList() as T, - null => null, - _ => throw ArgumentError(object), - }; + ) + as T, + front_end.UnresolvedExpression o => dart_model.UnresolvedExpression() as T, + front_end.UnresolvedTypeAnnotation o => + dart_model.UnresolvedTypeAnnotation() as T, + front_end.VoidTypeAnnotation o => + dart_model.VoidTypeAnnotation(reference: convertToReference(o.reference)) + as T, + String o => o as T, + int o => o as T, + bool o => o as T, + double o => o as T, + // Manually added converters for lists of union types. + List o => + o.map((i) => convertToArgument(i)!).toList() as T, + List o => o.map((i) => convertToElement(i)!).toList() as T, + List o => + o.map((i) => convertToExpression(i)!).toList() as T, + List o => + o.map((i) => convertToRecordField(i)!).toList() as T, + List o => + o.map((i) => convertToStringLiteralPart(i)!).toList() as T, + List o => + o.map((i) => convertToTypeAnnotation(i)!).toList() as T, + List o => o.map((i) => convert>(i)!).toList() as T, + null => null, + _ => throw ArgumentError(object), +}; diff --git a/pkgs/_analyzer_cfe_macros/pubspec.yaml b/pkgs/_analyzer_cfe_macros/pubspec.yaml index 9119b39d..026c3cd3 100644 --- a/pkgs/_analyzer_cfe_macros/pubspec.yaml +++ b/pkgs/_analyzer_cfe_macros/pubspec.yaml @@ -4,7 +4,7 @@ description: Macro support for the analyzer and CFE. resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: _fe_analyzer_shared: any diff --git a/pkgs/_analyzer_cfe_macros/test/metadata_converter_test.dart b/pkgs/_analyzer_cfe_macros/test/metadata_converter_test.dart index e3c125d4..00237200 100644 --- a/pkgs/_analyzer_cfe_macros/test/metadata_converter_test.dart +++ b/pkgs/_analyzer_cfe_macros/test/metadata_converter_test.dart @@ -9,13 +9,18 @@ import 'package:test/test.dart'; void main() { test('converts with unions', () { - final invocation = MethodInvocation(DoubleLiteral('1.23'), 'round', [], []); + final invocation = MethodInvocation( + DoubleLiteral('1.23', 1.23), + 'round', + [], + [], + ); Scope.query.run(() { expect(convert(invocation), { 'receiver': { 'type': 'DoubleLiteral', - 'value': {'text': '1.23'} + 'value': {'text': '1.23'}, }, 'name': 'round', 'typeArguments': [], @@ -26,32 +31,39 @@ void main() { test('converts with enums', () { final expression = BinaryExpression( - DoubleLiteral('1.23'), BinaryOperator.minus, DoubleLiteral('1.24')); + DoubleLiteral('1.23', 1.23), + BinaryOperator.minus, + DoubleLiteral('1.24', 1.24), + ); Scope.query.run(() { expect(convert(expression), { 'left': { 'type': 'DoubleLiteral', - 'value': {'text': '1.23'} + 'value': {'text': '1.23'}, }, 'operator': 'minus', 'right': { 'type': 'DoubleLiteral', - 'value': {'text': '1.24'} - } + 'value': {'text': '1.24'}, + }, }); }); }); test('converts with lists', () { - final invocation = MethodInvocation(DoubleLiteral('1.23'), 'round', [], - [PositionalArgument(IntegerLiteral('4'))]); + final invocation = MethodInvocation( + DoubleLiteral('1.23', 1.23), + 'round', + [], + [PositionalArgument(IntegerLiteral.fromText('4'))], + ); Scope.query.run(() { expect(convert(invocation), { 'receiver': { 'type': 'DoubleLiteral', - 'value': {'text': '1.23'} + 'value': {'text': '1.23'}, }, 'name': 'round', 'typeArguments': [], @@ -61,11 +73,11 @@ void main() { 'value': { 'expression': { 'type': 'IntegerLiteral', - 'value': {'text': '4'} - } - } - } - ] + 'value': {'text': '4'}, + }, + }, + }, + ], }); }); }); diff --git a/pkgs/_analyzer_macros/bin/server.dart b/pkgs/_analyzer_macros/bin/server.dart index 3fe39a11..9f887729 100644 --- a/pkgs/_analyzer_macros/bin/server.dart +++ b/pkgs/_analyzer_macros/bin/server.dart @@ -21,12 +21,16 @@ import 'package:macro_service/macro_service.dart'; /// `PACKAGE_CONFIG_PATH`. void main(List args) async { injected.macroImplementation = await AnalyzerMacroImplementation.start( - protocol: Protocol( - encoding: ProtocolEncoding.binary, version: ProtocolVersion.macros1), - // TODO(davidmorgan): this needs to come from the analyzer, not be - // hardcoded. - packageConfig: - Uri.file(const String.fromEnvironment('PACKAGE_CONFIG_PATH'))); + protocol: Protocol( + encoding: ProtocolEncoding.binary, + version: ProtocolVersion.macros1, + ), + // TODO(davidmorgan): this needs to come from the analyzer, not be + // hardcoded. + packageConfig: Uri.file( + const String.fromEnvironment('PACKAGE_CONFIG_PATH'), + ), + ); var starter = ServerStarter(); starter.start(args); diff --git a/pkgs/_analyzer_macros/lib/macro_implementation.dart b/pkgs/_analyzer_macros/lib/macro_implementation.dart index 10cff455..c24cc99a 100644 --- a/pkgs/_analyzer_macros/lib/macro_implementation.dart +++ b/pkgs/_analyzer_macros/lib/macro_implementation.dart @@ -30,14 +30,15 @@ class AnalyzerMacroImplementation implements injected.MacroImplementation { static Future start({ required Protocol protocol, required Uri packageConfig, - }) async => - AnalyzerMacroImplementation._( - packageConfig, - await MacroHost.serve( - // TODO(davidmorgan): support serving multiple protocols. - protocol: protocol, - packageConfig: packageConfig, - queryService: AnalyzerQueryService())); + }) async => AnalyzerMacroImplementation._( + packageConfig, + await MacroHost.serve( + // TODO(davidmorgan): support serving multiple protocols. + protocol: protocol, + packageConfig: packageConfig, + queryService: AnalyzerQueryService(), + ), + ); @override injected.MacroPackageConfigs get packageConfigs => @@ -64,10 +65,12 @@ class AnalyzerMacroRunner implements injected.MacroRunner { @override injected.RunningMacro run(Uri uri, String name) => AnalyzerRunningMacro.run( - _impl, + _impl, + QualifiedName(uri: '$uri', name: name), + _impl._host.lookupMacroImplementation( QualifiedName(uri: '$uri', name: name), - _impl._host - .lookupMacroImplementation(QualifiedName(uri: '$uri', name: name))!); + )!, + ); } class AnalyzerRunningMacro implements injected.RunningMacro { @@ -81,70 +84,85 @@ class AnalyzerRunningMacro implements injected.RunningMacro { AnalyzerRunningMacro._(this._impl, this.name, this.implementation); - static AnalyzerRunningMacro run(AnalyzerMacroImplementation impl, - QualifiedName name, QualifiedName implementation) { + static AnalyzerRunningMacro run( + AnalyzerMacroImplementation impl, + QualifiedName name, + QualifiedName implementation, + ) { return AnalyzerRunningMacro._(impl, name, implementation); } /// Queries for [target] and returns the [Model] representing the result. /// /// TODO: Make this a more limited query which doesn't fetch members. - Future _queryTarget(QualifiedName target) => - Scope.query.run(() async => (await _impl._host.hostService.handle( - MacroRequest.queryRequest( - QueryRequest(query: Query(target: target)), - id: nextRequestId))) - .asQueryResponse - .model); + Future _queryTarget(QualifiedName target) => Scope.query.run( + () async => + (await _impl._host.hostService.handle( + MacroRequest.queryRequest( + QueryRequest(query: Query(target: target)), + id: nextRequestId, + ), + )).asQueryResponse.model, + ); @override Future executeDeclarationsPhase( - macros_api_v1.MacroTarget target, - macros_api_v1.DeclarationPhaseIntrospector - declarationsPhaseIntrospector) async { + macros_api_v1.MacroTarget target, + macros_api_v1.DeclarationPhaseIntrospector declarationsPhaseIntrospector, + ) async { // TODO(davidmorgan): this is a hack to access analyzer internals; remove. introspector = declarationsPhaseIntrospector; return await AnalyzerMacroExecutionResult.dartModelToInjected( - target, - await _impl._host.augment( - name, - AugmentRequest( - phase: 2, - target: target.qualifiedName, - model: await _queryTarget(target.qualifiedName)))); + target, + await _impl._host.augment( + name, + AugmentRequest( + phase: 2, + target: target.qualifiedName, + model: await _queryTarget(target.qualifiedName), + ), + ), + ); } @override Future executeDefinitionsPhase( - macros_api_v1.MacroTarget target, - macros_api_v1.DefinitionPhaseIntrospector - definitionPhaseIntrospector) async { + macros_api_v1.MacroTarget target, + macros_api_v1.DefinitionPhaseIntrospector definitionPhaseIntrospector, + ) async { // TODO(davidmorgan): this is a hack to access analyzer internals; remove. introspector = definitionPhaseIntrospector; return await AnalyzerMacroExecutionResult.dartModelToInjected( - target, - await _impl._host.augment( - name, - AugmentRequest( - phase: 3, - target: target.qualifiedName, - model: await _queryTarget(target.qualifiedName)))); + target, + await _impl._host.augment( + name, + AugmentRequest( + phase: 3, + target: target.qualifiedName, + model: await _queryTarget(target.qualifiedName), + ), + ), + ); } @override Future executeTypesPhase( - macros_api_v1.MacroTarget target, - macros_api_v1.TypePhaseIntrospector typePhaseIntrospector) async { + macros_api_v1.MacroTarget target, + macros_api_v1.TypePhaseIntrospector typePhaseIntrospector, + ) async { // TODO(davidmorgan): this is a hack to access analyzer internals; remove. introspector = typePhaseIntrospector; return await AnalyzerMacroExecutionResult.dartModelToInjected( - target, - await _impl._host.augment( - name, - AugmentRequest( - phase: 1, - target: target.qualifiedName, - model: await _queryTarget(target.qualifiedName)))); + target, + await _impl._host.augment( + name, + AugmentRequest( + phase: 1, + target: target.qualifiedName, + model: await _queryTarget(target.qualifiedName), + ), + ), + ); } } @@ -157,19 +175,23 @@ class AnalyzerMacroExecutionResult final macros_api_v1.MacroTarget target; @override final Map> - typeAugmentations; + typeAugmentations; AnalyzerMacroExecutionResult( - this.target, Iterable declarations) - // TODO(davidmorgan): this assumes augmentations are for the macro - // application target. Instead, it should be explicit in - // `AugmentResponse`. - : typeAugmentations = { - (target as macros_api_v1.Declaration).identifier: declarations - }; + this.target, + Iterable declarations, + ) + // TODO(davidmorgan): this assumes augmentations are for the macro + // application target. Instead, it should be explicit in + // `AugmentResponse`. + : typeAugmentations = { + (target as macros_api_v1.Declaration).identifier: declarations, + }; static Future dartModelToInjected( - macros_api_v1.MacroTarget target, AugmentResponse augmentResponse) async { + macros_api_v1.MacroTarget target, + AugmentResponse augmentResponse, + ) async { final declarations = []; if (augmentResponse.typeAugmentations?.isNotEmpty == true) { // TODO: Handle targets that are not interfaces, or test that this works @@ -177,21 +199,28 @@ class AnalyzerMacroExecutionResult for (final entry in augmentResponse.typeAugmentations!.entries) { if (entry.key != target.qualifiedName.name) { throw UnimplementedError( - 'Type augmentations are only implemented when the type is the ' - 'target of the augmentation, expected ' - '${target.qualifiedName.name} but got ${entry.key}'); + 'Type augmentations are only implemented when the type is the ' + 'target of the augmentation, expected ' + '${target.qualifiedName.name} but got ${entry.key}', + ); } for (final augmentation in entry.value) { - declarations.add(macros_api_v1.DeclarationCode.fromParts( - await _resolveNames(augmentation.code))); + declarations.add( + macros_api_v1.DeclarationCode.fromParts( + await _resolveNames(augmentation.code), + ), + ); } } } for (final augmentation in augmentResponse.libraryAugmentations ?? const []) { - declarations.add(macros_api_v1.DeclarationCode.fromParts( - await _resolveNames(augmentation.code))); + declarations.add( + macros_api_v1.DeclarationCode.fromParts( + await _resolveNames(augmentation.code), + ), + ); } if (augmentResponse.enumValueAugmentations?.isNotEmpty == true) { @@ -211,25 +240,25 @@ class AnalyzerMacroExecutionResult @override Map> - get enumValueAugmentations => {}; + get enumValueAugmentations => {}; @override macros_api_v1.MacroException? get exception => null; @override Map - get extendsTypeAugmentations => {}; + get extendsTypeAugmentations => {}; @override Map> - get interfaceAugmentations => {}; + get interfaceAugmentations => {}; @override Iterable get libraryAugmentations => {}; @override Map> - get mixinAugmentations => {}; + get mixinAugmentations => {}; @override Iterable get newTypeNames => []; @@ -240,9 +269,10 @@ class AnalyzerMacroExecutionResult extension MacroTargetExtension on macros_api_v1.MacroTarget { QualifiedName get qualifiedName { - final element = ((this as macros_api_v1.Declaration).identifier - as analyzer.IdentifierImpl) - .element!; + final element = + ((this as macros_api_v1.Declaration).identifier + as analyzer.IdentifierImpl) + .element!; return element.qualifiedName; } } @@ -254,19 +284,27 @@ extension QualifiedNameForElement on Element { if (enclosingElement == null) { throw UnsupportedError('Library macro targets are not yet supported'); } - final scope = (enclosingElement is LibraryElement || - enclosingElement is CompilationUnitElement) - ? null - : enclosingElement.displayName; - final isStatic = scope == null - ? null - : switch (this) { - ClassMemberElement self => self.isStatic, - _ => throw UnimplementedError( - 'Cannot create a QualifiedName for $runtimeType'), - }; + final scope = + (enclosingElement is LibraryElement || + enclosingElement is CompilationUnitElement) + ? null + : enclosingElement.displayName; + final isStatic = + scope == null + ? null + : switch (this) { + ClassMemberElement self => self.isStatic, + _ => + throw UnimplementedError( + 'Cannot create a QualifiedName for $runtimeType', + ), + }; return QualifiedName( - uri: uri, name: displayName, scope: scope, isStatic: isStatic); + uri: uri, + name: displayName, + scope: scope, + isStatic: isStatic, + ); } } @@ -285,15 +323,19 @@ Future> _resolveNames(List codes) async { qualifiedNameStrings.map(QualifiedName.parse).toList(); final identifierFutures = >[]; for (final qualifiedName in qualifiedNamesList) { - identifierFutures.add((introspector as macros_api_v1.TypePhaseIntrospector) - // ignore: deprecated_member_use - .resolveIdentifier(Uri.parse(qualifiedName.uri), qualifiedName.name)); + identifierFutures.add( + (introspector as macros_api_v1.TypePhaseIntrospector) + // ignore: deprecated_member_use + .resolveIdentifier(Uri.parse(qualifiedName.uri), qualifiedName.name), + ); } final identifiers = await Future.wait(identifierFutures); // Build the result using the looked up [Identifier]s. - final identifiersByQualifiedNameStrings = - Map.fromIterables(qualifiedNameStrings, identifiers); + final identifiersByQualifiedNameStrings = Map.fromIterables( + qualifiedNameStrings, + identifiers, + ); final result = []; for (final code in codes) { if (code.type == CodeType.string) { diff --git a/pkgs/_analyzer_macros/lib/query_service.dart b/pkgs/_analyzer_macros/lib/query_service.dart index 6aceb67d..d5502519 100644 --- a/pkgs/_analyzer_macros/lib/query_service.dart +++ b/pkgs/_analyzer_macros/lib/query_service.dart @@ -43,62 +43,77 @@ final class AnalyzerQueryService extends QueryService { for (final annotation in clazz.metadata) { metadataAnnotations.add( MetadataAnnotation( - expression: metadata_converter.convertToExpression( - analyzer.parseAnnotation( - annotation as analyzer.ElementAnnotationImpl))), + expression: metadata_converter.convertToExpression( + analyzer.parseAnnotation( + annotation as analyzer.ElementAnnotationImpl, + ), + ), + ), ); } final interface = Interface( - properties: Properties(isClass: true), - metadataAnnotations: metadataAnnotations); + properties: Properties(isClass: true), + metadataAnnotations: metadataAnnotations, + ); try { for (final constructor in clazz.constructors) { interface.members[constructor.name] = Member( - requiredPositionalParameters: constructor - .requiredPositionalParameters(types.translator, types.context), - optionalPositionalParameters: constructor - .optionalPositionalParameters(types.translator, types.context), - namedParameters: - constructor.namedParameters(types.translator, types.context), - properties: Properties( - isAbstract: constructor.isAbstract, - isConstructor: true, - isGetter: false, - isField: false, - isMethod: false, - isStatic: false, - )); + requiredPositionalParameters: constructor + .requiredPositionalParameters(types.translator, types.context), + optionalPositionalParameters: constructor + .optionalPositionalParameters(types.translator, types.context), + namedParameters: constructor.namedParameters( + types.translator, + types.context, + ), + properties: Properties( + isAbstract: constructor.isAbstract, + isConstructor: true, + isGetter: false, + isField: false, + isMethod: false, + isStatic: false, + ), + ); } for (final field in clazz.fields) { interface.members[field.name] = Member( - properties: Properties( - isAbstract: field.isAbstract, - isConstructor: false, - isGetter: false, - isField: true, - isMethod: false, - isStatic: field.isStatic, - ), - returnType: types.addDartType(field.type)); + properties: Properties( + isAbstract: field.isAbstract, + isConstructor: false, + isGetter: false, + isField: true, + isMethod: false, + isStatic: field.isStatic, + ), + returnType: types.addDartType(field.type), + ); } for (final method in clazz.methods) { interface.members[method.name] = Member( - requiredPositionalParameters: method.requiredPositionalParameters( - types.translator, types.context), - optionalPositionalParameters: method.optionalPositionalParameters( - types.translator, types.context), - namedParameters: - method.namedParameters(types.translator, types.context), - properties: Properties( - isAbstract: method.isAbstract, - isConstructor: false, - isGetter: false, - isField: false, - isMethod: true, - isStatic: method.isStatic, - ), - returnType: types.addDartType(method.returnType)); + requiredPositionalParameters: method.requiredPositionalParameters( + types.translator, + types.context, + ), + optionalPositionalParameters: method.optionalPositionalParameters( + types.translator, + types.context, + ), + namedParameters: method.namedParameters( + types.translator, + types.context, + ), + properties: Properties( + isAbstract: method.isAbstract, + isConstructor: false, + isGetter: false, + isField: false, + isMethod: true, + isStatic: method.isStatic, + ), + returnType: types.addDartType(method.returnType), + ); } } catch (_) { // TODO: Fails in types phase, implement fine grained queries. @@ -129,9 +144,10 @@ class AnalyzerTypeHierarchy { /// Adds [element] and any supertypes to the hierarchy, if not already /// present. void addInterfaceElement(InterfaceElement element) { - final asNamedType = element.thisType - .acceptWithArgument(translator, context) - .asNamedTypeDesc; + final asNamedType = + element.thisType + .acceptWithArgument(translator, context) + .asNamedTypeDesc; final maybeEntry = typeHierarchy.named[asNamedType.name.asString]; if (maybeEntry != null) { @@ -156,7 +172,7 @@ class AnalyzerTypeHierarchy { ], supertypes: [ for (final superType in superTypes) - superType.acceptWithArgument(translator, context).asNamedTypeDesc + superType.acceptWithArgument(translator, context).asNamedTypeDesc, ], ); } @@ -164,27 +180,30 @@ class AnalyzerTypeHierarchy { extension ExecutableElementExtension on ExecutableElement { List requiredPositionalParameters( - AnalyzerTypesToMacros translator, TypeTranslationContext context) => - [ - for (final parameter in parameters) - if (parameter.isRequiredPositional) - parameter.type.acceptWithArgument(translator, context) - ]; + AnalyzerTypesToMacros translator, + TypeTranslationContext context, + ) => [ + for (final parameter in parameters) + if (parameter.isRequiredPositional) + parameter.type.acceptWithArgument(translator, context), + ]; List optionalPositionalParameters( - AnalyzerTypesToMacros translator, TypeTranslationContext context) => - [ - for (final parameter in parameters) - if (parameter.isOptionalPositional) - parameter.type.acceptWithArgument(translator, context) - ]; + AnalyzerTypesToMacros translator, + TypeTranslationContext context, + ) => [ + for (final parameter in parameters) + if (parameter.isOptionalPositional) + parameter.type.acceptWithArgument(translator, context), + ]; List namedParameters( - AnalyzerTypesToMacros translator, TypeTranslationContext context) => - [ - for (final parameter in parameters) - if (parameter.isNamed) - parameter.type.acceptWithArgument(translator, context) - as NamedFunctionTypeParameter - ]; + AnalyzerTypesToMacros translator, + TypeTranslationContext context, + ) => [ + for (final parameter in parameters) + if (parameter.isNamed) + parameter.type.acceptWithArgument(translator, context) + as NamedFunctionTypeParameter, + ]; } diff --git a/pkgs/_analyzer_macros/lib/src/type_translation.dart b/pkgs/_analyzer_macros/lib/src/type_translation.dart index 59b9257d..1049f33e 100644 --- a/pkgs/_analyzer_macros/lib/src/type_translation.dart +++ b/pkgs/_analyzer_macros/lib/src/type_translation.dart @@ -15,37 +15,54 @@ final class TypeTranslationContext { int idFor(TypeParameterElement parameter) { return _typeParameterIds.putIfAbsent( - parameter, () => _typeParameterIds.length); + parameter, + () => _typeParameterIds.length, + ); } } -final class AnalyzerTypesToMacros extends UnifyingTypeVisitorWithArgument< - model.StaticTypeDesc, TypeTranslationContext> { +final class AnalyzerTypesToMacros + extends + UnifyingTypeVisitorWithArgument< + model.StaticTypeDesc, + TypeTranslationContext + > { const AnalyzerTypesToMacros(); model.StaticTypeParameterDesc translateTypeParameter( - TypeParameterElement param, TypeTranslationContext context) { + TypeParameterElement param, + TypeTranslationContext context, + ) { final id = context.idFor(param); return model.StaticTypeParameterDesc( - identifier: id, bound: param.bound?.acceptWithArgument(this, context)); + identifier: id, + bound: param.bound?.acceptWithArgument(this, context), + ); } @override model.StaticTypeDesc visitDartType( - DartType type, TypeTranslationContext argument) { + DartType type, + TypeTranslationContext argument, + ) { return {'type': '_unknown'} as model.StaticTypeDesc; } @override model.StaticTypeDesc visitDynamicType( - DynamicType type, TypeTranslationContext argument) { - return model.StaticTypeDesc.dynamicTypeDesc(model.DynamicTypeDesc()) - .applyNullabilitySuffix(type.nullabilitySuffix); + DynamicType type, + TypeTranslationContext argument, + ) { + return model.StaticTypeDesc.dynamicTypeDesc( + model.DynamicTypeDesc(), + ).applyNullabilitySuffix(type.nullabilitySuffix); } @override model.StaticTypeDesc visitFunctionType( - FunctionType type, TypeTranslationContext argument) { + FunctionType type, + TypeTranslationContext argument, + ) { return model.StaticTypeDesc.functionTypeDesc( model.FunctionTypeDesc( typeParameters: [ @@ -77,56 +94,71 @@ final class AnalyzerTypesToMacros extends UnifyingTypeVisitorWithArgument< @override model.StaticTypeDesc visitInterfaceType( - InterfaceType type, TypeTranslationContext argument) { + InterfaceType type, + TypeTranslationContext argument, + ) { final element = type.element; - return model.StaticTypeDesc.namedTypeDesc(model.NamedTypeDesc( - name: element.qualifiedName, - instantiation: [ - for (final arg in type.typeArguments) - arg.acceptWithArgument(this, argument), - ], - )).applyNullabilitySuffix(type.nullabilitySuffix); + return model.StaticTypeDesc.namedTypeDesc( + model.NamedTypeDesc( + name: element.qualifiedName, + instantiation: [ + for (final arg in type.typeArguments) + arg.acceptWithArgument(this, argument), + ], + ), + ).applyNullabilitySuffix(type.nullabilitySuffix); } @override model.StaticTypeDesc visitNeverType( - NeverType type, TypeTranslationContext argument) { - return model.StaticTypeDesc.neverTypeDesc(model.NeverTypeDesc()) - .applyNullabilitySuffix(type.nullabilitySuffix); + NeverType type, + TypeTranslationContext argument, + ) { + return model.StaticTypeDesc.neverTypeDesc( + model.NeverTypeDesc(), + ).applyNullabilitySuffix(type.nullabilitySuffix); } @override model.StaticTypeDesc visitRecordType( - RecordType type, TypeTranslationContext argument) { - return model.StaticTypeDesc.recordTypeDesc(model.RecordTypeDesc( - positional: [ - for (final positional in type.positionalFields) - positional.type.acceptWithArgument(this, argument), - ], - named: [ - for (final named in type.namedFields) - model.NamedRecordField( - name: named.name, - type: named.type.acceptWithArgument(this, argument), - ), - ], - )).applyNullabilitySuffix(type.nullabilitySuffix); + RecordType type, + TypeTranslationContext argument, + ) { + return model.StaticTypeDesc.recordTypeDesc( + model.RecordTypeDesc( + positional: [ + for (final positional in type.positionalFields) + positional.type.acceptWithArgument(this, argument), + ], + named: [ + for (final named in type.namedFields) + model.NamedRecordField( + name: named.name, + type: named.type.acceptWithArgument(this, argument), + ), + ], + ), + ).applyNullabilitySuffix(type.nullabilitySuffix); } @override model.StaticTypeDesc visitTypeParameterType( - TypeParameterType type, TypeTranslationContext argument) { + TypeParameterType type, + TypeTranslationContext argument, + ) { return model.StaticTypeDesc.typeParameterTypeDesc( - model.TypeParameterTypeDesc( - parameterId: argument.idFor(type.element))) - .applyNullabilitySuffix(type.nullabilitySuffix); + model.TypeParameterTypeDesc(parameterId: argument.idFor(type.element)), + ).applyNullabilitySuffix(type.nullabilitySuffix); } @override model.StaticTypeDesc visitVoidType( - VoidType type, TypeTranslationContext argument) { - return model.StaticTypeDesc.voidTypeDesc(model.VoidTypeDesc()) - .applyNullabilitySuffix(type.nullabilitySuffix); + VoidType type, + TypeTranslationContext argument, + ) { + return model.StaticTypeDesc.voidTypeDesc( + model.VoidTypeDesc(), + ).applyNullabilitySuffix(type.nullabilitySuffix); } } @@ -134,7 +166,8 @@ extension on model.StaticTypeDesc { model.StaticTypeDesc applyNullabilitySuffix(NullabilitySuffix suffix) { if (suffix == NullabilitySuffix.question) { return model.StaticTypeDesc.nullableTypeDesc( - model.NullableTypeDesc(inner: this)); + model.NullableTypeDesc(inner: this), + ); } else { return this; } diff --git a/pkgs/_analyzer_macros/pubspec.yaml b/pkgs/_analyzer_macros/pubspec.yaml index 58c274c9..fab1d500 100644 --- a/pkgs/_analyzer_macros/pubspec.yaml +++ b/pkgs/_analyzer_macros/pubspec.yaml @@ -4,7 +4,7 @@ description: Macro support for the analyzer. resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: _analyzer_cfe_macros: any diff --git a/pkgs/_analyzer_macros/test/analyzer_test.dart b/pkgs/_analyzer_macros/test/analyzer_test.dart index 0d2e42be..18c07a58 100644 --- a/pkgs/_analyzer_macros/test/analyzer_test.dart +++ b/pkgs/_analyzer_macros/test/analyzer_test.dart @@ -21,21 +21,24 @@ void main() { // Set up analyzer. final directory = Directory.fromUri(Uri.parse('./test/package_under_test')).absolute; - final contextCollection = - AnalysisContextCollection(includedPaths: [directory.path]); + final contextCollection = AnalysisContextCollection( + includedPaths: [directory.path], + ); analysisContext = contextCollection.contexts.first; injected.macroImplementation = await AnalyzerMacroImplementation.start( - protocol: Protocol( - encoding: ProtocolEncoding.binary, - version: ProtocolVersion.macros1), - packageConfig: Isolate.packageConfigSync!); + protocol: Protocol( + encoding: ProtocolEncoding.binary, + version: ProtocolVersion.macros1, + ), + packageConfig: Isolate.packageConfigSync!, + ); }); test('discovers macros, runs them, applies augmentations', () async { - final path = File.fromUri( - Uri.parse('./test/package_under_test/lib/apply_declare_x.dart')) - .absolute - .path; + final path = + File.fromUri( + Uri.parse('./test/package_under_test/lib/apply_declare_x.dart'), + ).absolute.path; // No analysis errors. final errors = @@ -43,8 +46,9 @@ void main() { expect(errors.errors, isEmpty); // The expected new declaration augmentation was applied. - final resolvedLibrary = (await analysisContext.currentSession - .getResolvedLibrary(path)) as ResolvedLibraryResult; + final resolvedLibrary = + (await analysisContext.currentSession.getResolvedLibrary(path)) + as ResolvedLibraryResult; final clazz = resolvedLibrary.element.getClass('ClassWithMacroApplied')!; expect(clazz.fields, isEmpty); expect(clazz.augmented.fields, isNotEmpty); diff --git a/pkgs/_analyzer_macros/test/golden_test.dart b/pkgs/_analyzer_macros/test/golden_test.dart index bcdcda75..52dfd893 100644 --- a/pkgs/_analyzer_macros/test/golden_test.dart +++ b/pkgs/_analyzer_macros/test/golden_test.dart @@ -21,20 +21,24 @@ void main() { group('analyzer with injected macro impl query result matches golden', () { final directory = Directory( - Isolate.resolvePackageUriSync(Uri.parse('package:foo/foo.dart'))! - .resolve('../../../goldens') - .toFilePath()); + Isolate.resolvePackageUriSync( + Uri.parse('package:foo/foo.dart'), + )!.resolve('../../../goldens').toFilePath(), + ); setUp(() async { // Set up analyzer. - final contextCollection = - AnalysisContextCollection(includedPaths: [directory.path]); + final contextCollection = AnalysisContextCollection( + includedPaths: [directory.path], + ); analysisContext = contextCollection.contexts.first; injected.macroImplementation = await AnalyzerMacroImplementation.start( - protocol: Protocol( - encoding: ProtocolEncoding.binary, - version: ProtocolVersion.macros1), - packageConfig: Isolate.packageConfigSync!); + protocol: Protocol( + encoding: ProtocolEncoding.binary, + version: ProtocolVersion.macros1, + ), + packageConfig: Isolate.packageConfigSync!, + ); }); for (final file in directory @@ -63,8 +67,9 @@ void main() { introspectionGoldenFile = null; } - applicationGoldenFile = - File(p.setExtension(path, '.analyzer.augmentations')); + applicationGoldenFile = File( + p.setExtension(path, '.analyzer.augmentations'), + ); if (applicationGoldenFile!.existsSync()) { applicationGolden = applicationGoldenFile!.readAsStringSync(); } else { @@ -76,11 +81,14 @@ void main() { tearDown(() { if (introspectionGoldenFile != null && introspectionMacroOutput != null) { - final string = (const JsonEncoder.withIndent(' ')) - .convert(introspectionMacroOutput); + final string = (const JsonEncoder.withIndent( + ' ', + )).convert(introspectionMacroOutput); if (introspectionGoldenFile!.readAsStringSync() != string) { - print('Updating mismatched golden: ' - '${introspectionGoldenFile!.path}'); + print( + 'Updating mismatched golden: ' + '${introspectionGoldenFile!.path}', + ); introspectionGoldenFile!.writeAsStringSync(string); } } @@ -88,7 +96,8 @@ void main() { if (applicationGoldenFile!.readAsStringSync() != applicationMacroOutput) { print( - 'Updating mismatched golden: ${applicationGoldenFile!.path}'); + 'Updating mismatched golden: ${applicationGoldenFile!.path}', + ); applicationGoldenFile!.writeAsStringSync(applicationMacroOutput!); } } @@ -101,16 +110,20 @@ void main() { return; } - final errors = (await analysisContext.currentSession.getErrors(path)) - as ErrorsResult; + final errors = + (await analysisContext.currentSession.getErrors(path)) + as ErrorsResult; expect( - errors.errors.where((e) => e.severity == Severity.error).toList(), - isEmpty); + errors.errors.where((e) => e.severity == Severity.error).toList(), + isEmpty, + ); - final resolvedLibrary = (await analysisContext.currentSession - .getResolvedLibrary(path)) as ResolvedLibraryResult; - final augmentationUnit = - resolvedLibrary.units.singleWhere((u) => u.isMacroPart); + final resolvedLibrary = + (await analysisContext.currentSession.getResolvedLibrary(path)) + as ResolvedLibraryResult; + final augmentationUnit = resolvedLibrary.units.singleWhere( + (u) => u.isMacroPart, + ); if (introspectionGolden != null) { // Each `QueryClass` outputs its query result as a comment in an @@ -119,24 +132,35 @@ void main() { final macroOutputs = augmentationUnit.content .split('\n') .where((l) => l.startsWith('// ')) - .map((l) => json.decode(l.substring('// '.length)) - as Map); + .map( + (l) => + json.decode(l.substring('// '.length)) + as Map, + ); introspectionMacroOutput = _merge(macroOutputs); - expect(introspectionMacroOutput, introspectionGolden, - reason: updateGoldens - ? '\n--> Goldens updated! Should pass on rerun.' - : '\n--> To update goldens, run: ' - 'UPDATE_GOLDENS=yes dart test'); + expect( + introspectionMacroOutput, + introspectionGolden, + reason: + updateGoldens + ? '\n--> Goldens updated! Should pass on rerun.' + : '\n--> To update goldens, run: ' + 'UPDATE_GOLDENS=yes dart test', + ); } if (applicationGolden != null) { applicationMacroOutput = augmentationUnit.content; - expect(applicationMacroOutput, applicationGolden, - reason: updateGoldens - ? '\n--> Goldens updated! Should pass on rerun.' - : '\n--> To update goldens, run: ' - 'UPDATE_GOLDENS=yes dart test'); + expect( + applicationMacroOutput, + applicationGolden, + reason: + updateGoldens + ? '\n--> Goldens updated! Should pass on rerun.' + : '\n--> To update goldens, run: ' + 'UPDATE_GOLDENS=yes dart test', + ); } }); } @@ -148,8 +172,10 @@ Map _merge(Iterable> maps) { for (final map in maps) { for (final entry in map.entries) { if (result[entry.key] case final Map nested) { - result[entry.key] = - _merge([nested, entry.value as Map]); + result[entry.key] = _merge([ + nested, + entry.value as Map, + ]); } else { result[entry.key] = entry.value; } diff --git a/pkgs/_analyzer_macros/test/package_under_test/pubspec.yaml b/pkgs/_analyzer_macros/test/package_under_test/pubspec.yaml index fde900bd..6f1f2a4b 100644 --- a/pkgs/_analyzer_macros/test/package_under_test/pubspec.yaml +++ b/pkgs/_analyzer_macros/test/package_under_test/pubspec.yaml @@ -3,7 +3,7 @@ publish-to: none resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: _test_macros: any diff --git a/pkgs/_cfe_macros/lib/macro_implementation.dart b/pkgs/_cfe_macros/lib/macro_implementation.dart index aa90a22a..1d50d59b 100644 --- a/pkgs/_cfe_macros/lib/macro_implementation.dart +++ b/pkgs/_cfe_macros/lib/macro_implementation.dart @@ -30,13 +30,14 @@ class CfeMacroImplementation implements injected.MacroImplementation { // TODO(davidmorgan): support serving multiple protocols. required Protocol protocol, required Uri packageConfig, - }) async => - CfeMacroImplementation._( - packageConfig, - await MacroHost.serve( - protocol: protocol, - packageConfig: packageConfig, - queryService: CfeQueryService())); + }) async => CfeMacroImplementation._( + packageConfig, + await MacroHost.serve( + protocol: protocol, + packageConfig: packageConfig, + queryService: CfeQueryService(), + ), + ); @override injected.MacroPackageConfigs get packageConfigs => @@ -63,10 +64,12 @@ class CfeMacroRunner implements injected.MacroRunner { @override injected.RunningMacro run(Uri uri, String name) => CfeRunningMacro.run( - _impl, + _impl, + QualifiedName(uri: '$uri', name: name), + _impl._host.lookupMacroImplementation( QualifiedName(uri: '$uri', name: name), - _impl._host - .lookupMacroImplementation(QualifiedName(uri: '$uri', name: name))!); + )!, + ); } class CfeRunningMacro implements injected.RunningMacro { @@ -76,70 +79,85 @@ class CfeRunningMacro implements injected.RunningMacro { CfeRunningMacro._(this._impl, this.name, this.implementation); - static CfeRunningMacro run(CfeMacroImplementation impl, QualifiedName name, - QualifiedName implementation) { + static CfeRunningMacro run( + CfeMacroImplementation impl, + QualifiedName name, + QualifiedName implementation, + ) { return CfeRunningMacro._(impl, name, implementation); } /// Queries for [target] and returns the [Model] representing the result. /// /// TODO: Make this a more limited query which doesn't fetch members. - Future _queryTarget(QualifiedName target) => - Scope.query.run(() async => (await _impl._host.hostService.handle( - MacroRequest.queryRequest( - QueryRequest(query: Query(target: target)), - id: nextRequestId))) - .asQueryResponse - .model); + Future _queryTarget(QualifiedName target) => Scope.query.run( + () async => + (await _impl._host.hostService.handle( + MacroRequest.queryRequest( + QueryRequest(query: Query(target: target)), + id: nextRequestId, + ), + )).asQueryResponse.model, + ); @override Future executeDeclarationsPhase( - macros_api_v1.MacroTarget target, - macros_api_v1.DeclarationPhaseIntrospector - declarationsPhaseIntrospector) async { + macros_api_v1.MacroTarget target, + macros_api_v1.DeclarationPhaseIntrospector declarationsPhaseIntrospector, + ) async { // TODO(davidmorgan): this is a hack to access CFE internals; remove. introspector = declarationsPhaseIntrospector; return await CfeMacroExecutionResult.dartModelToInjected( - target, - await _impl._host.augment( - name, - AugmentRequest( - phase: 2, - target: target.qualifiedName, - model: await _queryTarget(target.qualifiedName)))); + target, + await _impl._host.augment( + name, + AugmentRequest( + phase: 2, + target: target.qualifiedName, + model: await _queryTarget(target.qualifiedName), + ), + ), + ); } @override Future executeDefinitionsPhase( - macros_api_v1.MacroTarget target, - macros_api_v1.DefinitionPhaseIntrospector - definitionPhaseIntrospector) async { + macros_api_v1.MacroTarget target, + macros_api_v1.DefinitionPhaseIntrospector definitionPhaseIntrospector, + ) async { // TODO(davidmorgan): this is a hack to access CFE internals; remove. introspector = definitionPhaseIntrospector; return await CfeMacroExecutionResult.dartModelToInjected( - target, - await _impl._host.augment( - name, - AugmentRequest( - phase: 3, - target: target.qualifiedName, - model: await _queryTarget(target.qualifiedName)))); + target, + await _impl._host.augment( + name, + AugmentRequest( + phase: 3, + target: target.qualifiedName, + model: await _queryTarget(target.qualifiedName), + ), + ), + ); } @override Future executeTypesPhase( - macros_api_v1.MacroTarget target, - macros_api_v1.TypePhaseIntrospector typePhaseIntrospector) async { + macros_api_v1.MacroTarget target, + macros_api_v1.TypePhaseIntrospector typePhaseIntrospector, + ) async { // TODO(davidmorgan): this is a hack to access CFE internals; remove. introspector = typePhaseIntrospector; return await CfeMacroExecutionResult.dartModelToInjected( - target, - await _impl._host.augment( - name, - AugmentRequest( - phase: 1, - target: target.qualifiedName, - model: await _queryTarget(target.qualifiedName)))); + target, + await _impl._host.augment( + name, + AugmentRequest( + phase: 1, + target: target.qualifiedName, + model: await _queryTarget(target.qualifiedName), + ), + ), + ); } } @@ -151,22 +169,26 @@ class CfeMacroExecutionResult implements macros_api_v1.MacroExecutionResult { final macros_api_v1.MacroTarget target; @override final Map> - typeAugmentations; + typeAugmentations; CfeMacroExecutionResult( - this.target, Iterable declarations) - // TODO(davidmorgan): this assumes augmentations are for the macro - // application target. Instead, it should be explicit in - // `AugmentResponse`. - : typeAugmentations = { - // TODO(davidmorgan): empty augmentations response breaks the test, - // it's not clear why. - if (declarations.isNotEmpty) - (target as macros_api_v1.Declaration).identifier: declarations - }; + this.target, + Iterable declarations, + ) + // TODO(davidmorgan): this assumes augmentations are for the macro + // application target. Instead, it should be explicit in + // `AugmentResponse`. + : typeAugmentations = { + // TODO(davidmorgan): empty augmentations response breaks the test, + // it's not clear why. + if (declarations.isNotEmpty) + (target as macros_api_v1.Declaration).identifier: declarations, + }; static Future dartModelToInjected( - macros_api_v1.MacroTarget target, AugmentResponse augmentResponse) async { + macros_api_v1.MacroTarget target, + AugmentResponse augmentResponse, + ) async { final declarations = []; if (augmentResponse.typeAugmentations?.isNotEmpty == true) { // TODO: Handle multiple type augmentations, or augmentations where the @@ -174,12 +196,16 @@ class CfeMacroExecutionResult implements macros_api_v1.MacroExecutionResult { final entry = augmentResponse.typeAugmentations!.entries.single; if (entry.key != target.qualifiedName.name) { throw UnimplementedError( - 'Type augmentations are only implemented when the type is the ' - 'target of the augmentation.'); + 'Type augmentations are only implemented when the type is the ' + 'target of the augmentation.', + ); } for (final augmentation in entry.value) { - declarations.add(macros_api_v1.DeclarationCode.fromParts( - await _resolveNames(augmentation.code))); + declarations.add( + macros_api_v1.DeclarationCode.fromParts( + await _resolveNames(augmentation.code), + ), + ); } } @@ -204,25 +230,25 @@ class CfeMacroExecutionResult implements macros_api_v1.MacroExecutionResult { @override Map> - get enumValueAugmentations => {}; + get enumValueAugmentations => {}; @override macros_api_v1.MacroException? get exception => null; @override Map - get extendsTypeAugmentations => {}; + get extendsTypeAugmentations => {}; @override Map> - get interfaceAugmentations => {}; + get interfaceAugmentations => {}; @override Iterable get libraryAugmentations => {}; @override Map> - get mixinAugmentations => {}; + get mixinAugmentations => {}; @override Iterable get newTypeNames => []; @@ -237,20 +263,22 @@ extension MacroTargetExtension on macros_api_v1.MacroTarget { ((this as macros_api_v1.Declaration).identifier as cfe.IdentifierImpl) .resolveIdentifier(); return QualifiedName( - uri: '${identifier.uri}', - name: identifier.name, - scope: switch (identifier.kind) { - macros_api_v1.IdentifierKind.local || - macros_api_v1.IdentifierKind.topLevelMember => - null, - macros_api_v1.IdentifierKind.instanceMember => - throw UnimplementedError( - 'We dont have access to the parent scope for instance ' - 'members in the CFE yet'), - macros_api_v1.IdentifierKind.staticInstanceMember => - identifier.staticScope!, - }, - isStatic: identifier.staticScope != null); + uri: '${identifier.uri}', + name: identifier.name, + scope: switch (identifier.kind) { + macros_api_v1.IdentifierKind.local || + macros_api_v1.IdentifierKind.topLevelMember => + null, + macros_api_v1.IdentifierKind.instanceMember => + throw UnimplementedError( + 'We dont have access to the parent scope for instance ' + 'members in the CFE yet', + ), + macros_api_v1.IdentifierKind.staticInstanceMember => + identifier.staticScope!, + }, + isStatic: identifier.staticScope != null, + ); } } @@ -270,15 +298,19 @@ Future> _resolveNames(List codes) async { qualifiedNameStrings.map(QualifiedName.parse).toList(); final identifierFutures = >[]; for (final qualifiedName in qualifiedNamesList) { - identifierFutures.add((introspector as macros_api_v1.TypePhaseIntrospector) - // ignore: deprecated_member_use - .resolveIdentifier(Uri.parse(qualifiedName.uri), qualifiedName.name)); + identifierFutures.add( + (introspector as macros_api_v1.TypePhaseIntrospector) + // ignore: deprecated_member_use + .resolveIdentifier(Uri.parse(qualifiedName.uri), qualifiedName.name), + ); } final identifiers = await Future.wait(identifierFutures); // Build the result using the looked up [Identifier]s. - final identifiersByQualifiedNameStrings = - Map.fromIterables(qualifiedNameStrings, identifiers); + final identifiersByQualifiedNameStrings = Map.fromIterables( + qualifiedNameStrings, + identifiers, + ); final result = []; for (final code in codes) { if (code.type == CodeType.string) { diff --git a/pkgs/_cfe_macros/lib/query_service.dart b/pkgs/_cfe_macros/lib/query_service.dart index 1ca0912f..8cdab369 100644 --- a/pkgs/_cfe_macros/lib/query_service.dart +++ b/pkgs/_cfe_macros/lib/query_service.dart @@ -27,13 +27,15 @@ final class CfeQueryService extends QueryService { @override Future handle(QueryRequest request) async { return QueryResponse( - model: await _evaluateClassQuery(request.query.target)); + model: await _evaluateClassQuery(request.query.target), + ); } Future _evaluateClassQuery(QualifiedName target) async { final uri = target.uri; - final libraryBuilder = sourceLoader.sourceLibraryBuilders - .singleWhere((l) => l.importUri.toString() == target.uri); + final libraryBuilder = sourceLoader.sourceLibraryBuilders.singleWhere( + (l) => l.importUri.toString() == target.uri, + ); final classBuilderIterator = libraryBuilder.fullMemberIterator(); cfe.SourceClassBuilder? classBuilder; @@ -49,13 +51,14 @@ final class CfeQueryService extends QueryService { while (fieldIterator.moveNext()) { final current = fieldIterator.current; interface.members[current.name] = Member( - properties: Properties( - isAbstract: current.isAbstract, - isGetter: current.isGetter, - isField: true, - isMethod: false, - isStatic: current.isStatic, - )); + properties: Properties( + isAbstract: current.isAbstract, + isGetter: current.isGetter, + isField: true, + isMethod: false, + isStatic: current.isStatic, + ), + ); } TypeHierarchy? types; try { @@ -64,12 +67,13 @@ final class CfeQueryService extends QueryService { // TODO: Fails in types phase, implement fine grained queries. } return Model(types: types) - ..uris[uri] = (Library() - .. - // TODO(davidmorgan): return more than just fields. - // TODO(davidmorgan): specify in the query what to return. - - scopes[target.name] = interface); + ..uris[uri] = + (Library() + .. + // TODO(davidmorgan): return more than just fields. + // TODO(davidmorgan): specify in the query what to return. + scopes[target.name] = + interface); } TypeHierarchy _buildTypeHierarchy(Set classes) { @@ -100,10 +104,11 @@ final class CfeQueryService extends QueryService { const translator = KernelTypeToMacros(); final result = TypeHierarchy(); for (final element in classes) { - final asNamedType = element - .getThisType(coreTypes, kernel.Nullability.nonNullable) - .accept1(translator, context) - .asNamedTypeDesc; + final asNamedType = + element + .getThisType(coreTypes, kernel.Nullability.nonNullable) + .accept1(translator, context) + .asNamedTypeDesc; result.named[asNamedType.name.asString] = TypeHierarchyEntry( self: asNamedType, @@ -115,7 +120,7 @@ final class CfeQueryService extends QueryService { for (final superType in element.supers) superType.asInterfaceType .accept1(translator, context) - .asNamedTypeDesc + .asNamedTypeDesc, ], ); } diff --git a/pkgs/_cfe_macros/lib/src/type_translation.dart b/pkgs/_cfe_macros/lib/src/type_translation.dart index d104be1d..366eb7a4 100644 --- a/pkgs/_cfe_macros/lib/src/type_translation.dart +++ b/pkgs/_cfe_macros/lib/src/type_translation.dart @@ -6,53 +6,73 @@ import 'package:kernel/kernel.dart' as kernel; final class TypeTranslationContext { final Map - _typeParameterIds = {}; + _typeParameterIds = {}; int idFor(kernel.Node parameter) { return _typeParameterIds.putIfAbsent( - parameter, () => _typeParameterIds.length); + parameter, + () => _typeParameterIds.length, + ); } } -final class KernelTypeToMacros extends kernel - .DartTypeVisitor1 +final class KernelTypeToMacros + extends + kernel.DartTypeVisitor1 with - kernel.DartTypeVisitor1DefaultMixin { + kernel.DartTypeVisitor1DefaultMixin< + model.StaticTypeDesc, + TypeTranslationContext + > { const KernelTypeToMacros(); model.StaticTypeParameterDesc translateTypeParameter( - kernel.TypeParameter param, TypeTranslationContext context) { + kernel.TypeParameter param, + TypeTranslationContext context, + ) { return _translateTypeParameter(param, context, param.bound); } model.StaticTypeParameterDesc translateStructuralParameter( - kernel.StructuralParameter param, TypeTranslationContext context) { + kernel.StructuralParameter param, + TypeTranslationContext context, + ) { return _translateTypeParameter(param, context, param.bound); } - model.StaticTypeParameterDesc _translateTypeParameter(kernel.Node node, - TypeTranslationContext context, kernel.DartType? bound) { + model.StaticTypeParameterDesc _translateTypeParameter( + kernel.Node node, + TypeTranslationContext context, + kernel.DartType? bound, + ) { final id = context.idFor(node); return model.StaticTypeParameterDesc( - identifier: id, bound: bound?.accept1(this, context)); + identifier: id, + bound: bound?.accept1(this, context), + ); } @override model.StaticTypeDesc defaultDartType( - kernel.DartType node, TypeTranslationContext arg) { + kernel.DartType node, + TypeTranslationContext arg, + ) { return {'type': '_unknown'} as model.StaticTypeDesc; } @override model.StaticTypeDesc visitDynamicType( - kernel.DynamicType node, TypeTranslationContext arg) { + kernel.DynamicType node, + TypeTranslationContext arg, + ) { return model.StaticTypeDesc.dynamicTypeDesc(model.DynamicTypeDesc()); } @override model.StaticTypeDesc visitFunctionType( - kernel.FunctionType node, TypeTranslationContext arg) { + kernel.FunctionType node, + TypeTranslationContext arg, + ) { return model.StaticTypeDesc.functionTypeDesc( model.FunctionTypeDesc( typeParameters: [ @@ -61,13 +81,15 @@ final class KernelTypeToMacros extends kernel ], returnType: node.returnType.accept1(this, arg), requiredPositionalParameters: [ - for (final positional - in node.positionalParameters.take(node.requiredParameterCount)) + for (final positional in node.positionalParameters.take( + node.requiredParameterCount, + )) positional.accept1(this, arg), ], optionalPositionalParameters: [ - for (final positional - in node.positionalParameters.skip(node.requiredParameterCount)) + for (final positional in node.positionalParameters.skip( + node.requiredParameterCount, + )) positional.accept1(this, arg), ], namedParameters: [ @@ -84,82 +106,106 @@ final class KernelTypeToMacros extends kernel @override model.StaticTypeDesc visitFutureOrType( - kernel.FutureOrType node, TypeTranslationContext arg) { + kernel.FutureOrType node, + TypeTranslationContext arg, + ) { // Pretend that this is a `FutureOr` class instantiation, which macros use // to represent `FutureOr` types. - return model.StaticTypeDesc.namedTypeDesc(model.NamedTypeDesc( - name: model.QualifiedName(uri: 'dart:async', name: 'FutureOr'), - instantiation: [ - node.typeArgument.accept1(this, arg), - ], - )).applyNullability(node.declaredNullability); + return model.StaticTypeDesc.namedTypeDesc( + model.NamedTypeDesc( + name: model.QualifiedName(uri: 'dart:async', name: 'FutureOr'), + instantiation: [node.typeArgument.accept1(this, arg)], + ), + ).applyNullability(node.declaredNullability); } @override model.StaticTypeDesc visitInterfaceType( - kernel.InterfaceType node, TypeTranslationContext arg) { + kernel.InterfaceType node, + TypeTranslationContext arg, + ) { final definingClass = node.classNode; final library = definingClass.enclosingLibrary; - return model.StaticTypeDesc.namedTypeDesc(model.NamedTypeDesc( - name: model.QualifiedName( - uri: '${library.importUri}', name: definingClass.name), - instantiation: [ - for (final typeArg in node.typeArguments) typeArg.accept1(this, arg), - ], - )).applyNullability(node.declaredNullability); + return model.StaticTypeDesc.namedTypeDesc( + model.NamedTypeDesc( + name: model.QualifiedName( + uri: '${library.importUri}', + name: definingClass.name, + ), + instantiation: [ + for (final typeArg in node.typeArguments) typeArg.accept1(this, arg), + ], + ), + ).applyNullability(node.declaredNullability); } @override model.StaticTypeDesc visitNeverType( - kernel.NeverType node, TypeTranslationContext arg) { - return model.StaticTypeDesc.neverTypeDesc(model.NeverTypeDesc()) - .applyNullability(node.declaredNullability); + kernel.NeverType node, + TypeTranslationContext arg, + ) { + return model.StaticTypeDesc.neverTypeDesc( + model.NeverTypeDesc(), + ).applyNullability(node.declaredNullability); } @override model.StaticTypeDesc visitRecordType( - kernel.RecordType node, TypeTranslationContext arg) { - return model.StaticTypeDesc.recordTypeDesc(model.RecordTypeDesc( - positional: [ - for (final positional in node.positional) positional.accept1(this, arg), - ], - named: [ - for (final named in node.named) - model.NamedRecordField( - name: named.name, - type: named.type.accept1(this, arg), - ), - ], - )).applyNullability(node.declaredNullability); + kernel.RecordType node, + TypeTranslationContext arg, + ) { + return model.StaticTypeDesc.recordTypeDesc( + model.RecordTypeDesc( + positional: [ + for (final positional in node.positional) + positional.accept1(this, arg), + ], + named: [ + for (final named in node.named) + model.NamedRecordField( + name: named.name, + type: named.type.accept1(this, arg), + ), + ], + ), + ).applyNullability(node.declaredNullability); } @override model.StaticTypeDesc visitTypedefType( - kernel.TypedefType node, TypeTranslationContext arg) { + kernel.TypedefType node, + TypeTranslationContext arg, + ) { // Type aliases are not represented in the macro type hierarchy. return node.unalias.accept1(this, arg); } @override model.StaticTypeDesc visitTypeParameterType( - kernel.TypeParameterType node, TypeTranslationContext arg) { + kernel.TypeParameterType node, + TypeTranslationContext arg, + ) { return model.StaticTypeDesc.typeParameterTypeDesc( - model.TypeParameterTypeDesc(parameterId: arg.idFor(node.parameter))) - .applyNullability(node.declaredNullability); + model.TypeParameterTypeDesc(parameterId: arg.idFor(node.parameter)), + ).applyNullability(node.declaredNullability); } @override model.StaticTypeDesc visitStructuralParameterType( - kernel.StructuralParameterType node, TypeTranslationContext arg) { + kernel.StructuralParameterType node, + TypeTranslationContext arg, + ) { return model.StaticTypeDesc.typeParameterTypeDesc( - model.TypeParameterTypeDesc(parameterId: arg.idFor(node.parameter))) - .applyNullability(node.declaredNullability); + model.TypeParameterTypeDesc(parameterId: arg.idFor(node.parameter)), + ).applyNullability(node.declaredNullability); } @override model.StaticTypeDesc visitVoidType( - kernel.VoidType node, TypeTranslationContext arg) { + kernel.VoidType node, + TypeTranslationContext arg, + ) { return model.StaticTypeDesc.voidTypeDesc(model.VoidTypeDesc()); } } @@ -168,7 +214,8 @@ extension on model.StaticTypeDesc { model.StaticTypeDesc applyNullability(kernel.Nullability nullability) { if (nullability == kernel.Nullability.nullable) { return model.StaticTypeDesc.nullableTypeDesc( - model.NullableTypeDesc(inner: this)); + model.NullableTypeDesc(inner: this), + ); } else { return this; } diff --git a/pkgs/_cfe_macros/pubspec.yaml b/pkgs/_cfe_macros/pubspec.yaml index e4a66073..52198b2a 100644 --- a/pkgs/_cfe_macros/pubspec.yaml +++ b/pkgs/_cfe_macros/pubspec.yaml @@ -4,7 +4,7 @@ description: Macro support for the CFE. resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: _macro_host: any diff --git a/pkgs/_cfe_macros/test/cfe_test.dart b/pkgs/_cfe_macros/test/cfe_test.dart index 7e3b9b39..87132d03 100644 --- a/pkgs/_cfe_macros/test/cfe_test.dart +++ b/pkgs/_cfe_macros/test/cfe_test.dart @@ -22,8 +22,10 @@ void main() { // TODO(davidmorgan): this dill comes from the Dart SDK running the test, // but `package:frontend_server` and `package:front_end` are used as a // library, so we will see version skew breakage. Find a better way. - productPlatformDill = File('${Platform.resolvedExecutable}/../../' - 'lib/_internal/vm_platform_strong_product.dill'); + productPlatformDill = File( + '${Platform.resolvedExecutable}/../../' + 'lib/_internal/vm_platform_strong_product.dill', + ); if (!File.fromUri(productPlatformDill.uri).existsSync()) { throw StateError('Failed to find platform dill: $productPlatformDill'); } @@ -31,16 +33,19 @@ void main() { // Inject test macro implementation. injected.macroImplementation = await CfeMacroImplementation.start( - protocol: Protocol( - encoding: ProtocolEncoding.json, - version: ProtocolVersion.macros1), - packageConfig: Isolate.packageConfigSync!); + protocol: Protocol( + encoding: ProtocolEncoding.json, + version: ProtocolVersion.macros1, + ), + packageConfig: Isolate.packageConfigSync!, + ); }); test('discovers macros, runs them, applies augmentations', () async { final packagesUri = Isolate.packageConfigSync; - final sourceFile = - File('test/package_under_test/lib/apply_declare_x.dart'); + final sourceFile = File( + 'test/package_under_test/lib/apply_declare_x.dart', + ); final outputFile = File('${tempDir.path}/out.dill'); final computeKernelResult = await computeKernel([ diff --git a/pkgs/_cfe_macros/test/golden_test.dart b/pkgs/_cfe_macros/test/golden_test.dart index aa810979..1db45b22 100644 --- a/pkgs/_cfe_macros/test/golden_test.dart +++ b/pkgs/_cfe_macros/test/golden_test.dart @@ -19,9 +19,10 @@ void main() { late Directory tempDir; final directory = Directory( - Isolate.resolvePackageUriSync(Uri.parse('package:foo/foo.dart'))! - .resolve('../../../goldens') - .toFilePath()); + Isolate.resolvePackageUriSync( + Uri.parse('package:foo/foo.dart'), + )!.resolve('../../../goldens').toFilePath(), + ); setUp(() async { // Set up CFE. @@ -29,8 +30,10 @@ void main() { // TODO(davidmorgan): this dill comes from the Dart SDK running the test, // but `package:frontend_server` and `package:front_end` are used as a // library, so we will see version skew breakage. Find a better way. - productPlatformDill = File('${Platform.resolvedExecutable}/../../' - 'lib/_internal/vm_platform_strong_product.dill'); + productPlatformDill = File( + '${Platform.resolvedExecutable}/../../' + 'lib/_internal/vm_platform_strong_product.dill', + ); if (!File.fromUri(productPlatformDill.uri).existsSync()) { throw StateError('Failed to find platform dill: $productPlatformDill'); } @@ -38,10 +41,12 @@ void main() { // Inject test macro implementation. injected.macroImplementation = await CfeMacroImplementation.start( - protocol: Protocol( - encoding: ProtocolEncoding.json, - version: ProtocolVersion.macros1), - packageConfig: Isolate.packageConfigSync!); + protocol: Protocol( + encoding: ProtocolEncoding.json, + version: ProtocolVersion.macros1, + ), + packageConfig: Isolate.packageConfigSync!, + ); }); for (final file in directory @@ -71,8 +76,9 @@ void main() { introspectionGoldenFile = null; } - applicationGoldenFile = - File(p.setExtension(path, '.cfe.augmentations')); + applicationGoldenFile = File( + p.setExtension(path, '.cfe.augmentations'), + ); if (applicationGoldenFile!.existsSync()) { applicationGolden = applicationGoldenFile!.readAsStringSync(); } else { @@ -83,11 +89,14 @@ void main() { tearDown(() { if (introspectionGoldenFile != null && introspectionMacroOutput != null) { - final string = (const JsonEncoder.withIndent(' ')) - .convert(introspectionMacroOutput); + final string = (const JsonEncoder.withIndent( + ' ', + )).convert(introspectionMacroOutput); if (introspectionGoldenFile!.readAsStringSync() != string) { - print('Updating mismatched golden: ' - '${introspectionGoldenFile!.path}'); + print( + 'Updating mismatched golden: ' + '${introspectionGoldenFile!.path}', + ); introspectionGoldenFile!.writeAsStringSync(string); } } @@ -95,7 +104,8 @@ void main() { if (applicationGoldenFile!.readAsStringSync() != applicationMacroOutput) { print( - 'Updating mismatched golden: ${applicationGoldenFile!.path}'); + 'Updating mismatched golden: ${applicationGoldenFile!.path}', + ); applicationGoldenFile!.writeAsStringSync(applicationMacroOutput!); } } @@ -128,12 +138,17 @@ void main() { '--enable-experiment=macros', ]); - final sources = computeKernelResult - .previousState!.incrementalCompiler!.context.uriToSource; - applicationMacroOutput = sources.entries - .singleWhere((e) => e.key.scheme == 'dart-macro+file') - .value - .text; + final sources = + computeKernelResult + .previousState! + .incrementalCompiler! + .context + .uriToSource; + applicationMacroOutput = + sources.entries + .singleWhere((e) => e.key.scheme == 'dart-macro+file') + .value + .text; if (introspectionGolden != null) { // Each `QueryClass` outputs its query result as a comment in an @@ -142,23 +157,34 @@ void main() { final macroOutputs = applicationMacroOutput! .split('\n') .where((l) => l.startsWith('// ')) - .map((l) => json.decode(l.substring('// '.length)) - as Map); + .map( + (l) => + json.decode(l.substring('// '.length)) + as Map, + ); introspectionMacroOutput = _merge(macroOutputs); - expect(introspectionMacroOutput, introspectionGolden, - reason: updateGoldens - ? '\n--> Goldens updated! Should pass on rerun.' - : '\n--> To update goldens, run: ' - 'UPDATE_GOLDENS=yes dart test'); + expect( + introspectionMacroOutput, + introspectionGolden, + reason: + updateGoldens + ? '\n--> Goldens updated! Should pass on rerun.' + : '\n--> To update goldens, run: ' + 'UPDATE_GOLDENS=yes dart test', + ); } if (applicationGolden != null) { - expect(applicationMacroOutput, applicationGolden, - reason: updateGoldens - ? '\n--> Goldens updated! Should pass on rerun.' - : '\n--> To update goldens, run: ' - 'UPDATE_GOLDENS=yes dart test'); + expect( + applicationMacroOutput, + applicationGolden, + reason: + updateGoldens + ? '\n--> Goldens updated! Should pass on rerun.' + : '\n--> To update goldens, run: ' + 'UPDATE_GOLDENS=yes dart test', + ); } }); } @@ -170,8 +196,10 @@ Map _merge(Iterable> maps) { for (final map in maps) { for (final entry in map.entries) { if (result[entry.key] case final Map nested) { - result[entry.key] = - _merge([nested, entry.value as Map]); + result[entry.key] = _merge([ + nested, + entry.value as Map, + ]); } else { result[entry.key] = entry.value; } diff --git a/pkgs/_cfe_macros/test/package_under_test/pubspec.yaml b/pkgs/_cfe_macros/test/package_under_test/pubspec.yaml index 81c0d22a..9d91f2fc 100644 --- a/pkgs/_cfe_macros/test/package_under_test/pubspec.yaml +++ b/pkgs/_cfe_macros/test/package_under_test/pubspec.yaml @@ -3,7 +3,7 @@ publish-to: none resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: _test_macros: any diff --git a/pkgs/_macro_builder/lib/macro_builder.dart b/pkgs/_macro_builder/lib/macro_builder.dart index 0c10da0e..461a7b2d 100644 --- a/pkgs/_macro_builder/lib/macro_builder.dart +++ b/pkgs/_macro_builder/lib/macro_builder.dart @@ -27,7 +27,9 @@ class MacroBuilder { /// TODO(davidmorgan): support (or decide not to support) in-memory overlay /// filesystems. Future build( - Uri packageConfig, Iterable macroImplementations) async { + Uri packageConfig, + Iterable macroImplementations, + ) async { final script = createBootstrap(macroImplementations.toList()); return await MacroBuild(packageConfig, script).build(); @@ -49,8 +51,9 @@ class BuiltMacroBundle { class MacroBuild { final Uri packageConfig; final String script; - final Directory workspace = - Directory.systemTemp.createTempSync('macro_builder'); + final Directory workspace = Directory.systemTemp.createTempSync( + 'macro_builder', + ); /// Creates a build for [script] with [packageConfig], which must have all /// the needed deps. @@ -64,11 +67,13 @@ class MacroBuild { await scriptFile.create(recursive: true); await scriptFile.writeAsString(script.toString()); - final targetPackageConfig = - File.fromUri(workspace.uri.resolve('.dart_tool/package_config.json')); + final targetPackageConfig = File.fromUri( + workspace.uri.resolve('.dart_tool/package_config.json'), + ); targetPackageConfig.parent.createSync(recursive: true); - targetPackageConfig - .writeAsStringSync(_makePackageConfigAbsolute(packageConfig)); + targetPackageConfig.writeAsStringSync( + _makePackageConfigAbsolute(packageConfig), + ); // See package:analyzer/src/summary2/kernel_compilation_service.dart for an // example of compiling macros using the frontend server. @@ -76,17 +81,19 @@ class MacroBuild { // For now just use the command line. final result = Process.runSync( - // TODO(davidmorgan): this is wrong if run from an AOT-compiled - // executable. - Platform.resolvedExecutable, - ['compile', 'exe', 'bin/main.dart', '--output=bin/main.exe'], - workingDirectory: workspace.path); + // TODO(davidmorgan): this is wrong if run from an AOT-compiled + // executable. + Platform.resolvedExecutable, + ['compile', 'exe', 'bin/main.dart', '--output=bin/main.exe'], + workingDirectory: workspace.path, + ); if (result.exitCode != 0) { throw StateError('Compile failed: ${result.stderr}'); } return BuiltMacroBundle( - File.fromUri(scriptFile.parent.uri.resolve('main.exe')).path); + File.fromUri(scriptFile.parent.uri.resolve('main.exe')).path, + ); } /// Returns the contents of [packageConfig] with relative paths replaced to @@ -94,8 +101,9 @@ class MacroBuild { String _makePackageConfigAbsolute(Uri packageConfig) { final file = File.fromUri(packageConfig); final root = file.parent.parent.absolute.uri; - return file - .readAsStringSync() - .replaceAll('"rootUri": "../', '"rootUri": "$root'); + return file.readAsStringSync().replaceAll( + '"rootUri": "../', + '"rootUri": "$root', + ); } } diff --git a/pkgs/_macro_builder/pubspec.yaml b/pkgs/_macro_builder/pubspec.yaml index e85c65d1..fecd21a4 100644 --- a/pkgs/_macro_builder/pubspec.yaml +++ b/pkgs/_macro_builder/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/dart-lang/macros/tree/master/pkgs/_macro_builder resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: dart_model: any diff --git a/pkgs/_macro_builder/test/macro_builder_test.dart b/pkgs/_macro_builder/test/macro_builder_test.dart index 4eb473ef..2368dd8f 100644 --- a/pkgs/_macro_builder/test/macro_builder_test.dart +++ b/pkgs/_macro_builder/test/macro_builder_test.dart @@ -15,12 +15,17 @@ void main() { test('bootstrap matches golden', () async { final script = createBootstrap([ QualifiedName( - uri: 'package:_test_macros/declare_x_macro.dart', name: 'DeclareX'), + uri: 'package:_test_macros/declare_x_macro.dart', + name: 'DeclareX', + ), QualifiedName( - uri: 'package:_test_macros/declare_y_macro.dart', name: 'DeclareY'), + uri: 'package:_test_macros/declare_y_macro.dart', + name: 'DeclareY', + ), QualifiedName( - uri: 'package:_more_macros/other_macro.dart', - name: 'OtherMacroImplementation') + uri: 'package:_more_macros/other_macro.dart', + name: 'OtherMacroImplementation', + ), ]); expect(script, ''' @@ -46,8 +51,9 @@ void main(List arguments) { final bundle = await builder.build(Isolate.packageConfigSync!, [ QualifiedName( - uri: 'package:_test_macros/declare_x_macro.dart', - name: 'DeclareXImplementation') + uri: 'package:_test_macros/declare_x_macro.dart', + name: 'DeclareXImplementation', + ), ]); expect(File(bundle.executablePath).existsSync(), true); diff --git a/pkgs/_macro_client/lib/macro_client.dart b/pkgs/_macro_client/lib/macro_client.dart index b036a2f7..dc26f4bf 100644 --- a/pkgs/_macro_client/lib/macro_client.dart +++ b/pkgs/_macro_client/lib/macro_client.dart @@ -48,15 +48,20 @@ class MacroClient { // Send `HandshakeRequest` telling the host what protocols this macro // bundle supports. Protocol.handshakeProtocol.send( - socket.add, - HandshakeRequest(protocols: [ + socket.add, + HandshakeRequest( + protocols: [ Protocol( - encoding: ProtocolEncoding.json, - version: ProtocolVersion.macros1), + encoding: ProtocolEncoding.json, + version: ProtocolVersion.macros1, + ), Protocol( - encoding: ProtocolEncoding.binary, - version: ProtocolVersion.macros1), - ]).node); + encoding: ProtocolEncoding.binary, + version: ProtocolVersion.macros1, + ), + ], + ).node, + ); // Read `HandshakeResponse`, get from it the protocol to use for the rest of // the stream, and decode+handle using that protocol. final handshakeResponse = HandshakeResponse.fromJson(await firstResponse); @@ -69,9 +74,14 @@ class MacroClient { // a `MacroStartedRequest` that is sent next. for (final macro in macros) { - unawaited(_sendRequest(MacroRequest.macroStartedRequest( - MacroStartedRequest(macroDescription: macro.description), - id: nextRequestId))); + unawaited( + _sendRequest( + MacroRequest.macroStartedRequest( + MacroStartedRequest(macroDescription: macro.description), + id: nextRequestId, + ), + ), + ); } } @@ -101,41 +111,67 @@ class MacroClient { final hostRequest = HostRequest.fromJson(jsonData); switch (hostRequest.type) { case HostRequestType.augmentRequest: - final macro = macros - .where((m) => - m.description.annotation.equals(hostRequest.macroAnnotation)) - .singleOrNull; + final macro = + macros + .where( + (m) => m.description.annotation.equals( + hostRequest.macroAnnotation, + ), + ) + .singleOrNull; if (macro == null) { - _sendResponse(Response.errorResponse( + _sendResponse( + Response.errorResponse( requestId: hostRequest.id, ErrorResponse( - error: 'No macro for annotation: ' - '${hostRequest.macroAnnotation.asString}'))); + error: + 'No macro for annotation: ' + '${hostRequest.macroAnnotation.asString}', + ), + ), + ); } else { final augmentRequest = hostRequest.asAugmentRequest; await Scope.macro.runAsync(() async { MacroScope.current.addModel(augmentRequest.model); - return _sendResponse(Response.augmentResponse( + return _sendResponse( + Response.augmentResponse( switch (augmentRequest.phase) { - 1 => macro.description.runsInPhases.contains(1) - ? await executeTypesMacro( - macro, _host, augmentRequest) - : null, - 2 => macro.description.runsInPhases.contains(2) - ? await executeDeclarationsMacro( - macro, _host, augmentRequest) - : null, - 3 => macro.description.runsInPhases.contains(3) - ? await executeDefinitionsMacro( - macro, _host, augmentRequest) - : null, - _ => throw StateError( + 1 => + macro.description.runsInPhases.contains(1) + ? await executeTypesMacro( + macro, + _host, + augmentRequest, + ) + : null, + 2 => + macro.description.runsInPhases.contains(2) + ? await executeDeclarationsMacro( + macro, + _host, + augmentRequest, + ) + : null, + 3 => + macro.description.runsInPhases.contains(3) + ? await executeDefinitionsMacro( + macro, + _host, + augmentRequest, + ) + : null, + _ => + throw StateError( 'Unexpected phase ${augmentRequest.phase}, ' - 'expected 1, 2, or 3.') + 'expected 1, 2, or 3.', + ), } ?? AugmentResponse(), - requestId: hostRequest.id)); + requestId: hostRequest.id, + ), + ); }); } default: @@ -179,11 +215,15 @@ class RemoteMacroHost implements Host { Future query(Query query) async { // The macro scope is used to accumulate augment results, drop into // "none" scope to avoid clashing with those when sending the query. - final model = (await Scope.none.runAsync(() async => _client._sendRequest( - MacroRequest.queryRequest(QueryRequest(query: query), - id: nextRequestId)))) - .asQueryResponse - .model; + final model = + (await Scope.none.runAsync( + () async => _client._sendRequest( + MacroRequest.queryRequest( + QueryRequest(query: query), + id: nextRequestId, + ), + ), + )).asQueryResponse.model; MacroScope.current.addModel(model); return model; } diff --git a/pkgs/_macro_client/lib/src/builder_impls.dart b/pkgs/_macro_client/lib/src/builder_impls.dart index cbe59021..9dd07553 100644 --- a/pkgs/_macro_client/lib/src/builder_impls.dart +++ b/pkgs/_macro_client/lib/src/builder_impls.dart @@ -20,7 +20,7 @@ abstract base class BuilderBase implements Builder { Model get model => MacroScope.current.model; BuilderBase(this.target, this.host) - : response = AugmentResponse(libraryAugmentations: [], newTypeNames: []); + : response = AugmentResponse(libraryAugmentations: [], newTypeNames: []); BuilderBase.nested(this.target, this.host, this.response); @@ -33,7 +33,7 @@ abstract base class TypesBuilderBase extends BuilderBase TypesBuilderBase(super.target, super.host); TypesBuilderBase.nested(super.target, super.host, super.response) - : super.nested(); + : super.nested(); @override void declareType(String name, Augmentation typeDeclaration) { @@ -61,7 +61,8 @@ base mixin ExtendsClauseBuilderImpl on TypesBuilderBase } base mixin ImplementsClauseBuilderImpl - on TypesBuilderBase implements ImplementsClauseBuilder { + on TypesBuilderBase + implements ImplementsClauseBuilder { /// Appends [interfaces] to the list of interfaces for this type. @override void appendInterfaces(Iterable interfaces) { @@ -96,15 +97,16 @@ final class ClassTypesBuilderImpl ClassTypesBuilderImpl(super.target, super.host); ClassTypesBuilderImpl.nested(super.target, super.host, super.response) - : super.nested(); + : super.nested(); } abstract base class DeclarationsBuilderBase - extends BuilderBase implements DeclarationsBuilder { + extends BuilderBase + implements DeclarationsBuilder { DeclarationsBuilderBase(super.target, super.host); DeclarationsBuilderBase.nested(super.target, super.host, super.response) - : super.nested(); + : super.nested(); @override void declareInLibrary(Augmentation declaration) { @@ -113,11 +115,12 @@ abstract base class DeclarationsBuilderBase } abstract base class MemberDeclarationsBuilderBase - extends DeclarationsBuilderBase implements MemberDeclarationsBuilder { + extends DeclarationsBuilderBase + implements MemberDeclarationsBuilder { MemberDeclarationsBuilderBase(super.target, super.host); MemberDeclarationsBuilderBase.nested(super.target, super.host, super.response) - : super.nested(); + : super.nested(); @override void declareInType(Augmentation declaration) { @@ -135,54 +138,75 @@ final class ClassDeclarationsBuilderImpl ClassDeclarationsBuilderImpl(super.target, super.host); ClassDeclarationsBuilderImpl.nested(super.target, super.host, super.response) - : super.nested(); + : super.nested(); } final class MethodDefinitionsBuilderImpl - extends BuilderBase implements MethodDefinitionsBuilder { + extends BuilderBase + implements MethodDefinitionsBuilder { MethodDefinitionsBuilderImpl(super.target, super.host); MethodDefinitionsBuilderImpl.nested(super.target, super.host, super.response) - : super.nested(); + : super.nested(); @override void augment({Augmentation? body, Augmentation? docCommentsAndMetadata}) { - final augmentation = _buildFunctionAugmentation(body, target, model, - docComments: docCommentsAndMetadata); + final augmentation = _buildFunctionAugmentation( + body, + target, + model, + docComments: docCommentsAndMetadata, + ); response.typeAugmentations!.update( - target.parentInterface.name, (value) => value..add(augmentation), - ifAbsent: () => [augmentation]); + target.parentInterface.name, + (value) => value..add(augmentation), + ifAbsent: () => [augmentation], + ); } } final class ConstructorDefinitionsBuilderImpl - extends BuilderBase implements ConstructorDefinitionsBuilder { + extends BuilderBase + implements ConstructorDefinitionsBuilder { ConstructorDefinitionsBuilderImpl(super.target, super.host); ConstructorDefinitionsBuilderImpl.nested( - super.target, super.host, super.response) - : super.nested(); + super.target, + super.host, + super.response, + ) : super.nested(); @override - void augment( - {Augmentation? body, - List? initializers, - Augmentation? docCommentsAndMetadata}) { - final augmentation = _buildFunctionAugmentation(body, target, model, - initializers: initializers, docComments: docCommentsAndMetadata); + void augment({ + Augmentation? body, + List? initializers, + Augmentation? docCommentsAndMetadata, + }) { + final augmentation = _buildFunctionAugmentation( + body, + target, + model, + initializers: initializers, + docComments: docCommentsAndMetadata, + ); response.typeAugmentations!.update( - target.parentInterface.name, (value) => value..add(augmentation), - ifAbsent: () => [augmentation]); + target.parentInterface.name, + (value) => value..add(augmentation), + ifAbsent: () => [augmentation], + ); } } abstract base class InterfaceDefinitionsBuilderBase - extends BuilderBase implements InterfaceDefinitionsBuilder { + extends BuilderBase + implements InterfaceDefinitionsBuilder { InterfaceDefinitionsBuilderBase(super.target, super.host); InterfaceDefinitionsBuilderBase.nested( - super.target, super.host, super.response) - : super.nested(); + super.target, + super.host, + super.response, + ) : super.nested(); /// Retrieve a [FieldDefinitionsBuilder] for a field with [name] in /// [target]. @@ -201,7 +225,10 @@ abstract base class InterfaceDefinitionsBuilderBase @override MethodDefinitionsBuilder buildMethod(QualifiedName name) => MethodDefinitionsBuilderImpl.nested( - Member.fromJson(model.lookup(name)!), host, response); + Member.fromJson(model.lookup(name)!), + host, + response, + ); /// Retrieve a [ConstructorDefinitionsBuilder] for a constructor with [name] /// in [target]. @@ -211,7 +238,10 @@ abstract base class InterfaceDefinitionsBuilderBase @override ConstructorDefinitionsBuilder buildConstructor(QualifiedName name) => ConstructorDefinitionsBuilderImpl.nested( - Member.fromJson(model.lookup(name)!), host, response); + Member.fromJson(model.lookup(name)!), + host, + response, + ); } final class ClassDefinitionsBuilderImpl @@ -220,7 +250,7 @@ final class ClassDefinitionsBuilderImpl ClassDefinitionsBuilderImpl(super.target, super.host); ClassDefinitionsBuilderImpl.nested(super.target, super.host, super.response) - : super.nested(); + : super.nested(); @override void augment({Augmentation? docCommentsAndMetadata}) { @@ -239,8 +269,12 @@ final class ClassDefinitionsBuilderImpl /// The [initializers] parameter can only be used if [declaration] is a /// constructor. Augmentation _buildFunctionAugmentation( - Augmentation? body, Member declaration, Model model, - {List? initializers, Augmentation? docComments}) { + Augmentation? body, + Member declaration, + Model model, { + List? initializers, + Augmentation? docComments, +}) { assert(initializers == null || declaration.properties.isConstructor); final properties = declaration.properties; final qualifiedName = model.qualifiedNameOf(declaration.node)!; @@ -325,20 +359,17 @@ Augmentation _buildFunctionAugmentation( ...initializer.code, ], ], - if (body == null) - ';' - else ...[ - ' ', - ...body.code, - ] + if (body == null) ';' else ...[' ', ...body.code], ]; - return Augmentation(code: [ - for (var part in parts) - switch (part) { - String() => Code.string(part), - // TODO: All maps will pass this check... - Code() => part, - _ => throw StateError('Unexpected code kind $part'), - }, - ]); + return Augmentation( + code: [ + for (var part in parts) + switch (part) { + String() => Code.string(part), + // TODO: All maps will pass this check... + Code() => part, + _ => throw StateError('Unexpected code kind $part'), + }, + ], + ); } diff --git a/pkgs/_macro_client/lib/src/execute_macro.dart b/pkgs/_macro_client/lib/src/execute_macro.dart index 5f496e23..c0fa5879 100644 --- a/pkgs/_macro_client/lib/src/execute_macro.dart +++ b/pkgs/_macro_client/lib/src/execute_macro.dart @@ -13,7 +13,10 @@ import 'builder_impls.dart'; /// Runs [macro] in the types phase and returns an [AugmentResponse]. Future executeTypesMacro( - Macro macro, Host host, AugmentRequest request) async { + Macro macro, + Host host, + AugmentRequest request, +) async { final target = request.target; final model = request.model; final interface = model.uris[target.uri]!.scopes[target.name]!; @@ -37,14 +40,19 @@ Future executeTypesMacro( case (_, TypeAliasTypesMacro()): throw UnimplementedError('Unimplemented macro target'); default: - throw UnsupportedError('Unsupported macro type or invalid target:\n' - 'macro: $macro\ntarget: $target'); + throw UnsupportedError( + 'Unsupported macro type or invalid target:\n' + 'macro: $macro\ntarget: $target', + ); } } /// Runs [macro] in the declarations phase and returns an [AugmentResponse]. Future executeDeclarationsMacro( - Macro macro, Host host, AugmentRequest request) async { + Macro macro, + Host host, + AugmentRequest request, +) async { final target = request.target; final model = request.model; final interface = model.uris[target.uri]!.scopes[target.name]!; @@ -68,14 +76,19 @@ Future executeDeclarationsMacro( case (_, TypeAliasDeclarationsMacro()): throw UnimplementedError('Unimplemented macro target'); default: - throw UnsupportedError('Unsupported macro type or invalid target:\n' - 'macro: $macro\ntarget: $target'); + throw UnsupportedError( + 'Unsupported macro type or invalid target:\n' + 'macro: $macro\ntarget: $target', + ); } } /// Runs [macro] in the definitions phase and returns an [AugmentResponse]. Future executeDefinitionsMacro( - Macro macro, Host host, AugmentRequest request) async { + Macro macro, + Host host, + AugmentRequest request, +) async { final target = request.target; final model = request.model; final interface = model.uris[target.uri]!.scopes[target.name]!; @@ -98,7 +111,9 @@ Future executeDefinitionsMacro( case (_, VariableDefinitionsMacro()): throw UnimplementedError('Unimplemented macro target'); default: - throw UnsupportedError('Unsupported macro type or invalid target:\n' - 'macro: $macro\ntarget: $target'); + throw UnsupportedError( + 'Unsupported macro type or invalid target:\n' + 'macro: $macro\ntarget: $target', + ); } } diff --git a/pkgs/_macro_client/pubspec.yaml b/pkgs/_macro_client/pubspec.yaml index 516515d4..b647c612 100644 --- a/pkgs/_macro_client/pubspec.yaml +++ b/pkgs/_macro_client/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/dart-lang/macros/tree/master/pkgs/_macro_client resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: dart_model: any diff --git a/pkgs/_macro_client/test/macro_client_test.dart b/pkgs/_macro_client/test/macro_client_test.dart index 91d9bcbf..2589a6b2 100644 --- a/pkgs/_macro_client/test/macro_client_test.dart +++ b/pkgs/_macro_client/test/macro_client_test.dart @@ -15,14 +15,22 @@ import 'package:test/test.dart'; void main() { final fooTarget = QualifiedName(name: 'Foo', uri: 'package:foo/foo.dart'); - final fooModel = Scope.query.run(() => Model() - ..uris[fooTarget.uri] = (Library() - ..scopes['Foo'] = Interface(properties: Properties(isClass: true)))); + final fooModel = Scope.query.run( + () => + Model() + ..uris[fooTarget.uri] = + (Library() + ..scopes['Foo'] = Interface( + properties: Properties(isClass: true), + )), + ); for (final protocol in [ Protocol(encoding: ProtocolEncoding.json, version: ProtocolVersion.macros1), Protocol( - encoding: ProtocolEncoding.binary, version: ProtocolVersion.macros1) + encoding: ProtocolEncoding.binary, + version: ProtocolVersion.macros1, + ), ]) { group('MacroClient using ${protocol.encoding}', () { /// Waits for [HandshakRequest] on [socket], sends response choosing @@ -36,11 +44,13 @@ void main() { expect(handshakeRequest, { 'protocols': [ {'encoding': 'json', 'version': 'macros1'}, - {'encoding': 'binary', 'version': 'macros1'} - ] + {'encoding': 'binary', 'version': 'macros1'}, + ], }); - Protocol.handshakeProtocol - .send(socket.add, HandshakeResponse(protocol: protocol).node); + Protocol.handshakeProtocol.send( + socket.add, + HandshakeResponse(protocol: protocol).node, + ); return result; } @@ -49,9 +59,12 @@ void main() { final serverSocket = await ServerSocket.bind('localhost', 0); addTearDown(serverSocket.close); - unawaited(MacroClient.run( + unawaited( + MacroClient.run( endpoint: HostEndpoint(port: serverSocket.port), - macros: [DeclareXImplementation()])); + macros: [DeclareXImplementation()], + ), + ); final socket = await serverSocket.first; await handshake(socket); @@ -60,9 +73,12 @@ void main() { test('error response if no such macro', () async { final serverSocket = await ServerSocket.bind('localhost', 0); - unawaited(MacroClient.run( + unawaited( + MacroClient.run( endpoint: HostEndpoint(port: serverSocket.port), - macros: [QueryClassImplementation()])); + macros: [QueryClassImplementation()], + ), + ); final socket = await serverSocket.first; final responses = await handshake(socket); @@ -72,33 +88,38 @@ void main() { final requestId = nextRequestId; protocol.send( - socket.add, - HostRequest.augmentRequest( - id: requestId, - macroAnnotation: QualifiedName( - uri: 'package:_test_macros/declare_x_macro.dart', - name: 'DeclareX'), - AugmentRequest( - phase: 2, target: fooTarget, model: fooModel)) - .node); + socket.add, + HostRequest.augmentRequest( + id: requestId, + macroAnnotation: QualifiedName( + uri: 'package:_test_macros/declare_x_macro.dart', + name: 'DeclareX', + ), + AugmentRequest(phase: 2, target: fooTarget, model: fooModel), + ).node, + ); final augmentResponse = await responses.next; expect(augmentResponse, { 'requestId': requestId, 'type': 'ErrorResponse', 'value': { - 'error': 'No macro for annotation: ' - 'package:_test_macros/declare_x_macro.dart#DeclareX' - } + 'error': + 'No macro for annotation: ' + 'package:_test_macros/declare_x_macro.dart#DeclareX', + }, }); }); test('sends augmentation requests to macros, sends response', () async { final serverSocket = await ServerSocket.bind('localhost', 0); - unawaited(MacroClient.run( + unawaited( + MacroClient.run( endpoint: HostEndpoint(port: serverSocket.port), - macros: [DeclareXImplementation()])); + macros: [DeclareXImplementation()], + ), + ); final socket = await serverSocket.first; final responses = await handshake(socket); @@ -113,22 +134,23 @@ void main() { 'uri': 'package:_test_macros/declare_x_macro.dart', 'name': 'DeclareX', }, - 'runsInPhases': [2] - } - } + 'runsInPhases': [2], + }, + }, }); final requestId = nextRequestId; protocol.send( - socket.add, - HostRequest.augmentRequest( - id: requestId, - macroAnnotation: QualifiedName( - uri: 'package:_test_macros/declare_x_macro.dart', - name: 'DeclareX'), - AugmentRequest( - phase: 2, target: fooTarget, model: fooModel)) - .node); + socket.add, + HostRequest.augmentRequest( + id: requestId, + macroAnnotation: QualifiedName( + uri: 'package:_test_macros/declare_x_macro.dart', + name: 'DeclareX', + ), + AugmentRequest(phase: 2, target: fooTarget, model: fooModel), + ).node, + ); final augmentResponse = await responses.next; expect(augmentResponse, { @@ -145,10 +167,7 @@ void main() { 'Foo': [ { 'code': [ - { - 'type': 'String', - 'value': 'int get x => 3;', - }, + {'type': 'String', 'value': 'int get x => 3;'}, ], }, ], @@ -160,9 +179,12 @@ void main() { test('sends query requests to host, sends response', () async { final serverSocket = await ServerSocket.bind('localhost', 0); - unawaited(MacroClient.run( + unawaited( + MacroClient.run( endpoint: HostEndpoint(port: serverSocket.port), - macros: [QueryClassImplementation()])); + macros: [QueryClassImplementation()], + ), + ); final socket = await serverSocket.first; final responses = await handshake(socket); @@ -177,78 +199,82 @@ void main() { 'uri': 'package:_test_macros/query_class.dart', 'name': 'QueryClass', }, - 'runsInPhases': [3] - } + 'runsInPhases': [3], + }, }, }); final requestId = nextRequestId; protocol.send( - socket.add, - HostRequest.augmentRequest( - id: requestId, - macroAnnotation: QualifiedName( - uri: 'package:_test_macros/query_class.dart', - name: 'QueryClass'), - AugmentRequest(phase: 3, target: fooTarget, model: fooModel), - ).node); + socket.add, + HostRequest.augmentRequest( + id: requestId, + macroAnnotation: QualifiedName( + uri: 'package:_test_macros/query_class.dart', + name: 'QueryClass', + ), + AugmentRequest(phase: 3, target: fooTarget, model: fooModel), + ).node, + ); final queryRequest = await responses.next; final queryRequestId = MacroRequest.fromJson(queryRequest).id; - expect( - queryRequest, - { - 'id': queryRequestId, - 'type': 'QueryRequest', - 'value': { - 'query': {'target': fooTarget} - }, + expect(queryRequest, { + 'id': queryRequestId, + 'type': 'QueryRequest', + 'value': { + 'query': {'target': fooTarget}, }, - ); + }); - Scope.query.run(() => protocol.send( + Scope.query.run( + () => protocol.send( socket.add, - Response.queryResponse(QueryResponse(model: fooModel), - requestId: queryRequestId) - .node)); + Response.queryResponse( + QueryResponse(model: fooModel), + requestId: queryRequestId, + ).node, + ), + ); final augmentResponse = await responses.next; - expect( - augmentResponse, - { - 'requestId': requestId, - 'type': 'AugmentResponse', - 'value': { - 'enumValueAugmentations': {}, - 'extendsTypeAugmentations': {}, - 'interfaceAugmentations': {}, - 'mixinAugmentations': {}, - 'libraryAugmentations': [], - 'newTypeNames': [], - 'typeAugmentations': { - 'Foo': [ - { - 'code': [ - { - 'type': 'String', - 'value': '// {"uris":{"${fooTarget.uri}":{"scopes":{"Foo":' - '{"members":{},"properties":{"isClass":true}}}}}}', - }, - ], - }, - ], - }, + expect(augmentResponse, { + 'requestId': requestId, + 'type': 'AugmentResponse', + 'value': { + 'enumValueAugmentations': {}, + 'extendsTypeAugmentations': {}, + 'interfaceAugmentations': {}, + 'mixinAugmentations': {}, + 'libraryAugmentations': [], + 'newTypeNames': [], + 'typeAugmentations': { + 'Foo': [ + { + 'code': [ + { + 'type': 'String', + 'value': + '// {"uris":{"${fooTarget.uri}":{"scopes":{"Foo":' + '{"members":{},"properties":{"isClass":true}}}}}}', + }, + ], + }, + ], }, }, - ); + }); }); test('handles concurrent queries', () async { final serverSocket = await ServerSocket.bind('localhost', 0); - unawaited(MacroClient.run( + unawaited( + MacroClient.run( endpoint: HostEndpoint(port: serverSocket.port), - macros: [QueryClassImplementation()])); + macros: [QueryClassImplementation()], + ), + ); final socket = await serverSocket.first; final responses = await handshake(socket); @@ -260,98 +286,100 @@ void main() { final requestId2 = nextRequestId; for (final requestId in [requestId1, requestId2]) { protocol.send( - socket.add, - HostRequest.augmentRequest( - id: requestId, - macroAnnotation: QualifiedName( - uri: 'package:_test_macros/query_class.dart', - name: 'QueryClass'), - AugmentRequest(phase: 3, target: fooTarget, model: fooModel), - ).node); + socket.add, + HostRequest.augmentRequest( + id: requestId, + macroAnnotation: QualifiedName( + uri: 'package:_test_macros/query_class.dart', + name: 'QueryClass', + ), + AugmentRequest(phase: 3, target: fooTarget, model: fooModel), + ).node, + ); } final queryRequest1 = await responses.next; final queryRequestId1 = MacroRequest.fromJson(queryRequest1).id; - Scope.query.run(() => protocol.send( + Scope.query.run( + () => protocol.send( socket.add, Response.queryResponse( - QueryResponse( - model: Model() - ..uris['package:foo/foo1.dart'] = Library()), - requestId: queryRequestId1) - .node)); + QueryResponse( + model: Model()..uris['package:foo/foo1.dart'] = Library(), + ), + requestId: queryRequestId1, + ).node, + ), + ); final queryRequest2 = await responses.next; final queryRequestId2 = MacroRequest.fromJson(queryRequest2).id; - Scope.query.run(() => protocol.send( + Scope.query.run( + () => protocol.send( socket.add, Response.queryResponse( - QueryResponse( - model: Model() - ..uris['package:foo/foo2.dart'] = Library()), - requestId: queryRequestId2) - .node)); + QueryResponse( + model: Model()..uris['package:foo/foo2.dart'] = Library(), + ), + requestId: queryRequestId2, + ).node, + ), + ); final augmentResponse1 = await responses.next; final augmentResponse2 = await responses.next; - expect( - augmentResponse1, - { - 'requestId': requestId1, - 'type': 'AugmentResponse', - 'value': { - 'enumValueAugmentations': {}, - 'extendsTypeAugmentations': {}, - 'interfaceAugmentations': {}, - 'mixinAugmentations': {}, - 'libraryAugmentations': [], - 'newTypeNames': [], - 'typeAugmentations': { - 'Foo': [ - { - 'code': [ - { - 'type': 'String', - 'value': - '// {"uris":{"package:foo/foo1.dart":{"scopes":{}}}}', - }, - ], - }, - ], - }, + expect(augmentResponse1, { + 'requestId': requestId1, + 'type': 'AugmentResponse', + 'value': { + 'enumValueAugmentations': {}, + 'extendsTypeAugmentations': {}, + 'interfaceAugmentations': {}, + 'mixinAugmentations': {}, + 'libraryAugmentations': [], + 'newTypeNames': [], + 'typeAugmentations': { + 'Foo': [ + { + 'code': [ + { + 'type': 'String', + 'value': + '// {"uris":{"package:foo/foo1.dart":{"scopes":{}}}}', + }, + ], + }, + ], }, }, - ); + }); - expect( - augmentResponse2, - { - 'requestId': requestId2, - 'type': 'AugmentResponse', - 'value': { - 'enumValueAugmentations': {}, - 'extendsTypeAugmentations': {}, - 'interfaceAugmentations': {}, - 'mixinAugmentations': {}, - 'libraryAugmentations': [], - 'newTypeNames': [], - 'typeAugmentations': { - 'Foo': [ - { - 'code': [ - { - 'type': 'String', - 'value': - '// {"uris":{"package:foo/foo2.dart":{"scopes":{}}}}', - }, - ], - }, - ], - }, + expect(augmentResponse2, { + 'requestId': requestId2, + 'type': 'AugmentResponse', + 'value': { + 'enumValueAugmentations': {}, + 'extendsTypeAugmentations': {}, + 'interfaceAugmentations': {}, + 'mixinAugmentations': {}, + 'libraryAugmentations': [], + 'newTypeNames': [], + 'typeAugmentations': { + 'Foo': [ + { + 'code': [ + { + 'type': 'String', + 'value': + '// {"uris":{"package:foo/foo2.dart":{"scopes":{}}}}', + }, + ], + }, + ], }, }, - ); + }); }); }); } diff --git a/pkgs/_macro_host/lib/src/macro_cache.dart b/pkgs/_macro_host/lib/src/macro_cache.dart index a81f7085..e7b45b57 100644 --- a/pkgs/_macro_host/lib/src/macro_cache.dart +++ b/pkgs/_macro_host/lib/src/macro_cache.dart @@ -32,12 +32,15 @@ class MacroResultsCache { phase: request.phase, )] = ( queries: queryResults.map((q) => q.query), - resultsHash: queryResults - .skip(1) - .fold(queryResults.first.response, - (model, next) => model.mergeWith(next.response)) - .fingerprint, - response: response + resultsHash: + queryResults + .skip(1) + .fold( + queryResults.first.response, + (model, next) => model.mergeWith(next.response), + ) + .fingerprint, + response: response, ); } @@ -46,22 +49,32 @@ class MacroResultsCache { /// /// Otherwise, invalidates the cache for this request and returns `null`. Future cachedResult( - QualifiedName annotation, AugmentRequest request) async { + QualifiedName annotation, + AugmentRequest request, + ) async { final cacheKey = ( annotation: annotation.asRecord, target: request.target.asRecord, - phase: request.phase + phase: request.phase, ); final cached = _cache[cacheKey]; if (cached == null) return null; - final queryResults = await Scope.query.run(() => Future.wait(cached.queries - .map((query) => queryService.handle(QueryRequest(query: query))))); - final newResultsHash = queryResults - .skip(1) - .fold(queryResults.first.model, - (model, next) => model.mergeWith(next.model)) - .fingerprint; + final queryResults = await Scope.query.run( + () => Future.wait( + cached.queries.map( + (query) => queryService.handle(QueryRequest(query: query)), + ), + ), + ); + final newResultsHash = + queryResults + .skip(1) + .fold( + queryResults.first.model, + (model, next) => model.mergeWith(next.model), + ) + .fingerprint; if (newResultsHash != cached.resultsHash) { _cache.remove(cacheKey); return null; @@ -70,29 +83,23 @@ class MacroResultsCache { } } -typedef _MacroResultsCacheKey = ({ - QualifiedNameRecord annotation, - QualifiedNameRecord target, - int phase, -}); +typedef _MacroResultsCacheKey = + ({QualifiedNameRecord annotation, QualifiedNameRecord target, int phase}); -typedef _MacroResultsCacheValue = ({ - /// All queries done by a macro in a given phase. - Iterable queries, +typedef _MacroResultsCacheValue = + ({ + /// All queries done by a macro in a given phase. + Iterable queries, - /// The `identityHash` of the merged model from all query responses. - int resultsHash, + /// The `identityHash` of the merged model from all query responses. + int resultsHash, - /// The macro augmentation response that was cached. - AugmentResponse response, -}); + /// The macro augmentation response that was cached. + AugmentResponse response, + }); -typedef QualifiedNameRecord = ( - String uri, - String? scope, - String name, - bool? isStatic -); +typedef QualifiedNameRecord = + (String uri, String? scope, String name, bool? isStatic); extension on QualifiedName { QualifiedNameRecord get asRecord => (uri, scope, name, isStatic); diff --git a/pkgs/_macro_host/lib/src/macro_host.dart b/pkgs/_macro_host/lib/src/macro_host.dart index b61946e7..3476dc2d 100644 --- a/pkgs/_macro_host/lib/src/macro_host.dart +++ b/pkgs/_macro_host/lib/src/macro_host.dart @@ -32,7 +32,7 @@ class MacroHost { QueryService get _queryService => _hostService.queryService; MacroHost._(this.macroPackageConfig, this.macroServer, this._hostService) - : _macroResultsCache = MacroResultsCache(_hostService.queryService); + : _macroResultsCache = MacroResultsCache(_hostService.queryService); /// Starts a macro host with introspection queries handled by [queryService]. static Future serve({ @@ -43,8 +43,10 @@ class MacroHost { }) async { final macroPackageConfig = MacroPackageConfig.readFromUri(packageConfig); final hostService = _HostService(queryService); - final server = - await MacroServer.serve(protocol: protocol, service: hostService); + final server = await MacroServer.serve( + protocol: protocol, + service: hostService, + ); return MacroHost._(macroPackageConfig, server, hostService); } @@ -61,33 +63,44 @@ class MacroHost { /// Determines which phases the macro triggered by [annotation] runs in. Future> queryMacroPhases( - Uri packageConfig, QualifiedName annotation) async { + Uri packageConfig, + QualifiedName annotation, + ) async { await _ensureRunning(annotation); return _hostService._macroState[annotation.asString]!.phases; } /// Sends [request] to the macro triggered by [annotation]. Future augment( - QualifiedName annotation, AugmentRequest request) async { + QualifiedName annotation, + AugmentRequest request, + ) async { // TODO: Save the query results or pre-emptively send them to the macro? final cached = await _macroResultsCache.cachedResult(annotation, request); if (cached != null) return cached; await _ensureRunning(annotation); _queryService.startTrackingQueries(); - final response = (await macroServer.sendToMacro(HostRequest.augmentRequest( - macroAnnotation: annotation, request, id: nextRequestId))) - .asAugmentResponse; + final response = + (await macroServer.sendToMacro( + HostRequest.augmentRequest( + macroAnnotation: annotation, + request, + id: nextRequestId, + ), + )).asAugmentResponse; _macroResultsCache.cache( - annotation: annotation, - request: request, - queryResults: _queryService.stopTrackingQueries() - // Add an initial query for the model itself also. - ..add(( - query: Query(target: request.target), - response: request.model, - )), - response: response); + annotation: annotation, + request: request, + queryResults: + _queryService.stopTrackingQueries() + // Add an initial query for the model itself also. + ..add(( + query: Query(target: request.target), + response: request.model, + )), + response: response, + ); return response; } @@ -109,8 +122,9 @@ class MacroHost { // is still building; currently requests while the macro is building will // time out after 5s. _hostService._macroState[annotation.asString] = _MacroState(); - final macroBundle = await macroBuilder.build( - macroPackageConfig.uri, [lookupMacroImplementation(annotation)!]); + final macroBundle = await macroBuilder.build(macroPackageConfig.uri, [ + lookupMacroImplementation(annotation)!, + ]); macroRunner.start(macroBundle: macroBundle, endpoint: macroServer.endpoint); } } @@ -132,16 +146,22 @@ class _HostService implements HostService { _macroState[macroStartedRequest.macroDescription.annotation.asString]! ._phasesCompleter .complete( - macroStartedRequest.macroDescription.runsInPhases.toSet()); - return Response.macroStartedResponse(MacroStartedResponse(), - requestId: request.id); + macroStartedRequest.macroDescription.runsInPhases.toSet(), + ); + return Response.macroStartedResponse( + MacroStartedResponse(), + requestId: request.id, + ); case MacroRequestType.queryRequest: return Response.queryResponse( - await queryService.handle(request.asQueryRequest), - requestId: request.id); + await queryService.handle(request.asQueryRequest), + requestId: request.id, + ); default: - return Response.errorResponse(ErrorResponse(error: 'unsupported'), - requestId: request.id); + return Response.errorResponse( + ErrorResponse(error: 'unsupported'), + requestId: request.id, + ); } } } @@ -160,7 +180,8 @@ abstract base class QueryService { void startTrackingQueries() { if (_trackedQueries != null) { throw StateError( - 'Already tracking queries, cannot handle concurrent macros'); + 'Already tracking queries, cannot handle concurrent macros', + ); } _trackedQueries = []; } @@ -173,7 +194,8 @@ abstract base class QueryService { List<({Query query, Model response})> stopTrackingQueries() { if (_trackedQueries == null) { throw StateError( - 'Not tracking queries, must call `startTrackingQueries` first.'); + 'Not tracking queries, must call `startTrackingQueries` first.', + ); } final result = _trackedQueries!; _trackedQueries = null; diff --git a/pkgs/_macro_host/lib/src/package_config.dart b/pkgs/_macro_host/lib/src/package_config.dart index f615c5b4..dd302c28 100644 --- a/pkgs/_macro_host/lib/src/package_config.dart +++ b/pkgs/_macro_host/lib/src/package_config.dart @@ -15,9 +15,12 @@ class MacroPackageConfig { MacroPackageConfig({required this.uri, required this.packageConfig}); factory MacroPackageConfig.readFromUri(Uri uri) => MacroPackageConfig( - uri: uri, - packageConfig: - PackageConfig.parseBytes(File.fromUri(uri).readAsBytesSync(), uri)); + uri: uri, + packageConfig: PackageConfig.parseBytes( + File.fromUri(uri).readAsBytesSync(), + uri, + ), + ); /// Checks whether [name] is a macro annotation. /// diff --git a/pkgs/_macro_host/pubspec.yaml b/pkgs/_macro_host/pubspec.yaml index f73ce3a8..3e7807be 100644 --- a/pkgs/_macro_host/pubspec.yaml +++ b/pkgs/_macro_host/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/dart-lang/macros/tree/master/pkgs/_macro_host resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: _macro_builder: any diff --git a/pkgs/_macro_host/test/macro_host_test.dart b/pkgs/_macro_host/test/macro_host_test.dart index c111097e..ac1e9f1d 100644 --- a/pkgs/_macro_host/test/macro_host_test.dart +++ b/pkgs/_macro_host/test/macro_host_test.dart @@ -11,97 +11,131 @@ import 'package:test/test.dart'; void main() { final fooTarget = QualifiedName(name: 'Foo', uri: 'package:foo/foo.dart'); - final fooModel = Scope.query.run(() => Model() - ..uris[fooTarget.uri] = (Library() - ..scopes['Foo'] = Interface(properties: Properties(isClass: true)))); + final fooModel = Scope.query.run( + () => + Model() + ..uris[fooTarget.uri] = + (Library() + ..scopes['Foo'] = Interface( + properties: Properties(isClass: true), + )), + ); final packageConfig = Isolate.packageConfigSync!; for (final protocol in [ Protocol(encoding: ProtocolEncoding.json, version: ProtocolVersion.macros1), Protocol( - encoding: ProtocolEncoding.binary, version: ProtocolVersion.macros1) + encoding: ProtocolEncoding.binary, + version: ProtocolVersion.macros1, + ), ]) { group('MacroHost using ${protocol.encoding}', () { test('hosts a macro, receives augmentations', () async { final macroAnnotation = QualifiedName( - uri: 'package:_test_macros/declare_x_macro.dart', name: 'DeclareX'); + uri: 'package:_test_macros/declare_x_macro.dart', + name: 'DeclareX', + ); final queryService = TestQueryService(); final host = await MacroHost.serve( - protocol: protocol, - packageConfig: Isolate.packageConfigSync!, - queryService: queryService); + protocol: protocol, + packageConfig: Isolate.packageConfigSync!, + queryService: queryService, + ); expect(host.isMacro(macroAnnotation), true); - expect( - await host.queryMacroPhases(packageConfig, macroAnnotation), {2}); + expect(await host.queryMacroPhases(packageConfig, macroAnnotation), { + 2, + }); expect( - await host.augment(macroAnnotation, - AugmentRequest(phase: 2, target: fooTarget, model: fooModel)), - Scope.macro.run(() => + await host.augment( + macroAnnotation, + AugmentRequest(phase: 2, target: fooTarget, model: fooModel), + ), + Scope.macro.run( + () => AugmentResponse(libraryAugmentations: [], newTypeNames: []) ..typeAugmentations!['Foo'] = [ - Augmentation(code: [ - Code.string('int get x => 3;'), - ]), - ])); + Augmentation(code: [Code.string('int get x => 3;')]), + ], + ), + ); }); test('hosts a macro, responds to queries', () async { final macroAnnotation = QualifiedName( - uri: 'package:_test_macros/query_class.dart', name: 'QueryClass'); + uri: 'package:_test_macros/query_class.dart', + name: 'QueryClass', + ); final queryService = TestQueryService(); final host = await MacroHost.serve( - protocol: protocol, - packageConfig: Isolate.packageConfigSync!, - queryService: queryService); + protocol: protocol, + packageConfig: Isolate.packageConfigSync!, + queryService: queryService, + ); final packageConfig = Isolate.packageConfigSync!; expect(host.isMacro(macroAnnotation), true); - expect( - await host.queryMacroPhases(packageConfig, macroAnnotation), {3}); + expect(await host.queryMacroPhases(packageConfig, macroAnnotation), { + 3, + }); expect( - await host.augment(macroAnnotation, - AugmentRequest(phase: 3, target: fooTarget, model: fooModel)), - Scope.macro.run(() => - AugmentResponse(libraryAugmentations: [], newTypeNames: []) - ..typeAugmentations!['Foo'] = [ - Augmentation(code: [ - Code.string( - '// {"uris":{"package:foo/foo.dart":{"scopes":{"Foo":{' - '"members":{},"properties":{"isClass":true}}}}}}'), - ]), - ])); + await host.augment( + macroAnnotation, + AugmentRequest(phase: 3, target: fooTarget, model: fooModel), + ), + Scope.macro.run( + () => AugmentResponse(libraryAugmentations: [], newTypeNames: []) + ..typeAugmentations!['Foo'] = [ + Augmentation( + code: [ + Code.string( + '// {"uris":{"package:foo/foo.dart":{"scopes":{"Foo":{' + '"members":{},"properties":{"isClass":true}}}}}}', + ), + ], + ), + ], + ), + ); }); test('hosts two macros', () async { final macroNames = [ QualifiedName( - uri: 'package:_test_macros/declare_x_macro.dart', - name: 'DeclareX'), + uri: 'package:_test_macros/declare_x_macro.dart', + name: 'DeclareX', + ), QualifiedName( - uri: 'package:_test_macros/query_class.dart', name: 'QueryClass'), + uri: 'package:_test_macros/query_class.dart', + name: 'QueryClass', + ), ]; final queryService = TestQueryService(); final host = await MacroHost.serve( - protocol: protocol, - packageConfig: Isolate.packageConfigSync!, - queryService: queryService); + protocol: protocol, + packageConfig: Isolate.packageConfigSync!, + queryService: queryService, + ); for (final macroName in macroNames) { - await host.augment(macroName, - AugmentRequest(phase: 3, target: fooTarget, model: fooModel)); + await host.augment( + macroName, + AugmentRequest(phase: 3, target: fooTarget, model: fooModel), + ); } }); group('caching', () { final macroAnnotation = QualifiedName( - uri: 'package:_test_macros/declare_x_macro.dart', name: 'DeclareX'); + uri: 'package:_test_macros/declare_x_macro.dart', + name: 'DeclareX', + ); late AugmentResponse initialResult; late MacroHost host; @@ -110,30 +144,41 @@ void main() { setUp(() async { queryService = TestQueryService(); host = await MacroHost.serve( - protocol: protocol, - packageConfig: Isolate.packageConfigSync!, - queryService: queryService); + protocol: protocol, + packageConfig: Isolate.packageConfigSync!, + queryService: queryService, + ); - initialResult = await host.augment(macroAnnotation, - AugmentRequest(phase: 2, target: fooTarget, model: fooModel)); + initialResult = await host.augment( + macroAnnotation, + AugmentRequest(phase: 2, target: fooTarget, model: fooModel), + ); }); test('re-uses results if queries don\'t change', () async { - final rerunResult = await host.augment(macroAnnotation, - AugmentRequest(phase: 2, target: fooTarget, model: fooModel)); + final rerunResult = await host.augment( + macroAnnotation, + AugmentRequest(phase: 2, target: fooTarget, model: fooModel), + ); expect(identical(initialResult, rerunResult), true); }); test('Invalidates results if queries do change', () async { queryService.handleRequest = (QueryRequest request) async { return QueryResponse( - model: Model() - ..uris[request.query.target.uri] = (Library() - ..scopes[request.query.target.name] = - Interface(properties: Properties(isClass: false)))); + model: + Model() + ..uris[request.query.target.uri] = + (Library() + ..scopes[request.query.target.name] = Interface( + properties: Properties(isClass: false), + )), + ); }; - final rerunResult = await host.augment(macroAnnotation, - AugmentRequest(phase: 2, target: fooTarget, model: fooModel)); + final rerunResult = await host.augment( + macroAnnotation, + AugmentRequest(phase: 2, target: fooTarget, model: fooModel), + ); expect(identical(initialResult, rerunResult), false); }); }); @@ -143,13 +188,18 @@ void main() { final class TestQueryService extends QueryService { /// Actual implementatin of request handling, can be overwritten. - Future Function(QueryRequest request) handleRequest = - (QueryRequest request) async { + Future Function(QueryRequest request) handleRequest = ( + QueryRequest request, + ) async { return QueryResponse( - model: Model() - ..uris[request.query.target.uri] = (Library() - ..scopes[request.query.target.name] = - Interface(properties: Properties(isClass: true)))); + model: + Model() + ..uris[request.query.target.uri] = + (Library() + ..scopes[request.query.target.name] = Interface( + properties: Properties(isClass: true), + )), + ); }; @override diff --git a/pkgs/_macro_host/test/package_config_test.dart b/pkgs/_macro_host/test/package_config_test.dart index 05499646..2e7c9a78 100644 --- a/pkgs/_macro_host/test/package_config_test.dart +++ b/pkgs/_macro_host/test/package_config_test.dart @@ -12,31 +12,40 @@ import 'package:test/test.dart'; void main() { group(MacroPackageConfig, () { test('can look up macro implementations from package URIs', () async { - final packageConfig = - MacroPackageConfig.readFromUri(Isolate.packageConfigSync!); + final packageConfig = MacroPackageConfig.readFromUri( + Isolate.packageConfigSync!, + ); expect( - packageConfig - .lookupMacroImplementation(QualifiedName( - uri: 'package:_test_macros/declare_x_macro.dart', - name: 'DeclareX'))! - .asString, - 'package:_test_macros/declare_x_macro.dart#DeclareXImplementation'); + packageConfig + .lookupMacroImplementation( + QualifiedName( + uri: 'package:_test_macros/declare_x_macro.dart', + name: 'DeclareX', + ), + )! + .asString, + 'package:_test_macros/declare_x_macro.dart#DeclareXImplementation', + ); }); test('can look up macro implementations from file URIs', () async { - final packageConfig = - MacroPackageConfig.readFromUri(Isolate.packageConfigSync!); + final packageConfig = MacroPackageConfig.readFromUri( + Isolate.packageConfigSync!, + ); - final sourceFileUri = Directory.current.uri - .resolve('../_test_macros/lib/declare_x_macro.dart'); + final sourceFileUri = Directory.current.uri.resolve( + '../_test_macros/lib/declare_x_macro.dart', + ); expect( - packageConfig - .lookupMacroImplementation( - QualifiedName(uri: '$sourceFileUri', name: 'DeclareX'))! - .asString, - 'package:_test_macros/declare_x_macro.dart#DeclareXImplementation'); + packageConfig + .lookupMacroImplementation( + QualifiedName(uri: '$sourceFileUri', name: 'DeclareX'), + )! + .asString, + 'package:_test_macros/declare_x_macro.dart#DeclareXImplementation', + ); }); }); } diff --git a/pkgs/_macro_runner/lib/macro_runner.dart b/pkgs/_macro_runner/lib/macro_runner.dart index 1ced9729..a3f2b09b 100644 --- a/pkgs/_macro_runner/lib/macro_runner.dart +++ b/pkgs/_macro_runner/lib/macro_runner.dart @@ -13,10 +13,13 @@ import 'package:macro_service/macro_service.dart'; /// TODO(davidmorgan): support shutdown/cleanup. class MacroRunner { /// Starts [macroBundle] connected to [endpoint]. - void start( - {required BuiltMacroBundle macroBundle, required HostEndpoint endpoint}) { - Process.run(macroBundle.executablePath, [json.encode(endpoint)]) - .then((result) { + void start({ + required BuiltMacroBundle macroBundle, + required HostEndpoint endpoint, + }) { + Process.run(macroBundle.executablePath, [json.encode(endpoint)]).then(( + result, + ) { if (result.exitCode != 0) { print('Macro process exited with error: ${result.stderr}'); } diff --git a/pkgs/_macro_runner/pubspec.yaml b/pkgs/_macro_runner/pubspec.yaml index 6b76822b..42219700 100644 --- a/pkgs/_macro_runner/pubspec.yaml +++ b/pkgs/_macro_runner/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/dart-lang/macros/tree/master/pkgs/_macro_runner resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: _macro_builder: any diff --git a/pkgs/_macro_runner/test/macro_runner_test.dart b/pkgs/_macro_runner/test/macro_runner_test.dart index 9fd081e3..791e6c05 100644 --- a/pkgs/_macro_runner/test/macro_runner_test.dart +++ b/pkgs/_macro_runner/test/macro_runner_test.dart @@ -14,15 +14,16 @@ import 'package:test/test.dart'; void main() { for (final protocol in [ Protocol(encoding: ProtocolEncoding.json), - Protocol(encoding: ProtocolEncoding.binary) + Protocol(encoding: ProtocolEncoding.binary), ]) { group('MacroRunner with ${protocol.encoding}', () { test('runs macros', () async { final builder = MacroBuilder(); final bundle = await builder.build(Isolate.packageConfigSync!, [ QualifiedName( - uri: 'package:_test_macros/declare_x_macro.dart', - name: 'DeclareXImplementation') + uri: 'package:_test_macros/declare_x_macro.dart', + name: 'DeclareXImplementation', + ), ]); final serverSocket = await ServerSocket.bind('localhost', 0); @@ -30,11 +31,14 @@ void main() { final runner = MacroRunner(); runner.start( - macroBundle: bundle, - endpoint: HostEndpoint(port: serverSocket.port)); + macroBundle: bundle, + endpoint: HostEndpoint(port: serverSocket.port), + ); expect( - serverSocket.first.timeout(const Duration(seconds: 10)), completes); + serverSocket.first.timeout(const Duration(seconds: 10)), + completes, + ); }); }); } diff --git a/pkgs/_macro_server/lib/macro_server.dart b/pkgs/_macro_server/lib/macro_server.dart index 1fc12a75..18c9e575 100644 --- a/pkgs/_macro_server/lib/macro_server.dart +++ b/pkgs/_macro_server/lib/macro_server.dart @@ -35,7 +35,11 @@ class MacroServer { }) async { final serverSocket = await ServerSocket.bind('localhost', 0); return MacroServer._( - protocol, service, HostEndpoint(port: serverSocket.port), serverSocket); + protocol, + service, + HostEndpoint(port: serverSocket.port), + serverSocket, + ); } /// Sends to the macro identified by `request#macroAnnotation`. @@ -44,15 +48,21 @@ class MacroServer { /// macro to connect and checks again. /// /// Throws [TimeoutException] if no such macro connects in the time allowed. - Future sendToMacro(HostRequest request, - {Duration timeout = const Duration(seconds: 5)}) async { + Future sendToMacro( + HostRequest request, { + Duration timeout = const Duration(seconds: 5), + }) async { _Connection? connection; while (true) { // Look up the connection with the macro corresponding to `annotation`. - connection = _connections - .where((c) => c.descriptions - .any((d) => d.annotation.equals(request.macroAnnotation))) - .singleOrNull; + connection = + _connections + .where( + (c) => c.descriptions.any( + (d) => d.annotation.equals(request.macroAnnotation), + ), + ) + .singleOrNull; // If it's found: done. if (connection != null) break; // Not found, wait [timeout] then recheck. Throws `StateError` on @@ -82,21 +92,26 @@ class MacroServer { // matching `MacroStartedRequest` from the bundle before sending to it, // and `MacroStartedRequest` is sent after this message is received and // the protocol set. - Protocol.handshakeProtocol - .send(socket.add, HandshakeResponse(protocol: protocol).node); + Protocol.handshakeProtocol.send( + socket.add, + HandshakeResponse(protocol: protocol).node, + ); protocol.decode(broadcastStream).forEach((jsonData) { final request = MacroRequest.fromJson(jsonData); if (request.type.isKnown) { if (request.type == MacroRequestType.macroStartedRequest) { - connection.descriptions - .add(request.asMacroStartedRequest.macroDescription); + connection.descriptions.add( + request.asMacroStartedRequest.macroDescription, + ); _macroDescriptionBecomesKnown.add(null); } // Each query is handled and responded to in a new query scope. - Scope.query.runAsync(() async => service - .handle(request) - .then((response) => protocol.send(socket.add, response.node))); + Scope.query.runAsync( + () async => service + .handle(request) + .then((response) => protocol.send(socket.add, response.node)), + ); } final response = Response.fromJson(jsonData); if (response.type.isKnown) { diff --git a/pkgs/_macro_server/pubspec.yaml b/pkgs/_macro_server/pubspec.yaml index 66bef946..8f5ba911 100644 --- a/pkgs/_macro_server/pubspec.yaml +++ b/pkgs/_macro_server/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/dart-lang/macros/tree/master/pkgs/_macro_server resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: dart_model: any diff --git a/pkgs/_macro_server/test/macro_server_test.dart b/pkgs/_macro_server/test/macro_server_test.dart index 96dfc01e..47091aa0 100644 --- a/pkgs/_macro_server/test/macro_server_test.dart +++ b/pkgs/_macro_server/test/macro_server_test.dart @@ -14,115 +14,174 @@ import 'package:test/test.dart'; void main() { final fooTarget = QualifiedName(name: 'Foo', uri: 'package:foo/foo.dart'); - final fooModel = Scope.query.run(() => Model() - ..uris[fooTarget.uri] = (Library() - ..scopes['Foo'] = Interface(properties: Properties(isClass: true)))); + final fooModel = Scope.query.run( + () => + Model() + ..uris[fooTarget.uri] = + (Library() + ..scopes['Foo'] = Interface( + properties: Properties(isClass: true), + )), + ); for (final protocol in [ Protocol(encoding: ProtocolEncoding.json, version: ProtocolVersion.macros1), Protocol( - encoding: ProtocolEncoding.binary, version: ProtocolVersion.macros1) + encoding: ProtocolEncoding.binary, + version: ProtocolVersion.macros1, + ), ]) { group('MacroServer using ${protocol.encoding}', () { test('serves a macro service', () async { final service = TestHostService(); - final server = - await MacroServer.serve(protocol: protocol, service: service); + final server = await MacroServer.serve( + protocol: protocol, + service: service, + ); await MacroClient.run( - endpoint: server.endpoint, macros: [DeclareXImplementation()]); + endpoint: server.endpoint, + macros: [DeclareXImplementation()], + ); // Check that the macro sent its description to the host on startup. - expect((await service.macroStartedRequests.first).macroDescription, - DeclareXImplementation().description); + expect( + (await service.macroStartedRequests.first).macroDescription, + DeclareXImplementation().description, + ); }); test('throws on send to macro that is not running', () async { final service = TestHostService(); - final server = - await MacroServer.serve(protocol: protocol, service: service); + final server = await MacroServer.serve( + protocol: protocol, + service: service, + ); expect( - server.sendToMacro(HostRequest.augmentRequest( - AugmentRequest(phase: 1, target: fooTarget, model: fooModel), - id: 1, - macroAnnotation: QualifiedName( - uri: 'package:_test_macros/test_macros.dart', - name: 'DeclareX'))), - throwsException); + server.sendToMacro( + HostRequest.augmentRequest( + AugmentRequest(phase: 1, target: fooTarget, model: fooModel), + id: 1, + macroAnnotation: QualifiedName( + uri: 'package:_test_macros/test_macros.dart', + name: 'DeclareX', + ), + ), + ), + throwsException, + ); }); test('send to a macro that is running succeeds', () async { final service = TestHostService(); - final server = - await MacroServer.serve(protocol: protocol, service: service); - - unawaited(MacroClient.run( - endpoint: server.endpoint, macros: [DeclareXImplementation()])); - - await server.sendToMacro(HostRequest.augmentRequest( - id: 1, - macroAnnotation: QualifiedName( - uri: 'package:_test_macros/declare_x_macro.dart', - name: 'DeclareX'), - AugmentRequest(phase: 1, target: fooTarget, model: fooModel), - )); - }); - - test('send to macro succeeds with two connected macro binaries', - () async { - final service = TestHostService(); - final server = - await MacroServer.serve(protocol: protocol, service: service); - - unawaited(MacroClient.run( - endpoint: server.endpoint, macros: [DeclareXImplementation()])); + final server = await MacroServer.serve( + protocol: protocol, + service: service, + ); - unawaited(MacroClient.run( - endpoint: server.endpoint, macros: [QueryClassImplementation()])); + unawaited( + MacroClient.run( + endpoint: server.endpoint, + macros: [DeclareXImplementation()], + ), + ); - await Future.wait([ - server.sendToMacro(HostRequest.augmentRequest( + await server.sendToMacro( + HostRequest.augmentRequest( id: 1, macroAnnotation: QualifiedName( - uri: 'package:_test_macros/declare_x_macro.dart', - name: 'DeclareX'), + uri: 'package:_test_macros/declare_x_macro.dart', + name: 'DeclareX', + ), AugmentRequest(phase: 1, target: fooTarget, model: fooModel), - )), - server.sendToMacro(HostRequest.augmentRequest( - id: 2, - macroAnnotation: QualifiedName( - uri: 'package:_test_macros/query_class.dart', - name: 'QueryClass'), - AugmentRequest(phase: 1, target: fooTarget, model: fooModel))) - ]); + ), + ); }); test( - 'send to macro succeeds with one connected macro binary containing ' + 'send to macro succeeds with two connected macro binaries', + () async { + final service = TestHostService(); + final server = await MacroServer.serve( + protocol: protocol, + service: service, + ); + + unawaited( + MacroClient.run( + endpoint: server.endpoint, + macros: [DeclareXImplementation()], + ), + ); + + unawaited( + MacroClient.run( + endpoint: server.endpoint, + macros: [QueryClassImplementation()], + ), + ); + + await Future.wait([ + server.sendToMacro( + HostRequest.augmentRequest( + id: 1, + macroAnnotation: QualifiedName( + uri: 'package:_test_macros/declare_x_macro.dart', + name: 'DeclareX', + ), + AugmentRequest(phase: 1, target: fooTarget, model: fooModel), + ), + ), + server.sendToMacro( + HostRequest.augmentRequest( + id: 2, + macroAnnotation: QualifiedName( + uri: 'package:_test_macros/query_class.dart', + name: 'QueryClass', + ), + AugmentRequest(phase: 1, target: fooTarget, model: fooModel), + ), + ), + ]); + }, + ); + + test('send to macro succeeds with one connected macro binary containing ' 'two macros', () async { final service = TestHostService(); - final server = - await MacroServer.serve(protocol: protocol, service: service); + final server = await MacroServer.serve( + protocol: protocol, + service: service, + ); - unawaited(MacroClient.run( + unawaited( + MacroClient.run( endpoint: server.endpoint, - macros: [DeclareXImplementation(), QueryClassImplementation()])); + macros: [DeclareXImplementation(), QueryClassImplementation()], + ), + ); await Future.wait([ - server.sendToMacro(HostRequest.augmentRequest( - id: 1, - macroAnnotation: QualifiedName( + server.sendToMacro( + HostRequest.augmentRequest( + id: 1, + macroAnnotation: QualifiedName( uri: 'package:_test_macros/declare_x_macro.dart', - name: 'DeclareX'), - AugmentRequest(phase: 1, target: fooTarget, model: fooModel), - )), - server.sendToMacro(HostRequest.augmentRequest( - id: 2, - macroAnnotation: QualifiedName( + name: 'DeclareX', + ), + AugmentRequest(phase: 1, target: fooTarget, model: fooModel), + ), + ), + server.sendToMacro( + HostRequest.augmentRequest( + id: 2, + macroAnnotation: QualifiedName( uri: 'package:_test_macros/query_class.dart', - name: 'QueryClass'), - AugmentRequest(phase: 1, target: fooTarget, model: fooModel), - )) + name: 'QueryClass', + ), + AugmentRequest(phase: 1, target: fooTarget, model: fooModel), + ), + ), ]); }); }); @@ -139,10 +198,14 @@ class TestHostService implements HostService { Future handle(MacroRequest request) async { if (request.type == MacroRequestType.macroStartedRequest) { _macroStartedRequestsController.add(request.asMacroStartedRequest); - return Response.macroStartedResponse(MacroStartedResponse(), - requestId: request.id); + return Response.macroStartedResponse( + MacroStartedResponse(), + requestId: request.id, + ); } - return Response.errorResponse(ErrorResponse(error: 'unimplemented'), - requestId: request.id); + return Response.errorResponse( + ErrorResponse(error: 'unimplemented'), + requestId: request.id, + ); } } diff --git a/pkgs/_macro_tool/lib/analyzer_macro_runner.dart b/pkgs/_macro_tool/lib/analyzer_macro_runner.dart index f6a543b1..2cc7f3c8 100644 --- a/pkgs/_macro_tool/lib/analyzer_macro_runner.dart +++ b/pkgs/_macro_tool/lib/analyzer_macro_runner.dart @@ -24,11 +24,13 @@ class AnalyzerMacroRunner implements MacroRunner { late final AnalysisContext analysisContext; AnalyzerMacroImplementation? analyzerMacroImplementation; - AnalyzerMacroRunner( - {required this.workspacePath, required this.packageConfigPath}) - : sourceFiles = SourceFile.findDartInWorkspace(workspacePath) { - final contextCollection = - AnalysisContextCollection(includedPaths: [workspacePath]); + AnalyzerMacroRunner({ + required this.workspacePath, + required this.packageConfigPath, + }) : sourceFiles = SourceFile.findDartInWorkspace(workspacePath) { + final contextCollection = AnalysisContextCollection( + includedPaths: [workspacePath], + ); analysisContext = contextCollection.contexts.single; } @@ -40,10 +42,12 @@ class AnalyzerMacroRunner implements MacroRunner { Future run({bool injectImplementation = true}) async { if (injectImplementation) { analyzerMacroImplementation ??= await AnalyzerMacroImplementation.start( - protocol: Protocol( - encoding: ProtocolEncoding.binary, - version: ProtocolVersion.macros1), - packageConfig: Uri.file(packageConfigPath)); + protocol: Protocol( + encoding: ProtocolEncoding.binary, + version: ProtocolVersion.macros1, + ), + packageConfig: Uri.file(packageConfigPath), + ); injected_analyzer.macroImplementation = analyzerMacroImplementation; } else { injected_analyzer.macroImplementation = null; @@ -59,25 +63,28 @@ class AnalyzerMacroRunner implements MacroRunner { (await analysisContext.currentSession.getResolvedLibrary(sourceFile)) as ResolvedLibraryResult; - final errors = ((await analysisContext.currentSession - .getErrors(sourceFile)) as ErrorsResult) - .errors - .where((e) => e.severity == Severity.error) - .map((e) => e.toString()) - .toList(); + final errors = + ((await analysisContext.currentSession.getErrors(sourceFile)) + as ErrorsResult) + .errors + .where((e) => e.severity == Severity.error) + .map((e) => e.toString()) + .toList(); final augmentationUnits = resolvedLibrary.units.where((u) => u.isMacroPart).toList(); final output = augmentationUnits.singleOrNull?.content; fileResults.add( - FileResult(sourceFile: sourceFile, output: output, errors: errors)); + FileResult(sourceFile: sourceFile, output: output, errors: errors), + ); firstDuration ??= stopwatch.elapsed; } return WorkspaceResult( - fileResults: fileResults, - firstResultAfter: firstDuration!, - lastResultAfter: stopwatch.elapsed); + fileResults: fileResults, + firstResultAfter: firstDuration!, + lastResultAfter: stopwatch.elapsed, + ); } } diff --git a/pkgs/_macro_tool/lib/cfe_macro_runner.dart b/pkgs/_macro_tool/lib/cfe_macro_runner.dart index 1136131e..2045950d 100644 --- a/pkgs/_macro_tool/lib/cfe_macro_runner.dart +++ b/pkgs/_macro_tool/lib/cfe_macro_runner.dart @@ -23,7 +23,7 @@ class CfeMacroRunner implements MacroRunner { CfeMacroImplementation? cfeMacroImplementation; CfeMacroRunner({required this.workspacePath, required this.packageConfigPath}) - : sourceFiles = SourceFile.findDartInWorkspace(workspacePath); + : sourceFiles = SourceFile.findDartInWorkspace(workspacePath); void notifyChange(String sourcePath) { // No incremental compile. @@ -33,8 +33,12 @@ class CfeMacroRunner implements MacroRunner { // TODO(davidmorgan): this dill comes from the Dart SDK running the test, // but `package:frontend_server` and `package:front_end` are used as a // library, so we will see version skew breakage. Find a better way. - final result = File(p.canonicalize('${Platform.resolvedExecutable}/../../' - 'lib/_internal/vm_platform_strong_product.dill')); + final result = File( + p.canonicalize( + '${Platform.resolvedExecutable}/../../' + 'lib/_internal/vm_platform_strong_product.dill', + ), + ); if (!result.existsSync()) { throw StateError('Failed to find platform dill: $result'); } @@ -45,10 +49,12 @@ class CfeMacroRunner implements MacroRunner { Future run({bool injectImplementation = true}) async { if (injectImplementation) { cfeMacroImplementation ??= await CfeMacroImplementation.start( - protocol: Protocol( - encoding: ProtocolEncoding.json, - version: ProtocolVersion.macros1), - packageConfig: Uri.file(packageConfigPath)); + protocol: Protocol( + encoding: ProtocolEncoding.json, + version: ProtocolVersion.macros1, + ), + packageConfig: Uri.file(packageConfigPath), + ); injected_cfe.macroImplementation = cfeMacroImplementation; } else { injected_cfe.macroImplementation = null; @@ -79,23 +85,31 @@ class CfeMacroRunner implements MacroRunner { '--use-incremental-compiler', ]); - final sources = computeKernelResult - .previousState!.incrementalCompiler!.context.uriToSource; + final sources = + computeKernelResult + .previousState! + .incrementalCompiler! + .context + .uriToSource; for (final sourceFile in sourceFiles) { final macroSource = sources[Uri.file(sourceFile.path).replace(scheme: 'dart-macro+file')]; if (macroSource != null) { - fileResults.add(FileResult( + fileResults.add( + FileResult( sourceFile: sourceFile, output: macroSource.text, - errors: computeKernelResult.succeeded ? [] : ['compile failed'])); + errors: computeKernelResult.succeeded ? [] : ['compile failed'], + ), + ); } } return WorkspaceResult( - fileResults: fileResults, - firstResultAfter: stopwatch.elapsed, - lastResultAfter: stopwatch.elapsed); + fileResults: fileResults, + firstResultAfter: stopwatch.elapsed, + lastResultAfter: stopwatch.elapsed, + ); } } diff --git a/pkgs/_macro_tool/lib/macro_runner.dart b/pkgs/_macro_tool/lib/macro_runner.dart index 682908c2..976d77d2 100644 --- a/pkgs/_macro_tool/lib/macro_runner.dart +++ b/pkgs/_macro_tool/lib/macro_runner.dart @@ -34,14 +34,16 @@ class WorkspaceResult { /// Time taken to produce all results. Duration lastResultAfter; - WorkspaceResult( - {required this.fileResults, - required this.firstResultAfter, - required this.lastResultAfter}); + WorkspaceResult({ + required this.fileResults, + required this.firstResultAfter, + required this.lastResultAfter, + }); /// Errors from all [FileResult]s. - List get allErrors => - [for (final result in fileResults) ...result.errors]; + List get allErrors => [ + for (final result in fileResults) ...result.errors, + ]; } /// [MacroRunner] result for one file. @@ -55,6 +57,9 @@ class FileResult { /// Errors for this file. final List errors; - FileResult( - {required this.sourceFile, required this.output, required this.errors}); + FileResult({ + required this.sourceFile, + required this.output, + required this.errors, + }); } diff --git a/pkgs/_macro_tool/lib/macro_tool.dart b/pkgs/_macro_tool/lib/macro_tool.dart index 97ebd307..72670236 100644 --- a/pkgs/_macro_tool/lib/macro_tool.dart +++ b/pkgs/_macro_tool/lib/macro_tool.dart @@ -55,7 +55,8 @@ class MacroTool { void patchForAnalyzer() { if (_applyResult == null) { throw UnsupportedError( - '"patch_for_analyzer" command requires "apply" first.'); + '"patch_for_analyzer" command requires "apply" first.', + ); } for (final result in _applyResult!.fileResults) { @@ -90,17 +91,13 @@ class MacroTool { throw UnsupportedError('"run" command requires "--script".'); } - final result = Process.runSync( - Platform.resolvedExecutable, - [ - 'run', - '--enable-experiment=macros', - '--enable-experiment=enhanced-parts', - '--packages=$packageConfigPath', - scriptPath! - ], - workingDirectory: workspacePath, - ); + final result = Process.runSync(Platform.resolvedExecutable, [ + 'run', + '--enable-experiment=macros', + '--enable-experiment=enhanced-parts', + '--packages=$packageConfigPath', + scriptPath!, + ], workingDirectory: workspacePath); stdout.write(result.stdout); stderr.write(result.stderr); return result.exitCode; @@ -130,8 +127,9 @@ class MacroTool { // Busts caches, applies, throws if error, returns result. Future measure() async { bustCaches(); - _applyResult = - await macroRunner.run(injectImplementation: injectImplementation); + _applyResult = await macroRunner.run( + injectImplementation: injectImplementation, + ); if (_applyResult!.allErrors.isNotEmpty) { throw StateError('Errors: ${_applyResult!.allErrors}'); } @@ -173,7 +171,8 @@ class MacroTool { } if (!cacheBusterFound) { throw StateError( - 'Did not find CACHEBUSTER in any source, no changes were made.'); + 'Did not find CACHEBUSTER in any source, no changes were made.', + ); } } @@ -185,8 +184,10 @@ class MacroTool { // `asBroadcastStream` so repeated use of `first` below waits for the next // change. var events = File(scriptPath!).watch().asBroadcastStream(); - print('Caution: timings can be misleading due to JIT warmup, host ' - 'caching, and random variation. Check with benchmarks :)'); + print( + 'Caution: timings can be misleading due to JIT warmup, host ' + 'caching, and random variation. Check with benchmarks :)', + ); print('Watching for changes to: $scriptPath'); while (true) { _applyResult = await macroRunner.run(); @@ -200,8 +201,9 @@ class MacroTool { } stdout.write( - 'Macros ran in in ${_applyResult!.firstResultAfter.inMilliseconds}ms,' - ' watching...'); + 'Macros ran in in ${_applyResult!.firstResultAfter.inMilliseconds}ms,' + ' watching...', + ); await events.first; print('changed, rerunning.'); macroRunner.notifyChange(SourceFile(scriptPath!)); diff --git a/pkgs/_macro_tool/lib/main.dart b/pkgs/_macro_tool/lib/main.dart index b24551ce..5b45acb9 100644 --- a/pkgs/_macro_tool/lib/main.dart +++ b/pkgs/_macro_tool/lib/main.dart @@ -11,14 +11,21 @@ import 'analyzer_macro_runner.dart'; import 'cfe_macro_runner.dart'; import 'macro_tool.dart'; -final argParser = ArgParser() - ..addOption('host', - defaultsTo: 'analyzer', help: 'The macro host: "analyzer" or "cfe".') - ..addOption('workspace', help: 'Path to workspace.') - ..addOption('packageConfig', help: 'Path to package config.') - ..addOption('script', help: 'Path to script.') - ..addOption('benchmark-iterations', - defaultsTo: '5', help: 'Benchmark iterations.'); +final argParser = + ArgParser() + ..addOption( + 'host', + defaultsTo: 'analyzer', + help: 'The macro host: "analyzer" or "cfe".', + ) + ..addOption('workspace', help: 'Path to workspace.') + ..addOption('packageConfig', help: 'Path to package config.') + ..addOption('script', help: 'Path to script.') + ..addOption( + 'benchmark-iterations', + defaultsTo: '5', + help: 'Benchmark iterations.', + ); Future main(List arguments) async { final args = argParser.parse(arguments); @@ -45,15 +52,16 @@ ${argParser.usage}'''); final canonicalizedWorkspace = p.canonicalize(workspace); final tool = MacroTool( - macroRunner: host == HostOption.analyzer - ? AnalyzerMacroRunner( - packageConfigPath: canonicalizedPackageConfig, - workspacePath: canonicalizedWorkspace, - ) - : CfeMacroRunner( - packageConfigPath: canonicalizedPackageConfig, - workspacePath: canonicalizedWorkspace, - ), + macroRunner: + host == HostOption.analyzer + ? AnalyzerMacroRunner( + packageConfigPath: canonicalizedPackageConfig, + workspacePath: canonicalizedWorkspace, + ) + : CfeMacroRunner( + packageConfigPath: canonicalizedPackageConfig, + workspacePath: canonicalizedWorkspace, + ), packageConfigPath: canonicalizedPackageConfig, workspacePath: canonicalizedWorkspace, benchmarkIterations: int.parse(args['benchmark-iterations']), @@ -95,8 +103,8 @@ enum HostOption { cfe; static HostOption? forString(String? option) => switch (option) { - 'analyzer' => HostOption.analyzer, - 'cfe' => HostOption.cfe, - _ => throw ArgumentError('Not a valid host: $option'), - }; + 'analyzer' => HostOption.analyzer, + 'cfe' => HostOption.cfe, + _ => throw ArgumentError('Not a valid host: $option'), + }; } diff --git a/pkgs/_macro_tool/lib/source_file.dart b/pkgs/_macro_tool/lib/source_file.dart index 58f6f34a..c9ed3f7a 100644 --- a/pkgs/_macro_tool/lib/source_file.dart +++ b/pkgs/_macro_tool/lib/source_file.dart @@ -49,8 +49,12 @@ extension type SourceFile(String path) implements String { final line = "part '$partName'; $_addedMarker\n"; final file = File(path); - file.writeAsStringSync(_insertAfterLastImport( - line, _removeToolAddedLinesFromSource(file.readAsStringSync()))); + file.writeAsStringSync( + _insertAfterLastImport( + line, + _removeToolAddedLinesFromSource(file.readAsStringSync()), + ), + ); macroRunner.notifyChange(path); } @@ -77,13 +81,17 @@ extension type SourceFile(String path) implements String { final file = File(path); file.writeAsStringSync( - line + _removeToolAddedLinesFromSource(file.readAsStringSync())); + line + _removeToolAddedLinesFromSource(file.readAsStringSync()), + ); macroRunner.notifyChange(path); final toolOutputFile = File(toolOutputPath); - toolOutputFile.writeAsStringSync(toolOutputFile - .readAsStringSync() - .replaceAll('part of ', 'augment library ')); + toolOutputFile.writeAsStringSync( + toolOutputFile.readAsStringSync().replaceAll( + 'part of ', + 'augment library ', + ), + ); macroRunner.notifyChange(toolOutputPath); } @@ -93,8 +101,11 @@ extension type SourceFile(String path) implements String { /// [macroRunner] is notified of the change. void revert(MacroRunner macroRunner) { final file = File(path); - file.writeAsStringSync(_resetCacheBusters( - _removeToolAddedLinesFromSource(file.readAsStringSync()))); + file.writeAsStringSync( + _resetCacheBusters( + _removeToolAddedLinesFromSource(file.readAsStringSync()), + ), + ); macroRunner.notifyChange(path); final toolOutputFile = File(toolOutputPath); if (toolOutputFile.existsSync()) { @@ -118,20 +129,19 @@ extension type SourceFile(String path) implements String { /// /// [macroRunner] is notified of the change. bool bustCaches(MacroRunner macroRunner) { - final token = _random.nextInt(1 << 32).toRadixString(16) + + final token = + _random.nextInt(1 << 32).toRadixString(16) + _random.nextInt(1 << 32).toRadixString(16); var cacheBusterFound = false; - for (final path in [ - path, - toolOutputPath, - ]) { + for (final path in [path, toolOutputPath]) { final file = File(path); if (!file.existsSync()) continue; final source = file.readAsStringSync(); if (source.contains(_cacheBusterRegexp)) { cacheBusterFound = true; file.writeAsStringSync( - source.replaceAll(_cacheBusterRegexp, '$_cacheBusterString$token')); + source.replaceAll(_cacheBusterRegexp, '$_cacheBusterString$token'), + ); macroRunner.notifyChange(path); } } diff --git a/pkgs/_macro_tool/pubspec.yaml b/pkgs/_macro_tool/pubspec.yaml index 081c61de..c264e9d5 100644 --- a/pkgs/_macro_tool/pubspec.yaml +++ b/pkgs/_macro_tool/pubspec.yaml @@ -4,7 +4,7 @@ description: >- CLI for running code with macros applied. resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: _analyzer_macros: any diff --git a/pkgs/_macro_tool/test/macro_tool_test.dart b/pkgs/_macro_tool/test/macro_tool_test.dart index 5d42822b..01013bef 100644 --- a/pkgs/_macro_tool/test/macro_tool_test.dart +++ b/pkgs/_macro_tool/test/macro_tool_test.dart @@ -16,30 +16,32 @@ void main() { test('apply macros with analyzer then run', () async { expect( - await macro_tool.main([ - '--workspace=test/package_under_test', - '--packageConfig=../../.dart_tool/package_config.json', - '--script=test/package_under_test/lib/apply_declare_x.dart', - 'apply', - 'patch_for_cfe', - 'run', - ]), - // The script exit code is the macro-generated value: 3. - 3); + await macro_tool.main([ + '--workspace=test/package_under_test', + '--packageConfig=../../.dart_tool/package_config.json', + '--script=test/package_under_test/lib/apply_declare_x.dart', + 'apply', + 'patch_for_cfe', + 'run', + ]), + // The script exit code is the macro-generated value: 3. + 3, + ); }); test('apply macros with CFE then run', () async { expect( - await macro_tool.main([ - '--workspace=test/package_under_test', - '--packageConfig=../../.dart_tool/package_config.json', - '--script=test/package_under_test/lib/apply_declare_x.dart', - '--host=cfe', - 'apply', - 'patch_for_cfe', - 'run', - ]), - // The script exit code is the macro-generated value: 3. - 3); + await macro_tool.main([ + '--workspace=test/package_under_test', + '--packageConfig=../../.dart_tool/package_config.json', + '--script=test/package_under_test/lib/apply_declare_x.dart', + '--host=cfe', + 'apply', + 'patch_for_cfe', + 'run', + ]), + // The script exit code is the macro-generated value: 3. + 3, + ); }); } diff --git a/pkgs/_macro_tool/test/package_under_test/pubspec.yaml b/pkgs/_macro_tool/test/package_under_test/pubspec.yaml index 420931f6..d39c42cc 100644 --- a/pkgs/_macro_tool/test/package_under_test/pubspec.yaml +++ b/pkgs/_macro_tool/test/package_under_test/pubspec.yaml @@ -3,7 +3,7 @@ publish-to: none resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: _test_macros: any diff --git a/pkgs/_test_macros/lib/declare_x_macro.dart b/pkgs/_test_macros/lib/declare_x_macro.dart index e3b414ad..612489a1 100644 --- a/pkgs/_test_macros/lib/declare_x_macro.dart +++ b/pkgs/_test_macros/lib/declare_x_macro.dart @@ -17,13 +17,17 @@ class DeclareXImplementation implements ClassDeclarationsMacro { // TODO(davidmorgan): this should be injected by the bootstrap script. @override MacroDescription get description => MacroDescription( - annotation: QualifiedName( - uri: 'package:_test_macros/declare_x_macro.dart', name: 'DeclareX'), - runsInPhases: [2]); + annotation: QualifiedName( + uri: 'package:_test_macros/declare_x_macro.dart', + name: 'DeclareX', + ), + runsInPhases: [2], + ); @override void buildDeclarationsForClass(ClassDeclarationsBuilder builder) { - builder - .declareInType(Augmentation(code: expandTemplate('int get x => 3;'))); + builder.declareInType( + Augmentation(code: expandTemplate('int get x => 3;')), + ); } } diff --git a/pkgs/_test_macros/lib/json_codable.dart b/pkgs/_test_macros/lib/json_codable.dart index 5f886b79..04ad6de6 100644 --- a/pkgs/_test_macros/lib/json_codable.dart +++ b/pkgs/_test_macros/lib/json_codable.dart @@ -22,30 +22,42 @@ class JsonCodableImplementation implements ClassDeclarationsMacro, ClassDefinitionsMacro { @override MacroDescription get description => MacroDescription( - annotation: QualifiedName( - uri: 'package:_test_macros/json_codable.dart', name: 'JsonCodable'), - runsInPhases: [2, 3]); + annotation: QualifiedName( + uri: 'package:_test_macros/json_codable.dart', + name: 'JsonCodable', + ), + runsInPhases: [2, 3], + ); @override void buildDeclarationsForClass(ClassDeclarationsBuilder builder) { final name = builder.model.qualifiedNameOf(builder.target.node)!.name; builder - ..declareInType(Augmentation(code: expandTemplate(''' + ..declareInType( + Augmentation( + code: expandTemplate(''' // TODO(davidmorgan): see https://github.com/dart-lang/macros/issues/80. // external $name.fromJson($_jsonMapType json); - '''))) - ..declareInType(Augmentation(code: expandTemplate(''' + '''), + ), + ) + ..declareInType( + Augmentation( + code: expandTemplate(''' // TODO(davidmorgan): see https://github.com/dart-lang/macros/issues/80. // external $_jsonMapType toJson(); - '''))); + '''), + ), + ); } @override void buildDefinitionsForClass(ClassDefinitionsBuilder builder) async { final qualifiedName = builder.model.qualifiedNameOf(builder.target.node)!; // TODO(davidmorgan): put `extends` information directly in `Interface`. - final superclassName = - MacroScope.current.typeSystem.supertypeOf(qualifiedName); + final superclassName = MacroScope.current.typeSystem.supertypeOf( + qualifiedName, + ); await _generateFromJson(builder, qualifiedName, superclassName); await _generateToJson(builder, qualifiedName, superclassName); @@ -69,19 +81,22 @@ class JsonCodableImplementation } else { // TODO(davidmorgan): report as a diagnostic. throw ArgumentError( - 'Serialization of classes that extend other classes is only ' - 'supported if those classes have a valid ' - '`fromJson(Map json)` constructor.'); + 'Serialization of classes that extend other classes is only ' + 'supported if those classes have a valid ' + '`fromJson(Map json)` constructor.', + ); } } final initializers = []; - for (final field in builder.target.members.entries - .where((m) => m.value.properties.isField)) { + for (final field in builder.target.members.entries.where( + (m) => m.value.properties.isField, + )) { final name = field.key; final type = field.value.returnType; - initializers - .add('$name = ${_convertTypeFromJson("json[r'$name']", type)}'); + initializers.add( + '$name = ${_convertTypeFromJson("json[r'$name']", type)}', + ); } if (superclassHasFromJson) { @@ -89,12 +104,17 @@ class JsonCodableImplementation } builder - .buildConstructor(builder.model - .qualifiedNameOf(builder.target.members['fromJson']!.node)!) - .augment(initializers: [ - for (var initializer in initializers) - Augmentation(code: expandTemplate(initializer)), - ]); + .buildConstructor( + builder.model.qualifiedNameOf( + builder.target.members['fromJson']!.node, + )!, + ) + .augment( + initializers: [ + for (var initializer in initializers) + Augmentation(code: expandTemplate(initializer)), + ], + ); } Future _generateToJson( @@ -114,15 +134,17 @@ class JsonCodableImplementation } else { // TODO(davidmorgan): report as a diagnostic. throw ArgumentError( - 'Serialization of classes that extend other classes is only ' - 'supported if those classes have a valid ' - '`Map json toJson()` method.'); + 'Serialization of classes that extend other classes is only ' + 'supported if those classes have a valid ' + '`Map json toJson()` method.', + ); } } final serializers = []; - for (final field in builder.target.members.entries - .where((m) => m.value.properties.isField)) { + for (final field in builder.target.members.entries.where( + (m) => m.value.properties.isField, + )) { final name = field.key; final type = field.value.returnType; var serializer = "json[r'$name'] = ${_convertTypeToJson(name, type)};\n"; @@ -137,15 +159,22 @@ class JsonCodableImplementation final jsonInitializer = superclassHasToJson ? 'super.toJson()' : '$_jsonMapTypeForLiteral{}'; builder - .buildMethod(builder.model - .qualifiedNameOf(builder.target.members['toJson']!.node)!) - .augment(body: Augmentation(code: expandTemplate(''' + .buildMethod( + builder.model.qualifiedNameOf( + builder.target.members['toJson']!.node, + )!, + ) + .augment( + body: Augmentation( + code: expandTemplate(''' { final json = $jsonInitializer; ${serializers.join('')} return json; } -'''))); +'''), + ), + ); } /// Returns whether [constructor] is a constructor @@ -158,7 +187,8 @@ ${serializers.join('')} constructor.requiredPositionalParameters[0].type == StaticTypeDescType.namedTypeDesc && _isJsonMapType( - constructor.requiredPositionalParameters[0].asNamedTypeDesc); + constructor.requiredPositionalParameters[0].asNamedTypeDesc, + ); /// Returns whether [method] is a method /// `toJson(Map)`. @@ -176,7 +206,12 @@ ${serializers.join('')} type.instantiation[0].asNamedTypeDesc.name.asString == 'dart:core#String' && type.instantiation[1].type == StaticTypeDescType.nullableTypeDesc && - type.instantiation[1].asNullableTypeDesc.inner.asNamedTypeDesc.name + type + .instantiation[1] + .asNullableTypeDesc + .inner + .asNamedTypeDesc + .name .asString == 'dart:core#Object'; @@ -188,9 +223,10 @@ ${serializers.join('')} final nullable = type.type == StaticTypeDescType.nullableTypeDesc; final orNull = nullable ? '?' : ''; final nullCheck = nullable ? '$reference == null ? null : ' : ''; - final underlyingType = type.type == StaticTypeDescType.nullableTypeDesc - ? type.asNullableTypeDesc.inner - : type; + final underlyingType = + type.type == StaticTypeDescType.nullableTypeDesc + ? type.asNullableTypeDesc.inner + : type; if (underlyingType.type == StaticTypeDescType.namedTypeDesc) { final namedType = underlyingType.asNamedTypeDesc; @@ -237,9 +273,10 @@ ${serializers.join('')} final nullable = type.type == StaticTypeDescType.nullableTypeDesc; final nullCheck = nullable ? '$reference == null ? null : ' : ''; final nullCheckedReference = nullable ? '$reference!' : reference; - final underlyingType = type.type == StaticTypeDescType.nullableTypeDesc - ? type.asNullableTypeDesc.inner - : type; + final underlyingType = + type.type == StaticTypeDescType.nullableTypeDesc + ? type.asNullableTypeDesc.inner + : type; if (underlyingType.type == StaticTypeDescType.namedTypeDesc) { final namedType = underlyingType.asNamedTypeDesc; diff --git a/pkgs/_test_macros/lib/literal_params.dart b/pkgs/_test_macros/lib/literal_params.dart index 2659e5e6..9bbeae20 100644 --- a/pkgs/_test_macros/lib/literal_params.dart +++ b/pkgs/_test_macros/lib/literal_params.dart @@ -29,48 +29,62 @@ class LiteralParams { final List? strings; final List? objects; - const LiteralParams( - {required this.anInt, - this.aNum, - this.aDouble, - this.aString, - this.anObject, - this.ints, - this.nums, - this.doubles, - this.strings, - this.objects}); + const LiteralParams({ + required this.anInt, + this.aNum, + this.aDouble, + this.aString, + this.anObject, + this.ints, + this.nums, + this.doubles, + this.strings, + this.objects, + }); } class LiteralParamsImplementation implements ClassDeclarationsMacro { // TODO(davidmorgan): this should be injected by the bootstrap script. @override MacroDescription get description => MacroDescription( - annotation: QualifiedName( - uri: 'package:_test_macros/literal_params.dart', - name: 'LiteralParams'), - runsInPhases: [2]); + annotation: QualifiedName( + uri: 'package:_test_macros/literal_params.dart', + name: 'LiteralParams', + ), + runsInPhases: [2], + ); @override Future buildDeclarationsForClass( - ClassDeclarationsBuilder builder) async { + ClassDeclarationsBuilder builder, + ) async { // TODO(davidmorgan): need a way to find the correct annotation, this just // uses the first. - final annotation = builder - .target.metadataAnnotations.first.expression.asConstructorInvocation; + final annotation = + builder + .target + .metadataAnnotations + .first + .expression + .asConstructorInvocation; final namedArguments = { for (final argument in annotation.arguments) if (argument.type == ArgumentType.namedArgument) argument.asNamedArgument.name: - argument.asNamedArgument.expression.evaluate + argument.asNamedArgument.expression.evaluate, }; - builder.declareInType(Augmentation( - code: expandTemplate([ - for (final entry in namedArguments.entries) - ' // ${entry.key}: ${entry.value}, ${entry.value.runtimeType}', - ].join('\n')))); + builder.declareInType( + Augmentation( + code: expandTemplate( + [ + for (final entry in namedArguments.entries) + ' // ${entry.key}: ${entry.value}, ${entry.value.runtimeType}', + ].join('\n'), + ), + ), + ); } } @@ -78,44 +92,49 @@ class LiteralParamsImplementation implements ClassDeclarationsMacro { // all have to write expression evaluation code. extension ExpressionExtension on Expression { Object get evaluate => switch (type) { - ExpressionType.integerLiteral => int.parse(asIntegerLiteral.text), - ExpressionType.doubleLiteral => double.parse(asDoubleLiteral.text), - ExpressionType.stringLiteral => asStringLiteral.evaluate, - ExpressionType.booleanLiteral => bool.parse(asBooleanLiteral.text), - ExpressionType.listLiteral => - asListLiteral.elements.map((e) => e.evaluate).toList(), - // TODO(davidmorgan): need the type name to do something useful here, - // for now just return the JSON. - ExpressionType.constructorInvocation => - asConstructorInvocation.toString(), - // TODO(davidmorgan): need to follow references to do something useful - // here, for now just return the JSON. - ExpressionType.staticGet => asStaticGet.toString(), - _ => throw UnsupportedError( - 'Not supported in @LiteralParams annotation: $this'), - }; + ExpressionType.integerLiteral => int.parse(asIntegerLiteral.text), + ExpressionType.doubleLiteral => double.parse(asDoubleLiteral.text), + ExpressionType.stringLiteral => asStringLiteral.evaluate, + ExpressionType.booleanLiteral => bool.parse(asBooleanLiteral.text), + ExpressionType.listLiteral => + asListLiteral.elements.map((e) => e.evaluate).toList(), + // TODO(davidmorgan): need the type name to do something useful here, + // for now just return the JSON. + ExpressionType.constructorInvocation => asConstructorInvocation.toString(), + // TODO(davidmorgan): need to follow references to do something useful + // here, for now just return the JSON. + ExpressionType.staticGet => asStaticGet.toString(), + _ => + throw UnsupportedError( + 'Not supported in @LiteralParams annotation: $this', + ), + }; } extension ElementExtension on Element { Object get evaluate => switch (type) { - ElementType.expressionElement => - asExpressionElement.expression.evaluate, - _ => throw UnsupportedError( - 'Not supported in @LiteralParams annotation: $this'), - }; + ElementType.expressionElement => asExpressionElement.expression.evaluate, + _ => + throw UnsupportedError( + 'Not supported in @LiteralParams annotation: $this', + ), + }; } extension StringLiteralExtension on StringLiteral { Object get evaluate { if (parts.length != 1) { throw UnsupportedError( - 'Not supported in @LiteralParams annotation: $this'); + 'Not supported in @LiteralParams annotation: $this', + ); } final part = parts.single; return switch (part.type) { StringLiteralPartType.stringPart => part.asStringPart.text, - _ => throw UnsupportedError( - 'Not supported in @LiteralParams annotation: $this'), + _ => + throw UnsupportedError( + 'Not supported in @LiteralParams annotation: $this', + ), }; } } diff --git a/pkgs/_test_macros/lib/query_class.dart b/pkgs/_test_macros/lib/query_class.dart index 92b01070..5fcd8a2e 100644 --- a/pkgs/_test_macros/lib/query_class.dart +++ b/pkgs/_test_macros/lib/query_class.dart @@ -20,16 +20,21 @@ class QueryClassImplementation implements ClassDefinitionsMacro { // TODO(davidmorgan): this should be injected by the bootstrap script. @override MacroDescription get description => MacroDescription( - annotation: QualifiedName( - uri: 'package:_test_macros/query_class.dart', name: 'QueryClass'), - runsInPhases: [3]); + annotation: QualifiedName( + uri: 'package:_test_macros/query_class.dart', + name: 'QueryClass', + ), + runsInPhases: [3], + ); @override Future buildDefinitionsForClass(ClassDefinitionsBuilder builder) async { final qualifiedName = builder.model.qualifiedNameOf(builder.target.node)!; final result = await builder.query(Query(target: qualifiedName)); builder.augment( - docCommentsAndMetadata: - Augmentation(code: expandTemplate('// ${json.encode(result)}'))); + docCommentsAndMetadata: Augmentation( + code: expandTemplate('// ${json.encode(result)}'), + ), + ); } } diff --git a/pkgs/_test_macros/pubspec.yaml b/pkgs/_test_macros/pubspec.yaml index 75c2eb6a..ed8471c2 100644 --- a/pkgs/_test_macros/pubspec.yaml +++ b/pkgs/_test_macros/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/dart-lang/macros/tree/master/pkgs/_test_macros resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: dart_model: any diff --git a/pkgs/dart_model/benchmark/builder_maps_builder_wire_benchmark.dart b/pkgs/dart_model/benchmark/builder_maps_builder_wire_benchmark.dart index 98c068d3..6b0fba05 100644 --- a/pkgs/dart_model/benchmark/builder_maps_builder_wire_benchmark.dart +++ b/pkgs/dart_model/benchmark/builder_maps_builder_wire_benchmark.dart @@ -25,14 +25,16 @@ class BuilderMapsBuilderWireBenchmark extends SerializationBenchmark { final intKey = int.parse(key); final members = buffer.createGrowableMap(); map[key] = Interface( - members: members, - properties: Properties( - isAbstract: (intKey & 1) == 1, - isClass: (intKey & 2) == 2, - isGetter: (intKey & 4) == 4, - isField: (intKey & 8) == 8, - isMethod: (intKey & 16) == 16, - isStatic: (intKey & 32) == 32)); + members: members, + properties: Properties( + isAbstract: (intKey & 1) == 1, + isClass: (intKey & 2) == 2, + isGetter: (intKey & 4) == 4, + isField: (intKey & 8) == 8, + isMethod: (intKey & 16) == 16, + isStatic: (intKey & 32) == 32, + ), + ); for (final memberName in makeMemberNames(intKey)) { members[memberName] = _makeMember(memberName); } @@ -49,13 +51,15 @@ class BuilderMapsBuilderWireBenchmark extends SerializationBenchmark { Member _makeMember(String key) { final intKey = key.length; return Member( - properties: Properties( - isAbstract: (intKey & 1) == 1, - isClass: (intKey & 2) == 2, - isGetter: (intKey & 4) == 4, - isField: const [true, false, null][intKey % 3], - isMethod: (intKey & 16) == 16, - isStatic: (intKey & 32) == 32)); + properties: Properties( + isAbstract: (intKey & 1) == 1, + isClass: (intKey & 2) == 2, + isGetter: (intKey & 4) == 4, + isField: const [true, false, null][intKey % 3], + isMethod: (intKey & 16) == 16, + isStatic: (intKey & 32) == 32, + ), + ); } } @@ -66,11 +70,8 @@ extension type Interface.fromJson(Map node) { 'properties': Type.typedMapPointer, }); - Interface({ - Map? members, - Properties? properties, - }) : this.fromJson( - runningBuffer!.createTypedMap(schema, members, properties)); + Interface({Map? members, Properties? properties}) + : this.fromJson(runningBuffer!.createTypedMap(schema, members, properties)); /// Map of members by name. Map get members => (node['members'] as Map).cast(); @@ -80,13 +81,12 @@ extension type Interface.fromJson(Map node) { } extension type Member.fromJson(Map node) { - static TypedMapSchema schema = TypedMapSchema( - {'properties': Type.typedMapPointer}, - ); + static TypedMapSchema schema = TypedMapSchema({ + 'properties': Type.typedMapPointer, + }); - Member({ - Properties? properties, - }) : this.fromJson(runningBuffer!.createTypedMap(schema, properties)); + Member({Properties? properties}) + : this.fromJson(runningBuffer!.createTypedMap(schema, properties)); /// The properties of this member. Properties get properties => node['properties'] as Properties; @@ -110,8 +110,17 @@ extension type Properties.fromJson(Map node) { bool? isField, bool? isMethod, bool? isStatic, - }) : this.fromJson(runningBuffer!.createTypedMap(schema, isAbstract, isClass, - isGetter, isField, isMethod, isStatic)); + }) : this.fromJson( + runningBuffer!.createTypedMap( + schema, + isAbstract, + isClass, + isGetter, + isField, + isMethod, + isStatic, + ), + ); /// Whether the entity is abstract, meaning it has no definition. bool get isAbstract => node['isAbstract'] as bool; diff --git a/pkgs/dart_model/benchmark/json_buffer.dart b/pkgs/dart_model/benchmark/json_buffer.dart index 44a995f8..56a7e92b 100644 --- a/pkgs/dart_model/benchmark/json_buffer.dart +++ b/pkgs/dart_model/benchmark/json_buffer.dart @@ -138,8 +138,11 @@ class JsonBuffer { final key = keys[i]; _writeInt(start + _intSize + i * _intSize * 2, _intSize, _addString(key)); final value = lookup(key); - _writeInt(start + _intSize + i * _intSize * 2 + _intSize, _intSize, - _addValue(value)); + _writeInt( + start + _intSize + i * _intSize * 2 + _intSize, + _intSize, + _addValue(value), + ); } } @@ -327,7 +330,8 @@ class JsonBuffer { if (maybeResult != null) return maybeResult; final length = _readInt(pointer, _intSize); return _decodedStrings[pointer] ??= utf8.decode( - _buffer.sublist(pointer + _intSize, pointer + _intSize + length)); + _buffer.sublist(pointer + _intSize, pointer + _intSize + length), + ); } /// Reads the `bool` at [_Pointer]. @@ -364,14 +368,18 @@ class _JsonBufferMap } @override - late Iterable keys = - _JsonBufferMapEntryIterable(_buffer, _pointer, readValues: false) - .map((e) => e.key); + late Iterable keys = _JsonBufferMapEntryIterable( + _buffer, + _pointer, + readValues: false, + ).map((e) => e.key); @override - late Iterable values = - _JsonBufferMapEntryIterable(_buffer, _pointer, readKeys: false) - .map((e) => e.value); + late Iterable values = _JsonBufferMapEntryIterable( + _buffer, + _pointer, + readKeys: false, + ).map((e) => e.value); @override late Iterable> entries = @@ -402,13 +410,21 @@ class _JsonBufferMapEntryIterable final bool readKeys; final bool readValues; - _JsonBufferMapEntryIterable(this._buffer, this._pointer, - {this.readKeys = true, this.readValues = true}); + _JsonBufferMapEntryIterable( + this._buffer, + this._pointer, { + this.readKeys = true, + this.readValues = true, + }); @override Iterator> get iterator => - _JsonBufferMapEntryIterator(_buffer, _pointer, - readKeys: readKeys, readValues: readValues); + _JsonBufferMapEntryIterator( + _buffer, + _pointer, + readKeys: readKeys, + readValues: readValues, + ); } /// `Iterator` that reads a `Map` in a [JsonBuffer]. @@ -422,19 +438,24 @@ class _JsonBufferMapEntryIterator final bool readKeys; final bool readValues; - _JsonBufferMapEntryIterator(this._buffer, _Pointer pointer, - {this.readKeys = true, this.readValues = true}) - : _last = pointer + - _intSize + - _buffer._readInt(pointer, _intSize) * 2 * _intSize, - _pointer = pointer - _intSize; + _JsonBufferMapEntryIterator( + this._buffer, + _Pointer pointer, { + this.readKeys = true, + this.readValues = true, + }) : _last = + pointer + + _intSize + + _buffer._readInt(pointer, _intSize) * 2 * _intSize, + _pointer = pointer - _intSize; @override MapEntry get current => MapEntry( - readKeys ? _buffer._readString(_buffer._readPointer(_pointer)) : '', - readValues - ? _buffer._readValue(_buffer._readPointer(_pointer + _intSize)) - : null); + readKeys ? _buffer._readString(_buffer._readPointer(_pointer)) : '', + readValues + ? _buffer._readValue(_buffer._readPointer(_pointer + _intSize)) + : null, + ); @override bool moveNext() { @@ -459,8 +480,9 @@ class _JsonBufferList with ListMixin implements List { throw UnsupportedError('JsonBufferList is readonly.'); @override - Object? operator [](int index) => _buffer - ._readValue(_buffer._readPointer(_pointer + _intSize + index * _intSize)); + Object? operator [](int index) => _buffer._readValue( + _buffer._readPointer(_pointer + _intSize + index * _intSize), + ); @override void operator []=(int index, Object? value) { @@ -480,13 +502,7 @@ typedef _Pointer = int; /// /// TODO(davidmorgan): we can get more use out of "type" bytes, for example /// encoding bools directly in the type byte. -enum Type { - string, - bool, - map, - list, - int, -} +enum Type { string, bool, map, list, int } /// Bytes needed by [Type]. final _typeSize = 1; diff --git a/pkgs/dart_model/benchmark/lazy_maps_buffer_wire_benchmark.dart b/pkgs/dart_model/benchmark/lazy_maps_buffer_wire_benchmark.dart index 4302423a..34259b5b 100644 --- a/pkgs/dart_model/benchmark/lazy_maps_buffer_wire_benchmark.dart +++ b/pkgs/dart_model/benchmark/lazy_maps_buffer_wire_benchmark.dart @@ -51,19 +51,20 @@ class LazyMapsBufferWireBenchmark extends SerializationBenchmark { /// An interface. extension type Interface.fromJson(Map node) { - Interface({ - Map? members, - Properties? properties, - }) : this.fromJson(LazyMap( - [ - if (members != null) 'members', - if (properties != null) 'properties', - ], - (key) => switch (key) { - 'members' => members, - 'properties' => properties, - _ => null, - })); + Interface({Map? members, Properties? properties}) + : this.fromJson( + LazyMap( + [ + if (members != null) 'members', + if (properties != null) 'properties', + ], + (key) => switch (key) { + 'members' => members, + 'properties' => properties, + _ => null, + }, + ), + ); /// Map of members by name. Map get members => (node['members'] as Map).cast(); @@ -73,16 +74,16 @@ extension type Interface.fromJson(Map node) { } extension type Member.fromJson(Map node) { - Member({ - Properties? properties, - }) : this.fromJson(LazyMap( - [ - if (properties != null) 'properties', - ], - (key) => switch (key) { - 'properties' => properties, - _ => null, - })); + Member({Properties? properties}) + : this.fromJson( + LazyMap( + [if (properties != null) 'properties'], + (key) => switch (key) { + 'properties' => properties, + _ => null, + }, + ), + ); /// The properties of this member. Properties get properties => node['properties'] as Properties; @@ -97,24 +98,27 @@ extension type Properties.fromJson(Map node) { bool? isField, bool? isMethod, bool? isStatic, - }) : this.fromJson(LazyMap( - [ - if (isAbstract != null) 'isAbstract', - if (isClass != null) 'isClass', - if (isGetter != null) 'isGetter', - if (isField != null) 'isField', - if (isMethod != null) 'isMethod', - if (isStatic != null) 'isStatic', - ], - (key) => switch (key) { - 'isAbstract' => isAbstract, - 'isClass' => isClass, - 'isGetter' => isGetter, - 'isField' => isField, - 'isMethod' => isMethod, - 'isStatic' => isStatic, - _ => null, - })); + }) : this.fromJson( + LazyMap( + [ + if (isAbstract != null) 'isAbstract', + if (isClass != null) 'isClass', + if (isGetter != null) 'isGetter', + if (isField != null) 'isField', + if (isMethod != null) 'isMethod', + if (isStatic != null) 'isStatic', + ], + (key) => switch (key) { + 'isAbstract' => isAbstract, + 'isClass' => isClass, + 'isGetter' => isGetter, + 'isField' => isField, + 'isMethod' => isMethod, + 'isStatic' => isStatic, + _ => null, + }, + ), + ); /// Whether the entity is abstract, meaning it has no definition. bool get isAbstract => node['isAbstract'] as bool; diff --git a/pkgs/dart_model/benchmark/main.dart b/pkgs/dart_model/benchmark/main.dart index 5b09f0d2..21c7c66a 100644 --- a/pkgs/dart_model/benchmark/main.dart +++ b/pkgs/dart_model/benchmark/main.dart @@ -52,9 +52,12 @@ void main() { for (final benchmark in serializationBenchmarks.skip(1)) { if (!const DeepCollectionEquality().equals( - benchmark.deserialized, serializationBenchmarks.first.deserialized)) { + benchmark.deserialized, + serializationBenchmarks.first.deserialized, + )) { throw StateError( - 'Validation failed for ${benchmark.name}, deserialized does not match.'); + 'Validation failed for ${benchmark.name}, deserialized does not match.', + ); } } print('\nDeserialized output validated.\n'); diff --git a/pkgs/dart_model/benchmark/sdk_maps_json_wire_benchmark.dart b/pkgs/dart_model/benchmark/sdk_maps_json_wire_benchmark.dart index 1a411289..81c8e384 100644 --- a/pkgs/dart_model/benchmark/sdk_maps_json_wire_benchmark.dart +++ b/pkgs/dart_model/benchmark/sdk_maps_json_wire_benchmark.dart @@ -15,21 +15,27 @@ class SdkMapsJsonWireBenchmark extends SerializationBenchmark { } Map createData() { - return Map.fromIterable(mapKeys, value: (key) { - final intKey = int.parse(key as String); - return Interface( - members: Map.fromIterable(makeMemberNames(intKey), - value: (k) => _makeMember(k as String)).cast(), - properties: Properties( - isAbstract: (intKey & 1) == 1, - isClass: (intKey & 2) == 2, - isGetter: (intKey & 4) == 4, - isField: (intKey & 8) == 8, - isMethod: (intKey & 16) == 16, - isStatic: (intKey & 32) == 32, - ), - ); - }); + return Map.fromIterable( + mapKeys, + value: (key) { + final intKey = int.parse(key as String); + return Interface( + members: + Map.fromIterable( + makeMemberNames(intKey), + value: (k) => _makeMember(k as String), + ).cast(), + properties: Properties( + isAbstract: (intKey & 1) == 1, + isClass: (intKey & 2) == 2, + isGetter: (intKey & 4) == 4, + isField: (intKey & 8) == 8, + isMethod: (intKey & 16) == 16, + isStatic: (intKey & 32) == 32, + ), + ); + }, + ); } Member _makeMember(String key) { @@ -54,13 +60,11 @@ class SdkMapsJsonWireBenchmark extends SerializationBenchmark { /// An interface. extension type Interface.fromJson(Map node) { - Interface({ - Map? members, - Properties? properties, - }) : this.fromJson({ - if (members != null) 'members': members, - if (properties != null) 'properties': properties, - }); + Interface({Map? members, Properties? properties}) + : this.fromJson({ + if (members != null) 'members': members, + if (properties != null) 'properties': properties, + }); /// Map of members by name. Map get members => (node['members'] as Map).cast(); @@ -70,11 +74,8 @@ extension type Interface.fromJson(Map node) { } extension type Member.fromJson(Map node) { - Member({ - Properties? properties, - }) : this.fromJson({ - if (properties != null) 'properties': properties, - }); + Member({Properties? properties}) + : this.fromJson({if (properties != null) 'properties': properties}); /// The properties of this member. Properties get properties => node['properties'] as Properties; @@ -90,13 +91,13 @@ extension type Properties.fromJson(Map node) { bool? isMethod, bool? isStatic, }) : this.fromJson({ - if (isAbstract != null) 'isAbstract': isAbstract, - if (isClass != null) 'isClass': isClass, - if (isGetter != null) 'isGetter': isGetter, - if (isField != null) 'isField': isField, - if (isMethod != null) 'isMethod': isMethod, - if (isStatic != null) 'isStatic': isStatic, - }); + if (isAbstract != null) 'isAbstract': isAbstract, + if (isClass != null) 'isClass': isClass, + if (isGetter != null) 'isGetter': isGetter, + if (isField != null) 'isField': isField, + if (isMethod != null) 'isMethod': isMethod, + if (isStatic != null) 'isStatic': isStatic, + }); /// Whether the entity is abstract, meaning it has no definition. bool get isAbstract => node['isAbstract'] as bool; diff --git a/pkgs/dart_model/benchmark/serialization_benchmark.dart b/pkgs/dart_model/benchmark/serialization_benchmark.dart index b18e8311..d0b0adf7 100644 --- a/pkgs/dart_model/benchmark/serialization_benchmark.dart +++ b/pkgs/dart_model/benchmark/serialization_benchmark.dart @@ -31,9 +31,10 @@ abstract class SerializationBenchmark extends BenchmarkBase { List makeMemberNames(int key) { final length = key % 10; return List.generate( - // "key % 2999" so some member names are reused. - length, - (i) => 'interface${key % 2999}member$i'); + // "key % 2999" so some member names are reused. + length, + (i) => 'interface${key % 2999}member$i', + ); } } diff --git a/pkgs/dart_model/lib/src/dart_model.dart b/pkgs/dart_model/lib/src/dart_model.dart index 666ad6e2..f395e14a 100644 --- a/pkgs/dart_model/lib/src/dart_model.dart +++ b/pkgs/dart_model/lib/src/dart_model.dart @@ -34,8 +34,11 @@ extension ModelExtension on Model { int get fingerprint { // TODO: Implementation for non-buffer maps? var node = this.node as MapInBuffer; - return node.buffer.fingerprint(node.pointer, - type: Type.typedMapPointer, alreadyDereferenced: true); + return node.buffer.fingerprint( + node.pointer, + type: Type.typedMapPointer, + alreadyDereferenced: true, + ); } /// Looks up [name] in `this`. @@ -49,7 +52,8 @@ extension ModelExtension on Model { if (library == null) return null; if (name.scope == null) { throw UnsupportedError( - 'Can only look up names in nested scopes for now.'); + 'Can only look up names in nested scopes for now.', + ); } final scope = library.scopes[name.scope!]; if (scope == null) return null; @@ -95,17 +99,24 @@ extension ModelExtension on Model { if (path case [final uri, 'scopes', final name]) { return QualifiedName(uri: uri, name: name); - } else if (path - case [final uri, 'scopes', final scope, 'members', final name]) { + } else if (path case [ + final uri, + 'scopes', + final scope, + 'members', + final name, + ]) { return QualifiedName( - uri: uri, - scope: scope, - name: name, - isStatic: Member.fromJson(model).properties.isStatic); + uri: uri, + scope: scope, + name: name, + isStatic: Member.fromJson(model).properties.isStatic, + ); } throw UnsupportedError( - 'Unsupported node type for `qualifiedNameOf`, only top level members ' - 'are supported for now. $path'); + 'Unsupported node type for `qualifiedNameOf`, only top level members ' + 'are supported for now. $path', + ); } /// Returns the key of [value] in [map]. @@ -147,8 +158,10 @@ extension ModelExtension on Model { } /// Builds a `Map` from values to parent `Map`s. - static void _buildParentsMap(Map parent, - Map, Map> result) { + static void _buildParentsMap( + Map parent, + Map, Map> result, + ) { for (final child in parent.values.whereType>()) { for (final map in child.expandWithMerged) { if (result.containsKey(map)) continue; diff --git a/pkgs/dart_model/lib/src/dart_model.g.dart b/pkgs/dart_model/lib/src/dart_model.g.dart index 788b0afd..a6686429 100644 --- a/pkgs/dart_model/lib/src/dart_model.g.dart +++ b/pkgs/dart_model/lib/src/dart_model.g.dart @@ -16,12 +16,8 @@ extension type Augmentation.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'code': Type.closedListPointer, }); - Augmentation({ - List? code, - }) : this.fromJson(Scope.createMap( - _schema, - code, - )); + Augmentation({List? code}) + : this.fromJson(Scope.createMap(_schema, code)); /// Augmentation code. List get code => (node['code'] as List).cast(); @@ -42,16 +38,9 @@ extension type Code.fromJson(Map node) implements Object { 'value': Type.anyPointer, }); static Code qualifiedName(QualifiedName qualifiedName) => - Code.fromJson(Scope.createMap( - _schema, - 'QualifiedName', - qualifiedName, - )); - static Code string(String string) => Code.fromJson(Scope.createMap( - _schema, - 'String', - string, - )); + Code.fromJson(Scope.createMap(_schema, 'QualifiedName', qualifiedName)); + static Code string(String string) => + Code.fromJson(Scope.createMap(_schema, 'String', string)); CodeType get type { switch (node['type'] as String) { case 'QualifiedName': @@ -99,14 +88,16 @@ extension type FunctionTypeDesc.fromJson(Map node) List? requiredPositionalParameters, List? optionalPositionalParameters, List? namedParameters, - }) : this.fromJson(Scope.createMap( - _schema, - returnType, - typeParameters, - requiredPositionalParameters, - optionalPositionalParameters, - namedParameters, - )); + }) : this.fromJson( + Scope.createMap( + _schema, + returnType, + typeParameters, + requiredPositionalParameters, + optionalPositionalParameters, + namedParameters, + ), + ); /// The return type of this function type. StaticTypeDesc get returnType => node['returnType'] as StaticTypeDesc; @@ -128,12 +119,8 @@ extension type MetadataAnnotation.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'expression': Type.typedMapPointer, }); - MetadataAnnotation({ - Expression? expression, - }) : this.fromJson(Scope.createMap( - _schema, - expression, - )); + MetadataAnnotation({Expression? expression}) + : this.fromJson(Scope.createMap(_schema, expression)); /// The expression of the annotation. Expression get expression => node['expression'] as Expression; @@ -162,13 +149,15 @@ extension type Interface.fromJson(Map node) NamedTypeDesc? thisType, List? metadataAnnotations, Properties? properties, - }) : this.fromJson(Scope.createMap( - _schema, - Scope.createGrowableMap(), - thisType, - metadataAnnotations, - properties, - )); + }) : this.fromJson( + Scope.createMap( + _schema, + Scope.createGrowableMap(), + thisType, + metadataAnnotations, + properties, + ), + ); /// Map of members by name. Map get members => @@ -184,10 +173,7 @@ extension type Library.fromJson(Map node) implements Object { 'scopes': Type.growableMapPointer, }); Library() - : this.fromJson(Scope.createMap( - _schema, - Scope.createGrowableMap(), - )); + : this.fromJson(Scope.createMap(_schema, Scope.createGrowableMap())); /// Scopes by name. Map get scopes => @@ -212,15 +198,17 @@ extension type Member.fromJson(Map node) List? namedParameters, List? metadataAnnotations, Properties? properties, - }) : this.fromJson(Scope.createMap( - _schema, - returnType, - requiredPositionalParameters, - optionalPositionalParameters, - namedParameters, - metadataAnnotations, - properties, - )); + }) : this.fromJson( + Scope.createMap( + _schema, + returnType, + requiredPositionalParameters, + optionalPositionalParameters, + namedParameters, + metadataAnnotations, + properties, + ), + ); /// The return type of this member, if it has one. StaticTypeDesc get returnType => node['returnType'] as StaticTypeDesc; @@ -244,13 +232,8 @@ extension type Model.fromJson(Map node) implements Object { 'uris': Type.growableMapPointer, 'types': Type.typedMapPointer, }); - Model({ - TypeHierarchy? types, - }) : this.fromJson(Scope.createMap( - _schema, - Scope.createGrowableMap(), - types, - )); + Model({TypeHierarchy? types}) + : this.fromJson(Scope.createMap(_schema, Scope.createGrowableMap(), types)); /// Libraries by URI. Map get uris => @@ -272,12 +255,7 @@ extension type NamedFunctionTypeParameter.fromJson(Map node) String? name, bool? required, StaticTypeDesc? type, - }) : this.fromJson(Scope.createMap( - _schema, - name, - required, - type, - )); + }) : this.fromJson(Scope.createMap(_schema, name, required, type)); String get name => node['name'] as String; bool get required => node['required'] as bool; StaticTypeDesc get type => node['type'] as StaticTypeDesc; @@ -290,14 +268,8 @@ extension type NamedRecordField.fromJson(Map node) 'name': Type.stringPointer, 'type': Type.typedMapPointer, }); - NamedRecordField({ - String? name, - StaticTypeDesc? type, - }) : this.fromJson(Scope.createMap( - _schema, - name, - type, - )); + NamedRecordField({String? name, StaticTypeDesc? type}) + : this.fromJson(Scope.createMap(_schema, name, type)); String get name => node['name'] as String; StaticTypeDesc get type => node['type'] as StaticTypeDesc; } @@ -309,14 +281,8 @@ extension type NamedTypeDesc.fromJson(Map node) 'name': Type.typedMapPointer, 'instantiation': Type.closedListPointer, }); - NamedTypeDesc({ - QualifiedName? name, - List? instantiation, - }) : this.fromJson(Scope.createMap( - _schema, - name, - instantiation, - )); + NamedTypeDesc({QualifiedName? name, List? instantiation}) + : this.fromJson(Scope.createMap(_schema, name, instantiation)); QualifiedName get name => node['name'] as QualifiedName; List get instantiation => (node['instantiation'] as List).cast(); @@ -333,12 +299,8 @@ extension type NullableTypeDesc.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'inner': Type.typedMapPointer, }); - NullableTypeDesc({ - StaticTypeDesc? inner, - }) : this.fromJson(Scope.createMap( - _schema, - inner, - )); + NullableTypeDesc({StaticTypeDesc? inner}) + : this.fromJson(Scope.createMap(_schema, inner)); /// The type T. StaticTypeDesc get inner => node['inner'] as StaticTypeDesc; @@ -364,16 +326,18 @@ extension type Properties.fromJson(Map node) bool? isField, bool? isMethod, bool? isStatic, - }) : this.fromJson(Scope.createMap( - _schema, - isAbstract, - isClass, - isConstructor, - isGetter, - isField, - isMethod, - isStatic, - )); + }) : this.fromJson( + Scope.createMap( + _schema, + isAbstract, + isClass, + isConstructor, + isGetter, + isField, + isMethod, + isStatic, + ), + ); /// Whether the entity is abstract, meaning it has no definition. bool get isAbstract => node['isAbstract'] as bool; @@ -406,18 +370,8 @@ extension type QualifiedName.fromJson(Map node) 'name': Type.stringPointer, 'isStatic': Type.boolean, }); - QualifiedName({ - String? uri, - String? scope, - String? name, - bool? isStatic, - }) : this.fromJson(Scope.createMap( - _schema, - uri, - scope, - name, - isStatic, - )); + QualifiedName({String? uri, String? scope, String? name, bool? isStatic}) + : this.fromJson(Scope.createMap(_schema, uri, scope, name, isStatic)); /// Parses [string] of the form `uri#[scope.|scope::]name`. /// @@ -444,10 +398,11 @@ extension type QualifiedName.fromJson(Map node) isStatic = null; } return QualifiedName( - uri: string.substring(0, index), - name: name, - scope: scope, - isStatic: isStatic); + uri: string.substring(0, index), + name: name, + scope: scope, + isStatic: isStatic, + ); } /// The URI of the file containing the name. @@ -465,11 +420,8 @@ extension type QualifiedName.fromJson(Map node) /// Query about a corpus of Dart source code. TODO(davidmorgan): this queries about a single class, expand to a union type for different types of queries. extension type Query.fromJson(Map node) implements Object { - Query({ - QualifiedName? target, - }) : this.fromJson({ - if (target != null) 'target': target, - }); + Query({QualifiedName? target}) + : this.fromJson({if (target != null) 'target': target}); /// The class to query about. QualifiedName get target => node['target'] as QualifiedName; @@ -485,11 +437,7 @@ extension type RecordTypeDesc.fromJson(Map node) RecordTypeDesc({ List? positional, List? named, - }) : this.fromJson(Scope.createMap( - _schema, - positional, - named, - )); + }) : this.fromJson(Scope.createMap(_schema, positional, named)); List get positional => (node['positional'] as List).cast(); List get named => (node['named'] as List).cast(); } @@ -516,54 +464,38 @@ extension type StaticTypeDesc.fromJson(Map node) 'value': Type.anyPointer, }); static StaticTypeDesc dynamicTypeDesc(DynamicTypeDesc dynamicTypeDesc) => - StaticTypeDesc.fromJson(Scope.createMap( - _schema, - 'DynamicTypeDesc', - dynamicTypeDesc, - )); + StaticTypeDesc.fromJson( + Scope.createMap(_schema, 'DynamicTypeDesc', dynamicTypeDesc), + ); static StaticTypeDesc functionTypeDesc(FunctionTypeDesc functionTypeDesc) => - StaticTypeDesc.fromJson(Scope.createMap( - _schema, - 'FunctionTypeDesc', - functionTypeDesc, - )); + StaticTypeDesc.fromJson( + Scope.createMap(_schema, 'FunctionTypeDesc', functionTypeDesc), + ); static StaticTypeDesc namedTypeDesc(NamedTypeDesc namedTypeDesc) => - StaticTypeDesc.fromJson(Scope.createMap( - _schema, - 'NamedTypeDesc', - namedTypeDesc, - )); + StaticTypeDesc.fromJson( + Scope.createMap(_schema, 'NamedTypeDesc', namedTypeDesc), + ); static StaticTypeDesc neverTypeDesc(NeverTypeDesc neverTypeDesc) => - StaticTypeDesc.fromJson(Scope.createMap( - _schema, - 'NeverTypeDesc', - neverTypeDesc, - )); + StaticTypeDesc.fromJson( + Scope.createMap(_schema, 'NeverTypeDesc', neverTypeDesc), + ); static StaticTypeDesc nullableTypeDesc(NullableTypeDesc nullableTypeDesc) => - StaticTypeDesc.fromJson(Scope.createMap( - _schema, - 'NullableTypeDesc', - nullableTypeDesc, - )); + StaticTypeDesc.fromJson( + Scope.createMap(_schema, 'NullableTypeDesc', nullableTypeDesc), + ); static StaticTypeDesc recordTypeDesc(RecordTypeDesc recordTypeDesc) => - StaticTypeDesc.fromJson(Scope.createMap( - _schema, - 'RecordTypeDesc', - recordTypeDesc, - )); + StaticTypeDesc.fromJson( + Scope.createMap(_schema, 'RecordTypeDesc', recordTypeDesc), + ); static StaticTypeDesc typeParameterTypeDesc( - TypeParameterTypeDesc typeParameterTypeDesc) => - StaticTypeDesc.fromJson(Scope.createMap( - _schema, - 'TypeParameterTypeDesc', - typeParameterTypeDesc, - )); + TypeParameterTypeDesc typeParameterTypeDesc, + ) => StaticTypeDesc.fromJson( + Scope.createMap(_schema, 'TypeParameterTypeDesc', typeParameterTypeDesc), + ); static StaticTypeDesc voidTypeDesc(VoidTypeDesc voidTypeDesc) => - StaticTypeDesc.fromJson(Scope.createMap( - _schema, - 'VoidTypeDesc', - voidTypeDesc, - )); + StaticTypeDesc.fromJson( + Scope.createMap(_schema, 'VoidTypeDesc', voidTypeDesc), + ); StaticTypeDescType get type { switch (node['type'] as String) { case 'DynamicTypeDesc': @@ -634,7 +566,8 @@ extension type StaticTypeDesc.fromJson(Map node) throw StateError('Not a TypeParameterTypeDesc.'); } return TypeParameterTypeDesc.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } VoidTypeDesc get asVoidTypeDesc { @@ -652,14 +585,8 @@ extension type StaticTypeParameterDesc.fromJson(Map node) 'identifier': Type.uint32, 'bound': Type.typedMapPointer, }); - StaticTypeParameterDesc({ - int? identifier, - StaticTypeDesc? bound, - }) : this.fromJson(Scope.createMap( - _schema, - identifier, - bound, - )); + StaticTypeParameterDesc({int? identifier, StaticTypeDesc? bound}) + : this.fromJson(Scope.createMap(_schema, identifier, bound)); int get identifier => node['identifier'] as int; StaticTypeDesc? get bound => node['bound'] as StaticTypeDesc?; } @@ -671,10 +598,7 @@ extension type TypeHierarchy.fromJson(Map node) 'named': Type.growableMapPointer, }); TypeHierarchy() - : this.fromJson(Scope.createMap( - _schema, - Scope.createGrowableMap(), - )); + : this.fromJson(Scope.createMap(_schema, Scope.createGrowableMap())); /// Map of qualified interface names to their resolved named type. Map get named => @@ -693,12 +617,9 @@ extension type TypeHierarchyEntry.fromJson(Map node) List? typeParameters, NamedTypeDesc? self, List? supertypes, - }) : this.fromJson(Scope.createMap( - _schema, - typeParameters, - self, - supertypes, - )); + }) : this.fromJson( + Scope.createMap(_schema, typeParameters, self, supertypes), + ); /// Type parameters defined on this interface-defining element. List get typeParameters => @@ -717,12 +638,8 @@ extension type TypeParameterTypeDesc.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'parameterId': Type.uint32, }); - TypeParameterTypeDesc({ - int? parameterId, - }) : this.fromJson(Scope.createMap( - _schema, - parameterId, - )); + TypeParameterTypeDesc({int? parameterId}) + : this.fromJson(Scope.createMap(_schema, parameterId)); int get parameterId => node['parameterId'] as int; } diff --git a/pkgs/dart_model/lib/src/deep_cast_map.dart b/pkgs/dart_model/lib/src/deep_cast_map.dart index 5b46eb38..b58deb1a 100644 --- a/pkgs/dart_model/lib/src/deep_cast_map.dart +++ b/pkgs/dart_model/lib/src/deep_cast_map.dart @@ -78,21 +78,27 @@ class _DeepCastMap extends MapBase { @override V update(K key, V Function(V value) update, {V Function()? ifAbsent}) { - return _castValue(_source.update( - key as SK, (SV value) => update(_castValue(value)) as SV, - ifAbsent: (ifAbsent == null) ? null : () => ifAbsent() as SV)); + return _castValue( + _source.update( + key as SK, + (SV value) => update(_castValue(value)) as SV, + ifAbsent: (ifAbsent == null) ? null : () => ifAbsent() as SV, + ), + ); } @override void updateAll(V Function(K key, V value) update) { _source.updateAll( - (SK key, SV value) => update(key as K, _castValue(value)) as SV); + (SK key, SV value) => update(key as K, _castValue(value)) as SV, + ); } @override Iterable> get entries { - return _source.entries.map>((MapEntry e) => - MapEntry(e.key as K, _castValue(e.value))); + return _source.entries.map>( + (MapEntry e) => MapEntry(e.key as K, _castValue(e.value)), + ); } @override @@ -104,7 +110,8 @@ class _DeepCastMap extends MapBase { @override void removeWhere(bool Function(K key, V value) test) { - _source - .removeWhere((SK key, SV value) => test(key as K, _castValue(value))); + _source.removeWhere( + (SK key, SV value) => test(key as K, _castValue(value)), + ); } } diff --git a/pkgs/dart_model/lib/src/json_buffer/closed_list.dart b/pkgs/dart_model/lib/src/json_buffer/closed_list.dart index 6ae5e684..38123729 100644 --- a/pkgs/dart_model/lib/src/json_buffer/closed_list.dart +++ b/pkgs/dart_model/lib/src/json_buffer/closed_list.dart @@ -51,7 +51,7 @@ class _ClosedList with ListMixin { final int length; _ClosedList(this._buffer, this._pointer) - : length = _buffer._readLength(_pointer); + : length = _buffer._readLength(_pointer); @override Object? operator [](int index) { @@ -95,9 +95,9 @@ class _ClosedListIterator implements Iterator { _Pointer _pointer; _ClosedListIterator(this._buffer, _Pointer pointer, int length) - : _last = pointer + _lengthSize + length * ClosedLists._valueSize, - // Subtract because `moveNext` is called before reading. - _pointer = pointer + _lengthSize - ClosedLists._valueSize; + : _last = pointer + _lengthSize + length * ClosedLists._valueSize, + // Subtract because `moveNext` is called before reading. + _pointer = pointer + _lengthSize - ClosedLists._valueSize; @override T get current => _buffer._readAny(_pointer) as T; diff --git a/pkgs/dart_model/lib/src/json_buffer/closed_map.dart b/pkgs/dart_model/lib/src/json_buffer/closed_map.dart index 1a4ab650..1a21b0ad 100644 --- a/pkgs/dart_model/lib/src/json_buffer/closed_map.dart +++ b/pkgs/dart_model/lib/src/json_buffer/closed_map.dart @@ -45,7 +45,9 @@ extension ClosedMaps on JsonBufferBuilder { /// Returns the [_ClosedMap] at [pointer]. Map _readClosedMap( - _Pointer pointer, Map? parent) { + _Pointer pointer, + Map? parent, + ) { return _ClosedMap(this, pointer, parent); } } @@ -63,7 +65,7 @@ class _ClosedMap final int length; _ClosedMap(this.buffer, this.pointer, this.parent) - : length = buffer._readLength(pointer); + : length = buffer._readLength(pointer); @override Object? operator [](Object? key) { @@ -76,36 +78,42 @@ class _ClosedMap @override late final Iterable keys = _IteratorFunctionIterable( - () => _ClosedMapKeyIterator(buffer, this, pointer, length), - length: length); + () => _ClosedMapKeyIterator(buffer, this, pointer, length), + length: length, + ); @override late final Iterable values = _IteratorFunctionIterable( - () => _ClosedMapValueIterator(buffer, this, pointer, length), - length: length); + () => _ClosedMapValueIterator(buffer, this, pointer, length), + length: length, + ); @override late final Iterable> entries = _IteratorFunctionIterable( - () => _ClosedMapEntryIterator(buffer, this, pointer, length), - length: length); + () => _ClosedMapEntryIterator(buffer, this, pointer, length), + length: length, + ); @override void operator []=(String key, Object? value) { throw UnsupportedError( - 'This JsonBufferBuilder map is read-only, see "createGrowableMap".'); + 'This JsonBufferBuilder map is read-only, see "createGrowableMap".', + ); } @override Object? remove(Object? key) { throw UnsupportedError( - 'This JsonBufferBuilder map is read-only, see "createGrowableMap".'); + 'This JsonBufferBuilder map is read-only, see "createGrowableMap".', + ); } @override void clear() { throw UnsupportedError( - 'This JsonBufferBuilder map is read-only, see "createGrowableMap".'); + 'This JsonBufferBuilder map is read-only, see "createGrowableMap".', + ); } @override @@ -134,9 +142,9 @@ abstract class _ClosedMapIterator implements Iterator { _Pointer _pointer; _ClosedMapIterator(this._buffer, this._parent, _Pointer pointer, int length) - : _last = pointer + _lengthSize + length * ClosedMaps._entrySize, - // Subtract because `moveNext` is called before reading. - _pointer = pointer + _lengthSize - ClosedMaps._entrySize; + : _last = pointer + _lengthSize + length * ClosedMaps._entrySize, + // Subtract because `moveNext` is called before reading. + _pointer = pointer + _lengthSize - ClosedMaps._entrySize; @override T get current; @@ -156,7 +164,11 @@ abstract class _ClosedMapIterator implements Iterator { class _ClosedMapKeyIterator extends _ClosedMapIterator { _ClosedMapKeyIterator( - super._buffer, super._parent, super.pointer, super.length); + super._buffer, + super._parent, + super.pointer, + super.length, + ); @override String get current => _currentKey; @@ -164,7 +176,11 @@ class _ClosedMapKeyIterator extends _ClosedMapIterator { class _ClosedMapValueIterator extends _ClosedMapIterator { _ClosedMapValueIterator( - super._buffer, super._parent, super.pointer, super.length); + super._buffer, + super._parent, + super.pointer, + super.length, + ); @override Object? get current => _currentValue; @@ -173,7 +189,11 @@ class _ClosedMapValueIterator extends _ClosedMapIterator { class _ClosedMapEntryIterator extends _ClosedMapIterator> { _ClosedMapEntryIterator( - super._buffer, super._parent, super.pointer, super.length); + super._buffer, + super._parent, + super.pointer, + super.length, + ); @override MapEntry get current => MapEntry(_currentKey, _currentValue); @@ -181,11 +201,15 @@ class _ClosedMapEntryIterator class _ClosedMapHashIterator extends _ClosedMapIterator { _ClosedMapHashIterator( - super._buffer, super._parent, super.pointer, super.length); + super._buffer, + super._parent, + super.pointer, + super.length, + ); @override int get current => Object.hash( - _buffer._fingerprint(_pointer, Type.stringPointer), - _buffer.fingerprint(_pointer + ClosedMaps._keySize), - ); + _buffer._fingerprint(_pointer, Type.stringPointer), + _buffer.fingerprint(_pointer + ClosedMaps._keySize), + ); } diff --git a/pkgs/dart_model/lib/src/json_buffer/explanations.dart b/pkgs/dart_model/lib/src/json_buffer/explanations.dart index 87839d9b..d4f69495 100644 --- a/pkgs/dart_model/lib/src/json_buffer/explanations.dart +++ b/pkgs/dart_model/lib/src/json_buffer/explanations.dart @@ -35,14 +35,17 @@ class _Explanations { /// Otherwise, this method throws on multiple writes. void explain(_Pointer pointer, {bool allowOverwrite = false}) { if (_explanationsStack.isNotEmpty) { - final explanation = _explanationsStack.join(', ') + + final explanation = + _explanationsStack.join(', ') + (allowOverwrite ? _allowOverwriteTag : ''); final oldExplanation = _explanationsByPointer[pointer]; if (oldExplanation != null) { if (!allowOverwrite || !oldExplanation.contains(_allowOverwriteTag)) { - throw StateError('Second write to $pointer!\n' - ' Old explanation: ${_explanationsByPointer[pointer]}\n' - ' New explanation: $explanation'); + throw StateError( + 'Second write to $pointer!\n' + ' Old explanation: ${_explanationsByPointer[pointer]}\n' + ' New explanation: $explanation', + ); } } _explanationsByPointer[pointer] = explanation; diff --git a/pkgs/dart_model/lib/src/json_buffer/growable_map.dart b/pkgs/dart_model/lib/src/json_buffer/growable_map.dart index d2406a3f..fd4b2a75 100644 --- a/pkgs/dart_model/lib/src/json_buffer/growable_map.dart +++ b/pkgs/dart_model/lib/src/json_buffer/growable_map.dart @@ -58,14 +58,18 @@ extension GrowableMaps on JsonBufferBuilder { /// Throws if [map is backed by a different buffer to `this`. void _checkGrowableMapOwnership(_GrowableMap map) { if (map.buffer != this) { - throw UnsupportedError('Maps created with `createGrowableMap` can only ' - 'be added to the JsonBufferBuilder instance that created them.'); + throw UnsupportedError( + 'Maps created with `createGrowableMap` can only ' + 'be added to the JsonBufferBuilder instance that created them.', + ); } } /// Returns the [_GrowableMap] at [pointer]. Map _readGrowableMap( - _Pointer pointer, Map? parent) { + _Pointer pointer, + Map? parent, + ) { return _GrowableMap(this, pointer, parent); } } @@ -83,7 +87,7 @@ class _GrowableMap _Pointer? _lastPointer; _GrowableMap(this.buffer, this.pointer, this.parent) - : _length = buffer._readLength(pointer + _pointerSize); + : _length = buffer._readLength(pointer + _pointerSize); @override int get length => _length; @@ -101,18 +105,21 @@ class _GrowableMap @override late final Iterable keys = _IteratorFunctionIterable( - () => _GrowableMapKeyIterator(buffer, this, pointer), - length: length); + () => _GrowableMapKeyIterator(buffer, this, pointer), + length: length, + ); @override late final Iterable values = _IteratorFunctionIterable( - () => _GrowableMapValueIterator(buffer, this, pointer), - length: length); + () => _GrowableMapValueIterator(buffer, this, pointer), + length: length, + ); @override late final Iterable> entries = _IteratorFunctionIterable( - () => _GrowableMapEntryIterator(buffer, this, pointer), - length: length); + () => _GrowableMapEntryIterator(buffer, this, pointer), + length: length, + ); /// Add [value] to the map with key [key]. /// @@ -192,9 +199,10 @@ abstract class _GrowableMapIterator implements Iterator { String get _currentKey => _buffer._readString(_buffer._readPointer(_pointer + _pointerSize)); - Object? get _currentValue => - _buffer._readAny(_pointer + _pointerSize + GrowableMaps._keySize, - parent: _parent); + Object? get _currentValue => _buffer._readAny( + _pointer + _pointerSize + GrowableMaps._keySize, + parent: _parent, + ); @override bool moveNext() { @@ -230,7 +238,7 @@ class _GrowableMapHashIterator extends _GrowableMapIterator { @override int get current => Object.hash( - _buffer._fingerprint(_pointer + _pointerSize, Type.stringPointer), - _buffer.fingerprint(_pointer + _pointerSize + GrowableMaps._keySize), - ); + _buffer._fingerprint(_pointer + _pointerSize, Type.stringPointer), + _buffer.fingerprint(_pointer + _pointerSize + GrowableMaps._keySize), + ); } diff --git a/pkgs/dart_model/lib/src/json_buffer/iterables.dart b/pkgs/dart_model/lib/src/json_buffer/iterables.dart index 82306145..88f40b9a 100644 --- a/pkgs/dart_model/lib/src/json_buffer/iterables.dart +++ b/pkgs/dart_model/lib/src/json_buffer/iterables.dart @@ -21,7 +21,7 @@ mixin _EntryMapMixin on Map { @override bool get isEmpty => length == 0; -// `MapMixin` uses `keys.isNotEmpty`. + // `MapMixin` uses `keys.isNotEmpty`. @override bool get isNotEmpty => length != 0; } diff --git a/pkgs/dart_model/lib/src/json_buffer/json_buffer_builder.dart b/pkgs/dart_model/lib/src/json_buffer/json_buffer_builder.dart index b9bf1677..733d24d7 100644 --- a/pkgs/dart_model/lib/src/json_buffer/json_buffer_builder.dart +++ b/pkgs/dart_model/lib/src/json_buffer/json_buffer_builder.dart @@ -40,15 +40,15 @@ class JsonBufferBuilder { final Map _pointersByString = {}; JsonBufferBuilder.deserialize(this._buffer) - : _allowWrites = false, - _nextFree = _buffer.length { + : _allowWrites = false, + _nextFree = _buffer.length { map = _readGrowableMap(0, null); } JsonBufferBuilder() - : _allowWrites = true, - _buffer = Uint8List(_initialBufferSize), - _nextFree = 0 { + : _allowWrites = true, + _buffer = Uint8List(_initialBufferSize), + _nextFree = 0 { map = createGrowableMap(); } @@ -67,8 +67,11 @@ class JsonBufferBuilder { type = _readType(pointer); pointer += _typeSize; } - return _fingerprint(pointer, type, - alreadyDereferenced: alreadyDereferenced); + return _fingerprint( + pointer, + type, + alreadyDereferenced: alreadyDereferenced, + ); } /// Computes the identity hash of the object at [pointer] with a known [type] @@ -77,8 +80,11 @@ class JsonBufferBuilder { /// If [alreadyDereferenced] is `true`, then for types which are pointers, /// [pointer] already points at the top of the object, and should not be /// followed before reading the object. - int _fingerprint(_Pointer pointer, Type type, - {bool alreadyDereferenced = false}) { + int _fingerprint( + _Pointer pointer, + Type type, { + bool alreadyDereferenced = false, + }) { // Dereference [pointer] if it is a pointer type, and hasn't already been // dereferenced. if (type.isPointer && !alreadyDereferenced) { @@ -212,7 +218,9 @@ class JsonBufferBuilder { case Type.growableMapPointer: _writePointer( - pointer, _pointerToGrowableMap(value as _GrowableMap)); + pointer, + _pointerToGrowableMap(value as _GrowableMap), + ); case Type.typedMapPointer: _writePointer(pointer, _pointerToTypedMap(value as _TypedMap)); @@ -243,7 +251,8 @@ class JsonBufferBuilder { String _readString(_Pointer pointer) { final length = _readLength(pointer); return utf8.decode( - _buffer.sublist(pointer + _lengthSize, pointer + _lengthSize + length)); + _buffer.sublist(pointer + _lengthSize, pointer + _lengthSize + length), + ); } /// Writes [type] at [pointer]. @@ -259,8 +268,11 @@ class JsonBufferBuilder { } /// Writes [length] at [pointer]. - void _writeLength(_Pointer pointer, int length, - {bool allowOverwrite = false}) { + void _writeLength( + _Pointer pointer, + int length, { + bool allowOverwrite = false, + }) { _explanations?.push('_writeLength $length'); __writeUint32(pointer, length, allowOverwrite: allowOverwrite); _explanations?.pop(); @@ -286,11 +298,19 @@ class JsonBufferBuilder { _explanations?.pop(); } - void __writeUint32(_Pointer pointer, int value, - {bool allowOverwrite = false}) { - _setFourBytes(pointer, value & 0xff, (value >> 8) & 0xff, - (value >> 16) & 0xff, (value >> 24) & 0xff, - allowOverwrite: allowOverwrite); + void __writeUint32( + _Pointer pointer, + int value, { + bool allowOverwrite = false, + }) { + _setFourBytes( + pointer, + value & 0xff, + (value >> 8) & 0xff, + (value >> 16) & 0xff, + (value >> 24) & 0xff, + allowOverwrite: allowOverwrite, + ); } /// Reads the uint32 at [_Pointer]. @@ -338,8 +358,14 @@ class JsonBufferBuilder { /// /// If [_explanations] is being used, [allowOverwrite] controls whether /// multiple writes to the same byte will be allowed or will throw. - void _setFourBytes(_Pointer pointer, int b1, int b2, int b3, int b4, - {bool allowOverwrite = false}) { + void _setFourBytes( + _Pointer pointer, + int b1, + int b2, + int b3, + int b4, { + bool allowOverwrite = false, + }) { _setByte(pointer, b1, allowOverwrite: allowOverwrite); _setByte(pointer + 1, b2, allowOverwrite: allowOverwrite); _setByte(pointer + 2, b3, allowOverwrite: allowOverwrite); diff --git a/pkgs/dart_model/lib/src/json_buffer/type.dart b/pkgs/dart_model/lib/src/json_buffer/type.dart index be5b2013..3ada111c 100644 --- a/pkgs/dart_model/lib/src/json_buffer/type.dart +++ b/pkgs/dart_model/lib/src/json_buffer/type.dart @@ -70,7 +70,8 @@ enum Type { return Type.closedMapPointer; } throw UnsupportedError( - 'Unsupported type: ${value.runtimeType}, value: $value'); + 'Unsupported type: ${value.runtimeType}, value: $value', + ); } /// The size in bytes of value of this type. diff --git a/pkgs/dart_model/lib/src/json_buffer/typed_map.dart b/pkgs/dart_model/lib/src/json_buffer/typed_map.dart index 0a8b4f2b..b20d85c9 100644 --- a/pkgs/dart_model/lib/src/json_buffer/typed_map.dart +++ b/pkgs/dart_model/lib/src/json_buffer/typed_map.dart @@ -26,18 +26,19 @@ class TypedMapSchema { /// Ordering is important: when a "typed map" is instantiated the values are /// passed in the same order that the fields are specified here. TypedMapSchema(Map fieldTypes) - : this._(fieldTypes.keys.toList(), fieldTypes.values.toList()); + : this._(fieldTypes.keys.toList(), fieldTypes.values.toList()); TypedMapSchema._(this._keys, this._valueTypes) - : _isAllBooleans = _valueTypes.every((t) => t == Type.boolean), - _fieldSetSize = (_keys.length + 7) ~/ 8, - _valueSizeAsBytes = - _valueTypes.map((t) => t._sizeInBytes).fold(0, (a, b) => a + b); + : _isAllBooleans = _valueTypes.every((t) => t == Type.boolean), + _fieldSetSize = (_keys.length + 7) ~/ 8, + _valueSizeAsBytes = _valueTypes + .map((t) => t._sizeInBytes) + .fold(0, (a, b) => a + b); /// The schema field names and value types as a `Map`. Map toMap() => { - for (var i = 0; i != _keys.length; ++i) _keys[i]: _valueTypes[i], - }; + for (var i = 0; i != _keys.length; ++i) _keys[i]: _valueTypes[i], + }; // Schemas should be instantiated once per type in generated code, so looking // up by identity is sufficient. It's also the fastest way to do it. @@ -184,11 +185,28 @@ extension TypedMaps on JsonBufferBuilder { // If the map is filled this is marked with the high bit of the schema // pointer, then the field set is omitted. final (valuesSize, filled) = schema._valueSizeOf( - v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); + v0, + v1, + v2, + v3, + v4, + v5, + v6, + v7, + v8, + v9, + v10, + v11, + v12, + v13, + v14, + v15, + ); // Layout is: pointer to schema, field set (unless filled!), values. final pointer = _reserve( - _pointerSize + (filled ? 0 : schema._fieldSetSize) + valuesSize); + _pointerSize + (filled ? 0 : schema._fieldSetSize) + valuesSize, + ); // Write the pointer to schema, setting the high bit if the map is filled. var schemaPointer = @@ -202,27 +220,29 @@ extension TypedMaps on JsonBufferBuilder { if (!filled) { if (schema._fieldSetSize >= 1) { _setByte( - pointer + _pointerSize, - (v0 == null ? 0 : 0x01) + - (v1 == null ? 0 : 0x02) + - (v2 == null ? 0 : 0x04) + - (v3 == null ? 0 : 0x08) + - (v4 == null ? 0 : 0x10) + - (v5 == null ? 0 : 0x20) + - (v6 == null ? 0 : 0x40) + - (v7 == null ? 0 : 0x80)); + pointer + _pointerSize, + (v0 == null ? 0 : 0x01) + + (v1 == null ? 0 : 0x02) + + (v2 == null ? 0 : 0x04) + + (v3 == null ? 0 : 0x08) + + (v4 == null ? 0 : 0x10) + + (v5 == null ? 0 : 0x20) + + (v6 == null ? 0 : 0x40) + + (v7 == null ? 0 : 0x80), + ); } if (schema._fieldSetSize >= 2) { _setByte( - pointer + _pointerSize + 1, - (v8 == null ? 0 : 0x01) + - (v9 == null ? 0 : 0x02) + - (v10 == null ? 0 : 0x04) + - (v11 == null ? 0 : 0x08) + - (v12 == null ? 0 : 0x10) + - (v13 == null ? 0 : 0x20) + - (v14 == null ? 0 : 0x40) + - (v15 == null ? 0 : 0x80)); + pointer + _pointerSize + 1, + (v8 == null ? 0 : 0x01) + + (v9 == null ? 0 : 0x02) + + (v10 == null ? 0 : 0x04) + + (v11 == null ? 0 : 0x08) + + (v12 == null ? 0 : 0x10) + + (v13 == null ? 0 : 0x20) + + (v14 == null ? 0 : 0x40) + + (v15 == null ? 0 : 0x80), + ); } } @@ -312,14 +332,18 @@ extension TypedMaps on JsonBufferBuilder { /// Throws if [map is backed by a different buffer to `this`. void _checkTypedMapOwnership(_TypedMap map) { if (map.buffer != this) { - throw UnsupportedError('Maps created with `createTypedMap` can only ' - 'be added to the JsonBufferBuilder instance that created them.'); + throw UnsupportedError( + 'Maps created with `createTypedMap` can only ' + 'be added to the JsonBufferBuilder instance that created them.', + ); } } /// Returns the [_TypedMap] at [pointer]. Map _readTypedMap( - _Pointer pointer, Map? parent) { + _Pointer pointer, + Map? parent, + ) { return _TypedMap(this, pointer, parent); } } @@ -344,8 +368,9 @@ class _TypedMap /// The schema of this "typed map" giving its field names and types. late final TypedMapSchema _schema = - buffer._schemasByPointer[_schemaPointer] ??= - TypedMapSchema(buffer._readClosedMap(_schemaPointer, null).cast()); + buffer._schemasByPointer[_schemaPointer] ??= TypedMapSchema( + buffer._readClosedMap(_schemaPointer, null).cast(), + ); /// Whether all fields are present, meaning no explicit field set was written. late final bool filled = (buffer._readPointer(pointer) & 0x80000000) != 0; @@ -356,7 +381,10 @@ class _TypedMap bool _hasField(int index) { if (index < 0 || index >= _schema.length) { throw RangeError.value( - index, 'index', 'Is out of range, length: ${_schema.length}.'); + index, + 'index', + 'Is out of range, length: ${_schema.length}.', + ); } if (filled) return true; final byte = index ~/ 8; @@ -389,42 +417,48 @@ class _TypedMap @override late final Iterable keys = _IteratorFunctionIterable( - _schema._isAllBooleans - ? () => _AllBoolsTypedMapKeyIterator(this) - : () => _PartialTypedMapKeyIterator(this), - length: length); + _schema._isAllBooleans + ? () => _AllBoolsTypedMapKeyIterator(this) + : () => _PartialTypedMapKeyIterator(this), + length: length, + ); @override late final Iterable values = _IteratorFunctionIterable( - _schema._isAllBooleans - ? () => _AllBoolsTypedMapValueIterator(this) - : () => _PartialTypedMapValueIterator(this), - length: length); + _schema._isAllBooleans + ? () => _AllBoolsTypedMapValueIterator(this) + : () => _PartialTypedMapValueIterator(this), + length: length, + ); @override late Iterable> entries = _IteratorFunctionIterable>( - _schema._isAllBooleans - ? () => _AllBoolsTypedMapEntryIterator(this) - : () => _PartialTypedMapEntryIterator(this), - length: length); + _schema._isAllBooleans + ? () => _AllBoolsTypedMapEntryIterator(this) + : () => _PartialTypedMapEntryIterator(this), + length: length, + ); @override void operator []=(String key, Object? value) { throw UnsupportedError( - 'This JsonBufferBuilder map is read-only, see "createGrowableMap".'); + 'This JsonBufferBuilder map is read-only, see "createGrowableMap".', + ); } @override Object? remove(Object? key) { throw UnsupportedError( - 'This JsonBufferBuilder map is read-only, see "createGrowableMap".'); + 'This JsonBufferBuilder map is read-only, see "createGrowableMap".', + ); } @override void clear() { throw UnsupportedError( - 'This JsonBufferBuilder map is read-only, see "createGrowableMap".'); + 'This JsonBufferBuilder map is read-only, see "createGrowableMap".', + ); } @override @@ -439,9 +473,10 @@ class _TypedMap // be one of multiple types, that type will be included in a `type` field // in the map. var hash = 0; - final iterator = _schema._isAllBooleans - ? _AllBoolsTypedMapHashIterator(this) - : _PartialTypedMapHashIterator(this); + final iterator = + _schema._isAllBooleans + ? _AllBoolsTypedMapHashIterator(this) + : _PartialTypedMapHashIterator(this); while (iterator.moveNext()) { hash = Object.hash(hash, iterator.current); } @@ -463,19 +498,22 @@ abstract class _PartialTypedMapIterator implements Iterator { int _offset = -1; _PartialTypedMapIterator(this._map) - : _buffer = _map.buffer, - _schema = _map._schema, - _valuesPointer = _map.pointer + - _pointerSize + - (_map.filled ? 0 : _map._schema._fieldSetSize); + : _buffer = _map.buffer, + _schema = _map._schema, + _valuesPointer = + _map.pointer + + _pointerSize + + (_map.filled ? 0 : _map._schema._fieldSetSize); @override T get current; String get _currentKey => _schema._keys[_index]; - Object? get _currentValue => - _buffer._read(_schema._valueTypes[_index], _valuesPointer + _offset, - parent: _map); + Object? get _currentValue => _buffer._read( + _schema._valueTypes[_index], + _valuesPointer + _offset, + parent: _map, + ); @override bool moveNext() { @@ -524,9 +562,9 @@ class _PartialTypedMapHashIterator extends _PartialTypedMapIterator { @override int get current => Object.hash( - _currentKey, - _buffer._fingerprint( - _valuesPointer + _offset, _schema._valueTypes[_index])); + _currentKey, + _buffer._fingerprint(_valuesPointer + _offset, _schema._valueTypes[_index]), + ); } /// `Iterator` that reads a "typed map" in a [JsonBufferBuilder] with all @@ -547,11 +585,12 @@ abstract class _AllBoolsTypedMapIterator implements Iterator { int _bitOffset = 7; _AllBoolsTypedMapIterator(this._map) - : _buffer = _map.buffer, - _schema = _map._schema, - _valuesPointer = _map.pointer + - _pointerSize + - (_map.filled ? 0 : _map._schema._fieldSetSize); + : _buffer = _map.buffer, + _schema = _map._schema, + _valuesPointer = + _map.pointer + + _pointerSize + + (_map.filled ? 0 : _map._schema._fieldSetSize); @override T get current; diff --git a/pkgs/dart_model/lib/src/lazy_merged_map.dart b/pkgs/dart_model/lib/src/lazy_merged_map.dart index 4e1815c3..df559961 100644 --- a/pkgs/dart_model/lib/src/lazy_merged_map.dart +++ b/pkgs/dart_model/lib/src/lazy_merged_map.dart @@ -41,14 +41,18 @@ class LazyMergedMapView extends MapBase { } if (leftValue is List && rightValue is List) { if (leftValue.length != rightValue.length) { - throw StateError('Cannot merge lists of different lengths, ' - 'got $leftValue and $rightValue'); + throw StateError( + 'Cannot merge lists of different lengths, ' + 'got $leftValue and $rightValue', + ); } // TODO: Something better for lists, it isn't clear how to merge them. return leftValue; } else if (leftValue != rightValue) { - throw StateError('Cannot merge maps with different values, and ' - '$leftValue != $rightValue'); + throw StateError( + 'Cannot merge maps with different values, and ' + '$leftValue != $rightValue', + ); } return leftValue; } diff --git a/pkgs/dart_model/lib/src/macro_metadata.g.dart b/pkgs/dart_model/lib/src/macro_metadata.g.dart index fd022236..09108589 100644 --- a/pkgs/dart_model/lib/src/macro_metadata.g.dart +++ b/pkgs/dart_model/lib/src/macro_metadata.g.dart @@ -23,17 +23,13 @@ extension type Argument.fromJson(Map node) implements Object { 'value': Type.anyPointer, }); static Argument positionalArgument(PositionalArgument positionalArgument) => - Argument.fromJson(Scope.createMap( - _schema, - 'PositionalArgument', - positionalArgument, - )); + Argument.fromJson( + Scope.createMap(_schema, 'PositionalArgument', positionalArgument), + ); static Argument namedArgument(NamedArgument namedArgument) => - Argument.fromJson(Scope.createMap( - _schema, - 'NamedArgument', - namedArgument, - )); + Argument.fromJson( + Scope.createMap(_schema, 'NamedArgument', namedArgument), + ); ArgumentType get type { switch (node['type'] as String) { case 'PositionalArgument': @@ -77,29 +73,18 @@ extension type Element.fromJson(Map node) implements Object { 'value': Type.anyPointer, }); static Element expressionElement(ExpressionElement expressionElement) => - Element.fromJson(Scope.createMap( - _schema, - 'ExpressionElement', - expressionElement, - )); + Element.fromJson( + Scope.createMap(_schema, 'ExpressionElement', expressionElement), + ); static Element mapEntryElement(MapEntryElement mapEntryElement) => - Element.fromJson(Scope.createMap( - _schema, - 'MapEntryElement', - mapEntryElement, - )); - static Element spreadElement(SpreadElement spreadElement) => - Element.fromJson(Scope.createMap( - _schema, - 'SpreadElement', - spreadElement, - )); + Element.fromJson( + Scope.createMap(_schema, 'MapEntryElement', mapEntryElement), + ); + static Element spreadElement(SpreadElement spreadElement) => Element.fromJson( + Scope.createMap(_schema, 'SpreadElement', spreadElement), + ); static Element ifElement(IfElement ifElement) => - Element.fromJson(Scope.createMap( - _schema, - 'IfElement', - ifElement, - )); + Element.fromJson(Scope.createMap(_schema, 'IfElement', ifElement)); ElementType get type { switch (node['type'] as String) { case 'ExpressionElement': @@ -191,209 +176,131 @@ extension type Expression.fromJson(Map node) 'value': Type.anyPointer, }); static Expression invalidExpression(InvalidExpression invalidExpression) => - Expression.fromJson(Scope.createMap( - _schema, - 'InvalidExpression', - invalidExpression, - )); + Expression.fromJson( + Scope.createMap(_schema, 'InvalidExpression', invalidExpression), + ); static Expression staticGet(StaticGet staticGet) => - Expression.fromJson(Scope.createMap( - _schema, - 'StaticGet', - staticGet, - )); + Expression.fromJson(Scope.createMap(_schema, 'StaticGet', staticGet)); static Expression functionTearOff(FunctionTearOff functionTearOff) => - Expression.fromJson(Scope.createMap( - _schema, - 'FunctionTearOff', - functionTearOff, - )); + Expression.fromJson( + Scope.createMap(_schema, 'FunctionTearOff', functionTearOff), + ); static Expression constructorTearOff(ConstructorTearOff constructorTearOff) => - Expression.fromJson(Scope.createMap( - _schema, - 'ConstructorTearOff', - constructorTearOff, - )); + Expression.fromJson( + Scope.createMap(_schema, 'ConstructorTearOff', constructorTearOff), + ); static Expression constructorInvocation( - ConstructorInvocation constructorInvocation) => - Expression.fromJson(Scope.createMap( - _schema, - 'ConstructorInvocation', - constructorInvocation, - )); + ConstructorInvocation constructorInvocation, + ) => Expression.fromJson( + Scope.createMap(_schema, 'ConstructorInvocation', constructorInvocation), + ); static Expression integerLiteral(IntegerLiteral integerLiteral) => - Expression.fromJson(Scope.createMap( - _schema, - 'IntegerLiteral', - integerLiteral, - )); + Expression.fromJson( + Scope.createMap(_schema, 'IntegerLiteral', integerLiteral), + ); static Expression doubleLiteral(DoubleLiteral doubleLiteral) => - Expression.fromJson(Scope.createMap( - _schema, - 'DoubleLiteral', - doubleLiteral, - )); + Expression.fromJson( + Scope.createMap(_schema, 'DoubleLiteral', doubleLiteral), + ); static Expression booleanLiteral(BooleanLiteral booleanLiteral) => - Expression.fromJson(Scope.createMap( - _schema, - 'BooleanLiteral', - booleanLiteral, - )); + Expression.fromJson( + Scope.createMap(_schema, 'BooleanLiteral', booleanLiteral), + ); static Expression nullLiteral(NullLiteral nullLiteral) => - Expression.fromJson(Scope.createMap( - _schema, - 'NullLiteral', - nullLiteral, - )); + Expression.fromJson(Scope.createMap(_schema, 'NullLiteral', nullLiteral)); static Expression symbolLiteral(SymbolLiteral symbolLiteral) => - Expression.fromJson(Scope.createMap( - _schema, - 'SymbolLiteral', - symbolLiteral, - )); + Expression.fromJson( + Scope.createMap(_schema, 'SymbolLiteral', symbolLiteral), + ); static Expression stringLiteral(StringLiteral stringLiteral) => - Expression.fromJson(Scope.createMap( - _schema, - 'StringLiteral', - stringLiteral, - )); + Expression.fromJson( + Scope.createMap(_schema, 'StringLiteral', stringLiteral), + ); static Expression adjacentStringLiterals( - AdjacentStringLiterals adjacentStringLiterals) => - Expression.fromJson(Scope.createMap( - _schema, - 'AdjacentStringLiterals', - adjacentStringLiterals, - )); + AdjacentStringLiterals adjacentStringLiterals, + ) => Expression.fromJson( + Scope.createMap(_schema, 'AdjacentStringLiterals', adjacentStringLiterals), + ); static Expression implicitInvocation(ImplicitInvocation implicitInvocation) => - Expression.fromJson(Scope.createMap( - _schema, - 'ImplicitInvocation', - implicitInvocation, - )); + Expression.fromJson( + Scope.createMap(_schema, 'ImplicitInvocation', implicitInvocation), + ); static Expression staticInvocation(StaticInvocation staticInvocation) => - Expression.fromJson(Scope.createMap( - _schema, - 'StaticInvocation', - staticInvocation, - )); + Expression.fromJson( + Scope.createMap(_schema, 'StaticInvocation', staticInvocation), + ); static Expression instantiation(Instantiation instantiation) => - Expression.fromJson(Scope.createMap( - _schema, - 'Instantiation', - instantiation, - )); + Expression.fromJson( + Scope.createMap(_schema, 'Instantiation', instantiation), + ); static Expression methodInvocation(MethodInvocation methodInvocation) => - Expression.fromJson(Scope.createMap( - _schema, - 'MethodInvocation', - methodInvocation, - )); + Expression.fromJson( + Scope.createMap(_schema, 'MethodInvocation', methodInvocation), + ); static Expression propertyGet(PropertyGet propertyGet) => - Expression.fromJson(Scope.createMap( - _schema, - 'PropertyGet', - propertyGet, - )); + Expression.fromJson(Scope.createMap(_schema, 'PropertyGet', propertyGet)); static Expression nullAwarePropertyGet( - NullAwarePropertyGet nullAwarePropertyGet) => - Expression.fromJson(Scope.createMap( - _schema, - 'NullAwarePropertyGet', - nullAwarePropertyGet, - )); + NullAwarePropertyGet nullAwarePropertyGet, + ) => Expression.fromJson( + Scope.createMap(_schema, 'NullAwarePropertyGet', nullAwarePropertyGet), + ); static Expression typeLiteral(TypeLiteral typeLiteral) => - Expression.fromJson(Scope.createMap( - _schema, - 'TypeLiteral', - typeLiteral, - )); + Expression.fromJson(Scope.createMap(_schema, 'TypeLiteral', typeLiteral)); static Expression parenthesizedExpression( - ParenthesizedExpression parenthesizedExpression) => - Expression.fromJson(Scope.createMap( - _schema, - 'ParenthesizedExpression', - parenthesizedExpression, - )); + ParenthesizedExpression parenthesizedExpression, + ) => Expression.fromJson( + Scope.createMap( + _schema, + 'ParenthesizedExpression', + parenthesizedExpression, + ), + ); static Expression conditionalExpression( - ConditionalExpression conditionalExpression) => - Expression.fromJson(Scope.createMap( - _schema, - 'ConditionalExpression', - conditionalExpression, - )); + ConditionalExpression conditionalExpression, + ) => Expression.fromJson( + Scope.createMap(_schema, 'ConditionalExpression', conditionalExpression), + ); static Expression listLiteral(ListLiteral listLiteral) => - Expression.fromJson(Scope.createMap( - _schema, - 'ListLiteral', - listLiteral, - )); + Expression.fromJson(Scope.createMap(_schema, 'ListLiteral', listLiteral)); static Expression setOrMapLiteral(SetOrMapLiteral setOrMapLiteral) => - Expression.fromJson(Scope.createMap( - _schema, - 'SetOrMapLiteral', - setOrMapLiteral, - )); + Expression.fromJson( + Scope.createMap(_schema, 'SetOrMapLiteral', setOrMapLiteral), + ); static Expression recordLiteral(RecordLiteral recordLiteral) => - Expression.fromJson(Scope.createMap( - _schema, - 'RecordLiteral', - recordLiteral, - )); + Expression.fromJson( + Scope.createMap(_schema, 'RecordLiteral', recordLiteral), + ); static Expression ifNull(IfNull ifNull) => - Expression.fromJson(Scope.createMap( - _schema, - 'IfNull', - ifNull, - )); + Expression.fromJson(Scope.createMap(_schema, 'IfNull', ifNull)); static Expression logicalExpression(LogicalExpression logicalExpression) => - Expression.fromJson(Scope.createMap( - _schema, - 'LogicalExpression', - logicalExpression, - )); + Expression.fromJson( + Scope.createMap(_schema, 'LogicalExpression', logicalExpression), + ); static Expression equalityExpression(EqualityExpression equalityExpression) => - Expression.fromJson(Scope.createMap( - _schema, - 'EqualityExpression', - equalityExpression, - )); + Expression.fromJson( + Scope.createMap(_schema, 'EqualityExpression', equalityExpression), + ); static Expression binaryExpression(BinaryExpression binaryExpression) => - Expression.fromJson(Scope.createMap( - _schema, - 'BinaryExpression', - binaryExpression, - )); + Expression.fromJson( + Scope.createMap(_schema, 'BinaryExpression', binaryExpression), + ); static Expression unaryExpression(UnaryExpression unaryExpression) => - Expression.fromJson(Scope.createMap( - _schema, - 'UnaryExpression', - unaryExpression, - )); + Expression.fromJson( + Scope.createMap(_schema, 'UnaryExpression', unaryExpression), + ); static Expression isTest(IsTest isTest) => - Expression.fromJson(Scope.createMap( - _schema, - 'IsTest', - isTest, - )); + Expression.fromJson(Scope.createMap(_schema, 'IsTest', isTest)); static Expression asExpression(AsExpression asExpression) => - Expression.fromJson(Scope.createMap( - _schema, - 'AsExpression', - asExpression, - )); + Expression.fromJson( + Scope.createMap(_schema, 'AsExpression', asExpression), + ); static Expression nullCheck(NullCheck nullCheck) => - Expression.fromJson(Scope.createMap( - _schema, - 'NullCheck', - nullCheck, - )); + Expression.fromJson(Scope.createMap(_schema, 'NullCheck', nullCheck)); static Expression unresolvedExpression( - UnresolvedExpression unresolvedExpression) => - Expression.fromJson(Scope.createMap( - _schema, - 'UnresolvedExpression', - unresolvedExpression, - )); + UnresolvedExpression unresolvedExpression, + ) => Expression.fromJson( + Scope.createMap(_schema, 'UnresolvedExpression', unresolvedExpression), + ); ExpressionType get type { switch (node['type'] as String) { case 'InvalidExpression': @@ -500,7 +407,8 @@ extension type Expression.fromJson(Map node) throw StateError('Not a ConstructorInvocation.'); } return ConstructorInvocation.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } IntegerLiteral get asIntegerLiteral { @@ -550,7 +458,8 @@ extension type Expression.fromJson(Map node) throw StateError('Not a AdjacentStringLiterals.'); } return AdjacentStringLiterals.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } ImplicitInvocation get asImplicitInvocation { @@ -607,7 +516,8 @@ extension type Expression.fromJson(Map node) throw StateError('Not a ParenthesizedExpression.'); } return ParenthesizedExpression.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } ConditionalExpression get asConditionalExpression { @@ -615,7 +525,8 @@ extension type Expression.fromJson(Map node) throw StateError('Not a ConditionalExpression.'); } return ConditionalExpression.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } ListLiteral get asListLiteral { @@ -719,18 +630,14 @@ extension type RecordField.fromJson(Map node) 'value': Type.anyPointer, }); static RecordField recordNamedField(RecordNamedField recordNamedField) => - RecordField.fromJson(Scope.createMap( - _schema, - 'RecordNamedField', - recordNamedField, - )); + RecordField.fromJson( + Scope.createMap(_schema, 'RecordNamedField', recordNamedField), + ); static RecordField recordPositionalField( - RecordPositionalField recordPositionalField) => - RecordField.fromJson(Scope.createMap( - _schema, - 'RecordPositionalField', - recordPositionalField, - )); + RecordPositionalField recordPositionalField, + ) => RecordField.fromJson( + Scope.createMap(_schema, 'RecordPositionalField', recordPositionalField), + ); RecordFieldType get type { switch (node['type'] as String) { case 'RecordNamedField': @@ -754,7 +661,8 @@ extension type RecordField.fromJson(Map node) throw StateError('Not a RecordPositionalField.'); } return RecordPositionalField.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } } @@ -781,68 +689,52 @@ extension type Reference.fromJson(Map node) implements Object { 'value': Type.anyPointer, }); static Reference fieldReference(FieldReference fieldReference) => - Reference.fromJson(Scope.createMap( - _schema, - 'FieldReference', - fieldReference, - )); + Reference.fromJson( + Scope.createMap(_schema, 'FieldReference', fieldReference), + ); static Reference functionReference(FunctionReference functionReference) => - Reference.fromJson(Scope.createMap( - _schema, - 'FunctionReference', - functionReference, - )); + Reference.fromJson( + Scope.createMap(_schema, 'FunctionReference', functionReference), + ); static Reference constructorReference( - ConstructorReference constructorReference) => - Reference.fromJson(Scope.createMap( - _schema, - 'ConstructorReference', - constructorReference, - )); + ConstructorReference constructorReference, + ) => Reference.fromJson( + Scope.createMap(_schema, 'ConstructorReference', constructorReference), + ); static Reference typeReference(TypeReference typeReference) => - Reference.fromJson(Scope.createMap( - _schema, - 'TypeReference', - typeReference, - )); + Reference.fromJson( + Scope.createMap(_schema, 'TypeReference', typeReference), + ); static Reference classReference(ClassReference classReference) => - Reference.fromJson(Scope.createMap( - _schema, - 'ClassReference', - classReference, - )); + Reference.fromJson( + Scope.createMap(_schema, 'ClassReference', classReference), + ); static Reference typedefReference(TypedefReference typedefReference) => - Reference.fromJson(Scope.createMap( - _schema, - 'TypedefReference', - typedefReference, - )); + Reference.fromJson( + Scope.createMap(_schema, 'TypedefReference', typedefReference), + ); static Reference extensionReference(ExtensionReference extensionReference) => - Reference.fromJson(Scope.createMap( - _schema, - 'ExtensionReference', - extensionReference, - )); + Reference.fromJson( + Scope.createMap(_schema, 'ExtensionReference', extensionReference), + ); static Reference extensionTypeReference( - ExtensionTypeReference extensionTypeReference) => - Reference.fromJson(Scope.createMap( - _schema, - 'ExtensionTypeReference', - extensionTypeReference, - )); + ExtensionTypeReference extensionTypeReference, + ) => Reference.fromJson( + Scope.createMap(_schema, 'ExtensionTypeReference', extensionTypeReference), + ); static Reference enumReference(EnumReference enumReference) => - Reference.fromJson(Scope.createMap( - _schema, - 'EnumReference', - enumReference, - )); + Reference.fromJson( + Scope.createMap(_schema, 'EnumReference', enumReference), + ); static Reference functionTypeParameterReference( - FunctionTypeParameterReference functionTypeParameterReference) => - Reference.fromJson(Scope.createMap( - _schema, - 'FunctionTypeParameterReference', - functionTypeParameterReference, - )); + FunctionTypeParameterReference functionTypeParameterReference, + ) => Reference.fromJson( + Scope.createMap( + _schema, + 'FunctionTypeParameterReference', + functionTypeParameterReference, + ), + ); ReferenceType get type { switch (node['type'] as String) { case 'FieldReference': @@ -924,7 +816,8 @@ extension type Reference.fromJson(Map node) implements Object { throw StateError('Not a ExtensionTypeReference.'); } return ExtensionTypeReference.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } EnumReference get asEnumReference { @@ -939,7 +832,8 @@ extension type Reference.fromJson(Map node) implements Object { throw StateError('Not a FunctionTypeParameterReference.'); } return FunctionTypeParameterReference.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } } @@ -959,18 +853,14 @@ extension type StringLiteralPart.fromJson(Map node) 'value': Type.anyPointer, }); static StringLiteralPart stringPart(StringPart stringPart) => - StringLiteralPart.fromJson(Scope.createMap( - _schema, - 'StringPart', - stringPart, - )); + StringLiteralPart.fromJson( + Scope.createMap(_schema, 'StringPart', stringPart), + ); static StringLiteralPart interpolationPart( - InterpolationPart interpolationPart) => - StringLiteralPart.fromJson(Scope.createMap( - _schema, - 'InterpolationPart', - interpolationPart, - )); + InterpolationPart interpolationPart, + ) => StringLiteralPart.fromJson( + Scope.createMap(_schema, 'InterpolationPart', interpolationPart), + ); StringLiteralPartType get type { switch (node['type'] as String) { case 'StringPart': @@ -1020,68 +910,58 @@ extension type TypeAnnotation.fromJson(Map node) 'value': Type.anyPointer, }); static TypeAnnotation namedTypeAnnotation( - NamedTypeAnnotation namedTypeAnnotation) => - TypeAnnotation.fromJson(Scope.createMap( - _schema, - 'NamedTypeAnnotation', - namedTypeAnnotation, - )); + NamedTypeAnnotation namedTypeAnnotation, + ) => TypeAnnotation.fromJson( + Scope.createMap(_schema, 'NamedTypeAnnotation', namedTypeAnnotation), + ); static TypeAnnotation nullableTypeAnnotation( - NullableTypeAnnotation nullableTypeAnnotation) => - TypeAnnotation.fromJson(Scope.createMap( - _schema, - 'NullableTypeAnnotation', - nullableTypeAnnotation, - )); + NullableTypeAnnotation nullableTypeAnnotation, + ) => TypeAnnotation.fromJson( + Scope.createMap(_schema, 'NullableTypeAnnotation', nullableTypeAnnotation), + ); static TypeAnnotation voidTypeAnnotation( - VoidTypeAnnotation voidTypeAnnotation) => - TypeAnnotation.fromJson(Scope.createMap( - _schema, - 'VoidTypeAnnotation', - voidTypeAnnotation, - )); + VoidTypeAnnotation voidTypeAnnotation, + ) => TypeAnnotation.fromJson( + Scope.createMap(_schema, 'VoidTypeAnnotation', voidTypeAnnotation), + ); static TypeAnnotation dynamicTypeAnnotation( - DynamicTypeAnnotation dynamicTypeAnnotation) => - TypeAnnotation.fromJson(Scope.createMap( - _schema, - 'DynamicTypeAnnotation', - dynamicTypeAnnotation, - )); + DynamicTypeAnnotation dynamicTypeAnnotation, + ) => TypeAnnotation.fromJson( + Scope.createMap(_schema, 'DynamicTypeAnnotation', dynamicTypeAnnotation), + ); static TypeAnnotation invalidTypeAnnotation( - InvalidTypeAnnotation invalidTypeAnnotation) => - TypeAnnotation.fromJson(Scope.createMap( - _schema, - 'InvalidTypeAnnotation', - invalidTypeAnnotation, - )); + InvalidTypeAnnotation invalidTypeAnnotation, + ) => TypeAnnotation.fromJson( + Scope.createMap(_schema, 'InvalidTypeAnnotation', invalidTypeAnnotation), + ); static TypeAnnotation unresolvedTypeAnnotation( - UnresolvedTypeAnnotation unresolvedTypeAnnotation) => - TypeAnnotation.fromJson(Scope.createMap( - _schema, - 'UnresolvedTypeAnnotation', - unresolvedTypeAnnotation, - )); + UnresolvedTypeAnnotation unresolvedTypeAnnotation, + ) => TypeAnnotation.fromJson( + Scope.createMap( + _schema, + 'UnresolvedTypeAnnotation', + unresolvedTypeAnnotation, + ), + ); static TypeAnnotation functionTypeAnnotation( - FunctionTypeAnnotation functionTypeAnnotation) => - TypeAnnotation.fromJson(Scope.createMap( - _schema, - 'FunctionTypeAnnotation', - functionTypeAnnotation, - )); + FunctionTypeAnnotation functionTypeAnnotation, + ) => TypeAnnotation.fromJson( + Scope.createMap(_schema, 'FunctionTypeAnnotation', functionTypeAnnotation), + ); static TypeAnnotation functionTypeParameterType( - FunctionTypeParameterType functionTypeParameterType) => - TypeAnnotation.fromJson(Scope.createMap( - _schema, - 'FunctionTypeParameterType', - functionTypeParameterType, - )); + FunctionTypeParameterType functionTypeParameterType, + ) => TypeAnnotation.fromJson( + Scope.createMap( + _schema, + 'FunctionTypeParameterType', + functionTypeParameterType, + ), + ); static TypeAnnotation recordTypeAnnotation( - RecordTypeAnnotation recordTypeAnnotation) => - TypeAnnotation.fromJson(Scope.createMap( - _schema, - 'RecordTypeAnnotation', - recordTypeAnnotation, - )); + RecordTypeAnnotation recordTypeAnnotation, + ) => TypeAnnotation.fromJson( + Scope.createMap(_schema, 'RecordTypeAnnotation', recordTypeAnnotation), + ); TypeAnnotationType get type { switch (node['type'] as String) { case 'NamedTypeAnnotation': @@ -1119,7 +999,8 @@ extension type TypeAnnotation.fromJson(Map node) throw StateError('Not a NullableTypeAnnotation.'); } return NullableTypeAnnotation.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } VoidTypeAnnotation get asVoidTypeAnnotation { @@ -1134,7 +1015,8 @@ extension type TypeAnnotation.fromJson(Map node) throw StateError('Not a DynamicTypeAnnotation.'); } return DynamicTypeAnnotation.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } InvalidTypeAnnotation get asInvalidTypeAnnotation { @@ -1142,7 +1024,8 @@ extension type TypeAnnotation.fromJson(Map node) throw StateError('Not a InvalidTypeAnnotation.'); } return InvalidTypeAnnotation.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } UnresolvedTypeAnnotation get asUnresolvedTypeAnnotation { @@ -1150,7 +1033,8 @@ extension type TypeAnnotation.fromJson(Map node) throw StateError('Not a UnresolvedTypeAnnotation.'); } return UnresolvedTypeAnnotation.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } FunctionTypeAnnotation get asFunctionTypeAnnotation { @@ -1158,7 +1042,8 @@ extension type TypeAnnotation.fromJson(Map node) throw StateError('Not a FunctionTypeAnnotation.'); } return FunctionTypeAnnotation.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } FunctionTypeParameterType get asFunctionTypeParameterType { @@ -1166,7 +1051,8 @@ extension type TypeAnnotation.fromJson(Map node) throw StateError('Not a FunctionTypeParameterType.'); } return FunctionTypeParameterType.fromJson( - node['value'] as Map); + node['value'] as Map, + ); } RecordTypeAnnotation get asRecordTypeAnnotation { @@ -1179,30 +1065,38 @@ extension type TypeAnnotation.fromJson(Map node) /// extension type const BinaryOperator.fromJson(String string) implements Object { - static const BinaryOperator greaterThan = - BinaryOperator.fromJson('greaterThan'); - static const BinaryOperator greaterThanOrEqual = - BinaryOperator.fromJson('greaterThanOrEqual'); + static const BinaryOperator greaterThan = BinaryOperator.fromJson( + 'greaterThan', + ); + static const BinaryOperator greaterThanOrEqual = BinaryOperator.fromJson( + 'greaterThanOrEqual', + ); static const BinaryOperator lessThan = BinaryOperator.fromJson('lessThan'); - static const BinaryOperator lessThanOrEqual = - BinaryOperator.fromJson('lessThanOrEqual'); + static const BinaryOperator lessThanOrEqual = BinaryOperator.fromJson( + 'lessThanOrEqual', + ); static const BinaryOperator shiftLeft = BinaryOperator.fromJson('shiftLeft'); - static const BinaryOperator signedShiftRight = - BinaryOperator.fromJson('signedShiftRight'); - static const BinaryOperator unsignedShiftRight = - BinaryOperator.fromJson('unsignedShiftRight'); + static const BinaryOperator signedShiftRight = BinaryOperator.fromJson( + 'signedShiftRight', + ); + static const BinaryOperator unsignedShiftRight = BinaryOperator.fromJson( + 'unsignedShiftRight', + ); static const BinaryOperator plus = BinaryOperator.fromJson('plus'); static const BinaryOperator minus = BinaryOperator.fromJson('minus'); static const BinaryOperator times = BinaryOperator.fromJson('times'); static const BinaryOperator divide = BinaryOperator.fromJson('divide'); - static const BinaryOperator integerDivide = - BinaryOperator.fromJson('integerDivide'); + static const BinaryOperator integerDivide = BinaryOperator.fromJson( + 'integerDivide', + ); static const BinaryOperator modulo = BinaryOperator.fromJson('modulo'); static const BinaryOperator bitwiseOr = BinaryOperator.fromJson('bitwiseOr'); - static const BinaryOperator bitwiseAnd = - BinaryOperator.fromJson('bitwiseAnd'); - static const BinaryOperator bitwiseXor = - BinaryOperator.fromJson('bitwiseXor'); + static const BinaryOperator bitwiseAnd = BinaryOperator.fromJson( + 'bitwiseAnd', + ); + static const BinaryOperator bitwiseXor = BinaryOperator.fromJson( + 'bitwiseXor', + ); } /// @@ -1225,14 +1119,8 @@ extension type AsExpression.fromJson(Map node) 'expression': Type.typedMapPointer, 'type': Type.typedMapPointer, }); - AsExpression({ - Expression? expression, - TypeAnnotation? type, - }) : this.fromJson(Scope.createMap( - _schema, - expression, - type, - )); + AsExpression({Expression? expression, TypeAnnotation? type}) + : this.fromJson(Scope.createMap(_schema, expression, type)); /// Expression get expression => node['expression'] as Expression; @@ -1253,12 +1141,7 @@ extension type BinaryExpression.fromJson(Map node) Expression? left, BinaryOperator? operator, Expression? right, - }) : this.fromJson(Scope.createMap( - _schema, - left, - operator, - right, - )); + }) : this.fromJson(Scope.createMap(_schema, left, operator, right)); /// Expression get left => node['left'] as Expression; @@ -1276,12 +1159,8 @@ extension type BooleanLiteral.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'text': Type.stringPointer, }); - BooleanLiteral({ - String? text, - }) : this.fromJson(Scope.createMap( - _schema, - text, - )); + BooleanLiteral({String? text}) + : this.fromJson(Scope.createMap(_schema, text)); /// String get text => node['text'] as String; @@ -1291,10 +1170,7 @@ extension type BooleanLiteral.fromJson(Map node) extension type ClassReference.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - ClassReference() - : this.fromJson(Scope.createMap( - _schema, - )); + ClassReference() : this.fromJson(Scope.createMap(_schema)); } /// @@ -1309,12 +1185,7 @@ extension type ConditionalExpression.fromJson(Map node) Expression? condition, Expression? then, Expression? otherwise, - }) : this.fromJson(Scope.createMap( - _schema, - condition, - then, - otherwise, - )); + }) : this.fromJson(Scope.createMap(_schema, condition, then, otherwise)); /// Expression get condition => node['condition'] as Expression; @@ -1338,12 +1209,7 @@ extension type ConstructorInvocation.fromJson(Map node) TypeAnnotation? type, Reference? constructor, List? arguments, - }) : this.fromJson(Scope.createMap( - _schema, - type, - constructor, - arguments, - )); + }) : this.fromJson(Scope.createMap(_schema, type, constructor, arguments)); /// TypeAnnotation get type => node['type'] as TypeAnnotation; @@ -1359,10 +1225,7 @@ extension type ConstructorInvocation.fromJson(Map node) extension type ConstructorReference.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - ConstructorReference() - : this.fromJson(Scope.createMap( - _schema, - )); + ConstructorReference() : this.fromJson(Scope.createMap(_schema)); } /// @@ -1372,14 +1235,8 @@ extension type ConstructorTearOff.fromJson(Map node) 'type': Type.typedMapPointer, 'reference': Type.typedMapPointer, }); - ConstructorTearOff({ - TypeAnnotation? type, - ConstructorReference? reference, - }) : this.fromJson(Scope.createMap( - _schema, - type, - reference, - )); + ConstructorTearOff({TypeAnnotation? type, ConstructorReference? reference}) + : this.fromJson(Scope.createMap(_schema, type, reference)); /// TypeAnnotation get type => node['type'] as TypeAnnotation; @@ -1395,12 +1252,7 @@ extension type DoubleLiteral.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'text': Type.stringPointer, }); - DoubleLiteral({ - String? text, - }) : this.fromJson(Scope.createMap( - _schema, - text, - )); + DoubleLiteral({String? text}) : this.fromJson(Scope.createMap(_schema, text)); /// String get text => node['text'] as String; @@ -1412,12 +1264,8 @@ extension type DynamicTypeAnnotation.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'reference': Type.typedMapPointer, }); - DynamicTypeAnnotation({ - Reference? reference, - }) : this.fromJson(Scope.createMap( - _schema, - reference, - )); + DynamicTypeAnnotation({Reference? reference}) + : this.fromJson(Scope.createMap(_schema, reference)); /// Reference get reference => node['reference'] as Reference; @@ -1427,10 +1275,7 @@ extension type DynamicTypeAnnotation.fromJson(Map node) extension type EnumReference.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - EnumReference() - : this.fromJson(Scope.createMap( - _schema, - )); + EnumReference() : this.fromJson(Scope.createMap(_schema)); } /// @@ -1441,16 +1286,8 @@ extension type EqualityExpression.fromJson(Map node) 'right': Type.typedMapPointer, 'isNotEquals': Type.boolean, }); - EqualityExpression({ - Expression? left, - Expression? right, - bool? isNotEquals, - }) : this.fromJson(Scope.createMap( - _schema, - left, - right, - isNotEquals, - )); + EqualityExpression({Expression? left, Expression? right, bool? isNotEquals}) + : this.fromJson(Scope.createMap(_schema, left, right, isNotEquals)); /// Expression get left => node['left'] as Expression; @@ -1469,14 +1306,8 @@ extension type ExpressionElement.fromJson(Map node) 'expression': Type.typedMapPointer, 'isNullAware': Type.boolean, }); - ExpressionElement({ - Expression? expression, - bool? isNullAware, - }) : this.fromJson(Scope.createMap( - _schema, - expression, - isNullAware, - )); + ExpressionElement({Expression? expression, bool? isNullAware}) + : this.fromJson(Scope.createMap(_schema, expression, isNullAware)); /// Expression get expression => node['expression'] as Expression; @@ -1489,60 +1320,42 @@ extension type ExpressionElement.fromJson(Map node) extension type ExtensionReference.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - ExtensionReference() - : this.fromJson(Scope.createMap( - _schema, - )); + ExtensionReference() : this.fromJson(Scope.createMap(_schema)); } /// extension type ExtensionTypeReference.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - ExtensionTypeReference() - : this.fromJson(Scope.createMap( - _schema, - )); + ExtensionTypeReference() : this.fromJson(Scope.createMap(_schema)); } /// extension type FieldReference.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - FieldReference() - : this.fromJson(Scope.createMap( - _schema, - )); + FieldReference() : this.fromJson(Scope.createMap(_schema)); } /// extension type FormalParameter.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - FormalParameter() - : this.fromJson(Scope.createMap( - _schema, - )); + FormalParameter() : this.fromJson(Scope.createMap(_schema)); } /// extension type FormalParameterGroup.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - FormalParameterGroup() - : this.fromJson(Scope.createMap( - _schema, - )); + FormalParameterGroup() : this.fromJson(Scope.createMap(_schema)); } /// extension type FunctionReference.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - FunctionReference() - : this.fromJson(Scope.createMap( - _schema, - )); + FunctionReference() : this.fromJson(Scope.createMap(_schema)); } /// @@ -1551,12 +1364,8 @@ extension type FunctionTearOff.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'reference': Type.typedMapPointer, }); - FunctionTearOff({ - FunctionReference? reference, - }) : this.fromJson(Scope.createMap( - _schema, - reference, - )); + FunctionTearOff({FunctionReference? reference}) + : this.fromJson(Scope.createMap(_schema, reference)); /// FunctionReference get reference => node['reference'] as FunctionReference; @@ -1574,12 +1383,9 @@ extension type FunctionTypeAnnotation.fromJson(Map node) TypeAnnotation? returnType, List? typeParameters, List? formalParameters, - }) : this.fromJson(Scope.createMap( - _schema, - returnType, - typeParameters, - formalParameters, - )); + }) : this.fromJson( + Scope.createMap(_schema, returnType, typeParameters, formalParameters), + ); /// TypeAnnotation? get returnType => node['returnType'] as TypeAnnotation?; @@ -1597,20 +1403,16 @@ extension type FunctionTypeAnnotation.fromJson(Map node) extension type FunctionTypeParameter.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - FunctionTypeParameter() - : this.fromJson(Scope.createMap( - _schema, - )); + FunctionTypeParameter() : this.fromJson(Scope.createMap(_schema)); } /// extension type FunctionTypeParameterReference.fromJson( - Map node) implements Object { + Map node +) + implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - FunctionTypeParameterReference() - : this.fromJson(Scope.createMap( - _schema, - )); + FunctionTypeParameterReference() : this.fromJson(Scope.createMap(_schema)); } /// @@ -1619,12 +1421,8 @@ extension type FunctionTypeParameterType.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'functionTypeParameter': Type.typedMapPointer, }); - FunctionTypeParameterType({ - FunctionTypeParameter? functionTypeParameter, - }) : this.fromJson(Scope.createMap( - _schema, - functionTypeParameter, - )); + FunctionTypeParameterType({FunctionTypeParameter? functionTypeParameter}) + : this.fromJson(Scope.createMap(_schema, functionTypeParameter)); /// FunctionTypeParameter get functionTypeParameter => @@ -1638,16 +1436,8 @@ extension type IfElement.fromJson(Map node) implements Object { 'then': Type.typedMapPointer, 'otherwise': Type.typedMapPointer, }); - IfElement({ - Expression? condition, - Element? then, - Element? otherwise, - }) : this.fromJson(Scope.createMap( - _schema, - condition, - then, - otherwise, - )); + IfElement({Expression? condition, Element? then, Element? otherwise}) + : this.fromJson(Scope.createMap(_schema, condition, then, otherwise)); /// Expression get condition => node['condition'] as Expression; @@ -1665,14 +1455,8 @@ extension type IfNull.fromJson(Map node) implements Object { 'left': Type.typedMapPointer, 'right': Type.typedMapPointer, }); - IfNull({ - Expression? left, - Expression? right, - }) : this.fromJson(Scope.createMap( - _schema, - left, - right, - )); + IfNull({Expression? left, Expression? right}) + : this.fromJson(Scope.createMap(_schema, left, right)); /// Expression get left => node['left'] as Expression; @@ -1693,12 +1477,9 @@ extension type ImplicitInvocation.fromJson(Map node) Expression? receiver, List? typeArguments, List? arguments, - }) : this.fromJson(Scope.createMap( - _schema, - receiver, - typeArguments, - arguments, - )); + }) : this.fromJson( + Scope.createMap(_schema, receiver, typeArguments, arguments), + ); /// Expression get receiver => node['receiver'] as Expression; @@ -1718,14 +1499,8 @@ extension type Instantiation.fromJson(Map node) 'receiver': Type.typedMapPointer, 'typeArguments': Type.closedListPointer, }); - Instantiation({ - Expression? receiver, - List? typeArguments, - }) : this.fromJson(Scope.createMap( - _schema, - receiver, - typeArguments, - )); + Instantiation({Expression? receiver, List? typeArguments}) + : this.fromJson(Scope.createMap(_schema, receiver, typeArguments)); /// Expression get receiver => node['receiver'] as Expression; @@ -1741,12 +1516,8 @@ extension type IntegerLiteral.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'text': Type.stringPointer, }); - IntegerLiteral({ - String? text, - }) : this.fromJson(Scope.createMap( - _schema, - text, - )); + IntegerLiteral({String? text}) + : this.fromJson(Scope.createMap(_schema, text)); /// String get text => node['text'] as String; @@ -1758,12 +1529,8 @@ extension type InterpolationPart.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'expression': Type.typedMapPointer, }); - InterpolationPart({ - Expression? expression, - }) : this.fromJson(Scope.createMap( - _schema, - expression, - )); + InterpolationPart({Expression? expression}) + : this.fromJson(Scope.createMap(_schema, expression)); /// Expression get expression => node['expression'] as Expression; @@ -1773,20 +1540,14 @@ extension type InterpolationPart.fromJson(Map node) extension type InvalidExpression.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - InvalidExpression() - : this.fromJson(Scope.createMap( - _schema, - )); + InvalidExpression() : this.fromJson(Scope.createMap(_schema)); } /// extension type InvalidTypeAnnotation.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - InvalidTypeAnnotation() - : this.fromJson(Scope.createMap( - _schema, - )); + InvalidTypeAnnotation() : this.fromJson(Scope.createMap(_schema)); } /// @@ -1796,16 +1557,8 @@ extension type IsTest.fromJson(Map node) implements Object { 'type': Type.typedMapPointer, 'isNot': Type.boolean, }); - IsTest({ - Expression? expression, - TypeAnnotation? type, - bool? isNot, - }) : this.fromJson(Scope.createMap( - _schema, - expression, - type, - isNot, - )); + IsTest({Expression? expression, TypeAnnotation? type, bool? isNot}) + : this.fromJson(Scope.createMap(_schema, expression, type, isNot)); /// Expression get expression => node['expression'] as Expression; @@ -1824,14 +1577,8 @@ extension type ListLiteral.fromJson(Map node) 'typeArguments': Type.closedListPointer, 'elements': Type.closedListPointer, }); - ListLiteral({ - List? typeArguments, - List? elements, - }) : this.fromJson(Scope.createMap( - _schema, - typeArguments, - elements, - )); + ListLiteral({List? typeArguments, List? elements}) + : this.fromJson(Scope.createMap(_schema, typeArguments, elements)); /// List get typeArguments => @@ -1853,12 +1600,7 @@ extension type LogicalExpression.fromJson(Map node) Expression? left, LogicalOperator? operator, Expression? right, - }) : this.fromJson(Scope.createMap( - _schema, - left, - operator, - right, - )); + }) : this.fromJson(Scope.createMap(_schema, left, operator, right)); /// Expression get left => node['left'] as Expression; @@ -1884,13 +1626,9 @@ extension type MapEntryElement.fromJson(Map node) Expression? value, bool? isNullAwareKey, bool? isNullAwareValue, - }) : this.fromJson(Scope.createMap( - _schema, - key, - value, - isNullAwareKey, - isNullAwareValue, - )); + }) : this.fromJson( + Scope.createMap(_schema, key, value, isNullAwareKey, isNullAwareValue), + ); /// Expression get key => node['key'] as Expression; @@ -1919,13 +1657,9 @@ extension type MethodInvocation.fromJson(Map node) String? name, List? typeArguments, List? arguments, - }) : this.fromJson(Scope.createMap( - _schema, - receiver, - name, - typeArguments, - arguments, - )); + }) : this.fromJson( + Scope.createMap(_schema, receiver, name, typeArguments, arguments), + ); /// Expression get receiver => node['receiver'] as Expression; @@ -1948,14 +1682,8 @@ extension type NamedArgument.fromJson(Map node) 'name': Type.stringPointer, 'expression': Type.typedMapPointer, }); - NamedArgument({ - String? name, - Expression? expression, - }) : this.fromJson(Scope.createMap( - _schema, - name, - expression, - )); + NamedArgument({String? name, Expression? expression}) + : this.fromJson(Scope.createMap(_schema, name, expression)); /// String get name => node['name'] as String; @@ -1974,11 +1702,7 @@ extension type NamedTypeAnnotation.fromJson(Map node) NamedTypeAnnotation({ Reference? reference, List? typeArguments, - }) : this.fromJson(Scope.createMap( - _schema, - reference, - typeArguments, - )); + }) : this.fromJson(Scope.createMap(_schema, reference, typeArguments)); /// Reference get reference => node['reference'] as Reference; @@ -1994,12 +1718,8 @@ extension type NullableTypeAnnotation.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'typeAnnotation': Type.typedMapPointer, }); - NullableTypeAnnotation({ - TypeAnnotation? typeAnnotation, - }) : this.fromJson(Scope.createMap( - _schema, - typeAnnotation, - )); + NullableTypeAnnotation({TypeAnnotation? typeAnnotation}) + : this.fromJson(Scope.createMap(_schema, typeAnnotation)); /// TypeAnnotation get typeAnnotation => node['typeAnnotation'] as TypeAnnotation; @@ -2012,14 +1732,8 @@ extension type NullAwarePropertyGet.fromJson(Map node) 'receiver': Type.typedMapPointer, 'name': Type.stringPointer, }); - NullAwarePropertyGet({ - Expression? receiver, - String? name, - }) : this.fromJson(Scope.createMap( - _schema, - receiver, - name, - )); + NullAwarePropertyGet({Expression? receiver, String? name}) + : this.fromJson(Scope.createMap(_schema, receiver, name)); /// Expression get receiver => node['receiver'] as Expression; @@ -2033,12 +1747,8 @@ extension type NullCheck.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({ 'expression': Type.typedMapPointer, }); - NullCheck({ - Expression? expression, - }) : this.fromJson(Scope.createMap( - _schema, - expression, - )); + NullCheck({Expression? expression}) + : this.fromJson(Scope.createMap(_schema, expression)); /// Expression get expression => node['expression'] as Expression; @@ -2048,10 +1758,7 @@ extension type NullCheck.fromJson(Map node) implements Object { extension type NullLiteral.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - NullLiteral() - : this.fromJson(Scope.createMap( - _schema, - )); + NullLiteral() : this.fromJson(Scope.createMap(_schema)); } /// @@ -2060,12 +1767,8 @@ extension type ParenthesizedExpression.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'expression': Type.typedMapPointer, }); - ParenthesizedExpression({ - Expression? expression, - }) : this.fromJson(Scope.createMap( - _schema, - expression, - )); + ParenthesizedExpression({Expression? expression}) + : this.fromJson(Scope.createMap(_schema, expression)); /// Expression get expression => node['expression'] as Expression; @@ -2077,12 +1780,8 @@ extension type PositionalArgument.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'expression': Type.typedMapPointer, }); - PositionalArgument({ - Expression? expression, - }) : this.fromJson(Scope.createMap( - _schema, - expression, - )); + PositionalArgument({Expression? expression}) + : this.fromJson(Scope.createMap(_schema, expression)); /// Expression get expression => node['expression'] as Expression; @@ -2095,14 +1794,8 @@ extension type PropertyGet.fromJson(Map node) 'receiver': Type.typedMapPointer, 'name': Type.stringPointer, }); - PropertyGet({ - Expression? receiver, - String? name, - }) : this.fromJson(Scope.createMap( - _schema, - receiver, - name, - )); + PropertyGet({Expression? receiver, String? name}) + : this.fromJson(Scope.createMap(_schema, receiver, name)); /// Expression get receiver => node['receiver'] as Expression; @@ -2117,12 +1810,8 @@ extension type RecordLiteral.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'fields': Type.closedListPointer, }); - RecordLiteral({ - List? fields, - }) : this.fromJson(Scope.createMap( - _schema, - fields, - )); + RecordLiteral({List? fields}) + : this.fromJson(Scope.createMap(_schema, fields)); /// List get fields => (node['fields'] as List).cast(); @@ -2135,14 +1824,8 @@ extension type RecordNamedField.fromJson(Map node) 'name': Type.stringPointer, 'expression': Type.typedMapPointer, }); - RecordNamedField({ - String? name, - Expression? expression, - }) : this.fromJson(Scope.createMap( - _schema, - name, - expression, - )); + RecordNamedField({String? name, Expression? expression}) + : this.fromJson(Scope.createMap(_schema, name, expression)); /// String get name => node['name'] as String; @@ -2157,12 +1840,8 @@ extension type RecordPositionalField.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'expression': Type.typedMapPointer, }); - RecordPositionalField({ - Expression? expression, - }) : this.fromJson(Scope.createMap( - _schema, - expression, - )); + RecordPositionalField({Expression? expression}) + : this.fromJson(Scope.createMap(_schema, expression)); /// Expression get expression => node['expression'] as Expression; @@ -2178,11 +1857,7 @@ extension type RecordTypeAnnotation.fromJson(Map node) RecordTypeAnnotation({ List? positional, List? named, - }) : this.fromJson(Scope.createMap( - _schema, - positional, - named, - )); + }) : this.fromJson(Scope.createMap(_schema, positional, named)); /// List get positional => (node['positional'] as List).cast(); @@ -2195,20 +1870,14 @@ extension type RecordTypeAnnotation.fromJson(Map node) extension type RecordTypeEntry.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - RecordTypeEntry() - : this.fromJson(Scope.createMap( - _schema, - )); + RecordTypeEntry() : this.fromJson(Scope.createMap(_schema)); } /// extension type References.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - References() - : this.fromJson(Scope.createMap( - _schema, - )); + References() : this.fromJson(Scope.createMap(_schema)); } /// @@ -2221,11 +1890,7 @@ extension type SetOrMapLiteral.fromJson(Map node) SetOrMapLiteral({ List? typeArguments, List? elements, - }) : this.fromJson(Scope.createMap( - _schema, - typeArguments, - elements, - )); + }) : this.fromJson(Scope.createMap(_schema, typeArguments, elements)); /// List get typeArguments => @@ -2242,14 +1907,8 @@ extension type SpreadElement.fromJson(Map node) 'expression': Type.typedMapPointer, 'isNullAware': Type.boolean, }); - SpreadElement({ - Expression? expression, - bool? isNullAware, - }) : this.fromJson(Scope.createMap( - _schema, - expression, - isNullAware, - )); + SpreadElement({Expression? expression, bool? isNullAware}) + : this.fromJson(Scope.createMap(_schema, expression, isNullAware)); /// Expression get expression => node['expression'] as Expression; @@ -2263,12 +1922,8 @@ extension type StaticGet.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({ 'reference': Type.typedMapPointer, }); - StaticGet({ - FieldReference? reference, - }) : this.fromJson(Scope.createMap( - _schema, - reference, - )); + StaticGet({FieldReference? reference}) + : this.fromJson(Scope.createMap(_schema, reference)); /// FieldReference get reference => node['reference'] as FieldReference; @@ -2286,12 +1941,9 @@ extension type StaticInvocation.fromJson(Map node) FunctionReference? function, List? typeArguments, List? arguments, - }) : this.fromJson(Scope.createMap( - _schema, - function, - typeArguments, - arguments, - )); + }) : this.fromJson( + Scope.createMap(_schema, function, typeArguments, arguments), + ); /// FunctionReference get function => node['function'] as FunctionReference; @@ -2310,12 +1962,8 @@ extension type AdjacentStringLiterals.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'expressions': Type.closedListPointer, }); - AdjacentStringLiterals({ - List? expressions, - }) : this.fromJson(Scope.createMap( - _schema, - expressions, - )); + AdjacentStringLiterals({List? expressions}) + : this.fromJson(Scope.createMap(_schema, expressions)); /// List get expressions => (node['expressions'] as List).cast(); @@ -2327,12 +1975,8 @@ extension type StringLiteral.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'parts': Type.closedListPointer, }); - StringLiteral({ - List? parts, - }) : this.fromJson(Scope.createMap( - _schema, - parts, - )); + StringLiteral({List? parts}) + : this.fromJson(Scope.createMap(_schema, parts)); /// List get parts => (node['parts'] as List).cast(); @@ -2344,12 +1988,7 @@ extension type StringPart.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'text': Type.stringPointer, }); - StringPart({ - String? text, - }) : this.fromJson(Scope.createMap( - _schema, - text, - )); + StringPart({String? text}) : this.fromJson(Scope.createMap(_schema, text)); /// String get text => node['text'] as String; @@ -2361,12 +2000,8 @@ extension type SymbolLiteral.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'parts': Type.closedListPointer, }); - SymbolLiteral({ - List? parts, - }) : this.fromJson(Scope.createMap( - _schema, - parts, - )); + SymbolLiteral({List? parts}) + : this.fromJson(Scope.createMap(_schema, parts)); /// List get parts => (node['parts'] as List).cast(); @@ -2376,10 +2011,7 @@ extension type SymbolLiteral.fromJson(Map node) extension type TypedefReference.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - TypedefReference() - : this.fromJson(Scope.createMap( - _schema, - )); + TypedefReference() : this.fromJson(Scope.createMap(_schema)); } /// @@ -2388,12 +2020,8 @@ extension type TypeLiteral.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'typeAnnotation': Type.typedMapPointer, }); - TypeLiteral({ - TypeAnnotation? typeAnnotation, - }) : this.fromJson(Scope.createMap( - _schema, - typeAnnotation, - )); + TypeLiteral({TypeAnnotation? typeAnnotation}) + : this.fromJson(Scope.createMap(_schema, typeAnnotation)); /// TypeAnnotation get typeAnnotation => node['typeAnnotation'] as TypeAnnotation; @@ -2403,10 +2031,7 @@ extension type TypeLiteral.fromJson(Map node) extension type TypeReference.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - TypeReference() - : this.fromJson(Scope.createMap( - _schema, - )); + TypeReference() : this.fromJson(Scope.createMap(_schema)); } /// @@ -2416,14 +2041,8 @@ extension type UnaryExpression.fromJson(Map node) 'operator': Type.stringPointer, 'expression': Type.typedMapPointer, }); - UnaryExpression({ - UnaryOperator? operator, - Expression? expression, - }) : this.fromJson(Scope.createMap( - _schema, - operator, - expression, - )); + UnaryExpression({UnaryOperator? operator, Expression? expression}) + : this.fromJson(Scope.createMap(_schema, operator, expression)); /// UnaryOperator get operator => node['operator'] as UnaryOperator; @@ -2436,20 +2055,14 @@ extension type UnaryExpression.fromJson(Map node) extension type UnresolvedExpression.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - UnresolvedExpression() - : this.fromJson(Scope.createMap( - _schema, - )); + UnresolvedExpression() : this.fromJson(Scope.createMap(_schema)); } /// extension type UnresolvedTypeAnnotation.fromJson(Map node) implements Object { static final TypedMapSchema _schema = TypedMapSchema({}); - UnresolvedTypeAnnotation() - : this.fromJson(Scope.createMap( - _schema, - )); + UnresolvedTypeAnnotation() : this.fromJson(Scope.createMap(_schema)); } /// @@ -2458,12 +2071,8 @@ extension type VoidTypeAnnotation.fromJson(Map node) static final TypedMapSchema _schema = TypedMapSchema({ 'reference': Type.typedMapPointer, }); - VoidTypeAnnotation({ - Reference? reference, - }) : this.fromJson(Scope.createMap( - _schema, - reference, - )); + VoidTypeAnnotation({Reference? reference}) + : this.fromJson(Scope.createMap(_schema, reference)); /// Reference get reference => node['reference'] as Reference; diff --git a/pkgs/dart_model/lib/src/scopes.dart b/pkgs/dart_model/lib/src/scopes.dart index e2094c7e..2229ac84 100644 --- a/pkgs/dart_model/lib/src/scopes.dart +++ b/pkgs/dart_model/lib/src/scopes.dart @@ -63,8 +63,10 @@ enum Scope { if (this == Scope.macro || this == Scope.query) { final current = _currentOrNull?.type ?? Scope.none; if (current != Scope.none) { - throw StateError('$this cannot be nested in another scope; ' - 'but, currently running: $current'); + throw StateError( + '$this cannot be nested in another scope; ' + 'but, currently running: $current', + ); } } } @@ -73,15 +75,17 @@ enum Scope { /// /// If there is no current scope, creates a buffer just for this map, which /// is slow. - static Map createMap(TypedMapSchema schema, - [Object? v0, - Object? v1, - Object? v2, - Object? v3, - Object? v4, - Object? v5, - Object? v6, - Object? v7]) { + static Map createMap( + TypedMapSchema schema, [ + Object? v0, + Object? v1, + Object? v2, + Object? v3, + Object? v4, + Object? v5, + Object? v6, + Object? v7, + ]) { final scope = Scope._currentOrNull; final buffer = scope?.buffer ?? JsonBufferBuilder(); return buffer.createTypedMap(schema, v0, v1, v2, v3, v4, v5, v6, v7); @@ -107,8 +111,10 @@ enum Scope { final scope = _currentOrNull; final buffer = scope?.buffer ?? JsonBufferBuilder(); if (buffer.map.isNotEmpty) { - throw StateError('Buffer was already used to send: ' - '${buffer.map}, tried to use it to send: $node'); + throw StateError( + 'Buffer was already used to send: ' + '${buffer.map}, tried to use it to send: $node', + ); } buffer.map.addAll(node); return buffer.serialize(); @@ -174,9 +180,11 @@ class MacroScope { final scope = Scope._currentOrNull; return switch (scope) { _ScopeData(:final macro?) => macro, - _ => throw StateError( + _ => + throw StateError( 'MacroScope.current can only be called in macro scope, ' - 'but currently running ${scope?.type ?? Scope.none}.'), + 'but currently running ${scope?.type ?? Scope.none}.', + ), }; } } diff --git a/pkgs/dart_model/lib/src/type.dart b/pkgs/dart_model/lib/src/type.dart index d7be0273..590ff82e 100644 --- a/pkgs/dart_model/lib/src/type.dart +++ b/pkgs/dart_model/lib/src/type.dart @@ -44,27 +44,38 @@ sealed class StaticType { StaticTypeDescType.dynamicTypeDesc => const DynamicType(), StaticTypeDescType.neverTypeDesc => const NeverType(), StaticTypeDescType.nullableTypeDesc => NullableType( - _translateFromDescription( - description.asNullableTypeDesc.inner, knownTypeParameters)), + _translateFromDescription( + description.asNullableTypeDesc.inner, + knownTypeParameters, + ), + ), StaticTypeDescType.namedTypeDesc => InterfaceType._translateFrom( - description.asNamedTypeDesc, knownTypeParameters), + description.asNamedTypeDesc, + knownTypeParameters, + ), StaticTypeDescType.recordTypeDesc => RecordType( - positional: [ - for (final positional in description.asRecordTypeDesc.positional) - _translateFromDescription(positional, knownTypeParameters), - ], - named: { - for (final named in description.asRecordTypeDesc.named) - named.name: - _translateFromDescription(named.type, knownTypeParameters), - }, - ), + positional: [ + for (final positional in description.asRecordTypeDesc.positional) + _translateFromDescription(positional, knownTypeParameters), + ], + named: { + for (final named in description.asRecordTypeDesc.named) + named.name: _translateFromDescription( + named.type, + knownTypeParameters, + ), + }, + ), StaticTypeDescType.functionTypeDesc => FunctionType._translateFrom( - description.asFunctionTypeDesc, knownTypeParameters), + description.asFunctionTypeDesc, + knownTypeParameters, + ), StaticTypeDescType.typeParameterTypeDesc => TypeParameterType( - parameter: knownTypeParameters[ - description.asTypeParameterTypeDesc.parameterId]!, - ), + parameter: + knownTypeParameters[description + .asTypeParameterTypeDesc + .parameterId]!, + ), StaticTypeDescType.voidTypeDesc => const VoidType(), _ => _UnknownType(description), }; @@ -149,18 +160,18 @@ final class InterfaceType extends StaticType { /// element [instantiation] containing a [VoidType]. final List instantiation; - const InterfaceType({ - required this.name, - required this.instantiation, - }) : super._(); + const InterfaceType({required this.name, required this.instantiation}) + : super._(); static InterfaceType _translateFrom( - NamedTypeDesc desc, Map parameters) { + NamedTypeDesc desc, + Map parameters, + ) { return InterfaceType( name: desc.name, instantiation: [ for (final type in desc.instantiation) - StaticType._translateFromDescription(type, parameters) + StaticType._translateFromDescription(type, parameters), ], ); } @@ -173,12 +184,14 @@ final class InterfaceType extends StaticType { @override StaticTypeDesc _buildDescription(_StaticTypeToDescription context) { - return StaticTypeDesc.namedTypeDesc(NamedTypeDesc( - name: name, - instantiation: [ - for (final type in instantiation) type._buildDescription(context), - ], - )); + return StaticTypeDesc.namedTypeDesc( + NamedTypeDesc( + name: name, + instantiation: [ + for (final type in instantiation) type._buildDescription(context), + ], + ), + ); } @override @@ -187,24 +200,34 @@ final class InterfaceType extends StaticType { } /// The [QualifiedName] for the [Object] type in `dart:core`. - static final QualifiedName objectName = - QualifiedName(uri: 'dart:core', name: 'Object'); + static final QualifiedName objectName = QualifiedName( + uri: 'dart:core', + name: 'Object', + ); /// The [QualifiedName] for the [Null] type in `dart:core`. - static final QualifiedName nullName = - QualifiedName(uri: 'dart:core', name: 'Null'); + static final QualifiedName nullName = QualifiedName( + uri: 'dart:core', + name: 'Null', + ); /// The [QualifiedName] for the [Function] type in `dart:core`. - static final QualifiedName functionName = - QualifiedName(uri: 'dart:core', name: 'Function'); + static final QualifiedName functionName = QualifiedName( + uri: 'dart:core', + name: 'Function', + ); /// The [QualifiedName] for the [Record] type in `dart:core`. - static final QualifiedName recordName = - QualifiedName(uri: 'dart:core', name: 'Record'); + static final QualifiedName recordName = QualifiedName( + uri: 'dart:core', + name: 'Record', + ); /// The [QualifiedName] for the [FutureOr] type in `dart:async`. - static final QualifiedName futureOrName = - QualifiedName(uri: 'dart:async', name: 'FutureOr'); + static final QualifiedName futureOrName = QualifiedName( + uri: 'dart:async', + name: 'FutureOr', + ); } /// A type of the form `T?`. @@ -217,7 +240,8 @@ final class NullableType extends StaticType { @override StaticTypeDesc _buildDescription(_StaticTypeToDescription context) { return StaticTypeDesc.nullableTypeDesc( - NullableTypeDesc(inner: inner._buildDescription(context))); + NullableTypeDesc(inner: inner._buildDescription(context)), + ); } @override @@ -249,8 +273,9 @@ final class TypeParameterType extends StaticType { @override StaticTypeDesc _buildDescription(_StaticTypeToDescription context) { - return StaticTypeDesc.typeParameterTypeDesc(TypeParameterTypeDesc( - parameterId: context.referenceParameter(parameter))); + return StaticTypeDesc.typeParameterTypeDesc( + TypeParameterTypeDesc(parameterId: context.referenceParameter(parameter)), + ); } } @@ -348,7 +373,9 @@ final class FunctionType extends StaticType { }) : super._(); static FunctionType _translateFrom( - FunctionTypeDesc desc, Map parameters) { + FunctionTypeDesc desc, + Map parameters, + ) { var typeParameters = const []; if (desc.typeParameters.isNotEmpty) { @@ -357,7 +384,9 @@ final class FunctionType extends StaticType { // half-baked type parameters and then patch things up later to create the // final representation. typeParameters = List.generate( - desc.typeParameters.length, (_) => StaticTypeParameter()); + desc.typeParameters.length, + (_) => StaticTypeParameter(), + ); parameters = { ...parameters, @@ -369,16 +398,20 @@ final class FunctionType extends StaticType { // bounds. for (final (i, desc) in desc.typeParameters.indexed) { if (desc.bound case final bound?) { - typeParameters[i].bound = - StaticType._translateFromDescription(bound, parameters); + typeParameters[i].bound = StaticType._translateFromDescription( + bound, + parameters, + ); } } } return FunctionType( typeParameters: typeParameters, - returnType: - StaticType._translateFromDescription(desc.returnType, parameters), + returnType: StaticType._translateFromDescription( + desc.returnType, + parameters, + ), requiredPositional: [ for (final desc in desc.requiredPositionalParameters) StaticType._translateFromDescription(desc, parameters), @@ -409,30 +442,34 @@ final class FunctionType extends StaticType { context.uniqueIdFor(parameter); } - return StaticTypeDesc.functionTypeDesc(FunctionTypeDesc( - returnType: returnType._buildDescription(context), - typeParameters: [ - for (final parameter in typeParameters) - StaticTypeParameterDesc( - identifier: context.referenceParameter(parameter), - bound: parameter.bound?._buildDescription(context), - ), - ], - requiredPositionalParameters: [ - for (final type in requiredPositional) type._buildDescription(context), - ], - optionalPositionalParameters: [ - for (final type in optionalPositional) type._buildDescription(context), - ], - namedParameters: [ - for (final type in named) - NamedFunctionTypeParameter( - type: type.type._buildDescription(context), - name: type.name, - required: type.required, - ), - ], - )); + return StaticTypeDesc.functionTypeDesc( + FunctionTypeDesc( + returnType: returnType._buildDescription(context), + typeParameters: [ + for (final parameter in typeParameters) + StaticTypeParameterDesc( + identifier: context.referenceParameter(parameter), + bound: parameter.bound?._buildDescription(context), + ), + ], + requiredPositionalParameters: [ + for (final type in requiredPositional) + type._buildDescription(context), + ], + optionalPositionalParameters: [ + for (final type in optionalPositional) + type._buildDescription(context), + ], + namedParameters: [ + for (final type in named) + NamedFunctionTypeParameter( + type: type.type._buildDescription(context), + name: type.name, + required: type.required, + ), + ], + ), + ); } /// Instantiates a generic function type with the given [typeArguments]. @@ -445,14 +482,19 @@ final class FunctionType extends StaticType { /// with `[VoidType()]` as type argument yields `void Function()`. FunctionType instantiate(List typeArguments) { if (typeArguments.length != typeParameters.length) { - throw ArgumentError.value(typeArguments, 'typeArguments', - 'Must match length of type parameters (${typeParameters.length})'); + throw ArgumentError.value( + typeArguments, + 'typeArguments', + 'Must match length of type parameters (${typeParameters.length})', + ); } - final substitution = TypeSubstitution(substitution: { - for (final (i, parameter) in typeParameters.indexed) - parameter: typeArguments[i] - }); + final substitution = TypeSubstitution( + substitution: { + for (final (i, parameter) in typeParameters.indexed) + parameter: typeArguments[i], + }, + ); return FunctionType( returnType: substitution.applyTo(returnType), @@ -550,18 +592,24 @@ final class _ApplyTypeSubstitution @override StaticType visitFunctionType(FunctionType type, TypeSubstitution arg) { - final newTypeParameters = - List.generate(type.typeParameters.length, (_) => StaticTypeParameter()); + final newTypeParameters = List.generate( + type.typeParameters.length, + (_) => StaticTypeParameter(), + ); - final innerSubstitution = TypeSubstitution(substitution: { - ...arg.substitution, - for (final (i, old) in type.typeParameters.indexed) - old: TypeParameterType(parameter: newTypeParameters[i]), - }); + final innerSubstitution = TypeSubstitution( + substitution: { + ...arg.substitution, + for (final (i, old) in type.typeParameters.indexed) + old: TypeParameterType(parameter: newTypeParameters[i]), + }, + ); for (final (i, newParam) in newTypeParameters.indexed) { - newParam.bound = - type.typeParameters[i].bound?.accept(this, innerSubstitution); + newParam.bound = type.typeParameters[i].bound?.accept( + this, + innerSubstitution, + ); } return FunctionType( @@ -619,7 +667,9 @@ final class _ApplyTypeSubstitution @override StaticType visitTypeParameterType( - TypeParameterType type, TypeSubstitution arg) { + TypeParameterType type, + TypeSubstitution arg, + ) { if (arg.substitution[type.parameter] case final substitution?) { return substitution; } diff --git a/pkgs/dart_model/lib/src/type_system.dart b/pkgs/dart_model/lib/src/type_system.dart index 9265d585..320f97e4 100644 --- a/pkgs/dart_model/lib/src/type_system.dart +++ b/pkgs/dart_model/lib/src/type_system.dart @@ -13,8 +13,9 @@ final class StaticTypeSystem { late final InterfaceType _object = _lookupNamed('dart:core#Object'); late final StaticType _objectQuestion = NullableType(_object); late final StaticType _null = _lookupNamed('dart:core#Null'); - late final InterfaceType _futureVoid = - _lookupEntry('dart:async#Future').instantiate([const VoidType()]); + late final InterfaceType _futureVoid = _lookupEntry( + 'dart:async#Future', + ).instantiate([const VoidType()]); StaticTypeSystem(this._hierarchy); @@ -26,7 +27,8 @@ final class StaticTypeSystem { InterfaceType _lookupNamed(String qualifiedName) { return StaticType( - StaticTypeDesc.namedTypeDesc(_lookupEntry(qualifiedName).self)) + StaticTypeDesc.namedTypeDesc(_lookupEntry(qualifiedName).self), + ) as InterfaceType; } @@ -112,11 +114,10 @@ final class StaticTypeSystem { // If `T0` is `FutureOr` for some `S`, then `T0 <: T1` iff // `S <: Object` - if (T1 - case InterfaceType( - isDartAsyncFutureOr: true, - instantiation: [final S] - )) { + if (T1 case InterfaceType( + isDartAsyncFutureOr: true, + instantiation: [final S], + )) { return _isSubtype(S, _object); } @@ -142,10 +143,7 @@ final class StaticTypeSystem { TypeParameterType() => false, // If `T1` is `FutureOr` for some `S`, then the query is true iff // `Null <: S`. - InterfaceType( - isDartAsyncFutureOr: true, - instantiation: [final S], - ) => + InterfaceType(isDartAsyncFutureOr: true, instantiation: [final S]) => _isSubtype(_null, S), // If `T1` is `Null`, `S?` or `S*` for some `S` then the query is true. InterfaceType(isDartCoreNull: true) || NullableType() => true, @@ -159,11 +157,10 @@ final class StaticTypeSystem { // Left FutureOr: If `T0` is `FutureOr` then: `T0 <: T1` iff // `Future <: T1` and `S0 <: T1`. - if (T0 - case InterfaceType( - isDartAsyncFutureOr: true, - instantiation: [final S0] - )) { + if (T0 case InterfaceType( + isDartAsyncFutureOr: true, + instantiation: [final S0], + )) { return _isSubtype(S0, T1) && _isSubtype(_future(S0), T1); } @@ -185,11 +182,10 @@ final class StaticTypeSystem { // Right FutureOr: If `T1` is `FutureOr` then `T0 <: T1` iff any of the // following hold: - if (T1 - case InterfaceType( - isDartAsyncFutureOr: true, - instantiation: [final S1] - )) { + if (T1 case InterfaceType( + isDartAsyncFutureOr: true, + instantiation: [final S1], + )) { if (_isSubtype(T0, _future(S1))) { // `T0 <: Future` return true; @@ -198,10 +194,9 @@ final class StaticTypeSystem { // `T0 <: T1` return true; } - if (T0 - case TypeParameterType( - parameter: StaticTypeParameter(bound: final S0?) - ) when _isSubtype(S0, T1)) { + if (T0 case TypeParameterType( + parameter: StaticTypeParameter(bound: final S0?), + ) when _isSubtype(S0, T1)) { // `T0` is `X0` and `X0` has bound `S0` and `S0 <: T1` return true; } @@ -221,10 +216,9 @@ final class StaticTypeSystem { if (_isSubtype(T0, _null)) { // or `T0 <: Null` } - if (T0 - case TypeParameterType( - parameter: StaticTypeParameter(bound: final S0?) - ) when _isSubtype(S0, T1)) { + if (T0 case TypeParameterType( + parameter: StaticTypeParameter(bound: final S0?), + ) when _isSubtype(S0, T1)) { // `T0` is `X0` and `X0` has bound `S0` and `S0 <: T1` return true; } @@ -239,9 +233,9 @@ final class StaticTypeSystem { // Left Type Variable Bound: `T0` is a type variable `X0` with bound `B0` // and `B0 <: T1`. - if (T0 - case TypeParameterType(parameter: StaticTypeParameter(bound: final B0?)) - when _isSubtype(B0, T1)) { + if (T0 case TypeParameterType( + parameter: StaticTypeParameter(bound: final B0?), + ) when _isSubtype(B0, T1)) { return true; } @@ -302,13 +296,17 @@ final class StaticTypeSystem { if (subType.name.equals(superType.name)) { return _matchingInstantiation( - subType.instantiation, superType.instantiation); + subType.instantiation, + superType.instantiation, + ); } for (final actualSuperType in _constructSuperTypes(subType, [])) { if (actualSuperType.name.equals(superType.name)) { return _matchingInstantiation( - actualSuperType.instantiation, superType.instantiation); + actualSuperType.instantiation, + superType.instantiation, + ); } } @@ -330,7 +328,9 @@ final class StaticTypeSystem { /// Walks the type hierarchy upwards from [type], yielding instantiated /// supertypes of that type. Iterable _constructSuperTypes( - InterfaceType type, List coveredClasses) sync* { + InterfaceType type, + List coveredClasses, + ) sync* { final hierarchyEntry = _hierarchy.named[type.name.asString]!; // Consider e.g. a class `List extends Iterable` for which we have an // instantiation `List` and now want to find supertypes. @@ -344,10 +344,12 @@ final class StaticTypeSystem { parameterIdToTypeParameter[parameter.identifier] = resolved; } - final substitution = TypeSubstitution(substitution: { - for (var i = 0; i < typeParameters.length; i++) - typeParameters[i]: type.instantiation[i] - }); + final substitution = TypeSubstitution( + substitution: { + for (var i = 0; i < typeParameters.length; i++) + typeParameters[i]: type.instantiation[i], + }, + ); for (final superType in hierarchyEntry.supertypes) { if (coveredClasses.contains(superType.name)) { @@ -368,22 +370,25 @@ final class StaticTypeSystem { // Which then allows instantiating the supertype based on the // instantiation of the subtype. - final instantiatedSuperType = substitution - .applyTo(superTypeUsingThisTypesTypeParameters) as InterfaceType; + final instantiatedSuperType = + substitution.applyTo(superTypeUsingThisTypesTypeParameters) + as InterfaceType; yield instantiatedSuperType; yield* _constructSuperTypes(instantiatedSuperType, coveredClasses); } } bool _checkFunctionSubtype(FunctionType left, FunctionType right) { - final freshTypeParams = - _freshTypeParameters(left.typeParameters, right.typeParameters); + final freshTypeParams = _freshTypeParameters( + left.typeParameters, + right.typeParameters, + ); if (freshTypeParams == null) { return false; } final freshTypeArgs = [ - for (final param in freshTypeParams) TypeParameterType(parameter: param) + for (final param in freshTypeParams) TypeParameterType(parameter: param), ]; // Turn the type parameters in the function types into free type variables @@ -409,12 +414,14 @@ final class StaticTypeSystem { } for (var i = 0; i < q; i++) { - final Si = i >= p - ? right.optionalPositional[i - p] - : right.optionalPositional[i]; - final Vi = i >= n - ? left.optionalPositional[i - n] - : left.requiredPositional[i]; + final Si = + i >= p + ? right.optionalPositional[i - p] + : right.optionalPositional[i]; + final Vi = + i >= n + ? left.optionalPositional[i - n] + : left.requiredPositional[i]; if (!_isSubtype(Si, Vi)) { return false; @@ -430,7 +437,9 @@ final class StaticTypeSystem { for (var i = 0; i < left.requiredPositional.length; i++) { if (!_isSubtype( - right.requiredPositional[i], left.requiredPositional[i])) { + right.requiredPositional[i], + left.requiredPositional[i], + )) { return false; } } @@ -477,7 +486,9 @@ final class StaticTypeSystem { /// This allows applying a substitution to the source types defining [a] and /// [b], which then makes comparing type parameters easier. List? _freshTypeParameters( - List a, List b) { + List a, + List b, + ) { if (a.length != b.length) { return null; } @@ -485,17 +496,25 @@ final class StaticTypeSystem { return const []; } - final freshParameters = - List.generate(a.length, (_) => StaticTypeParameter()); + final freshParameters = List.generate( + a.length, + (_) => StaticTypeParameter(), + ); final freshTypes = List.generate( - a.length, (i) => TypeParameterType(parameter: freshParameters[i])); - - final substitutionA = TypeSubstitution(substitution: { - for (final (i, parameter) in a.indexed) parameter: freshTypes[i] - }); - final substitutionB = TypeSubstitution(substitution: { - for (final (i, parameter) in b.indexed) parameter: freshTypes[i] - }); + a.length, + (i) => TypeParameterType(parameter: freshParameters[i]), + ); + + final substitutionA = TypeSubstitution( + substitution: { + for (final (i, parameter) in a.indexed) parameter: freshTypes[i], + }, + ); + final substitutionB = TypeSubstitution( + substitution: { + for (final (i, parameter) in b.indexed) parameter: freshTypes[i], + }, + ); for (var i = 0; i < a.length; i++) { var boundA = a[i].bound; diff --git a/pkgs/dart_model/pubspec.yaml b/pkgs/dart_model/pubspec.yaml index 766e2593..6b0a11b7 100644 --- a/pkgs/dart_model/pubspec.yaml +++ b/pkgs/dart_model/pubspec.yaml @@ -8,7 +8,7 @@ repository: https://github.com/dart-lang/macros/tree/master/pkgs/dart_model resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: collection: ^1.19.0 diff --git a/pkgs/dart_model/test/deep_cast_test.dart b/pkgs/dart_model/test/deep_cast_test.dart index 164e84e2..53e96ee8 100644 --- a/pkgs/dart_model/test/deep_cast_test.dart +++ b/pkgs/dart_model/test/deep_cast_test.dart @@ -8,11 +8,12 @@ import 'package:test/test.dart'; void main() { test('can perform deep casts on maps', () { final initial = { - 'x': [1, 2, 3] + 'x': [1, 2, 3], }; expect(initial, isNot(isA>>())); - final typed = - initial.deepCast>((v) => (v as List).cast()); + final typed = initial.deepCast>( + (v) => (v as List).cast(), + ); expect(typed, isA>>()); expect(typed['x']!, isA>()); expect(typed['x']!, [1, 2, 3]); @@ -21,13 +22,14 @@ void main() { test('can perform really deep casts on maps', () { final initial = { 'x': { - 'y': [1, 2, 3] + 'y': [1, 2, 3], }, }; expect(initial, isNot(isA>>>())); - final typed = initial.deepCast>>((v) => - (v as Map).deepCast>((v) => (v as List).cast())); + final typed = initial.deepCast>>( + (v) => (v as Map).deepCast>((v) => (v as List).cast()), + ); expect(typed, isA>>>()); expect(initial['x'], isNot(isA>>())); diff --git a/pkgs/dart_model/test/json_buffer/closed_list_test.dart b/pkgs/dart_model/test/json_buffer/closed_list_test.dart index dafb2d7e..fe708cc6 100644 --- a/pkgs/dart_model/test/json_buffer/closed_list_test.dart +++ b/pkgs/dart_model/test/json_buffer/closed_list_test.dart @@ -37,7 +37,7 @@ void main() { [ 'ccc', {'a': 3}, - ] + ], ]; builder.map['value'] = value; final deserializedValue = builder.map['value'] as List; diff --git a/pkgs/dart_model/test/json_buffer/closed_map_test.dart b/pkgs/dart_model/test/json_buffer/closed_map_test.dart index 58e8a295..f5b62237 100644 --- a/pkgs/dart_model/test/json_buffer/closed_map_test.dart +++ b/pkgs/dart_model/test/json_buffer/closed_map_test.dart @@ -53,7 +53,7 @@ void main() { 'a0': [], 'a00': {}, 'bb': { - 'ccc': {'a': 3} + 'ccc': {'a': 3}, }, 'cc': [ {'a': 'b'}, @@ -68,43 +68,38 @@ void main() { test('typed maps created in the same buffer are stored as typed maps', () { final typedMap = builder.createTypedMap(TypedMapSchema({})); - final value = { - 'a': typedMap, - }; + final value = {'a': typedMap}; builder.map['value'] = value; final deserializedValue = builder.map['value'] as Map; expect(deserializedValue['a'].runtimeType.toString(), '_TypedMap'); }); - test('typed maps created in a different buffer are copied to closed maps', - () { - final typedMap = JsonBufferBuilder().createTypedMap(TypedMapSchema({})); - final value = { - 'a': typedMap, - }; - builder.map['value'] = value; - final deserializedValue = builder.map['value'] as Map; - expect(deserializedValue['a'].runtimeType.toString(), '_ClosedMap'); - }); - test( - 'growable maps created in the same buffer are stored as growable ' + 'typed maps created in a different buffer are copied to closed maps', + () { + final typedMap = JsonBufferBuilder().createTypedMap(TypedMapSchema({})); + final value = {'a': typedMap}; + builder.map['value'] = value; + final deserializedValue = builder.map['value'] as Map; + expect(deserializedValue['a'].runtimeType.toString(), '_ClosedMap'); + }, + ); + + test('growable maps created in the same buffer are stored as growable ' 'maps', () { final growableMap = builder.createGrowableMap(); - final value = { - 'a': growableMap, - }; + final value = {'a': growableMap}; builder.map['value'] = value; final deserializedValue = builder.map['value'] as Map; - expect(deserializedValue['a'].runtimeType.toString(), - '_GrowableMap'); + expect( + deserializedValue['a'].runtimeType.toString(), + '_GrowableMap', + ); }); test('growable maps created in a different buffer are copied', () { final growableMap = JsonBufferBuilder().createGrowableMap(); - final value = { - 'a': growableMap, - }; + final value = {'a': growableMap}; builder.map['value'] = value; final deserializedValue = builder.map['value'] as Map; expect(deserializedValue['a'].runtimeType.toString(), '_ClosedMap'); diff --git a/pkgs/dart_model/test/json_buffer/growable_map_test.dart b/pkgs/dart_model/test/json_buffer/growable_map_test.dart index 1b69e854..bd40f644 100644 --- a/pkgs/dart_model/test/json_buffer/growable_map_test.dart +++ b/pkgs/dart_model/test/json_buffer/growable_map_test.dart @@ -95,7 +95,7 @@ void main() { 'D': [1, 2, 3], 'E': [], 'F': {}, - } + }, }); }); }); diff --git a/pkgs/dart_model/test/json_buffer/json_buffer_builder_test.dart b/pkgs/dart_model/test/json_buffer/json_buffer_builder_test.dart index 5cdcb359..77575697 100644 --- a/pkgs/dart_model/test/json_buffer/json_buffer_builder_test.dart +++ b/pkgs/dart_model/test/json_buffer/json_buffer_builder_test.dart @@ -43,7 +43,7 @@ void main() { Type.stringPointer, false, 0, - {'a': 'aa'} + {'a': 'aa'}, ], }; builder.map['value'] = value; @@ -68,7 +68,7 @@ void main() { '9': 'abc' * 10, '10': { 'a': {'aa': 'bb'}, - 'b': 2 + 'b': 2, }, '11': growableMap, }; @@ -83,8 +83,9 @@ void main() { }); test('deserialized does not allow modification', () { - final deserializedBuilder = - JsonBufferBuilder.deserialize(JsonBufferBuilder().serialize()); + final deserializedBuilder = JsonBufferBuilder.deserialize( + JsonBufferBuilder().serialize(), + ); expect(() => deserializedBuilder.map['a'] = 'b', throwsStateError); }); @@ -95,16 +96,21 @@ void main() { assert(a != b); expect(fingerprint({'a': a}), equals(fingerprint({'a': a}))); expect( + fingerprint({ + 'a': {'b': b}, + }), + equals( fingerprint({ - 'a': {'b': b} + 'a': {'b': b}, }), - equals(fingerprint({ - 'a': {'b': b} - }))); + ), + ); expect(fingerprint({'a': a}), isNot(equals(fingerprint({'a': b})))); expect(fingerprint({'a': a}), isNot(equals(fingerprint({'b': a})))); - expect(fingerprint({'a': a, 'b': b}), - isNot(equals(fingerprint({'a': b, 'b': a})))); + expect( + fingerprint({'a': a, 'b': b}), + isNot(equals(fingerprint({'a': b, 'b': a}))), + ); } test('boolean fields', () { @@ -139,18 +145,20 @@ void main() { test('growable map fields', () { final builderA = JsonBufferBuilder(); final builderB = JsonBufferBuilder(); - testFingerprint(builderA.createGrowableMap()..['a'] = 1, - builderB.createGrowableMap()..['a'] = 2); + testFingerprint( + builderA.createGrowableMap()..['a'] = 1, + builderB.createGrowableMap()..['a'] = 2, + ); }); test('typed maps with same schema', () { final builderA = JsonBufferBuilder(); final builderB = JsonBufferBuilder(); - final schema = TypedMapSchema({ - 'a': Type.stringPointer, - }); - testFingerprint(builderA.createTypedMap(schema, 'a'), - builderB.createTypedMap(schema, 'b')); + final schema = TypedMapSchema({'a': Type.stringPointer}); + testFingerprint( + builderA.createTypedMap(schema, 'a'), + builderB.createTypedMap(schema, 'b'), + ); }); }); }); @@ -160,8 +168,11 @@ int fingerprint(Map map) { final builder = map is MapInBuffer ? (map as MapInBuffer).buffer : JsonBufferBuilder() ..map.deepCopy(map); - return builder.fingerprint((builder.map as MapInBuffer).pointer, - type: Type.growableMapPointer, alreadyDereferenced: true); + return builder.fingerprint( + (builder.map as MapInBuffer).pointer, + type: Type.growableMapPointer, + alreadyDereferenced: true, + ); } extension on Map { diff --git a/pkgs/dart_model/test/json_buffer/testing.dart b/pkgs/dart_model/test/json_buffer/testing.dart index d53389f4..d80346d7 100644 --- a/pkgs/dart_model/test/json_buffer/testing.dart +++ b/pkgs/dart_model/test/json_buffer/testing.dart @@ -11,7 +11,9 @@ import 'package:test/test.dart'; /// /// Does additional checks on `map`. void expectFullyEquivalentMaps( - Map map, Map expected) { + Map map, + Map expected, +) { expect(map.entries.map((e) => e.key), expected.entries.map((e) => e.key)); expect(map.entries.map((e) => e.value), expected.entries.map((e) => e.value)); expect(map.isEmpty, expected.isEmpty); diff --git a/pkgs/dart_model/test/json_buffer/typed_map_test.dart b/pkgs/dart_model/test/json_buffer/typed_map_test.dart index 8627f268..a2bb5e48 100644 --- a/pkgs/dart_model/test/json_buffer/typed_map_test.dart +++ b/pkgs/dart_model/test/json_buffer/typed_map_test.dart @@ -43,7 +43,7 @@ void main() { 'b': Type.boolean, 'missing1': Type.stringPointer, 'c': Type.uint32, - 'missing2': Type.stringPointer + 'missing2': Type.stringPointer, }); final map = builder.createTypedMap(schema, 'aa', true, null, 12345, null); expectFullyEquivalentMaps(map, {'a': 'aa', 'b': true, 'c': 12345}); @@ -69,13 +69,19 @@ void main() { 'd': Type.boolean, }); final map = builder.createTypedMap(schema, false, true, false, true); - expectFullyEquivalentMaps( - map, {'a': false, 'b': true, 'c': false, 'd': true}); + expectFullyEquivalentMaps(map, { + 'a': false, + 'b': true, + 'c': false, + 'd': true, + }); }); test('schemas are written once per buffer', () { - final schema = - TypedMapSchema({'a': Type.stringPointer, 'b': Type.uint32}); + final schema = TypedMapSchema({ + 'a': Type.stringPointer, + 'b': Type.uint32, + }); // Write three times, checking how much the buffer grows. final length1 = builder.length; @@ -127,12 +133,30 @@ void main() { // Write once so schema is written. builder.createTypedMap( - schema, true, false, true, false, true, false, true, false); + schema, + true, + false, + true, + false, + true, + false, + true, + false, + ); // Check length of write with already-written schema. final length1 = builder.length; builder.createTypedMap( - schema, true, false, true, false, true, false, true, false); + schema, + true, + false, + true, + false, + true, + false, + true, + false, + ); final length2 = builder.length; // Size should be schema pointer, one byte for eight bools. @@ -153,12 +177,30 @@ void main() { // Write once so schema is written. builder.createTypedMap( - schema, null, false, true, false, true, false, true, false); + schema, + null, + false, + true, + false, + true, + false, + true, + false, + ); // Check length of write with already-written schema. final length1 = builder.length; builder.createTypedMap( - schema, true, null, true, false, true, false, true, false); + schema, + true, + null, + true, + false, + true, + false, + true, + false, + ); final length2 = builder.length; // Size should be schema pointer, one byte field set, one byte for seven @@ -197,20 +239,30 @@ void main() { 'g': Type.anyPointer, }); - final typedMap = - builder.createTypedMap(TypedMapSchema({'a': Type.boolean}), true); + final typedMap = builder.createTypedMap( + TypedMapSchema({'a': Type.boolean}), + true, + ); final growableMap = builder.createGrowableMap(); growableMap['foo'] = 3; - final map = builder.createTypedMap(schema, null, 1, false, {'a': 'b'}, - ['a', 'b', 'c'], typedMap, growableMap); + final map = builder.createTypedMap( + schema, + null, + 1, + false, + {'a': 'b'}, + ['a', 'b', 'c'], + typedMap, + growableMap, + ); expectFullyEquivalentMaps(map, { 'b': 1, 'c': false, 'd': {'a': 'b'}, 'e': ['a', 'b', 'c'], 'f': typedMap, - 'g': growableMap + 'g': growableMap, }); }); diff --git a/pkgs/dart_model/test/lazy_merged_map_test.dart b/pkgs/dart_model/test/lazy_merged_map_test.dart index c7384857..7eedec7d 100644 --- a/pkgs/dart_model/test/lazy_merged_map_test.dart +++ b/pkgs/dart_model/test/lazy_merged_map_test.dart @@ -18,47 +18,59 @@ void main() { expect(c.uris['package:b/b.dart'], libB); }); - test('Can merge models with different scopes from the same library', - () async { - final interfaceA = Interface(); - final interfaceB = Interface(); - final a = Model() - ..uris['package:a/a.dart'] = (Library()..scopes['A'] = interfaceA); - final b = Model() - ..uris['package:a/a.dart'] = (Library()..scopes['B'] = interfaceB); - final c = a.mergeWith(b); - expect(c.uris['package:a/a.dart'], isA()); - expect(c.uris['package:a/a.dart']!.scopes['A'], interfaceA); - expect(c.uris['package:a/a.dart']!.scopes['B'], interfaceB); - }); + test( + 'Can merge models with different scopes from the same library', + () async { + final interfaceA = Interface(); + final interfaceB = Interface(); + final a = + Model() + ..uris['package:a/a.dart'] = (Library()..scopes['A'] = interfaceA); + final b = + Model() + ..uris['package:a/a.dart'] = (Library()..scopes['B'] = interfaceB); + final c = a.mergeWith(b); + expect(c.uris['package:a/a.dart'], isA()); + expect(c.uris['package:a/a.dart']!.scopes['A'], interfaceA); + expect(c.uris['package:a/a.dart']!.scopes['B'], interfaceB); + }, + ); - test('Can merge models with the same interface but different properties', - () async { - final interfaceA1 = Interface(properties: Properties(isClass: true)); - final interfaceA2 = Interface(properties: Properties(isAbstract: true)); - final a = Model() - ..uris['package:a/a.dart'] = (Library()..scopes['A'] = interfaceA1); - final b = Model() - ..uris['package:a/a.dart'] = (Library()..scopes['A'] = interfaceA2); - final c = a.mergeWith(b); - final properties = c.uris['package:a/a.dart']!.scopes['A']!.properties; - expect(properties, isA()); - expect(properties.isClass, true); - expect(properties.isAbstract, true); - // Not set - expect(() => properties.isConstructor, throwsA(isA())); - }); + test( + 'Can merge models with the same interface but different properties', + () async { + final interfaceA1 = Interface(properties: Properties(isClass: true)); + final interfaceA2 = Interface(properties: Properties(isAbstract: true)); + final a = + Model() + ..uris['package:a/a.dart'] = (Library()..scopes['A'] = interfaceA1); + final b = + Model() + ..uris['package:a/a.dart'] = (Library()..scopes['A'] = interfaceA2); + final c = a.mergeWith(b); + final properties = c.uris['package:a/a.dart']!.scopes['A']!.properties; + expect(properties, isA()); + expect(properties.isClass, true); + expect(properties.isAbstract, true); + // Not set + expect(() => properties.isConstructor, throwsA(isA())); + }, + ); test('Errors if maps have same the key with different values', () async { final interfaceA1 = Interface(properties: Properties(isClass: true)); final interfaceA2 = Interface(properties: Properties(isClass: false)); - final a = Model() - ..uris['package:a/a.dart'] = (Library()..scopes['A'] = interfaceA1); - final b = Model() - ..uris['package:a/a.dart'] = (Library()..scopes['A'] = interfaceA2); + final a = + Model() + ..uris['package:a/a.dart'] = (Library()..scopes['A'] = interfaceA1); + final b = + Model() + ..uris['package:a/a.dart'] = (Library()..scopes['A'] = interfaceA2); final c = a.mergeWith(b); - expect(() => c.uris['package:a/a.dart']!.scopes['A']!.properties.isClass, - throwsA(isA())); + expect( + () => c.uris['package:a/a.dart']!.scopes['A']!.properties.isClass, + throwsA(isA()), + ); }); } diff --git a/pkgs/dart_model/test/model_test.dart b/pkgs/dart_model/test/model_test.dart index f17b0b6b..6fb3e0d6 100644 --- a/pkgs/dart_model/test/model_test.dart +++ b/pkgs/dart_model/test/model_test.dart @@ -13,13 +13,17 @@ void main() { setUp(() { Scope.macro.run(() { - model = Model() - ..uris['package:dart_model/dart_model.dart'] = (Library() - ..scopes['JsonData'] = (Interface( - properties: Properties(isClass: true), metadataAnnotations: []) - ..members['_root'] = Member( - properties: Properties(isField: true, isStatic: false), - ))); + model = + Model() + ..uris['package:dart_model/dart_model.dart'] = + (Library() + ..scopes['JsonData'] = (Interface( + properties: Properties(isClass: true), + metadataAnnotations: [], + ) + ..members['_root'] = Member( + properties: Properties(isField: true, isStatic: false), + ))); }); }); @@ -31,14 +35,14 @@ void main() { 'metadataAnnotations': >[], 'members': { '_root': { - 'properties': {'isField': true, 'isStatic': false} - } + 'properties': {'isField': true, 'isStatic': false}, + }, }, - 'properties': {'isClass': true} - } - } - } - } + 'properties': {'isClass': true}, + }, + }, + }, + }, }; test('maps to JSON', () { @@ -47,82 +51,111 @@ void main() { test('maps to JSON after deserialization', () { final deserializedModel = Model.fromJson( - json.decode(json.encode(model as Map)) as Map); + json.decode(json.encode(model as Map)) as Map, + ); expect(deserializedModel as Map, expected); }); test('maps can be accessed as fields', () { - expect(model.uris['package:dart_model/dart_model.dart'], - expected['uris']!['package:dart_model/dart_model.dart']); expect( - model.uris['package:dart_model/dart_model.dart']!.scopes['JsonData'], - expected['uris']!['package:dart_model/dart_model.dart']!['scopes']![ - 'JsonData']); + model.uris['package:dart_model/dart_model.dart'], + expected['uris']!['package:dart_model/dart_model.dart'], + ); expect( - model.uris['package:dart_model/dart_model.dart']!.scopes['JsonData']! - .properties, - expected['uris']!['package:dart_model/dart_model.dart']!['scopes']![ - 'JsonData']!['properties']); + model.uris['package:dart_model/dart_model.dart']!.scopes['JsonData'], + expected['uris']!['package:dart_model/dart_model.dart']!['scopes']!['JsonData'], + ); + expect( + model + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']! + .properties, + expected['uris']!['package:dart_model/dart_model.dart']!['scopes']!['JsonData']!['properties'], + ); }); test('maps can be accessed as fields after deserialization', () { final deserializedModel = Model.fromJson( - json.decode(json.encode(model as Map)) as Map); + json.decode(json.encode(model as Map)) as Map, + ); expect( - deserializedModel.uris['package:dart_model/dart_model.dart']! - .scopes['JsonData']!.properties, - expected['uris']!['package:dart_model/dart_model.dart']!['scopes']![ - 'JsonData']!['properties']); + deserializedModel + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']! + .properties, + expected['uris']!['package:dart_model/dart_model.dart']!['scopes']!['JsonData']!['properties'], + ); }); test('lists can be accessed as fields', () { expect( - model.uris['package:dart_model/dart_model.dart']!.scopes['JsonData']! - .members, - expected['uris']!['package:dart_model/dart_model.dart']!['scopes']![ - 'JsonData']!['members']); + model + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']! + .members, + expected['uris']!['package:dart_model/dart_model.dart']!['scopes']!['JsonData']!['members'], + ); }); test('lists can be accessed as fields after deserialization', () { final deserializedModel = Model.fromJson( - json.decode(json.encode(model as Map)) as Map); + json.decode(json.encode(model as Map)) as Map, + ); expect( - deserializedModel.uris['package:dart_model/dart_model.dart']! - .scopes['JsonData']!.members, - expected['uris']!['package:dart_model/dart_model.dart']!['scopes']![ - 'JsonData']!['members']); + deserializedModel + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']! + .members, + expected['uris']!['package:dart_model/dart_model.dart']!['scopes']!['JsonData']!['members'], + ); }); test('can give the path to Interfaces in buffer backed maps', () { final interface = model.uris['package:dart_model/dart_model.dart']!.scopes['JsonData']!; - expect(model.qualifiedNameOf(interface.node)!.asString, - 'package:dart_model/dart_model.dart#JsonData'); + expect( + model.qualifiedNameOf(interface.node)!.asString, + 'package:dart_model/dart_model.dart#JsonData', + ); }); test('can give the path to Members in buffer backed maps', () { - final member = model.uris['package:dart_model/dart_model.dart']! - .scopes['JsonData']!.members['_root']!; - expect(model.qualifiedNameOf(member.node)!.asString, - 'package:dart_model/dart_model.dart#JsonData._root'); + final member = + model + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']! + .members['_root']!; + expect( + model.qualifiedNameOf(member.node)!.asString, + 'package:dart_model/dart_model.dart#JsonData._root', + ); }); test('can give the path to Interfaces in SDK maps', () { final copiedModel = Model.fromJson(_copyMap(model.node)); - final interface = copiedModel - .uris['package:dart_model/dart_model.dart']!.scopes['JsonData']!; - expect(copiedModel.qualifiedNameOf(interface.node)!.asString, - 'package:dart_model/dart_model.dart#JsonData'); + final interface = + copiedModel + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']!; + expect( + copiedModel.qualifiedNameOf(interface.node)!.asString, + 'package:dart_model/dart_model.dart#JsonData', + ); }); test('can give the path to Members in SDK maps', () { final copiedModel = Model.fromJson(_copyMap(model.node)); - final member = copiedModel.uris['package:dart_model/dart_model.dart']! - .scopes['JsonData']!.members['_root']!; - expect(copiedModel.qualifiedNameOf(member.node)!.asString, - 'package:dart_model/dart_model.dart#JsonData._root'); + final member = + copiedModel + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']! + .members['_root']!; + expect( + copiedModel.qualifiedNameOf(member.node)!.asString, + 'package:dart_model/dart_model.dart#JsonData._root', + ); }); test('can give the path to Members in merged maps', () { @@ -131,25 +164,39 @@ void main() { /// Create one model in a different scope so it gets a different buffer. Scope.query.run(() { - otherModel = Model() - ..uris['package:dart_model/dart_model.dart'] = (Library() - ..scopes['JsonData'] = (Interface() - ..members['foo'] = - Member(properties: Properties(isStatic: true)))); - fooMember = otherModel.uris['package:dart_model/dart_model.dart']! - .scopes['JsonData']!.members['foo']!; + otherModel = + Model() + ..uris['package:dart_model/dart_model.dart'] = + (Library() + ..scopes['JsonData'] = + (Interface() + ..members['foo'] = Member( + properties: Properties(isStatic: true), + ))); + fooMember = + otherModel + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']! + .members['foo']!; }); Scope.macro.run(() { - final rootMember = model.uris['package:dart_model/dart_model.dart']! - .scopes['JsonData']!.members['_root']!; + final rootMember = + model + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']! + .members['_root']!; final mergedModel = model.mergeWith(otherModel); - expect(mergedModel.qualifiedNameOf(rootMember.node)!.asString, - 'package:dart_model/dart_model.dart#JsonData._root'); - expect(mergedModel.qualifiedNameOf(fooMember.node)!.asString, - 'package:dart_model/dart_model.dart#JsonData::foo'); + expect( + mergedModel.qualifiedNameOf(rootMember.node)!.asString, + 'package:dart_model/dart_model.dart#JsonData._root', + ); + expect( + mergedModel.qualifiedNameOf(fooMember.node)!.asString, + 'package:dart_model/dart_model.dart#JsonData::foo', + ); expect(model.qualifiedNameOf(fooMember.node), null); expect(otherModel.qualifiedNameOf(rootMember.node), null); @@ -160,16 +207,20 @@ void main() { final copiedModel = Model.fromJson(_copyMap(model.node)); // Add an invalid link creating a loop in the map structure. (copiedModel.node['uris'] as Map)['loop'] = copiedModel; - final member = copiedModel.uris['package:dart_model/dart_model.dart']! - .scopes['JsonData']!.members['_root']!; + final member = + copiedModel + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']! + .members['_root']!; expect( - copiedModel.qualifiedNameOf(member.node), - QualifiedName( - uri: 'package:dart_model/dart_model.dart', - scope: 'JsonData', - name: '_root', - isStatic: false, - )); + copiedModel.qualifiedNameOf(member.node), + QualifiedName( + uri: 'package:dart_model/dart_model.dart', + scope: 'JsonData', + name: '_root', + isStatic: false, + ), + ); }); test('path to Members works for reused node', () { @@ -177,27 +228,38 @@ void main() { // Reuse a node. copiedModel.uris['duplicate'] = copiedModel.uris['package:dart_model/dart_model.dart']!; - final member = copiedModel.uris['package:dart_model/dart_model.dart']! - .scopes['JsonData']!.members['_root']!; + final member = + copiedModel + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']! + .members['_root']!; expect( - copiedModel.qualifiedNameOf(member.node), - QualifiedName( - uri: 'package:dart_model/dart_model.dart', - scope: 'JsonData', - name: '_root', - isStatic: false, - )); + copiedModel.qualifiedNameOf(member.node), + QualifiedName( + uri: 'package:dart_model/dart_model.dart', + scope: 'JsonData', + name: '_root', + isStatic: false, + ), + ); }); test('path to Member returns null for Member in wrong Map', () { final copiedModel = Model.fromJson(_copyMap(model.node)); - final member = model.uris['package:dart_model/dart_model.dart']! - .scopes['JsonData']!.members['_root']!; - final copiedMember = Member.fromJson(_copyMap(model - .uris['package:dart_model/dart_model.dart']! - .scopes['JsonData']! - .members['_root']! - .node)); + final member = + model + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']! + .members['_root']!; + final copiedMember = Member.fromJson( + _copyMap( + model + .uris['package:dart_model/dart_model.dart']! + .scopes['JsonData']! + .members['_root']! + .node, + ), + ); expect(copiedModel.qualifiedNameOf(member.node), null); expect(model.qualifiedNameOf(copiedMember.node), null); }); @@ -205,29 +267,35 @@ void main() { group('QualifiedName', () { test('asString', () { - expect(QualifiedName(uri: 'package:foo/foo.dart', name: 'Foo').asString, - 'package:foo/foo.dart#Foo'); - expect( - QualifiedName( - uri: 'package:foo/foo.dart', - name: 'bar', - scope: 'Foo', - isStatic: false) - .asString, - 'package:foo/foo.dart#Foo.bar'); - expect( - QualifiedName( - uri: 'package:foo/foo.dart', - name: 'baz', - scope: 'Foo', - isStatic: true) - .asString, - 'package:foo/foo.dart#Foo::baz'); + expect( + QualifiedName(uri: 'package:foo/foo.dart', name: 'Foo').asString, + 'package:foo/foo.dart#Foo', + ); + expect( + QualifiedName( + uri: 'package:foo/foo.dart', + name: 'bar', + scope: 'Foo', + isStatic: false, + ).asString, + 'package:foo/foo.dart#Foo.bar', + ); + expect( + QualifiedName( + uri: 'package:foo/foo.dart', + name: 'baz', + scope: 'Foo', + isStatic: true, + ).asString, + 'package:foo/foo.dart#Foo::baz', + ); }); test('parse', () { - expect(QualifiedName.parse('package:foo/foo.dart#Foo').uri, - 'package:foo/foo.dart'); + expect( + QualifiedName.parse('package:foo/foo.dart#Foo').uri, + 'package:foo/foo.dart', + ); expect(QualifiedName.parse('package:foo/foo.dart#Foo').name, 'Foo'); final fooBar = QualifiedName.parse('package:foo/foo.dart#Foo.bar'); expect(fooBar.name, 'bar'); diff --git a/pkgs/dart_model/test/scopes_test.dart b/pkgs/dart_model/test/scopes_test.dart index 0e112de0..d841efc0 100644 --- a/pkgs/dart_model/test/scopes_test.dart +++ b/pkgs/dart_model/test/scopes_test.dart @@ -10,23 +10,35 @@ void main() { group('Scope', () { for (final scope in [Scope.none, Scope.macro, Scope.query]) { test('create maps and serialize work in $scope', () { - expect(scope.run(() => Scope.createMap(TypedMapSchema({}))), - {}); + expect( + scope.run(() => Scope.createMap(TypedMapSchema({}))), + {}, + ); expect(scope.run(Scope.createGrowableMap), {}); - expect(scope.run(() => Scope.serializeToBinary({})), - JsonBufferBuilder().serialize()); + expect( + scope.run(() => Scope.serializeToBinary({})), + JsonBufferBuilder().serialize(), + ); }); } test('macro and query scopes cannot be nested', () { - expect(() => Scope.macro.run(() => Scope.macro.run(() {})), - throwsStateError); - expect(() => Scope.macro.run(() => Scope.query.run(() {})), - throwsStateError); - expect(() => Scope.query.run(() => Scope.macro.run(() {})), - throwsStateError); - expect(() => Scope.query.run(() => Scope.query.run(() {})), - throwsStateError); + expect( + () => Scope.macro.run(() => Scope.macro.run(() {})), + throwsStateError, + ); + expect( + () => Scope.macro.run(() => Scope.query.run(() {})), + throwsStateError, + ); + expect( + () => Scope.query.run(() => Scope.macro.run(() {})), + throwsStateError, + ); + expect( + () => Scope.query.run(() => Scope.query.run(() {})), + throwsStateError, + ); }); test('none scope can be nested in macro or query scopes', () { @@ -39,8 +51,8 @@ void main() { late Model firstQuery; Scope.query.run(() { initial = Model()..uris['a'] = (Library()..scopes['A'] = Interface()); - firstQuery = Model() - ..uris['a'] = (Library()..scopes['B'] = Interface()); + firstQuery = + Model()..uris['a'] = (Library()..scopes['B'] = Interface()); }); Scope.macro.run(() { MacroScope.current.addModel(initial); diff --git a/pkgs/dart_model/test/type_system_test.dart b/pkgs/dart_model/test/type_system_test.dart index 3a87f6cc..4a054084 100644 --- a/pkgs/dart_model/test/type_system_test.dart +++ b/pkgs/dart_model/test/type_system_test.dart @@ -11,10 +11,14 @@ void main() { typeSystem = StaticTypeSystem(_model.types); }); - InterfaceType interfaceType(String name, - [List instantiation = const []]) { + InterfaceType interfaceType( + String name, [ + List instantiation = const [], + ]) { return InterfaceType( - name: QualifiedName.parse(name), instantiation: instantiation); + name: QualifiedName.parse(name), + instantiation: instantiation, + ); } InterfaceType future(StaticType of) { @@ -33,36 +37,49 @@ void main() { test('subtypes through class hierarchy', () { expect( - typeSystem.isSubtype(interfaceType('dart:core#double'), - interfaceType('dart:core#num')), - isTrue); + typeSystem.isSubtype( + interfaceType('dart:core#double'), + interfaceType('dart:core#num'), + ), + isTrue, + ); expect( - typeSystem.isSubtype(interfaceType('dart:core#double'), - interfaceType('dart:core#int')), - isFalse); + typeSystem.isSubtype( + interfaceType('dart:core#double'), + interfaceType('dart:core#int'), + ), + isFalse, + ); }); test('subtype check checks generics', () { // List <: Iterable expect( - typeSystem.isSubtype(interfaceType('dart:core#List', [object]), - interfaceType('dart:core#Iterable', [object])), - isTrue); + typeSystem.isSubtype( + interfaceType('dart:core#List', [object]), + interfaceType('dart:core#Iterable', [object]), + ), + isTrue, + ); // List <: Iterable expect( - typeSystem.isSubtype( - interfaceType('dart:core#List', [interfaceType('dart:core#int')]), - interfaceType( - 'dart:core#Iterable', [interfaceType('dart:core#num')])), - isTrue); + typeSystem.isSubtype( + interfaceType('dart:core#List', [interfaceType('dart:core#int')]), + interfaceType('dart:core#Iterable', [interfaceType('dart:core#num')]), + ), + isTrue, + ); // List is not a subtype of Iterable expect( - typeSystem.isSubtype( - interfaceType('dart:core#List', [interfaceType('dart:core#int')]), - interfaceType( - 'dart:core#Iterable', [interfaceType('dart:core#String')])), - isFalse); + typeSystem.isSubtype( + interfaceType('dart:core#List', [interfaceType('dart:core#int')]), + interfaceType('dart:core#Iterable', [ + interfaceType('dart:core#String'), + ]), + ), + isFalse, + ); }); }); @@ -78,10 +95,7 @@ void main() { }); test('Null? and Null are the same type', () { - expect( - typeSystem.areEqual(NullableType($null), $null), - isTrue, - ); + expect(typeSystem.areEqual(NullableType($null), $null), isTrue); }); test('Never is a subtype of everything', () { @@ -90,108 +104,104 @@ void main() { }); test('Never? and Null are the same type', () { - expect( - typeSystem.areEqual(const NullableType(never), $null), - isTrue, - ); + expect(typeSystem.areEqual(const NullableType(never), $null), isTrue); }); } -TypeHierarchyEntry _entryWithoutTypeArguments(String name, - [String supertype = 'dart:core#Object']) { +TypeHierarchyEntry _entryWithoutTypeArguments( + String name, [ + String supertype = 'dart:core#Object', +]) { return TypeHierarchyEntry( typeParameters: [], supertypes: [ - NamedTypeDesc( - name: QualifiedName.parse(supertype), - instantiation: [], - ), + NamedTypeDesc(name: QualifiedName.parse(supertype), instantiation: []), ], - self: NamedTypeDesc( - name: QualifiedName.parse(name), - instantiation: [], - ), + self: NamedTypeDesc(name: QualifiedName.parse(name), instantiation: []), ); } final _model = Model( - types: TypeHierarchy() - ..named.addAll( - { - 'dart:core#Object': TypeHierarchyEntry( - typeParameters: [], - supertypes: [], - self: NamedTypeDesc( - name: QualifiedName.parse('dart:core#Object'), - instantiation: [], - ), - ), - 'dart:core#Null': _entryWithoutTypeArguments('dart:core#Null'), - 'dart:core#Record': _entryWithoutTypeArguments('dart:core#Object'), - 'dart:core#Function': _entryWithoutTypeArguments('dart:core#Function'), - 'dart:core#String': _entryWithoutTypeArguments('dart:core#String'), - 'dart:core#num': _entryWithoutTypeArguments('dart:core#num'), - 'dart:core#int': - _entryWithoutTypeArguments('dart:core#int', 'dart:core#num'), - 'dart:core#double': - _entryWithoutTypeArguments('dart:core#double', 'dart:core#num'), - 'dart:core#Iterable': TypeHierarchyEntry( - typeParameters: [ - StaticTypeParameterDesc(identifier: 0), - ], - supertypes: [ - NamedTypeDesc( + types: + TypeHierarchy() + ..named.addAll({ + 'dart:core#Object': TypeHierarchyEntry( + typeParameters: [], + supertypes: [], + self: NamedTypeDesc( name: QualifiedName.parse('dart:core#Object'), instantiation: [], ), - ], - self: NamedTypeDesc( - name: QualifiedName.parse('dart:core#Iterable'), - instantiation: [ - StaticTypeDesc.typeParameterTypeDesc( - TypeParameterTypeDesc(parameterId: 0)), - ], ), - ), - 'dart:core#List': TypeHierarchyEntry( - typeParameters: [ - StaticTypeParameterDesc(identifier: 1), - ], - supertypes: [ - NamedTypeDesc( + 'dart:core#Null': _entryWithoutTypeArguments('dart:core#Null'), + 'dart:core#Record': _entryWithoutTypeArguments('dart:core#Object'), + 'dart:core#Function': _entryWithoutTypeArguments( + 'dart:core#Function', + ), + 'dart:core#String': _entryWithoutTypeArguments('dart:core#String'), + 'dart:core#num': _entryWithoutTypeArguments('dart:core#num'), + 'dart:core#int': _entryWithoutTypeArguments( + 'dart:core#int', + 'dart:core#num', + ), + 'dart:core#double': _entryWithoutTypeArguments( + 'dart:core#double', + 'dart:core#num', + ), + 'dart:core#Iterable': TypeHierarchyEntry( + typeParameters: [StaticTypeParameterDesc(identifier: 0)], + supertypes: [ + NamedTypeDesc( + name: QualifiedName.parse('dart:core#Object'), + instantiation: [], + ), + ], + self: NamedTypeDesc( name: QualifiedName.parse('dart:core#Iterable'), instantiation: [ StaticTypeDesc.typeParameterTypeDesc( - TypeParameterTypeDesc(parameterId: 1)), + TypeParameterTypeDesc(parameterId: 0), + ), ], ), - ], - self: NamedTypeDesc( - name: QualifiedName.parse('dart:core#List'), - instantiation: [ - StaticTypeDesc.typeParameterTypeDesc( - TypeParameterTypeDesc(parameterId: 1)), - ], ), - ), - 'dart:async#Future': TypeHierarchyEntry( - typeParameters: [ - StaticTypeParameterDesc(identifier: 2), - ], - supertypes: [ - NamedTypeDesc( - name: QualifiedName.parse('dart:core#Object'), - instantiation: [], + 'dart:core#List': TypeHierarchyEntry( + typeParameters: [StaticTypeParameterDesc(identifier: 1)], + supertypes: [ + NamedTypeDesc( + name: QualifiedName.parse('dart:core#Iterable'), + instantiation: [ + StaticTypeDesc.typeParameterTypeDesc( + TypeParameterTypeDesc(parameterId: 1), + ), + ], + ), + ], + self: NamedTypeDesc( + name: QualifiedName.parse('dart:core#List'), + instantiation: [ + StaticTypeDesc.typeParameterTypeDesc( + TypeParameterTypeDesc(parameterId: 1), + ), + ], ), - ], - self: NamedTypeDesc( - name: QualifiedName.parse('dart:async#Future'), - instantiation: [ - StaticTypeDesc.typeParameterTypeDesc( - TypeParameterTypeDesc(parameterId: 2)), + ), + 'dart:async#Future': TypeHierarchyEntry( + typeParameters: [StaticTypeParameterDesc(identifier: 2)], + supertypes: [ + NamedTypeDesc( + name: QualifiedName.parse('dart:core#Object'), + instantiation: [], + ), ], + self: NamedTypeDesc( + name: QualifiedName.parse('dart:async#Future'), + instantiation: [ + StaticTypeDesc.typeParameterTypeDesc( + TypeParameterTypeDesc(parameterId: 2), + ), + ], + ), ), - ), - }, - ), + }), ); diff --git a/pkgs/dart_model/test/type_test.dart b/pkgs/dart_model/test/type_test.dart index 5493ec0a..24cebeea 100644 --- a/pkgs/dart_model/test/type_test.dart +++ b/pkgs/dart_model/test/type_test.dart @@ -28,10 +28,12 @@ void main() { } StaticTypeDesc coreType(String name) { - return StaticTypeDesc.namedTypeDesc(NamedTypeDesc( - name: QualifiedName(name: name, uri: 'dart:core'), - instantiation: [], - )); + return StaticTypeDesc.namedTypeDesc( + NamedTypeDesc( + name: QualifiedName(name: name, uri: 'dart:core'), + instantiation: [], + ), + ); } test('isSubtype uses resolved model', () { diff --git a/pkgs/macro/lib/src/builders.dart b/pkgs/macro/lib/src/builders.dart index dbe8cc0c..b1b20b81 100644 --- a/pkgs/macro/lib/src/builders.dart +++ b/pkgs/macro/lib/src/builders.dart @@ -9,8 +9,9 @@ import 'macro.dart'; /// The base interface used to add declarations to the program as well /// as augment existing ones. abstract interface class Builder< - // TODO: Change to Declaration https://github.com/dart-lang/macros/issues/10 - T extends Object> { + // TODO: Change to Declaration https://github.com/dart-lang/macros/issues/10 + T extends Object +> { /// The target declaration of this macro application. T get target; @@ -27,16 +28,19 @@ abstract interface class Builder< /// The API used by [Macro]s to contribute new type declarations to the /// current library. abstract interface class TypesBuilder< - // TODO: Change to Declaration https://github.com/dart-lang/macros/issues/10 - T extends Object> implements Builder { + // TODO: Change to Declaration https://github.com/dart-lang/macros/issues/10 + T extends Object +> + implements Builder { /// Adds a new type declaration to the surrounding library. /// /// The [name] must match the name of the new [typeDeclaration] (this does /// not include any type parameters, just the name). void declareType( - String name, - // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 - Augmentation typeDeclaration); + String name, + // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 + Augmentation typeDeclaration, + ); } /// The API used by macros in the type phase to add interfaces to [target]s @@ -45,8 +49,9 @@ abstract interface class ImplementsClauseBuilder implements TypesBuilder { /// Appends [interfaces] to the `implements` clause on [target]. void appendInterfaces( - // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 - Iterable interfaces); + // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 + Iterable interfaces, + ); } /// The API used by macros in the type phase to add mixins to the [target]s @@ -55,8 +60,9 @@ abstract interface class WithClauseBuilder implements TypesBuilder { /// Appends [mixins] to the `with` clause on [target]. void appendMixins( - // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 - Iterable mixins); + // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 + Iterable mixins, + ); } /// The API used by macros in the type phase to set the `extends` clause @@ -67,8 +73,9 @@ abstract interface class ExtendsClauseBuilder /// /// The [target] type must not already have an `extends` clause. void extendsType( - // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 - Augmentation supertype); + // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 + Augmentation supertype, + ); } /// The builder API for [LibraryTypesMacro]s. @@ -77,33 +84,44 @@ abstract interface class LibraryTypesBuilder /// The builder API for [FunctionTypesMacro]s. abstract interface class FunctionTypesBuilder< - // TODO: Change to Function https://github.com/dart-lang/macros/issues/10 - T extends Object> implements TypesBuilder {} + // TODO: Change to Function https://github.com/dart-lang/macros/issues/10 + T extends Object +> + implements TypesBuilder {} /// The builder API for [MethodTypesMacro]s. abstract interface class MethodTypesBuilder< - // TODO: Change to Method https://github.com/dart-lang/macros/issues/10 - T extends Member> implements FunctionTypesBuilder {} + // TODO: Change to Method https://github.com/dart-lang/macros/issues/10 + T extends Member +> + implements FunctionTypesBuilder {} /// The builder API for [ConstructorTypesMacro]s. abstract interface class ConstructorTypesBuilder< - // TODO: Change to Constructor https://github.com/dart-lang/macros/issues/10 - T extends Member> implements MethodTypesBuilder {} + // TODO: Change to Constructor https://github.com/dart-lang/macros/issues/10 + T extends Member +> + implements MethodTypesBuilder {} /// The builder API for [VariableTypesMacro]s. abstract interface class VariableTypesBuilder< - // TODO: Change to Variable https://github.com/dart-lang/macros/issues/10 - T extends Object> implements TypesBuilder {} + // TODO: Change to Variable https://github.com/dart-lang/macros/issues/10 + T extends Object +> + implements TypesBuilder {} /// The builder API for [FieldTypesMacro]s. abstract interface class FieldTypesBuilder< - // TODO: Change to Field https://github.com/dart-lang/macros/issues/10 - T extends Member> implements VariableTypesBuilder {} + // TODO: Change to Field https://github.com/dart-lang/macros/issues/10 + T extends Member +> + implements VariableTypesBuilder {} /// The builder API for [ClassTypesMacro]s. abstract interface class ClassTypesBuilder< - // TODO: Change to Class https://github.com/dart-lang/macros/issues/10 - T extends Interface> + // TODO: Change to Class https://github.com/dart-lang/macros/issues/10 + T extends Interface +> implements TypesBuilder, ExtendsClauseBuilder, @@ -112,8 +130,9 @@ abstract interface class ClassTypesBuilder< /// The builder API for [EnumTypesMacro]s. abstract interface class EnumTypesBuilder< - // TODO: Change to Enum https://github.com/dart-lang/macros/issues/10 - T extends Interface> + // TODO: Change to Enum https://github.com/dart-lang/macros/issues/10 + T extends Interface +> implements TypesBuilder, ImplementsClauseBuilder, @@ -121,48 +140,60 @@ abstract interface class EnumTypesBuilder< /// The builder API for [EnumValueTypesMacro]s. abstract interface class EnumValueTypesBuilder< - // TODO: Change to EnumValue https://github.com/dart-lang/macros/issues/10 - T extends Member> implements TypesBuilder {} + // TODO: Change to EnumValue https://github.com/dart-lang/macros/issues/10 + T extends Member +> + implements TypesBuilder {} /// The builder API for [ExtensionTypesMacro]s. /// /// Note that augmentations do not allow altering the `on` clause. abstract interface class ExtensionTypesBuilder< - // TODO: Change to Extension https://github.com/dart-lang/macros/issues/10 - // ignore: lines_longer_than_80_chars - T extends Interface> implements TypesBuilder, ImplementsClauseBuilder {} + // TODO: Change to Extension https://github.com/dart-lang/macros/issues/10 + // ignore: lines_longer_than_80_chars + T extends Interface +> + implements TypesBuilder, ImplementsClauseBuilder {} /// The builder API for [ExtensionTypeTypesMacro]s. /// // TODO: Should this implement `WithClauseBuilder`, the spec is unclear? abstract interface class ExtensionTypeTypesBuilder< - // TODO: Change to ExtensionType https://github.com/dart-lang/macros/issues/10 - T extends Interface> implements TypesBuilder {} + // TODO: Change to ExtensionType https://github.com/dart-lang/macros/issues/10 + T extends Interface +> + implements TypesBuilder {} /// The builder API for [MixinTypesMacro]s. /// /// Note that mixins don't support mixins, only interfaces. abstract interface class MixinTypesBuilder< - // TODO: Change to Mixin https://github.com/dart-lang/macros/issues/10 - T extends Interface> + // TODO: Change to Mixin https://github.com/dart-lang/macros/issues/10 + T extends Interface +> implements TypesBuilder, ImplementsClauseBuilder {} /// The builder API for [TypeAliasTypesMacro]s. abstract interface class TypeAliasTypesBuilder< - // TODO: Change to TypeAlias https://github.com/dart-lang/macros/issues/10 - T extends Object> implements TypesBuilder {} + // TODO: Change to TypeAlias https://github.com/dart-lang/macros/issues/10 + T extends Object +> + implements TypesBuilder {} /// The base API used by all [Macro]s in the declarations phase. abstract interface class DeclarationsBuilder< - // TODO: Change to Declaration https://github.com/dart-lang/macros/issues/10 - T extends Object> implements Builder { + // TODO: Change to Declaration https://github.com/dart-lang/macros/issues/10 + T extends Object +> + implements Builder { /// Adds a new regular declaration to the library containing (or equal to) the /// [target]. /// /// Note that type declarations are not supported. void declareInLibrary( - // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 - Augmentation declaration); + // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 + Augmentation declaration, + ); } /// The builder API for [LibraryDeclarationsMacro]s. @@ -175,28 +206,38 @@ abstract interface class LibraryDeclarationsBuilder /// The builder API for [FunctionDeclarationsMacro]s. abstract interface class FunctionDeclarationsBuilder< - // TODO: Change to Function https://github.com/dart-lang/macros/issues/10 - T extends Object> implements DeclarationsBuilder {} + // TODO: Change to Function https://github.com/dart-lang/macros/issues/10 + T extends Object +> + implements DeclarationsBuilder {} /// The builder API for [MethodDeclarationsMacro]s. abstract interface class MethodDeclarationsBuilder< - // TODO: Change to Method https://github.com/dart-lang/macros/issues/10 - T extends Member> implements FunctionDeclarationsBuilder {} + // TODO: Change to Method https://github.com/dart-lang/macros/issues/10 + T extends Member +> + implements FunctionDeclarationsBuilder {} /// The builder API for [ConstructorDeclarationsMacro]s. abstract interface class ConstructorDeclarationsBuilder< - // TODO: Change to Constructor https://github.com/dart-lang/macros/issues/10 - T extends Member> implements MethodDeclarationsBuilder {} + // TODO: Change to Constructor https://github.com/dart-lang/macros/issues/10 + T extends Member +> + implements MethodDeclarationsBuilder {} /// The builder API for [VariableDeclarationsMacro]s. abstract interface class VariableDeclarationsBuilder< - // TODO: Change to Variable https://github.com/dart-lang/macros/issues/10 - T extends Object> implements DeclarationsBuilder {} + // TODO: Change to Variable https://github.com/dart-lang/macros/issues/10 + T extends Object +> + implements DeclarationsBuilder {} /// The builder API for [FieldDeclarationsMacro]s. abstract interface class FieldDeclarationsBuilder< - // TODO: Change to Field https://github.com/dart-lang/macros/issues/10 - T extends Member> implements VariableDeclarationsBuilder {} + // TODO: Change to Field https://github.com/dart-lang/macros/issues/10 + T extends Member +> + implements VariableDeclarationsBuilder {} /// The base builder API for [Macro]s which run on any [Interface] in the /// delarations phase. @@ -204,54 +245,72 @@ abstract interface class MemberDeclarationsBuilder implements DeclarationsBuilder { /// Adds a new declaration to the [target] interface. void declareInType( - // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 - Augmentation declaration); + // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 + Augmentation declaration, + ); } /// The builder API for [ClassDeclarationsMacro]s. abstract interface class ClassDeclarationsBuilder< - // TODO: Change to Class https://github.com/dart-lang/macros/issues/10 - T extends Interface> implements MemberDeclarationsBuilder {} + // TODO: Change to Class https://github.com/dart-lang/macros/issues/10 + T extends Interface +> + implements MemberDeclarationsBuilder {} /// The builder API for [EnumDeclarationsMacro]s. abstract interface class EnumDeclarationsBuilder< - // TODO: Change to Enum https://github.com/dart-lang/macros/issues/10 - T extends Interface> implements MemberDeclarationsBuilder { + // TODO: Change to Enum https://github.com/dart-lang/macros/issues/10 + T extends Interface +> + implements MemberDeclarationsBuilder { /// Adds a new enum value declaration to the [target] enum. void declareEnumValue( - // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 - Augmentation declaration); + // TODO: Tighten this type https://github.com/dart-lang/macros/issues/111 + Augmentation declaration, + ); } /// The builder API for [EnumValueDeclarationsMacro]s. abstract interface class EnumValueDeclarationsBuilder< - // TODO: Change to EnumValue https://github.com/dart-lang/macros/issues/10 - T extends Member> implements DeclarationsBuilder {} + // TODO: Change to EnumValue https://github.com/dart-lang/macros/issues/10 + T extends Member +> + implements DeclarationsBuilder {} /// The builder API for [ExtensionDeclarationsMacro]s. abstract interface class ExtensionDeclarationsBuilder< - // TODO: Change to Extension https://github.com/dart-lang/macros/issues/10 - T extends Interface> implements MemberDeclarationsBuilder {} + // TODO: Change to Extension https://github.com/dart-lang/macros/issues/10 + T extends Interface +> + implements MemberDeclarationsBuilder {} /// The builder API for [ExtensionTypeDeclarationsMacro]s. abstract interface class ExtensionTypeDeclarationsBuilder< - // TODO: Change to ExtensionType https://github.com/dart-lang/macros/issues/10 - T extends Interface> implements MemberDeclarationsBuilder {} + // TODO: Change to ExtensionType https://github.com/dart-lang/macros/issues/10 + T extends Interface +> + implements MemberDeclarationsBuilder {} /// The builder API for [MixinDeclarationsMacro]s. abstract interface class MixinDeclarationsBuilder< - // TODO: Change to Mixin https://github.com/dart-lang/macros/issues/10 - T extends Interface> implements MemberDeclarationsBuilder {} + // TODO: Change to Mixin https://github.com/dart-lang/macros/issues/10 + T extends Interface +> + implements MemberDeclarationsBuilder {} /// The builder API for [TypeAliasDeclarationsMacro]s. abstract interface class TypeAliasDeclarationsBuilder< - // TODO: Change to TypeAlias https://github.com/dart-lang/macros/issues/10 - T extends Object> implements DeclarationsBuilder {} + // TODO: Change to TypeAlias https://github.com/dart-lang/macros/issues/10 + T extends Object +> + implements DeclarationsBuilder {} /// The base builder API for [Macro]s which run in the definitions phase. abstract interface class DefinitionsBuilder< - // TODO: Change to Declaration https://github.com/dart-lang/macros/issues/10 - T extends Object> implements Builder { + // TODO: Change to Declaration https://github.com/dart-lang/macros/issues/10 + T extends Object +> + implements Builder { /// Augments an existing declaration. /// /// If [docCommentsAndMetadata] are supplied, they will be added above this @@ -289,8 +348,10 @@ abstract interface class LibraryDefinitionsBuilder /// The builder API for [FunctionDefinitionsMacro]s. abstract interface class FunctionDefinitionsBuilder< - // TODO: Change to Function https://github.com/dart-lang/macros/issues/10 - T extends Object> implements DefinitionsBuilder { + // TODO: Change to Function https://github.com/dart-lang/macros/issues/10 + T extends Object +> + implements DefinitionsBuilder { /// Augments an existing function. /// /// If [body] is supplied it will be used as the body for the augmenting @@ -309,13 +370,17 @@ abstract interface class FunctionDefinitionsBuilder< /// The builder API for [MethodDefinitionsMacro]s. abstract interface class MethodDefinitionsBuilder< - // TODO: Change to Method https://github.com/dart-lang/macros/issues/10 - T extends Member> implements FunctionDefinitionsBuilder {} + // TODO: Change to Method https://github.com/dart-lang/macros/issues/10 + T extends Member +> + implements FunctionDefinitionsBuilder {} /// The builder API for [ConstructorDefinitionsMacro]s. abstract interface class ConstructorDefinitionsBuilder< - // TODO: Change to Constructor https://github.com/dart-lang/macros/issues/10 - T extends Member> implements DefinitionsBuilder { + // TODO: Change to Constructor https://github.com/dart-lang/macros/issues/10 + T extends Member +> + implements DefinitionsBuilder { /// Augments an existing constructor body. /// /// If [body] is supplied it will be used as the body for the augmenting @@ -338,8 +403,10 @@ abstract interface class ConstructorDefinitionsBuilder< /// The builder API for [VariableDefinitionsMacro]s. abstract interface class VariableDefinitionsBuilder< - // TODO: Change to Variable https://github.com/dart-lang/macros/issues/10 - T extends Object> implements DefinitionsBuilder { + // TODO: Change to Variable https://github.com/dart-lang/macros/issues/10 + T extends Object +> + implements DefinitionsBuilder { /// Augments an existing variable. /// /// For [getter] and [setter] the full function declaration should be @@ -368,8 +435,10 @@ abstract interface class VariableDefinitionsBuilder< /// The builder API for [FieldDefinitionsMacro]s. abstract interface class FieldDefinitionsBuilder< - // TODO: Change to Field https://github.com/dart-lang/macros/issues/10 - T extends Member> implements VariableDefinitionsBuilder {} + // TODO: Change to Field https://github.com/dart-lang/macros/issues/10 + T extends Member +> + implements VariableDefinitionsBuilder {} /// The base builder API for [Macro]s which run on any [Interface] in the /// definitions phase. @@ -399,13 +468,17 @@ abstract interface class InterfaceDefinitionsBuilder /// The builder API for [ClassDefinitionsMacro]s. abstract interface class ClassDefinitionsBuilder< - // TODO: Change to Class https://github.com/dart-lang/macros/issues/10 - T extends Interface> implements InterfaceDefinitionsBuilder {} + // TODO: Change to Class https://github.com/dart-lang/macros/issues/10 + T extends Interface +> + implements InterfaceDefinitionsBuilder {} /// The builder API for [EnumDefinitionsMacro]s. abstract interface class EnumDefinitionsBuilder< - // TODO: Change to Enum https://github.com/dart-lang/macros/issues/10 - T extends Interface> implements InterfaceDefinitionsBuilder { + // TODO: Change to Enum https://github.com/dart-lang/macros/issues/10 + T extends Interface +> + implements InterfaceDefinitionsBuilder { /// Retrieve an [EnumValueDefinitionsBuilder] for an entry with [name] in /// [target]. /// @@ -416,25 +489,35 @@ abstract interface class EnumDefinitionsBuilder< /// The builder API for [EnumValueDefinitionsMacro]s. abstract interface class EnumValueDefinitionsBuilder< - // TODO: Change to EnumValue https://github.com/dart-lang/macros/issues/10 - T extends Member> implements DefinitionsBuilder {} + // TODO: Change to EnumValue https://github.com/dart-lang/macros/issues/10 + T extends Member +> + implements DefinitionsBuilder {} /// The builder API for [ExtensionDefinitionsMacro]s. abstract interface class ExtensionDefinitionsBuilder< - // TODO: Change to Field https://github.com/dart-lang/macros/issues/10 - T extends Interface> implements InterfaceDefinitionsBuilder {} + // TODO: Change to Field https://github.com/dart-lang/macros/issues/10 + T extends Interface +> + implements InterfaceDefinitionsBuilder {} /// The builder API for [ExtensionTypeDefinitionsMacro]s. abstract interface class ExtensionTypeDefinitionsBuilder< - // TODO: Change to ExtensionType https://github.com/dart-lang/macros/issues/10 - T extends Interface> implements InterfaceDefinitionsBuilder {} + // TODO: Change to ExtensionType https://github.com/dart-lang/macros/issues/10 + T extends Interface +> + implements InterfaceDefinitionsBuilder {} /// The builder API for [MixinDefinitionsMacro]s. abstract interface class MixinDefinitionsBuilder< - // TODO: Change to Mixin https://github.com/dart-lang/macros/issues/10 - T extends Interface> implements InterfaceDefinitionsBuilder {} + // TODO: Change to Mixin https://github.com/dart-lang/macros/issues/10 + T extends Interface +> + implements InterfaceDefinitionsBuilder {} /// The builder API for [TypeAliasDefinitionsMacro]s. abstract interface class TypeAliasDefinitionsBuilder< - // TODO: Change to TypeAlias https://github.com/dart-lang/macros/issues/10 - T extends Object> implements DefinitionsBuilder {} + // TODO: Change to TypeAlias https://github.com/dart-lang/macros/issues/10 + T extends Object +> + implements DefinitionsBuilder {} diff --git a/pkgs/macro/lib/src/macro.dart b/pkgs/macro/lib/src/macro.dart index db90c627..403d20a2 100644 --- a/pkgs/macro/lib/src/macro.dart +++ b/pkgs/macro/lib/src/macro.dart @@ -29,7 +29,8 @@ abstract interface class LibraryTypesMacro implements Macro { /// want to contribute new non-type declarations to the library. abstract interface class LibraryDeclarationsMacro implements Macro { FutureOr buildDeclarationsForLibrary( - LibraryDeclarationsBuilder builder); + LibraryDeclarationsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to a library directive, and @@ -50,7 +51,8 @@ abstract interface class FunctionTypesMacro implements Macro { /// declarations to the program. abstract interface class FunctionDeclarationsMacro implements Macro { FutureOr buildDeclarationsForFunction( - FunctionDeclarationsBuilder builder); + FunctionDeclarationsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any top level function, @@ -58,7 +60,8 @@ abstract interface class FunctionDeclarationsMacro implements Macro { /// definition. abstract interface class FunctionDefinitionsMacro implements Macro { FutureOr buildDefinitionsForFunction( - FunctionDefinitionsBuilder builder); + FunctionDefinitionsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any top level variable or @@ -73,14 +76,16 @@ abstract interface class VariableTypesMacro implements Macro { /// program. abstract interface class VariableDeclarationsMacro implements Macro { FutureOr buildDeclarationsForVariable( - VariableDeclarationsBuilder builder); + VariableDeclarationsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any top level variable /// or instance field, and want to augment the variable definition. abstract interface class VariableDefinitionsMacro implements Macro { FutureOr buildDefinitionsForVariable( - VariableDefinitionsBuilder builder); + VariableDefinitionsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any class, and want to @@ -129,14 +134,16 @@ abstract interface class EnumValueTypesMacro implements Macro { /// contribute new non-type declarations to the program. abstract interface class EnumValueDeclarationsMacro implements Macro { FutureOr buildDeclarationsForEnumValue( - EnumValueDeclarationsBuilder builder); + EnumValueDeclarationsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any enum, and want to /// augment the definitions of members or values of that enum. abstract interface class EnumValueDefinitionsMacro implements Macro { FutureOr buildDefinitionsForEnumValue( - EnumValueDefinitionsBuilder builder); + EnumValueDefinitionsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any field, and want to @@ -185,14 +192,16 @@ abstract interface class ConstructorTypesMacro implements Macro { /// want to contribute new non-type declarations to the program. abstract interface class ConstructorDeclarationsMacro implements Macro { FutureOr buildDeclarationsForConstructor( - ConstructorDeclarationsBuilder builder); + ConstructorDeclarationsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any constructor, and want /// to augment the function definition. abstract interface class ConstructorDefinitionsMacro implements Macro { FutureOr buildDefinitionsForConstructor( - ConstructorDefinitionsBuilder builder); + ConstructorDefinitionsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any mixin declaration, and @@ -223,14 +232,16 @@ abstract interface class ExtensionTypesMacro implements Macro { /// and want to contribute new non-type declarations to the program. abstract interface class ExtensionDeclarationsMacro implements Macro { FutureOr buildDeclarationsForExtension( - ExtensionDeclarationsBuilder builder); + ExtensionDeclarationsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any extension declaration, /// and want to augment the definitions of the members of that extension. abstract interface class ExtensionDefinitionsMacro implements Macro { FutureOr buildDefinitionsForExtension( - ExtensionDefinitionsBuilder builder); + ExtensionDefinitionsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any extension type @@ -244,7 +255,8 @@ abstract interface class ExtensionTypeTypesMacro implements Macro { /// program. abstract interface class ExtensionTypeDeclarationsMacro implements Macro { FutureOr buildDeclarationsForExtensionType( - ExtensionTypeDeclarationsBuilder builder); + ExtensionTypeDeclarationsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any extension type @@ -252,7 +264,8 @@ abstract interface class ExtensionTypeDeclarationsMacro implements Macro { /// extension. abstract interface class ExtensionTypeDefinitionsMacro implements Macro { FutureOr buildDefinitionsForExtensionType( - ExtensionTypeDefinitionsBuilder builder); + ExtensionTypeDefinitionsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any type alias @@ -266,7 +279,8 @@ abstract interface class TypeAliasTypesMacro implements Macro { /// program. abstract interface class TypeAliasDeclarationsMacro implements Macro { FutureOr buildDeclarationsForTypeAlias( - TypeAliasDeclarationsBuilder builder); + TypeAliasDeclarationsBuilder builder, + ); } /// The interface for [Macro]s that can be applied to any type alias @@ -274,5 +288,6 @@ abstract interface class TypeAliasDeclarationsMacro implements Macro { /// program. abstract interface class TypeAliasDefinitionsMacro implements Macro { FutureOr buildDeclarationsForTypeAlias( - TypeAliasDeclarationsBuilder builder); + TypeAliasDeclarationsBuilder builder, + ); } diff --git a/pkgs/macro/pubspec.yaml b/pkgs/macro/pubspec.yaml index 59f9d921..5191543c 100644 --- a/pkgs/macro/pubspec.yaml +++ b/pkgs/macro/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/dart-lang/macros/tree/master/pkgs/macro resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: collection: ^1.19.0 diff --git a/pkgs/macro_service/lib/src/handshake.g.dart b/pkgs/macro_service/lib/src/handshake.g.dart index bfd6dbfc..be15af7e 100644 --- a/pkgs/macro_service/lib/src/handshake.g.dart +++ b/pkgs/macro_service/lib/src/handshake.g.dart @@ -11,11 +11,8 @@ import 'package:dart_model/src/scopes.dart'; /// Request to pick a protocol. extension type HandshakeRequest.fromJson(Map node) implements Object { - HandshakeRequest({ - List? protocols, - }) : this.fromJson({ - if (protocols != null) 'protocols': protocols, - }); + HandshakeRequest({List? protocols}) + : this.fromJson({if (protocols != null) 'protocols': protocols}); /// Supported protocols. List get protocols => (node['protocols'] as List).cast(); @@ -24,11 +21,8 @@ extension type HandshakeRequest.fromJson(Map node) /// The picked protocol, or `null` if no requested protocol is supported. extension type HandshakeResponse.fromJson(Map node) implements Object { - HandshakeResponse({ - Protocol? protocol, - }) : this.fromJson({ - if (protocol != null) 'protocol': protocol, - }); + HandshakeResponse({Protocol? protocol}) + : this.fromJson({if (protocol != null) 'protocol': protocol}); /// Supported protocol. Protocol? get protocol => node['protocol'] as Protocol?; @@ -36,17 +30,17 @@ extension type HandshakeResponse.fromJson(Map node) /// The macro to host protocol version and encoding. TODO(davidmorgan): add the version. extension type Protocol.fromJson(Map node) implements Object { - Protocol({ - ProtocolEncoding? encoding, - ProtocolVersion? version, - }) : this.fromJson({ - if (encoding != null) 'encoding': encoding, - if (version != null) 'version': version, - }); + Protocol({ProtocolEncoding? encoding, ProtocolVersion? version}) + : this.fromJson({ + if (encoding != null) 'encoding': encoding, + if (version != null) 'version': version, + }); /// The initial protocol for any `host<->macro` connection. static Protocol handshakeProtocol = Protocol( - encoding: ProtocolEncoding.json, version: ProtocolVersion.handshake); + encoding: ProtocolEncoding.json, + version: ProtocolVersion.handshake, + ); /// The wire format: json or binary. ProtocolEncoding get encoding => node['encoding'] as ProtocolEncoding; @@ -64,7 +58,8 @@ extension type const ProtocolEncoding.fromJson(String string) /// The protocol version. extension type const ProtocolVersion.fromJson(String string) implements Object { - static const ProtocolVersion handshake = - ProtocolVersion.fromJson('handshake'); + static const ProtocolVersion handshake = ProtocolVersion.fromJson( + 'handshake', + ); static const ProtocolVersion macros1 = ProtocolVersion.fromJson('macros1'); } diff --git a/pkgs/macro_service/lib/src/macro_service.dart b/pkgs/macro_service/lib/src/macro_service.dart index 5ed2f114..d2c06858 100644 --- a/pkgs/macro_service/lib/src/macro_service.dart +++ b/pkgs/macro_service/lib/src/macro_service.dart @@ -59,12 +59,14 @@ extension ProtocolExtension on Protocol { // sense than fixed four bytes. final binary = node.serializeToBinary(); final length = binary.length; - sink(Uint8List.fromList([ - (length >> 24) & 255, - (length >> 16) & 255, - (length >> 8) & 255, - length & 255, - ])); + sink( + Uint8List.fromList([ + (length >> 24) & 255, + (length >> 16) & 255, + (length >> 8) & 255, + length & 255, + ]), + ); sink(binary); default: throw StateError('Unsupported protocol: $this.'); @@ -84,9 +86,9 @@ extension ProtocolExtension on Protocol { .map((line) => json.decode(line) as Map); case ProtocolEncoding.binary: - return MessageGrouper(stream) - .messageStream - .map((message) => message.deserializeFromBinary()); + return MessageGrouper( + stream, + ).messageStream.map((message) => message.deserializeFromBinary()); default: throw StateError('Unsupported protocol: $this'); } diff --git a/pkgs/macro_service/lib/src/macro_service.g.dart b/pkgs/macro_service/lib/src/macro_service.g.dart index 83d16713..7e96a863 100644 --- a/pkgs/macro_service/lib/src/macro_service.g.dart +++ b/pkgs/macro_service/lib/src/macro_service.g.dart @@ -17,11 +17,7 @@ extension type AugmentRequest.fromJson(Map node) required int phase, required QualifiedName target, required Model model, - }) : this.fromJson({ - 'phase': phase, - 'target': target, - 'model': model, - }); + }) : this.fromJson({'phase': phase, 'target': target, 'model': model}); /// Which phase to run: 1, 2 or 3. int get phase => node['phase'] as int; @@ -40,15 +36,15 @@ extension type AugmentResponse.fromJson(Map node) List? libraryAugmentations, List? newTypeNames, }) : this.fromJson({ - 'enumValueAugmentations': {}, - 'extendsTypeAugmentations': {}, - 'interfaceAugmentations': {}, - if (libraryAugmentations != null) - 'libraryAugmentations': libraryAugmentations, - 'mixinAugmentations': {}, - if (newTypeNames != null) 'newTypeNames': newTypeNames, - 'typeAugmentations': {}, - }); + 'enumValueAugmentations': {}, + 'extendsTypeAugmentations': {}, + 'interfaceAugmentations': {}, + if (libraryAugmentations != null) + 'libraryAugmentations': libraryAugmentations, + 'mixinAugmentations': {}, + if (newTypeNames != null) 'newTypeNames': newTypeNames, + 'typeAugmentations': {}, + }); /// Any augmentations to enum values that should be applied to an enum as a result of executing a macro, indexed by the name of the enum. Map>? get enumValueAugmentations => @@ -79,18 +75,16 @@ extension type AugmentResponse.fromJson(Map node) /// Any augmentations that should be applied to a class as a result of executing a macro, indexed by the name of the class. Map>? get typeAugmentations => - (node['typeAugmentations'] as Map?) - ?.deepCast>((v) => (v as List).cast()); + (node['typeAugmentations'] as Map?)?.deepCast>( + (v) => (v as List).cast(), + ); } /// Request could not be handled. extension type ErrorResponse.fromJson(Map node) implements Object { - ErrorResponse({ - String? error, - }) : this.fromJson({ - if (error != null) 'error': error, - }); + ErrorResponse({String? error}) + : this.fromJson({if (error != null) 'error': error}); /// The error. String get error => node['error'] as String; @@ -99,11 +93,7 @@ extension type ErrorResponse.fromJson(Map node) /// A macro host server endpoint. TODO(davidmorgan): this should be a oneOf supporting different types of connection. TODO(davidmorgan): it's not clear if this belongs in this package! But, where else? extension type HostEndpoint.fromJson(Map node) implements Object { - HostEndpoint({ - int? port, - }) : this.fromJson({ - if (port != null) 'port': port, - }); + HostEndpoint({int? port}) : this.fromJson({if (port != null) 'port': port}); /// TCP port to connect to. int get port => node['port'] as int; @@ -123,13 +113,12 @@ extension type HostRequest.fromJson(Map node) AugmentRequest augmentRequest, { required int id, QualifiedName? macroAnnotation, - }) => - HostRequest.fromJson({ - 'type': 'AugmentRequest', - 'value': augmentRequest, - 'id': id, - if (macroAnnotation != null) 'macroAnnotation': macroAnnotation, - }); + }) => HostRequest.fromJson({ + 'type': 'AugmentRequest', + 'value': augmentRequest, + 'id': id, + if (macroAnnotation != null) 'macroAnnotation': macroAnnotation, + }); HostRequestType get type { switch (node['type'] as String) { case 'AugmentRequest': @@ -156,13 +145,11 @@ extension type HostRequest.fromJson(Map node) /// Information about a macro that the macro provides to the host. extension type MacroDescription.fromJson(Map node) implements Object { - MacroDescription({ - QualifiedName? annotation, - List? runsInPhases, - }) : this.fromJson({ - if (annotation != null) 'annotation': annotation, - if (runsInPhases != null) 'runsInPhases': runsInPhases, - }); + MacroDescription({QualifiedName? annotation, List? runsInPhases}) + : this.fromJson({ + if (annotation != null) 'annotation': annotation, + if (runsInPhases != null) 'runsInPhases': runsInPhases, + }); /// The annotation that triggers the macro. QualifiedName get annotation => node['annotation'] as QualifiedName; @@ -174,11 +161,10 @@ extension type MacroDescription.fromJson(Map node) /// Informs the host that a macro has started. extension type MacroStartedRequest.fromJson(Map node) implements Object { - MacroStartedRequest({ - MacroDescription? macroDescription, - }) : this.fromJson({ - if (macroDescription != null) 'macroDescription': macroDescription, - }); + MacroStartedRequest({MacroDescription? macroDescription}) + : this.fromJson({ + if (macroDescription != null) 'macroDescription': macroDescription, + }); /// The macro description. MacroDescription get macroDescription => @@ -205,21 +191,19 @@ extension type MacroRequest.fromJson(Map node) static MacroRequest macroStartedRequest( MacroStartedRequest macroStartedRequest, { required int id, - }) => - MacroRequest.fromJson({ - 'type': 'MacroStartedRequest', - 'value': macroStartedRequest, - 'id': id, - }); + }) => MacroRequest.fromJson({ + 'type': 'MacroStartedRequest', + 'value': macroStartedRequest, + 'id': id, + }); static MacroRequest queryRequest( QueryRequest queryRequest, { required int id, - }) => - MacroRequest.fromJson({ - 'type': 'QueryRequest', - 'value': queryRequest, - 'id': id, - }); + }) => MacroRequest.fromJson({ + 'type': 'QueryRequest', + 'value': queryRequest, + 'id': id, + }); MacroRequestType get type { switch (node['type'] as String) { case 'MacroStartedRequest': @@ -252,11 +236,8 @@ extension type MacroRequest.fromJson(Map node) /// Macro's query about the code it should augment. extension type QueryRequest.fromJson(Map node) implements Object { - QueryRequest({ - Query? query, - }) : this.fromJson({ - if (query != null) 'query': query, - }); + QueryRequest({Query? query}) + : this.fromJson({if (query != null) 'query': query}); /// The query. Query get query => node['query'] as Query; @@ -265,11 +246,8 @@ extension type QueryRequest.fromJson(Map node) /// Host's response to a [QueryRequest]. extension type QueryResponse.fromJson(Map node) implements Object { - QueryResponse({ - Model? model, - }) : this.fromJson({ - if (model != null) 'model': model, - }); + QueryResponse({Model? model}) + : this.fromJson({if (model != null) 'model': model}); /// The model. Model get model => node['model'] as Model; @@ -290,39 +268,35 @@ extension type Response.fromJson(Map node) implements Object { static Response augmentResponse( AugmentResponse augmentResponse, { required int requestId, - }) => - Response.fromJson({ - 'type': 'AugmentResponse', - 'value': augmentResponse, - 'requestId': requestId, - }); + }) => Response.fromJson({ + 'type': 'AugmentResponse', + 'value': augmentResponse, + 'requestId': requestId, + }); static Response errorResponse( ErrorResponse errorResponse, { required int requestId, - }) => - Response.fromJson({ - 'type': 'ErrorResponse', - 'value': errorResponse, - 'requestId': requestId, - }); + }) => Response.fromJson({ + 'type': 'ErrorResponse', + 'value': errorResponse, + 'requestId': requestId, + }); static Response macroStartedResponse( MacroStartedResponse macroStartedResponse, { required int requestId, - }) => - Response.fromJson({ - 'type': 'MacroStartedResponse', - 'value': macroStartedResponse, - 'requestId': requestId, - }); + }) => Response.fromJson({ + 'type': 'MacroStartedResponse', + 'value': macroStartedResponse, + 'requestId': requestId, + }); static Response queryResponse( QueryResponse queryResponse, { required int requestId, - }) => - Response.fromJson({ - 'type': 'QueryResponse', - 'value': queryResponse, - 'requestId': requestId, - }); + }) => Response.fromJson({ + 'type': 'QueryResponse', + 'value': queryResponse, + 'requestId': requestId, + }); ResponseType get type { switch (node['type'] as String) { case 'AugmentResponse': diff --git a/pkgs/macro_service/lib/src/message_grouper.dart b/pkgs/macro_service/lib/src/message_grouper.dart index 580c6f0d..f98bd9ac 100644 --- a/pkgs/macro_service/lib/src/message_grouper.dart +++ b/pkgs/macro_service/lib/src/message_grouper.dart @@ -21,9 +21,11 @@ class MessageGrouper { _FixedBuffer? _messageBuffer; late final StreamController _messageStreamController = - StreamController(onCancel: () { - _inputStreamSubscription.cancel(); - }); + StreamController( + onCancel: () { + _inputStreamSubscription.cancel(); + }, + ); Stream get messageStream => _messageStreamController.stream; @@ -45,7 +47,8 @@ class MessageGrouper { _lengthBuffer.addByte(bytes[offset++]); } if (_lengthBuffer.isReady) { - final length = _lengthBuffer[0] << 24 | + final length = + _lengthBuffer[0] << 24 | _lengthBuffer[1] << 16 | _lengthBuffer[2] << 8 | _lengthBuffer[3]; diff --git a/pkgs/macro_service/pubspec.yaml b/pkgs/macro_service/pubspec.yaml index d5237db0..e1d355b1 100644 --- a/pkgs/macro_service/pubspec.yaml +++ b/pkgs/macro_service/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/dart-lang/macros/tree/master/pkgs/macro_service resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: async: ^2.11.0 diff --git a/pkgs/macro_service/test/protocol_test.dart b/pkgs/macro_service/test/protocol_test.dart index f317e103..740f444b 100644 --- a/pkgs/macro_service/test/protocol_test.dart +++ b/pkgs/macro_service/test/protocol_test.dart @@ -12,7 +12,7 @@ import 'package:test/test.dart'; void main() { for (final protocol in [ Protocol(encoding: ProtocolEncoding.json), - Protocol(encoding: ProtocolEncoding.binary) + Protocol(encoding: ProtocolEncoding.binary), ]) { group('Protocol using ${protocol.encoding}', () { test('can round trip JSON data', () async { @@ -21,7 +21,7 @@ void main() { 'int': 7, 'boolean': true, 'map': {'key': 'value'}, - 'list': [1, 'two', 3] + 'list': [1, 'two', 3], }; final receivedData = []; @@ -42,7 +42,7 @@ void main() { 'int': 7, 'boolean': true, 'map': {'key': 'value'}, - 'list': [1, 'two', 3] + 'list': [1, 'two', 3], }; final receivedData = []; @@ -58,8 +58,9 @@ void main() { var sizeToTake = 1; while (receivedData.isNotEmpty) { final take = min(sizeToTake++, receivedData.length); - final takenBytes = - Uint8List.fromList(receivedData.take(take).toList()); + final takenBytes = Uint8List.fromList( + receivedData.take(take).toList(), + ); receivedData.removeRange(0, take); streamController.add(takenBytes); } diff --git a/pubspec.yaml b/pubspec.yaml index ad3f5a70..88bf94e0 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: macros_workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dev_dependencies: dart_flutter_team_lints: ^3.1.0 publish_to: none @@ -31,134 +31,138 @@ dependency_overrides: git: url: https://github.com/dart-lang/sdk.git path: pkg/_fe_analyzer_shared - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev _js_interop_checks: git: url: https://github.com/dart-lang/sdk.git path: pkg/_js_interop_checks - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev _macros: git: url: https://github.com/dart-lang/sdk.git path: pkg/_macros - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev analysis_server: git: url: https://github.com/dart-lang/sdk.git path: pkg/analysis_server - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev analyzer: git: url: https://github.com/dart-lang/sdk.git path: pkg/analyzer - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev analyzer_plugin: git: url: https://github.com/dart-lang/sdk.git path: pkg/analyzer_plugin - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev analyzer_utilities: git: url: https://github.com/dart-lang/sdk.git path: pkg/analyzer_utilities - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev build_integration: git: url: https://github.com/dart-lang/sdk.git path: pkg/build_integration - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev compiler: git: url: https://github.com/dart-lang/sdk.git path: pkg/compiler - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev + dart_style: + git: + url: https://github.com/dart-lang/dart_style.git + ref: dc13a2f8e667825980cbc1a06ed645620f9bed70 # Not an SDK ref! dart2js_info: git: url: https://github.com/dart-lang/sdk.git path: pkg/dart2js_info - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev dart2wasm: git: url: https://github.com/dart-lang/sdk.git path: pkg/dart2wasm - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev dev_compiler: git: url: https://github.com/dart-lang/sdk.git path: pkg/dev_compiler - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev front_end: git: url: https://github.com/dart-lang/sdk.git path: pkg/front_end - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev frontend_server: git: url: https://github.com/dart-lang/sdk.git path: pkg/frontend_server - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev heap_snapshot: git: url: https://github.com/dart-lang/sdk.git path: pkg/heap_snapshot - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev js_ast: git: url: https://github.com/dart-lang/sdk.git path: pkg/js_ast - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev js_runtime: git: url: https://github.com/dart-lang/sdk.git path: pkg/js_runtime - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev js_shared: git: url: https://github.com/dart-lang/sdk.git path: pkg/js_shared - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev kernel: git: url: https://github.com/dart-lang/sdk.git path: pkg/kernel - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev analysis_server_plugin: git: url: https://github.com/dart-lang/sdk.git path: pkg/analysis_server_plugin - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev language_server_protocol: git: url: https://github.com/dart-lang/sdk.git path: third_party/pkg/language_server_protocol - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev linter: git: url: https://github.com/dart-lang/sdk.git path: pkg/linter - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev mmap: git: url: https://github.com/dart-lang/sdk.git path: pkg/mmap - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev telemetry: git: url: https://github.com/dart-lang/sdk.git path: pkg/telemetry - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev vm: git: url: https://github.com/dart-lang/sdk.git path: pkg/vm - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev vm_service: git: url: https://github.com/dart-lang/sdk.git path: pkg/vm_service - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev wasm_builder: git: url: https://github.com/dart-lang/sdk.git path: pkg/wasm_builder - ref: a8bee55e94979730890500026884afcf33e68f2f + ref: 3.7.0-123.0.dev diff --git a/tool/benchmark_generator/bin/benchmark_generator.dart b/tool/benchmark_generator/bin/benchmark_generator.dart index a336711e..0e60aa84 100644 --- a/tool/benchmark_generator/bin/benchmark_generator.dart +++ b/tool/benchmark_generator/bin/benchmark_generator.dart @@ -24,9 +24,10 @@ Creates packages to benchmark macro performance. Usage: final workspace = Workspace(workspaceName); print('Creating under: ${workspace.directory.path}'); final inputGenerator = JsonEncodableInputGenerator( - fieldsPerClass: 100, - classesPerLibrary: 10, - librariesPerCycle: libraryCount, - strategy: strategy); + fieldsPerClass: 100, + classesPerLibrary: 10, + librariesPerCycle: libraryCount, + strategy: strategy, + ); inputGenerator.generate(workspace); } diff --git a/tool/benchmark_generator/lib/json_encodable/input_generator.dart b/tool/benchmark_generator/lib/json_encodable/input_generator.dart index 41c8cf0a..0e4a349c 100644 --- a/tool/benchmark_generator/lib/json_encodable/input_generator.dart +++ b/tool/benchmark_generator/lib/json_encodable/input_generator.dart @@ -26,11 +26,12 @@ class JsonEncodableInputGenerator { final int librariesPerCycle; final Strategy strategy; - JsonEncodableInputGenerator( - {required this.fieldsPerClass, - required this.classesPerLibrary, - required this.librariesPerCycle, - required this.strategy}); + JsonEncodableInputGenerator({ + required this.fieldsPerClass, + required this.classesPerLibrary, + required this.librariesPerCycle, + required this.strategy, + }); void generate(Workspace workspace) { for (var i = 0; i != librariesPerCycle; ++i) { @@ -38,8 +39,11 @@ class JsonEncodableInputGenerator { } } - String _generateLibrary(int index, - {bool topLevelCacheBuster = false, bool fieldCacheBuster = false}) { + String _generateLibrary( + int index, { + bool topLevelCacheBuster = false, + bool fieldCacheBuster = false, + }) { final buffer = StringBuffer(); if (strategy == Strategy.macro) { @@ -68,8 +72,9 @@ class JsonEncodableInputGenerator { return 'a$fieldIndex'; } - final result = - StringBuffer(strategy == Strategy.macro ? '@JsonCodable()' : ''); + final result = StringBuffer( + strategy == Strategy.macro ? '@JsonCodable()' : '', + ); result.writeln('class $className {'); result.writeln(''' @@ -92,12 +97,14 @@ class JsonEncodableInputGenerator { result.writeln(' final result = {};'); for (var i = 0; i != fieldsPerClass; ++i) { result.writeln( - "if (${fieldName(i)} != null) result['${fieldName(i)}'] = ${fieldName(i)};"); + "if (${fieldName(i)} != null) result['${fieldName(i)}'] = ${fieldName(i)};", + ); } result.writeln('return result;'); result.writeln('}'); - result - .writeln('factory $className.fromJson(Map json) {'); + result.writeln( + 'factory $className.fromJson(Map json) {', + ); result.writeln('return $className._('); for (var i = 0; i != fieldsPerClass; ++i) { result.writeln("${fieldName(i)}: json['${fieldName(i)}'] as int,"); @@ -111,12 +118,16 @@ class JsonEncodableInputGenerator { } void changeIrrelevantInput(Workspace workspace) { - workspace.write('a0.dart', - source: _generateLibrary(0, topLevelCacheBuster: true)); + workspace.write( + 'a0.dart', + source: _generateLibrary(0, topLevelCacheBuster: true), + ); } void changeRevelantInput(Workspace workspace) { - workspace.write('a0.dart', - source: _generateLibrary(0, fieldCacheBuster: true)); + workspace.write( + 'a0.dart', + source: _generateLibrary(0, fieldCacheBuster: true), + ); } } diff --git a/tool/benchmark_generator/lib/workspace.dart b/tool/benchmark_generator/lib/workspace.dart index 5edb40da..4923c999 100644 --- a/tool/benchmark_generator/lib/workspace.dart +++ b/tool/benchmark_generator/lib/workspace.dart @@ -9,7 +9,8 @@ class Workspace { final String name; Directory get directory => Directory.fromUri( - Isolate.packageConfigSync!.resolve('../goldens/foo/lib/generated/$name')); + Isolate.packageConfigSync!.resolve('../goldens/foo/lib/generated/$name'), + ); Workspace(this.name) { if (directory.existsSync()) directory.deleteSync(recursive: true); diff --git a/tool/benchmark_generator/pubspec.yaml b/tool/benchmark_generator/pubspec.yaml index 4cd125ba..8b8a2383 100644 --- a/tool/benchmark_generator/pubspec.yaml +++ b/tool/benchmark_generator/pubspec.yaml @@ -2,7 +2,7 @@ name: benchmark_generator publish-to: none resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dev_dependencies: dart_flutter_team_lints: ^3.0.0 diff --git a/tool/dart_model_generator/lib/definitions.dart b/tool/dart_model_generator/lib/definitions.dart index 00598f69..4e2f7e05 100644 --- a/tool/dart_model_generator/lib/definitions.dart +++ b/tool/dart_model_generator/lib/definitions.dart @@ -12,48 +12,64 @@ final schemas = Schemas([ codePath: 'src/handshake.g.dart', rootTypes: ['HandshakeRequest', 'HandshakeResponse'], declarations: [ - Definition.clazz('HandshakeRequest', - description: 'Request to pick a protocol.', - properties: [ - Property( - 'protocols', - type: 'List', - description: 'Supported protocols.', - ), - ]), - Definition.clazz('HandshakeResponse', - description: - 'The picked protocol, or `null` if no requested protocol ' - 'is supported.', - properties: [ - Property( - 'protocol', - type: 'Protocol', - description: 'Supported protocol.', - nullable: true, - ), - ]), - Definition.clazz('Protocol', - description: 'The macro to host protocol version and encoding. ' - 'TODO(davidmorgan): add the version.', - properties: [ - Property('encoding', - type: 'ProtocolEncoding', - description: 'The wire format: json or binary.'), - Property('version', - type: 'ProtocolVersion', - description: 'The protocol version, a name and number.'), - ], - extraCode: ''' + Definition.clazz( + 'HandshakeRequest', + description: 'Request to pick a protocol.', + properties: [ + Property( + 'protocols', + type: 'List', + description: 'Supported protocols.', + ), + ], + ), + Definition.clazz( + 'HandshakeResponse', + description: + 'The picked protocol, or `null` if no requested protocol ' + 'is supported.', + properties: [ + Property( + 'protocol', + type: 'Protocol', + description: 'Supported protocol.', + nullable: true, + ), + ], + ), + Definition.clazz( + 'Protocol', + description: + 'The macro to host protocol version and encoding. ' + 'TODO(davidmorgan): add the version.', + properties: [ + Property( + 'encoding', + type: 'ProtocolEncoding', + description: 'The wire format: json or binary.', + ), + Property( + 'version', + type: 'ProtocolVersion', + description: 'The protocol version, a name and number.', + ), + ], + extraCode: ''' /// The initial protocol for any `host<->macro` connection. static Protocol handshakeProtocol = Protocol( encoding: ProtocolEncoding.json, version: ProtocolVersion.handshake); -'''), - Definition.$enum('ProtocolEncoding', - description: 'The wire encoding used.', values: ['json', 'binary']), - Definition.$enum('ProtocolVersion', - description: 'The protocol version.', - values: ['handshake', 'macros1']), +''', + ), + Definition.$enum( + 'ProtocolEncoding', + description: 'The wire encoding used.', + values: ['json', 'binary'], + ), + Definition.$enum( + 'ProtocolVersion', + description: 'The protocol version.', + values: ['handshake', 'macros1'], + ), ], ), Schema( @@ -64,219 +80,300 @@ static Protocol handshakeProtocol = Protocol( declarations: macro_metadata.definitions, ), Schema( - schemaPath: 'dart_model.schema.json', - codePackage: 'dart_model', - codePath: 'src/dart_model.g.dart', - rootTypes: [ - 'Model', - ], - declarations: [ - Definition.clazz( - 'Augmentation', - createInBuffer: true, - description: 'An augmentation to Dart code.', - properties: [ - Property('code', - type: 'List', description: 'Augmentation code.'), - ], - ), - Definition.union( - 'Code', - createInBuffer: true, - description: 'Code that is part of augmentations to Dart code.', - types: ['QualifiedName', 'String'], - properties: [], - ), - Definition.nullTypedef('DynamicTypeDesc', + schemaPath: 'dart_model.schema.json', + codePackage: 'dart_model', + codePath: 'src/dart_model.g.dart', + rootTypes: ['Model'], + declarations: [ + Definition.clazz( + 'Augmentation', + createInBuffer: true, + description: 'An augmentation to Dart code.', + properties: [ + Property( + 'code', + type: 'List', + description: 'Augmentation code.', + ), + ], + ), + Definition.union( + 'Code', + createInBuffer: true, + description: 'Code that is part of augmentations to Dart code.', + types: ['QualifiedName', 'String'], + properties: [], + ), + Definition.nullTypedef( + 'DynamicTypeDesc', + description: 'The type-hierarchy representation of the type `dynamic`.', + ), + Definition.clazz( + 'FunctionTypeDesc', + description: 'A static type representation for function types.', + createInBuffer: true, + properties: [ + Property( + 'returnType', + type: 'StaticTypeDesc', + description: 'The return type of this function type.', + ), + Property( + 'typeParameters', + type: 'List', description: - 'The type-hierarchy representation of the type `dynamic`.'), - Definition.clazz('FunctionTypeDesc', - description: 'A static type representation for function types.', - createInBuffer: true, - properties: [ - Property('returnType', - type: 'StaticTypeDesc', - description: 'The return type of this function type.'), - Property('typeParameters', - type: 'List', - description: - 'Static type parameters introduced by this function ' - 'type.'), - Property('requiredPositionalParameters', - type: 'List'), - Property('optionalPositionalParameters', - type: 'List'), - Property('namedParameters', - type: 'List'), - ]), - Definition.clazz('MetadataAnnotation', - description: 'A metadata annotation.', - createInBuffer: true, - properties: [ - Property('expression', - type: 'Expression', - description: 'The expression of the annotation.'), - ]), - Definition.clazz('Declaration', - description: 'Interface type for all declarations', - interfaceOnly: true, - properties: [ - Property('metadataAnnotations', - type: 'List', - description: - 'The metadata annotations attached to this declaration.'), - Property('properties', - type: 'Properties', - description: 'The properties of this declaration.'), - ]), - Definition.clazz( - 'Interface', - description: 'An interface.', - createInBuffer: true, - implements: [ - 'Declaration', - ], - properties: [ - Property('members', - type: 'Map', description: 'Map of members by name.'), - Property('thisType', - type: 'NamedTypeDesc', - description: - 'The type of the expression `this` when used in this ' - 'interface.'), - ], - ), - Definition.clazz('Library', - description: 'Library.', - createInBuffer: true, - properties: [ - Property('scopes', - type: 'Map', description: 'Scopes by name.'), - ]), - // TODO(davidmorgan): make `Member` a union. - Definition.clazz('Member', - description: 'Member of a scope.', - createInBuffer: true, - implements: [ - 'Declaration', - ], - properties: [ - Property( - 'returnType', - type: 'StaticTypeDesc', - description: 'The return type of this member, if it has one.', - ), - // TODO(davidmorgan): base on - // https://github.com/dart-lang/sdk/blob/main/pkg/_macros/lib/src/api/introspection.dart#L269 - Property('requiredPositionalParameters', - type: 'List', - description: - 'The required positional parameters of this member, ' - 'if it has them.'), - Property('optionalPositionalParameters', - type: 'List', - description: - 'The optional positional parameters of this member, ' - 'if it has them.'), - Property('namedParameters', - type: 'List', - description: 'The named parameters of this member, ' - 'if it has them.'), - ]), - Definition.clazz('Model', - description: 'Partial model of a corpus of Dart source code.', - createInBuffer: true, - properties: [ - Property('uris', - type: 'Map', description: 'Libraries by URI.'), - Property('types', - type: 'TypeHierarchy', - description: 'The resolved static type hierarchy.'), - ]), - Definition.clazz('NamedFunctionTypeParameter', + 'Static type parameters introduced by this function ' + 'type.', + ), + Property( + 'requiredPositionalParameters', + type: 'List', + ), + Property( + 'optionalPositionalParameters', + type: 'List', + ), + Property('namedParameters', type: 'List'), + ], + ), + Definition.clazz( + 'MetadataAnnotation', + description: 'A metadata annotation.', + createInBuffer: true, + properties: [ + Property( + 'expression', + type: 'Expression', + description: 'The expression of the annotation.', + ), + ], + ), + Definition.clazz( + 'Declaration', + description: 'Interface type for all declarations', + interfaceOnly: true, + properties: [ + Property( + 'metadataAnnotations', + type: 'List', description: - 'A resolved named parameter as part of a [FunctionTypeDesc].', - createInBuffer: true, - properties: [ - Property('name', type: 'String'), - Property('required', type: 'bool'), - Property('type', type: 'StaticTypeDesc'), - ]), - Definition.clazz('NamedRecordField', + 'The metadata annotations attached to this declaration.', + ), + Property( + 'properties', + type: 'Properties', + description: 'The properties of this declaration.', + ), + ], + ), + Definition.clazz( + 'Interface', + description: 'An interface.', + createInBuffer: true, + implements: ['Declaration'], + properties: [ + Property( + 'members', + type: 'Map', + description: 'Map of members by name.', + ), + Property( + 'thisType', + type: 'NamedTypeDesc', description: - 'A named field in a [RecordTypeDesc], consisting of the field ' - 'name and the associated type.', - createInBuffer: true, - properties: [ - Property('name', type: 'String'), - Property('type', type: 'StaticTypeDesc'), - ]), - Definition.clazz('NamedTypeDesc', - description: 'A resolved static type.', - createInBuffer: true, - properties: [ - Property('name', type: 'QualifiedName'), - Property('instantiation', type: 'List'), - ]), - Definition.nullTypedef('NeverTypeDesc', - description: 'Representation of the bottom type [Never].'), - Definition.clazz( - 'NullableTypeDesc', - description: 'A Dart type of the form `T?` for an inner type `T`.', - createInBuffer: true, - properties: [ - Property('inner', - type: 'StaticTypeDesc', description: 'The type T.') - ], - ), - Definition.clazz('Properties', - description: 'Set of boolean properties.', - createInBuffer: true, - properties: [ - Property('isAbstract', - type: 'bool', - description: - 'Whether the entity is abstract, meaning it has no ' - 'definition.'), - Property('isClass', - type: 'bool', description: 'Whether the entity is a class.'), - Property('isConstructor', - type: 'bool', - description: 'Whether the entity is a constructor.'), - Property('isGetter', - type: 'bool', description: 'Whether the entity is a getter.'), - Property('isField', - type: 'bool', description: 'Whether the entity is a field.'), - Property('isMethod', - type: 'bool', description: 'Whether the entity is a method.'), - Property('isStatic', - type: 'bool', description: 'Whether the entity is static.'), - ]), - Definition.clazz('QualifiedName', - description: 'A URI combined with a name and scope referring to a ' - 'declaration. The name and scope are looked up in the export ' - 'scope of the URI.', - createInBuffer: true, - properties: [ - Property('uri', - type: 'String', - description: 'The URI of the file containing the name.'), - Property('scope', - type: 'String', - description: 'The optional scope to look up the name in.', - nullable: true), - Property('name', - type: 'String', - description: 'The name of the declaration to look up.'), - Property('isStatic', - type: 'bool', - description: - 'Whether the name refers to something in the static ' - 'scope as opposed to the instance scope of `scope`. ' - 'Will be `null` if `scope` is `null`.', - nullable: true) - ], - extraCode: r''' + 'The type of the expression `this` when used in this ' + 'interface.', + ), + ], + ), + Definition.clazz( + 'Library', + description: 'Library.', + createInBuffer: true, + properties: [ + Property( + 'scopes', + type: 'Map', + description: 'Scopes by name.', + ), + ], + ), + // TODO(davidmorgan): make `Member` a union. + Definition.clazz( + 'Member', + description: 'Member of a scope.', + createInBuffer: true, + implements: ['Declaration'], + properties: [ + Property( + 'returnType', + type: 'StaticTypeDesc', + description: 'The return type of this member, if it has one.', + ), + // TODO(davidmorgan): base on + // https://github.com/dart-lang/sdk/blob/main/pkg/_macros/lib/src/api/introspection.dart#L269 + Property( + 'requiredPositionalParameters', + type: 'List', + description: + 'The required positional parameters of this member, ' + 'if it has them.', + ), + Property( + 'optionalPositionalParameters', + type: 'List', + description: + 'The optional positional parameters of this member, ' + 'if it has them.', + ), + Property( + 'namedParameters', + type: 'List', + description: + 'The named parameters of this member, ' + 'if it has them.', + ), + ], + ), + Definition.clazz( + 'Model', + description: 'Partial model of a corpus of Dart source code.', + createInBuffer: true, + properties: [ + Property( + 'uris', + type: 'Map', + description: 'Libraries by URI.', + ), + Property( + 'types', + type: 'TypeHierarchy', + description: 'The resolved static type hierarchy.', + ), + ], + ), + Definition.clazz( + 'NamedFunctionTypeParameter', + description: + 'A resolved named parameter as part of a [FunctionTypeDesc].', + createInBuffer: true, + properties: [ + Property('name', type: 'String'), + Property('required', type: 'bool'), + Property('type', type: 'StaticTypeDesc'), + ], + ), + Definition.clazz( + 'NamedRecordField', + description: + 'A named field in a [RecordTypeDesc], consisting of the field ' + 'name and the associated type.', + createInBuffer: true, + properties: [ + Property('name', type: 'String'), + Property('type', type: 'StaticTypeDesc'), + ], + ), + Definition.clazz( + 'NamedTypeDesc', + description: 'A resolved static type.', + createInBuffer: true, + properties: [ + Property('name', type: 'QualifiedName'), + Property('instantiation', type: 'List'), + ], + ), + Definition.nullTypedef( + 'NeverTypeDesc', + description: 'Representation of the bottom type [Never].', + ), + Definition.clazz( + 'NullableTypeDesc', + description: 'A Dart type of the form `T?` for an inner type `T`.', + createInBuffer: true, + properties: [ + Property('inner', type: 'StaticTypeDesc', description: 'The type T.'), + ], + ), + Definition.clazz( + 'Properties', + description: 'Set of boolean properties.', + createInBuffer: true, + properties: [ + Property( + 'isAbstract', + type: 'bool', + description: + 'Whether the entity is abstract, meaning it has no ' + 'definition.', + ), + Property( + 'isClass', + type: 'bool', + description: 'Whether the entity is a class.', + ), + Property( + 'isConstructor', + type: 'bool', + description: 'Whether the entity is a constructor.', + ), + Property( + 'isGetter', + type: 'bool', + description: 'Whether the entity is a getter.', + ), + Property( + 'isField', + type: 'bool', + description: 'Whether the entity is a field.', + ), + Property( + 'isMethod', + type: 'bool', + description: 'Whether the entity is a method.', + ), + Property( + 'isStatic', + type: 'bool', + description: 'Whether the entity is static.', + ), + ], + ), + Definition.clazz( + 'QualifiedName', + description: + 'A URI combined with a name and scope referring to a ' + 'declaration. The name and scope are looked up in the export ' + 'scope of the URI.', + createInBuffer: true, + properties: [ + Property( + 'uri', + type: 'String', + description: 'The URI of the file containing the name.', + ), + Property( + 'scope', + type: 'String', + description: 'The optional scope to look up the name in.', + nullable: true, + ), + Property( + 'name', + type: 'String', + description: 'The name of the declaration to look up.', + ), + Property( + 'isStatic', + type: 'bool', + description: + 'Whether the name refers to something in the static ' + 'scope as opposed to the instance scope of `scope`. ' + 'Will be `null` if `scope` is `null`.', + nullable: true, + ), + ], + extraCode: r''' /// Parses [string] of the form `uri#[scope.|scope::]name`. /// /// No scope indicates a top level declaration in the library. @@ -307,261 +404,333 @@ static QualifiedName parse(String string) { scope: scope, isStatic: isStatic); } -'''), - Definition.clazz('Query', - description: 'Query about a corpus of Dart source code. ' - 'TODO(davidmorgan): this queries about a single class, expand ' - 'to a union type for different types of queries.', - properties: [ - Property('target', - type: 'QualifiedName', - description: 'The class to query about.'), - ]), - Definition.clazz('RecordTypeDesc', - description: 'A resolved record type in the type hierarchy.', - createInBuffer: true, - properties: [ - Property('positional', type: 'List'), - Property('named', type: 'List') - ]), - Definition.union('StaticTypeDesc', +''', + ), + Definition.clazz( + 'Query', + description: + 'Query about a corpus of Dart source code. ' + 'TODO(davidmorgan): this queries about a single class, expand ' + 'to a union type for different types of queries.', + properties: [ + Property( + 'target', + type: 'QualifiedName', + description: 'The class to query about.', + ), + ], + ), + Definition.clazz( + 'RecordTypeDesc', + description: 'A resolved record type in the type hierarchy.', + createInBuffer: true, + properties: [ + Property('positional', type: 'List'), + Property('named', type: 'List'), + ], + ), + Definition.union( + 'StaticTypeDesc', + description: + 'A partially-resolved description of a type as it appears in ' + "Dart's type hierarchy.", + createInBuffer: true, + types: [ + 'DynamicTypeDesc', + 'FunctionTypeDesc', + 'NamedTypeDesc', + 'NeverTypeDesc', + 'NullableTypeDesc', + 'RecordTypeDesc', + 'TypeParameterTypeDesc', + 'VoidTypeDesc', + ], + properties: [], + ), + Definition.clazz( + 'StaticTypeParameterDesc', + description: + 'A resolved type parameter introduced by a [FunctionTypeDesc].', + createInBuffer: true, + properties: [ + Property('identifier', type: 'int'), + Property('bound', type: 'StaticTypeDesc', nullable: true), + ], + ), + Definition.clazz( + 'TypeHierarchy', + description: + "View of a subset of a Dart program's type hierarchy as part " + 'of a queried model.', + createInBuffer: true, + properties: [ + Property( + 'named', + type: 'Map', + description: + 'Map of qualified interface names to their resolved ' + 'named type.', + ), + ], + ), + Definition.clazz( + 'TypeHierarchyEntry', + description: + "Entry of an interface in Dart's type hierarchy, along with " + 'supertypes.', + createInBuffer: true, + properties: [ + Property( + 'typeParameters', + type: 'List', + description: + 'Type parameters defined on this interface-defining ' + 'element.', + ), + Property( + 'self', + type: 'NamedTypeDesc', + description: 'The named static type represented by this entry.', + ), + Property( + 'supertypes', + type: 'List', + description: 'All direct supertypes of this type.', + ), + ], + ), + Definition.clazz( + 'TypeParameterTypeDesc', + description: 'A type formed by a reference to a type parameter.', + createInBuffer: true, + properties: [Property('parameterId', type: 'int')], + ), + Definition.nullTypedef( + 'VoidTypeDesc', + description: 'The type-hierarchy representation of the type `void`.', + ), + ], + ), + Schema( + schemaPath: 'macro_service.schema.json', + codePackage: 'macro_service', + codePath: 'src/macro_service.g.dart', + rootTypes: ['HostRequest', 'MacroRequest', 'Response'], + declarations: [ + Definition.clazz( + 'AugmentRequest', + description: 'A request to a macro to augment some code.', + properties: [ + Property( + 'phase', + type: 'int', + required: true, + description: 'Which phase to run: 1, 2 or 3.', + ), + Property( + 'target', + type: 'QualifiedName', + required: true, description: - 'A partially-resolved description of a type as it appears in ' - "Dart's type hierarchy.", - createInBuffer: true, - types: [ - 'DynamicTypeDesc', - 'FunctionTypeDesc', - 'NamedTypeDesc', - 'NeverTypeDesc', - 'NullableTypeDesc', - 'RecordTypeDesc', - 'TypeParameterTypeDesc', - 'VoidTypeDesc', - ], - properties: []), - Definition.clazz('StaticTypeParameterDesc', + 'The class to augment. ' + 'TODO(davidmorgan): expand to more types of target.', + ), + Property( + 'model', + type: 'Model', + required: true, + description: 'A pre-computed query result for the target.', + ), + ], + ), + Definition.clazz( + 'AugmentResponse', + description: + "Macro's response to an [AugmentRequest]: the resulting " + 'augmentations.', + properties: [ + Property( + 'enumValueAugmentations', + type: 'Map>', description: - 'A resolved type parameter introduced by a [FunctionTypeDesc].', - createInBuffer: true, - properties: [ - Property('identifier', type: 'int'), - Property('bound', type: 'StaticTypeDesc', nullable: true), - ]), - Definition.clazz('TypeHierarchy', + 'Any augmentations to enum values that should be applied ' + 'to an enum as a result of executing a macro, indexed by ' + 'the name of the enum.', + nullable: true, + ), + Property( + 'extendsTypeAugmentations', + type: 'Map>', description: - "View of a subset of a Dart program's type hierarchy as part " - 'of a queried model.', - createInBuffer: true, - properties: [ - Property('named', - type: 'Map', - description: - 'Map of qualified interface names to their resolved ' - 'named type.') - ]), - Definition.clazz('TypeHierarchyEntry', + 'Any extends clauses that should be added to types as a ' + 'result of executing a macro, indexed by the name ' + 'of the augmented type declaration.', + nullable: true, + ), + Property( + 'interfaceAugmentations', + type: 'Map>', description: - "Entry of an interface in Dart's type hierarchy, along with " - 'supertypes.', - createInBuffer: true, - properties: [ - Property('typeParameters', - type: 'List', - description: - 'Type parameters defined on this interface-defining ' - 'element.'), - Property('self', - type: 'NamedTypeDesc', - description: - 'The named static type represented by this entry.'), - Property('supertypes', - type: 'List', - description: 'All direct supertypes of this type.'), - ]), - Definition.clazz('TypeParameterTypeDesc', - description: 'A type formed by a reference to a type parameter.', - createInBuffer: true, - properties: [ - Property('parameterId', type: 'int'), - ]), - Definition.nullTypedef('VoidTypeDesc', + 'Any interfaces that should be added to types as a ' + 'result of executing a macro, indexed by the name ' + 'of the augmented type declaration.', + nullable: true, + ), + Property( + 'libraryAugmentations', + type: 'List', description: - 'The type-hierarchy representation of the type `void`.'), - ]), - Schema( - schemaPath: 'macro_service.schema.json', - codePackage: 'macro_service', - codePath: 'src/macro_service.g.dart', - rootTypes: [ + 'Any augmentations that should be applied to the library ' + 'as a result of executing a macro.', + nullable: true, + ), + Property( + 'mixinAugmentations', + type: 'Map>', + description: + 'Any mixins that should be added to types as a result of ' + 'executing a macro, indexed by the name of the ' + 'augmented type declaration.', + nullable: true, + ), + Property( + 'newTypeNames', + type: 'List', + description: + 'The names of any new types declared in ' + '[libraryAugmentations].', + nullable: true, + ), + Property( + 'typeAugmentations', + type: 'Map>', + description: + 'Any augmentations that should be applied to a class as ' + 'a result of executing a macro, indexed by the ' + 'name of the class.', + nullable: true, + ), + ], + ), + Definition.clazz( + 'ErrorResponse', + description: 'Request could not be handled.', + properties: [ + Property('error', type: 'String', description: 'The error.'), + ], + ), + Definition.clazz( + 'HostEndpoint', + description: + 'A macro host server endpoint. TODO(davidmorgan): this should ' + 'be a oneOf supporting different types of connection. ' + "TODO(davidmorgan): it's not clear if this belongs in this " + 'package! But, where else?', + properties: [ + Property('port', type: 'int', description: 'TCP port to connect to.'), + ], + ), + Definition.union( 'HostRequest', - 'MacroRequest', - 'Response', - ], - declarations: [ - Definition.clazz('AugmentRequest', - description: 'A request to a macro to augment some code.', - properties: [ - Property('phase', - type: 'int', - required: true, - description: 'Which phase to run: 1, 2 or 3.'), - Property('target', - type: 'QualifiedName', - required: true, - description: 'The class to augment. ' - 'TODO(davidmorgan): expand to more types of target.'), - Property('model', - type: 'Model', - required: true, - description: 'A pre-computed query result for the target.'), - ]), - Definition.clazz('AugmentResponse', + description: 'A request sent from host to macro.', + types: ['AugmentRequest'], + properties: [ + Property( + 'id', + type: 'int', description: - "Macro's response to an [AugmentRequest]: the resulting " - 'augmentations.', - properties: [ - Property('enumValueAugmentations', - type: 'Map>', - description: - 'Any augmentations to enum values that should be applied ' - 'to an enum as a result of executing a macro, indexed by ' - 'the name of the enum.', - nullable: true), - Property('extendsTypeAugmentations', - type: 'Map>', - description: - 'Any extends clauses that should be added to types as a ' - 'result of executing a macro, indexed by the name ' - 'of the augmented type declaration.', - nullable: true), - Property('interfaceAugmentations', - type: 'Map>', - description: - 'Any interfaces that should be added to types as a ' - 'result of executing a macro, indexed by the name ' - 'of the augmented type declaration.', - nullable: true), - Property('libraryAugmentations', - type: 'List', - description: - 'Any augmentations that should be applied to the library ' - 'as a result of executing a macro.', - nullable: true), - Property('mixinAugmentations', - type: 'Map>', - description: - 'Any mixins that should be added to types as a result of ' - 'executing a macro, indexed by the name of the ' - 'augmented type declaration.', - nullable: true), - Property('newTypeNames', - type: 'List', - description: 'The names of any new types declared in ' - '[libraryAugmentations].', - nullable: true), - Property('typeAugmentations', - type: 'Map>', - description: - 'Any augmentations that should be applied to a class as ' - 'a result of executing a macro, indexed by the ' - 'name of the class.', - nullable: true), - ]), - Definition.clazz('ErrorResponse', - description: 'Request could not be handled.', - properties: [ - Property('error', type: 'String', description: 'The error.'), - ]), - Definition.clazz('HostEndpoint', + 'The id of this request, must be returned in responses.', + required: true, + ), + Property( + 'macroAnnotation', + type: 'QualifiedName', description: - 'A macro host server endpoint. TODO(davidmorgan): this should ' - 'be a oneOf supporting different types of connection. ' - "TODO(davidmorgan): it's not clear if this belongs in this " - 'package! But, where else?', - properties: [ - Property('port', - type: 'int', description: 'TCP port to connect to.'), - ]), - Definition.union('HostRequest', - description: 'A request sent from host to macro.', - types: [ - 'AugmentRequest' - ], - properties: [ - Property('id', - type: 'int', - description: - 'The id of this request, must be returned in responses.', - required: true), - Property( - 'macroAnnotation', - type: 'QualifiedName', - description: - 'The annotation identifying the macro that should handle ' - 'the request.', - ) - ]), - Definition.clazz('MacroDescription', + 'The annotation identifying the macro that should handle ' + 'the request.', + ), + ], + ), + Definition.clazz( + 'MacroDescription', + description: + 'Information about a macro that the macro provides to the ' + 'host.', + properties: [ + Property( + 'annotation', + type: 'QualifiedName', + description: 'The annotation that triggers the macro.', + ), + Property( + 'runsInPhases', + type: 'List', + description: 'Phases that the macro runs in: 1, 2 and/or 3.', + ), + ], + ), + Definition.clazz( + 'MacroStartedRequest', + description: 'Informs the host that a macro has started.', + properties: [ + Property( + 'macroDescription', + type: 'MacroDescription', + description: 'The macro description.', + ), + ], + ), + Definition.clazz( + 'MacroStartedResponse', + description: "Host's response to a [MacroStartedRequest].", + properties: [], + ), + Definition.union( + 'MacroRequest', + description: 'A request sent from macro to host.', + types: ['MacroStartedRequest', 'QueryRequest'], + properties: [ + Property( + 'id', + type: 'int', description: - 'Information about a macro that the macro provides to the ' - 'host.', - properties: [ - Property('annotation', - type: 'QualifiedName', - description: 'The annotation that triggers the macro.'), - Property('runsInPhases', - type: 'List', - description: 'Phases that the macro runs in: 1, 2 and/or 3.'), - ]), - Definition.clazz( - 'MacroStartedRequest', - description: 'Informs the host that a macro has started.', - properties: [ - Property('macroDescription', - type: 'MacroDescription', - description: 'The macro description.'), - ], - ), - Definition.clazz('MacroStartedResponse', - description: "Host's response to a [MacroStartedRequest].", - properties: []), - Definition.union('MacroRequest', - description: 'A request sent from macro to host.', - types: [ - 'MacroStartedRequest', - 'QueryRequest', - ], - properties: [ - Property('id', - type: 'int', - description: - 'The id of this request, must be returned in responses.', - required: true), - ]), - Definition.clazz('QueryRequest', - description: "Macro's query about the code it should augment.", - properties: [ - Property('query', type: 'Query', description: 'The query.'), - ]), - Definition.clazz('QueryResponse', - description: "Host's response to a [QueryRequest].", - properties: [ - Property('model', type: 'Model', description: 'The model.'), - ]), - Definition.union('Response', - description: 'A response to a request', - types: [ - 'AugmentResponse', - 'ErrorResponse', - 'MacroStartedResponse', - 'QueryResponse', - ], - properties: [ - Property('requestId', - type: 'int', - description: 'The id of the request this is responding to.', - required: true), - ]), - ]), + 'The id of this request, must be returned in responses.', + required: true, + ), + ], + ), + Definition.clazz( + 'QueryRequest', + description: "Macro's query about the code it should augment.", + properties: [ + Property('query', type: 'Query', description: 'The query.'), + ], + ), + Definition.clazz( + 'QueryResponse', + description: "Host's response to a [QueryRequest].", + properties: [ + Property('model', type: 'Model', description: 'The model.'), + ], + ), + Definition.union( + 'Response', + description: 'A response to a request', + types: [ + 'AugmentResponse', + 'ErrorResponse', + 'MacroStartedResponse', + 'QueryResponse', + ], + properties: [ + Property( + 'requestId', + type: 'int', + description: 'The id of the request this is responding to.', + required: true, + ), + ], + ), + ], + ), ]); diff --git a/tool/dart_model_generator/lib/generate_dart_model.dart b/tool/dart_model_generator/lib/generate_dart_model.dart index 23efa351..6839b178 100644 --- a/tool/dart_model_generator/lib/generate_dart_model.dart +++ b/tool/dart_model_generator/lib/generate_dart_model.dart @@ -48,10 +48,10 @@ class GenerationContext { /// Gets the declaration of the type named [typeName], or throws if it is not /// defined in any schema. Definition lookupDefinition(String typeName) { - final result = lookupDeclaringSchema(typeName) - ?.declarations - .where((d) => d.name == typeName) - .singleOrNull; + final result = + lookupDeclaringSchema( + typeName, + )?.declarations.where((d) => d.name == typeName).singleOrNull; if (result == null) throw ArgumentError('Unknown type: $typeName'); return result; } @@ -60,24 +60,27 @@ class GenerationContext { List generateImports(GenerationContext context) { // Find any types defined in schemas other than the current schema, add // imports for them. - final schemas = { - for (final typeName in currentSchema.allTypeNames(context)) - lookupDeclaringSchema(typeName), - }.nonNulls; + final schemas = + { + for (final typeName in currentSchema.allTypeNames(context)) + lookupDeclaringSchema(typeName), + }.nonNulls; return ([ - "import 'package:dart_model/src/json_buffer/json_buffer_builder.dart';", - "import 'package:dart_model/src/deep_cast_map.dart';", - "import 'package:dart_model/src/scopes.dart';", - for (final schema in schemas) - if (schema != currentSchema) - "import 'package:${schema.codePackage}/${schema.codePath}';", - ].toList() + "import 'package:dart_model/src/json_buffer/json_buffer_builder.dart';", + "import 'package:dart_model/src/deep_cast_map.dart';", + "import 'package:dart_model/src/scopes.dart';", + for (final schema in schemas) + if (schema != currentSchema) + "import 'package:${schema.codePackage}/${schema.codePath}';", + ].toList() ..sort()) - .expand((i) => [ - '// ignore: implementation_imports,' - 'unused_import,prefer_relative_imports', - i - ]) + .expand( + (i) => [ + '// ignore: implementation_imports,' + 'unused_import,prefer_relative_imports', + i, + ], + ) .toList(); } } @@ -103,15 +106,23 @@ class Schemas { final result = []; for (final schema in schemas) { final context = GenerationContext(this, schema); - final generatedSchema = const JsonEncoder.withIndent(' ') - .convert(schema.generateSchema(context)); - result.add(GenerationResult( - path: 'schemas/${schema.schemaPath}', content: '$generatedSchema\n')); + final generatedSchema = const JsonEncoder.withIndent( + ' ', + ).convert(schema.generateSchema(context)); + result.add( + GenerationResult( + path: 'schemas/${schema.schemaPath}', + content: '$generatedSchema\n', + ), + ); final generatedCode = _format(schema.generateCode(context)); - result.add(GenerationResult( + result.add( + GenerationResult( path: 'pkgs/${schema.codePackage}/lib/${schema.codePath}', - content: generatedCode)); + content: generatedCode, + ), + ); } return result; } @@ -147,17 +158,16 @@ class Schema { /// Generates JSON schema corresponding to this schema definition. Map generateSchema(GenerationContext context) => { - r'$schema': 'https://json-schema.org/draft/2020-12/schema', - 'oneOf': [ - for (var type in rootTypes) - TypeReference(type).generateSchema(context), - ], - r'$defs': { - for (var declaration in declarations) - if (declaration.includeInSchema) - declaration.name: declaration.generateSchema(context), - } - }; + r'$schema': 'https://json-schema.org/draft/2020-12/schema', + 'oneOf': [ + for (var type in rootTypes) TypeReference(type).generateSchema(context), + ], + r'$defs': { + for (var declaration in declarations) + if (declaration.includeInSchema) + declaration.name: declaration.generateSchema(context), + }, + }; /// Generates Dart code corresponding to this schema definition. String generateCode(GenerationContext context) { @@ -180,10 +190,10 @@ class Schema { /// The names of all types referenced in this schema. Set allTypeNames(GenerationContext context) => { - ...rootTypes, - for (final declaration in declarations) - ...declaration.allTypeNames(context) - }; + ...rootTypes, + for (final declaration in declarations) + ...declaration.allTypeNames(context), + }; } /// Definition of a type. @@ -211,29 +221,35 @@ abstract class Definition { /// Each type in [implements] will be added to the `implements` clause of this /// type in the generated code. All properties from all implemented types will /// copied directly into the schema for this type. - factory Definition.clazz(String name, - {required String description, - required List properties, - bool createInBuffer, - String? extraCode, - bool interfaceOnly, - List implements}) = ClassTypeDefinition; + factory Definition.clazz( + String name, { + required String description, + required List properties, + bool createInBuffer, + String? extraCode, + bool interfaceOnly, + List implements, + }) = ClassTypeDefinition; /// Defines a union. /// /// [createInBuffer] specifies whether the type is written directly to a /// buffer when created. If so, it must be created in a `Scope` which will /// provide the buffer. - factory Definition.union(String name, - {required String description, - required List types, - required List properties, - bool createInBuffer}) = UnionTypeDefinition; + factory Definition.union( + String name, { + required String description, + required List types, + required List properties, + bool createInBuffer, + }) = UnionTypeDefinition; /// Defines an enum. - factory Definition.$enum(String name, - {required String description, - required List values}) = EnumTypeDefinition; + factory Definition.$enum( + String name, { + required String description, + required List values, + }) = EnumTypeDefinition; /// Defines a named type represented in JSON as a string. factory Definition.stringTypedef(String name, {required String description}) = @@ -279,11 +295,12 @@ class Property { /// Generates JSON schema for this type. Map generateSchema(GenerationContext context) => { - name: type.generateSchema(context, description: description), - }; + name: type.generateSchema(context, description: description), + }; /// Dart code for declaring a parameter corresponding to this property. - String get parameterCode => '${required ? 'required ' : ''}' + String get parameterCode => + '${required ? 'required ' : ''}' '${_type(nullable: !required)} $name,'; /// Dart code for passing a named argument corresponding to this property. @@ -292,8 +309,10 @@ class Property { /// Dart code for a getter for this property. String get getterCode { - return _describe('${_type()} get $name => ' - '${type.castExpression("node['$name']", nullable: nullable)};'); + return _describe( + '${_type()} get $name => ' + '${type.castExpression("node['$name']", nullable: nullable)};', + ); } /// Dart code for entry in `TypedMapSchema`. @@ -356,9 +375,10 @@ class TypeReference { /// nullable, otherwise it won't. String castExpression(String value, {bool nullable = false}) { final q = nullable ? '?' : ''; - final representationName = isMap - ? 'Map' - : isList + final representationName = + isMap + ? 'Map' + : isList ? 'List' : name; final rawCast = '$value as $representationName$q'; @@ -408,8 +428,10 @@ class TypeReference { } /// Generates JSON schema for this type. - Map generateSchema(GenerationContext context, - {String? description}) { + Map generateSchema( + GenerationContext context, { + String? description, + }) { if (isList) { return { 'type': 'array', @@ -458,13 +480,15 @@ class ClassTypeDefinition implements Definition { final bool interfaceOnly; final List implements; - ClassTypeDefinition(this.name, - {required this.description, - required this.properties, - this.createInBuffer = false, - this.extraCode, - this.interfaceOnly = false, - this.implements = const []}); + ClassTypeDefinition( + this.name, { + required this.description, + required this.properties, + this.createInBuffer = false, + this.extraCode, + this.interfaceOnly = false, + this.implements = const [], + }); @override bool get includeInSchema => !interfaceOnly; @@ -473,9 +497,9 @@ class ClassTypeDefinition implements Definition { Iterable inheritedProperties(GenerationContext context) sync* { final seen = {}; for (var interface in implements) { - for (var property - in (context.lookupDefinition(interface) as ClassTypeDefinition) - .allProperties(context)) { + for (var property in (context.lookupDefinition(interface) + as ClassTypeDefinition) + .allProperties(context)) { if (seen.add(property)) yield property; } } @@ -491,8 +515,9 @@ class ClassTypeDefinition implements Definition { Map generateSchema(GenerationContext context) { if (interfaceOnly) { throw StateError( - 'Cannot generate schema for interface only definitions, check ' - '`includeInSchema` first.'); + 'Cannot generate schema for interface only definitions, check ' + '`includeInSchema` first.', + ); } return { 'type': 'object', @@ -500,7 +525,7 @@ class ClassTypeDefinition implements Definition { 'properties': { for (final property in allProperties(context)) ...property.generateSchema(context), - } + }, }; } @@ -522,14 +547,17 @@ class ClassTypeDefinition implements Definition { result.writeln('/// $description'); // Pure interfaces should only have a private constructor. final defaultConstructorName = interfaceOnly ? '_' : 'fromJson'; - result.write('extension type ' - '$name.$defaultConstructorName(Map node) implements ' - '${implements.isEmpty ? 'Object' : implements.join(', ')} {'); + result.write( + 'extension type ' + '$name.$defaultConstructorName(Map node) implements ' + '${implements.isEmpty ? 'Object' : implements.join(', ')} {', + ); if (createInBuffer) { if (interfaceOnly) { throw StateError( - 'Cannot have createInBuffer: true and interfaceOnly: true'); + 'Cannot have createInBuffer: true and interfaceOnly: true', + ); } result.write('static final TypedMapSchema _schema = TypedMapSchema({'); for (final property in allProperties(context)) { @@ -590,10 +618,11 @@ class ClassTypeDefinition implements Definition { } @override - Set allTypeNames(GenerationContext context) => allProperties(context) - .expand((f) => f.type.allTypeNames(context)) - .followedBy(implements) - .toSet(); + Set allTypeNames(GenerationContext context) => + allProperties(context) + .expand((f) => f.type.allTypeNames(context)) + .followedBy(implements) + .toSet(); @override String get representationTypeName => 'Map'; @@ -619,38 +648,36 @@ class UnionTypeDefinition implements Definition { final List types; final List properties; final bool createInBuffer; - UnionTypeDefinition(this.name, - {required this.description, - required this.types, - required this.properties, - this.createInBuffer = false}); + UnionTypeDefinition( + this.name, { + required this.description, + required this.types, + required this.properties, + this.createInBuffer = false, + }); @override bool get includeInSchema => true; @override Map generateSchema(GenerationContext context) => { - 'type': 'object', - 'description': description, - 'properties': { - 'type': { - 'type': 'string', - }, - 'value': { - 'oneOf': [ - for (final type in types) - TypeReference(type).generateSchema(context), - ], - }, - for (final property in properties) - ...property.generateSchema(context), - 'required': [ - 'type', - 'value', - ...properties.where((e) => e.required).map((e) => e.name) - ]..sort(), - } - }; + 'type': 'object', + 'description': description, + 'properties': { + 'type': {'type': 'string'}, + 'value': { + 'oneOf': [ + for (final type in types) TypeReference(type).generateSchema(context), + ], + }, + for (final property in properties) ...property.generateSchema(context), + 'required': [ + 'type', + 'value', + ...properties.where((e) => e.required).map((e) => e.name), + ]..sort(), + }, + }; @override String generateCode(GenerationContext context) { @@ -668,8 +695,9 @@ class UnionTypeDefinition implements Definition { // TODO(davidmorgan): add description. result.writeln( - 'extension type $name.fromJson(Map node) implements ' - 'Object {'); + 'extension type $name.fromJson(Map node) implements ' + 'Object {', + ); if (createInBuffer) { result @@ -733,16 +761,20 @@ class UnionTypeDefinition implements Definition { for (final type in types) { result ..writeln('$type get as$type {') - ..writeln("if (node['type'] != '$type') " - "{ throw StateError('Not a $type.'); }"); + ..writeln( + "if (node['type'] != '$type') " + "{ throw StateError('Not a $type.'); }", + ); // TODO(davidmorgan): this special case allows `String` to be in a union // type, see if there is a nice way to generalize to other primitives. if (type == 'String') { result.writeln("return node['value'] as String;"); } else { - result.writeln('return $type.fromJson' - "(node['value'] as " - '${context.lookupDefinition(type).representationTypeName});'); + result.writeln( + 'return $type.fromJson' + "(node['value'] as " + '${context.lookupDefinition(type).representationTypeName});', + ); } result.writeln('}'); } @@ -755,8 +787,10 @@ class UnionTypeDefinition implements Definition { } @override - Set allTypeNames(GenerationContext context) => - {...types, ...properties.expand((f) => f.type.allTypeNames(context))}; + Set allTypeNames(GenerationContext context) => { + ...types, + ...properties.expand((f) => f.type.allTypeNames(context)), + }; @override String get representationTypeName => 'Map'; @@ -769,25 +803,30 @@ class EnumTypeDefinition implements Definition { final String description; final List values; - EnumTypeDefinition(this.name, - {required this.description, required this.values}); + EnumTypeDefinition( + this.name, { + required this.description, + required this.values, + }); @override bool get includeInSchema => true; @override Map generateSchema(GenerationContext context) => { - 'type': 'string', - 'description': description, - }; + 'type': 'string', + 'description': description, + }; @override String generateCode(GenerationContext context) { final result = StringBuffer(); result.writeln('/// $description'); - result.write('extension type const $name.fromJson(String string)' - ' implements Object {'); + result.write( + 'extension type const $name.fromJson(String string)' + ' implements Object {', + ); for (final value in values) { result.writeln("static const $name $value = $name.fromJson('$value');"); } @@ -814,9 +853,9 @@ class StringTypedefDefinition implements Definition { @override Map generateSchema(GenerationContext context) => { - 'type': 'string', - 'description': description, - }; + 'type': 'string', + 'description': description, + }; @override String generateCode(GenerationContext context) { @@ -846,9 +885,9 @@ class NullTypedefDefinition implements Definition { @override Map generateSchema(GenerationContext context) => { - 'type': 'null', - 'description': description, - }; + 'type': 'null', + 'description': description, + }; @override String generateCode(GenerationContext context) { @@ -870,7 +909,9 @@ String _firstToLowerCase(String string) => String _format(String source) { try { - return DartFormatter().formatSource(SourceCode(source)).text; + return DartFormatter( + languageVersion: DartFormatter.latestLanguageVersion, + ).formatSource(SourceCode(source)).text; } catch (_) { print('Failed to format:\n---\n$source\n---'); rethrow; diff --git a/tool/dart_model_generator/lib/macro_metadata_definitions.dart b/tool/dart_model_generator/lib/macro_metadata_definitions.dart index 9ced9f69..488406c0 100644 --- a/tool/dart_model_generator/lib/macro_metadata_definitions.dart +++ b/tool/dart_model_generator/lib/macro_metadata_definitions.dart @@ -13,10 +13,7 @@ final definitions = [ 'Argument', createInBuffer: true, description: '', - types: [ - 'PositionalArgument', - 'NamedArgument', - ], + types: ['PositionalArgument', 'NamedArgument'], properties: [], ), Definition.union( @@ -76,10 +73,7 @@ final definitions = [ 'RecordField', createInBuffer: true, description: '', - types: [ - 'RecordNamedField', - 'RecordPositionalField', - ], + types: ['RecordNamedField', 'RecordPositionalField'], properties: [], ), Definition.union( @@ -104,10 +98,7 @@ final definitions = [ 'StringLiteralPart', createInBuffer: true, description: '', - types: [ - 'StringPart', - 'InterpolationPart', - ], + types: ['StringPart', 'InterpolationPart'], properties: [], ), Definition.union( @@ -149,22 +140,11 @@ final definitions = [ 'bitwiseXor', ], ), - Definition.$enum( - 'LogicalOperator', - description: '', - values: [ - 'and', - 'or', - ], - ), + Definition.$enum('LogicalOperator', description: '', values: ['and', 'or']), Definition.$enum( 'UnaryOperator', description: '', - values: [ - 'minus', - 'bang', - 'tilde', - ], + values: ['minus', 'bang', 'tilde'], ), Definition.clazz( 'AsExpression', @@ -189,9 +169,7 @@ final definitions = [ 'BooleanLiteral', createInBuffer: true, description: '', - properties: [ - Property('text', type: 'String', description: ''), - ], + properties: [Property('text', type: 'String', description: '')], ), Definition.clazz( 'ClassReference', @@ -238,17 +216,13 @@ final definitions = [ 'DoubleLiteral', createInBuffer: true, description: '', - properties: [ - Property('text', type: 'String', description: ''), - ], + properties: [Property('text', type: 'String', description: '')], ), Definition.clazz( 'DynamicTypeAnnotation', createInBuffer: true, description: '', - properties: [ - Property('reference', type: 'Reference', description: ''), - ], + properties: [Property('reference', type: 'Reference', description: '')], ), Definition.clazz( 'EnumReference', @@ -324,12 +298,22 @@ final definitions = [ createInBuffer: true, description: '', properties: [ - Property('returnType', - type: 'TypeAnnotation', description: '', nullable: true), - Property('typeParameters', - type: 'List', description: ''), - Property('formalParameters', - type: 'List', description: ''), + Property( + 'returnType', + type: 'TypeAnnotation', + description: '', + nullable: true, + ), + Property( + 'typeParameters', + type: 'List', + description: '', + ), + Property( + 'formalParameters', + type: 'List', + description: '', + ), ], ), Definition.clazz( @@ -349,8 +333,11 @@ final definitions = [ createInBuffer: true, description: '', properties: [ - Property('functionTypeParameter', - type: 'FunctionTypeParameter', description: ''), + Property( + 'functionTypeParameter', + type: 'FunctionTypeParameter', + description: '', + ), ], ), Definition.clazz( @@ -395,17 +382,13 @@ final definitions = [ 'IntegerLiteral', createInBuffer: true, description: '', - properties: [ - Property('text', type: 'String', description: ''), - ], + properties: [Property('text', type: 'String', description: '')], ), Definition.clazz( 'InterpolationPart', createInBuffer: true, description: '', - properties: [ - Property('expression', type: 'Expression', description: ''), - ], + properties: [Property('expression', type: 'Expression', description: '')], ), Definition.clazz( 'InvalidExpression', @@ -509,9 +492,7 @@ final definitions = [ 'NullCheck', createInBuffer: true, description: '', - properties: [ - Property('expression', type: 'Expression', description: ''), - ], + properties: [Property('expression', type: 'Expression', description: '')], ), Definition.clazz( 'NullLiteral', @@ -523,17 +504,13 @@ final definitions = [ 'ParenthesizedExpression', createInBuffer: true, description: '', - properties: [ - Property('expression', type: 'Expression', description: ''), - ], + properties: [Property('expression', type: 'Expression', description: '')], ), Definition.clazz( 'PositionalArgument', createInBuffer: true, description: '', - properties: [ - Property('expression', type: 'Expression', description: ''), - ], + properties: [Property('expression', type: 'Expression', description: '')], ), Definition.clazz( 'PropertyGet', @@ -565,9 +542,7 @@ final definitions = [ 'RecordPositionalField', createInBuffer: true, description: '', - properties: [ - Property('expression', type: 'Expression', description: ''), - ], + properties: [Property('expression', type: 'Expression', description: '')], ), Definition.clazz( 'RecordTypeAnnotation', @@ -646,17 +621,13 @@ final definitions = [ 'StringPart', createInBuffer: true, description: '', - properties: [ - Property('text', type: 'String', description: ''), - ], + properties: [Property('text', type: 'String', description: '')], ), Definition.clazz( 'SymbolLiteral', createInBuffer: true, description: '', - properties: [ - Property('parts', type: 'List', description: ''), - ], + properties: [Property('parts', type: 'List', description: '')], ), Definition.clazz( 'TypedefReference', @@ -703,8 +674,6 @@ final definitions = [ 'VoidTypeAnnotation', createInBuffer: true, description: '', - properties: [ - Property('reference', type: 'Reference', description: ''), - ], + properties: [Property('reference', type: 'Reference', description: '')], ), ]; diff --git a/tool/dart_model_generator/pubspec.yaml b/tool/dart_model_generator/pubspec.yaml index 21ca8d00..4b82ca22 100644 --- a/tool/dart_model_generator/pubspec.yaml +++ b/tool/dart_model_generator/pubspec.yaml @@ -2,11 +2,11 @@ name: generate_dart_model publish-to: none resolution: workspace environment: - sdk: ^3.7.0-39.0.dev + sdk: ^3.7.0-123.0.dev dependencies: dart_model: any - dart_style: ^2.3.6 + dart_style: any json_schema: ^5.1.7 dev_dependencies: diff --git a/tool/dart_model_generator/test/generated_output_test.dart b/tool/dart_model_generator/test/generated_output_test.dart index 7f1c0dfc..051bd698 100644 --- a/tool/dart_model_generator/test/generated_output_test.dart +++ b/tool/dart_model_generator/test/generated_output_test.dart @@ -14,13 +14,17 @@ void main() { final actual = File('../../${generationResult.path}').readAsStringSync(); // TODO: On windows we get carriage returns, which makes this fail // without ignoring white space. In theory this shouldn't happen. - expect(actual, equalsIgnoringWhitespace(expected), reason: ''' + expect( + actual, + equalsIgnoringWhitespace(expected), + reason: ''' Output is not up to date. Please run dart tool/dart_model_generator/bin/main.dart in repo root. -'''); +''', + ); }); } } diff --git a/tool/set_sdk_ref b/tool/set_sdk_ref index 5e803235..1ed0a1f0 100755 --- a/tool/set_sdk_ref +++ b/tool/set_sdk_ref @@ -2,6 +2,9 @@ # # Updates ref to SDK packages in pubspec.yaml. # +# Refs with a comment on the same line, starting `#`, are not updated: this is +# for the `dart_style` ref which is to another repo. +# # If it's a dev tag, also updates SDK version. REF=$1 @@ -18,4 +21,4 @@ else echo "Got a ref, not a dev tag: updating deps but not SDK version." fi -sed -i -e "s#^ ref: .*# ref: $REF#" pubspec.yaml +sed -i -e "s#^ ref: [^#]*\$# ref: $REF#" pubspec.yaml