From 679fc2b43c7b6b1f84d9ad7c5497dbbe884af529 Mon Sep 17 00:00:00 2001 From: tyron12233 <74818961+tyron12233@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:53:03 +0800 Subject: [PATCH 1/2] chore(plugins): the NDK, Dart, Swift and C# plugins live in their own repositories Each moved with its history, toolchain scripts and release workflows to tyron12233/codeassist-{ndk,dart,swift,dotnet}-plugin, where it compiles against the plugin SPI JitPack builds from a CodeAssist release tag. hello-plugin and lsp-plugin stay here as the examples that keep the SPI honest. CsPluginTest now takes the C# plugin's APK through -Pe2e.dotnetPluginApk. --- .github/workflows/dart-gen-snapshot.yml | 90 - .github/workflows/dart-plugin.yml | 285 - .github/workflows/dotnet-plugin.yml | 161 - .github/workflows/ndk-plugin.yml | 167 - .github/workflows/ndk-toolchain.yml | 159 - .github/workflows/swift-plugin.yml | 201 - app/ide-android-e2e/build.gradle.kts | 15 +- .../dev/ide/android/e2e/CsPluginTest.kt | 18 +- docs/custom-build-plugins.md | 2 +- docs/writing-plugins.md | 4 +- samples/dart-plugin/build.gradle.kts | 199 - .../dart-plugin/src/main/AndroidManifest.xml | 67 - .../codeassist/dart/DartConsoleTemplate.kt | 97 - .../dev/codeassist/dart/DartFileIcons.kt | 26 - .../dev/codeassist/dart/DartLanguageServer.kt | 76 - .../kotlin/dev/codeassist/dart/DartLex.kt | 74 - .../kotlin/dev/codeassist/dart/DartPlugin.kt | 79 - .../dev/codeassist/dart/DartPreviews.kt | 298 - .../kotlin/dev/codeassist/dart/DartProject.kt | 136 - .../kotlin/dev/codeassist/dart/DartRun.kt | 315 - .../kotlin/dev/codeassist/dart/DartSdk.kt | 232 - .../kotlin/dev/codeassist/dart/DartTests.kt | 388 - .../dev/codeassist/dart/DartUiPlugin.kt | 63 - .../codeassist/dart/FlutterAndroidFiles.kt | 153 - .../kotlin/dev/codeassist/dart/FlutterApk.kt | 480 - .../dev/codeassist/dart/FlutterAppTemplate.kt | 207 - .../dev/codeassist/dart/FlutterAssets.kt | 248 - .../codeassist/dart/FlutterPlayerActivity.kt | 97 - .../codeassist/dart/FlutterPlayerLauncher.kt | 68 - .../dev/codeassist/dart/FlutterPlugins.kt | 346 - .../dart/FlutterPreviewController.kt | 259 - .../dev/codeassist/dart/FlutterPreviewPane.kt | 382 - .../codeassist/dart/FlutterPreviewService.kt | 280 - .../kotlin/dev/codeassist/dart/FlutterRun.kt | 374 - .../codeassist/dart/FlutterRunParticipant.kt | 78 - .../kotlin/dev/codeassist/dart/FlutterSdk.kt | 183 - .../dev/codeassist/dart/FlutterSession.kt | 330 - .../dev/codeassist/dart/FrontendServer.kt | 165 - .../dev/codeassist/dart/PackageWatcher.kt | 136 - .../dev/codeassist/dart/PluginInfoActivity.kt | 112 - .../main/kotlin/dev/codeassist/dart/Pub.kt | 97 - .../kotlin/dev/codeassist/dart/PubImporter.kt | 278 - .../dev/codeassist/dart/ToolCancellation.kt | 74 - .../kotlin/dev/codeassist/dart/VmService.kt | 317 - .../src/main/res/raw/codeassist_plugin.toml | 31 - .../src/main/res/values/strings.xml | 4 - .../codeassist/dart/DartLanguageServerTest.kt | 20 - .../dev/codeassist/dart/DartPackagesTest.kt | 105 - .../dev/codeassist/dart/DartPreviewsTest.kt | 78 - .../dev/codeassist/dart/DartTestsTest.kt | 119 - .../dev/codeassist/dart/FlutterApkTest.kt | 177 - .../dev/codeassist/dart/FlutterImportTest.kt | 124 - .../dev/codeassist/dart/FlutterPluginsTest.kt | 273 - .../dart/FlutterRunParticipantTest.kt | 36 - .../kotlin/dev/codeassist/dart/FlutterTest.kt | 130 - .../dev/codeassist/dart/PackageWatcherTest.kt | 85 - .../dev/codeassist/dart/PubImporterTest.kt | 71 - .../flutter-create/AndroidManifest.xml.txt | 45 - .../flutter-create/app.build.gradle.kts.txt | 49 - samples/dotnet-plugin/README.md | 117 - samples/dotnet-plugin/build.gradle.kts | 147 - .../src/main/AndroidManifest.xml | 32 - .../dev/codeassist/csharp/CSharpPlugin.kt | 139 - .../codeassist/csharp/PluginInfoActivity.kt | 50 - .../codeassist/csharp/build/CsBuildPlugin.kt | 59 - .../csharp/build/tasks/CsCompileTask.kt | 482 - .../csharp/build/tasks/CsRestoreTask.kt | 58 - .../codeassist/csharp/build/tasks/CsRunIds.kt | 57 - .../csharp/build/tasks/CsRunProgramTask.kt | 139 - .../csharp/build/tasks/CsRunTaskProvider.kt | 206 - .../csharp/build/tasks/RunSupport.kt | 25 - .../csharp/build/tests/CsTestProvider.kt | 176 - .../csharp/build/tests/CsTestRunner.kt | 577 -- .../csharp/build/tests/CsTestScan.kt | 193 - .../completion/CsCompletionContributor.kt | 382 - .../csharp/completion/CsCompletionItems.kt | 61 - .../codeassist/csharp/completion/CsDocText.kt | 135 - .../csharp/completion/CsKeywords.kt | 17 - .../csharp/completion/CsNavigationLines.kt | 109 - .../csharp/completion/CsSemanticCompletion.kt | 272 - .../csharp/completion/CsSignatureLines.kt | 73 - .../csharp/completion/CsSymbolTable.kt | 64 - .../codeassist/csharp/completion/CsSymbols.kt | 316 - .../codeassist/csharp/completion/CsWords.kt | 65 - .../completion/CsprojCompletionContributor.kt | 58 - .../csharp/editor/CsDeclarationProvider.kt | 39 - .../codeassist/csharp/editor/CsFileNames.kt | 91 - .../csharp/editor/CsLanguageBackend.kt | 319 - .../dev/codeassist/csharp/editor/CsModules.kt | 27 - .../csharp/editor/CsReferenceProviders.kt | 155 - .../codeassist/csharp/editor/CsRunGutter.kt | 102 - .../csharp/editor/CsSignatureHelp.kt | 61 - .../csharp/editor/CsUsingCleanup.kt | 210 - .../codeassist/csharp/editor/CsWorkspace.kt | 117 - .../csharp/editor/CsprojAnalyzer.kt | 84 - .../diagnostics/CsDiagnosticProvider.kt | 458 - .../editor/diagnostics/CsDiagnosticTags.kt | 32 - .../editor/diagnostics/CsDiagnostics.kt | 74 - .../editor/diagnostics/CsLineOffsets.kt | 50 - .../editor/diagnostics/CsMaskedErrors.kt | 37 - .../csharp/editor/quickfixes/CsUsingFix.kt | 223 - .../editor/quickfixes/CsUsingFixProvider.kt | 148 - .../codeassist/csharp/project/CsMainScan.kt | 288 - .../dev/codeassist/csharp/project/CsMains.kt | 114 - .../codeassist/csharp/project/CsNewFiles.kt | 171 - .../codeassist/csharp/project/CsProject.kt | 140 - .../codeassist/csharp/project/CsRunConfig.kt | 52 - .../csharp/project/csproj/CsprojCheck.kt | 339 - .../csharp/project/csproj/CsprojCompleter.kt | 116 - .../csharp/project/csproj/CsprojCondition.kt | 49 - .../csharp/project/csproj/CsprojExtras.kt | 148 - .../csharp/project/csproj/CsprojGraph.kt | 108 - .../csharp/project/csproj/CsprojProject.kt | 528 - .../csharp/project/csproj/CsprojReferences.kt | 88 - .../csharp/project/csproj/CsprojSchema.kt | 102 - .../csharp/project/csproj/CsprojText.kt | 237 - .../csharp/project/nuget/CsPackageRestorer.kt | 175 - .../csharp/project/nuget/CsPackageWatcher.kt | 91 - .../codeassist/csharp/project/nuget/NuGet.kt | 458 - .../csharp/project/nuget/NuGetVersion.kt | 181 - .../project/templates/CsConsoleTemplate.kt | 68 - .../project/templates/CsLibraryTemplate.kt | 53 - .../project/templates/CsTemplateSupport.kt | 65 - .../dev/codeassist/csharp/sdk/CsChecker.kt | 133 - .../codeassist/csharp/sdk/CsCompilerHost.kt | 22 - .../dev/codeassist/csharp/sdk/CsCompleter.kt | 562 - .../dev/codeassist/csharp/sdk/CsFormatter.kt | 124 - .../dev/codeassist/csharp/sdk/CsNavigator.kt | 443 - .../dev/codeassist/csharp/sdk/CsServer.kt | 414 - .../dev/codeassist/csharp/sdk/DotnetSdk.kt | 240 - .../codeassist/csharp/sdk/ResidentProgram.kt | 556 - .../codeassist/csharp/sdk/RuntimeConfig.kt | 23 - .../dev/codeassist/csharp/ui/CsFileIcons.kt | 33 - .../dev/codeassist/csharp/ui/CsUiPlugin.kt | 66 - .../dev/codeassist/csharp/util/Logging.kt | 3 - .../codeassist/csharp/util/ProcessOutput.kt | 68 - .../codeassist/csharp/util/RestoreNotice.kt | 25 - .../csharp/util/ToolCancellation.kt | 74 - .../src/main/res/raw/codeassist_plugin.toml | 23 - .../src/main/res/values/strings.xml | 4 - .../kotlin/dev/codeassist/csharp/FakeHost.kt | 60 - .../kotlin/dev/codeassist/csharp/TestFiles.kt | 16 - .../codeassist/csharp/build/CsRunIdsTest.kt | 49 - .../csharp/build/tests/CsTestScanTest.kt | 151 - .../completion/CsCompletionItemsTest.kt | 79 - .../csharp/completion/CsDocTextTest.kt | 78 - .../completion/CsNavigationLinesTest.kt | 143 - .../csharp/completion/CsSignatureLinesTest.kt | 73 - .../csharp/completion/CsSymbolTableTest.kt | 86 - .../csharp/completion/CsWordsTest.kt | 58 - .../csharp/editor/CsFileNamesTest.kt | 63 - .../csharp/editor/CsUsingCleanupTest.kt | 117 - .../diagnostics/CsDiagnosticTagsTest.kt | 28 - .../editor/diagnostics/CsDiagnosticsTest.kt | 74 - .../editor/diagnostics/CsLineOffsetsTest.kt | 98 - .../editor/diagnostics/CsMaskedErrorsTest.kt | 62 - .../editor/quickfixes/CsUsingFixTest.kt | 179 - .../csharp/project/CsMainScanTest.kt | 169 - .../codeassist/csharp/project/CsMainsTest.kt | 112 - .../csharp/project/CsProjectTest.kt | 97 - .../csharp/project/CsRunConfigTest.kt | 56 - .../csharp/project/csproj/CsprojCheckTest.kt | 122 - .../project/csproj/CsprojCompleterTest.kt | 63 - .../csharp/project/csproj/CsprojExtrasTest.kt | 111 - .../csharp/project/csproj/CsprojGraphTest.kt | 143 - .../csharp/project/csproj/CsprojTest.kt | 499 - .../csharp/project/csproj/CsprojTextTest.kt | 79 - .../csharp/project/nuget/NuGetTest.kt | 305 - .../csharp/project/nuget/NuGetVersionTest.kt | 113 - .../csharp/sdk/CsFormatEditsTest.kt | 30 - .../codeassist/csharp/sdk/DotnetSdkTest.kt | 188 - .../csharp/sdk/RuntimeConfigTest.kt | 44 - .../csharp/util/ProcessOutputTest.kt | 105 - .../csharp/util/RestoreNoticeTest.kt | 24 - .../src/test/resources/assets/dotnet-sdk.zip | Bin 330 -> 0 bytes .../src/test/resources/assets/test.txt | 1 - samples/ndk-plugin/README.md | 417 - samples/ndk-plugin/build.gradle.kts | 175 - samples/ndk-plugin/run-tests-on-device.sh | 208 - .../ndk-plugin/src/main/AndroidManifest.xml | 32 - .../dev/codeassist/ndk/ClangCompletions.kt | 120 - .../kotlin/dev/codeassist/ndk/ClangDaemon.kt | 217 - .../dev/codeassist/ndk/ClangDiagnostics.kt | 162 - .../dev/codeassist/ndk/ClangPreamble.kt | 160 - .../kotlin/dev/codeassist/ndk/CppNewFiles.kt | 115 - .../codeassist/ndk/NativeActivityTemplate.kt | 188 - .../dev/codeassist/ndk/NativeAppTemplate.kt | 209 - .../codeassist/ndk/NativeConsoleTemplate.kt | 107 - .../dev/codeassist/ndk/NativeCppTemplate.kt | 148 - .../dev/codeassist/ndk/NativeIncremental.kt | 114 - .../main/kotlin/dev/codeassist/ndk/NdkAbi.kt | 53 - .../dev/codeassist/ndk/NdkBuildPlugin.kt | 436 - .../ndk/NdkCompletionContributor.kt | 162 - .../codeassist/ndk/NdkDiagnosticProvider.kt | 94 - .../kotlin/dev/codeassist/ndk/NdkFacet.kt | 167 - .../kotlin/dev/codeassist/ndk/NdkFileIcons.kt | 57 - .../kotlin/dev/codeassist/ndk/NdkFlags.kt | 62 - .../dev/codeassist/ndk/NdkLanguageBackend.kt | 204 - .../dev/codeassist/ndk/NdkModuleActions.kt | 118 - .../kotlin/dev/codeassist/ndk/NdkPlugin.kt | 202 - .../main/kotlin/dev/codeassist/ndk/NdkRun.kt | 356 - .../dev/codeassist/ndk/NdkSourceRoots.kt | 75 - .../dev/codeassist/ndk/NdkTemplateSupport.kt | 124 - .../kotlin/dev/codeassist/ndk/NdkToolchain.kt | 695 -- .../kotlin/dev/codeassist/ndk/NdkUiPlugin.kt | 129 - .../dev/codeassist/ndk/PluginInfoActivity.kt | 32 - .../dev/codeassist/ndk/PreambleCache.kt | 191 - .../dev/codeassist/ndk/ToolCancellation.kt | 75 - .../dev/codeassist/ndk/jni/CppJniScanner.kt | 42 - .../main/kotlin/dev/codeassist/ndk/jni/Jni.kt | 115 - .../dev/codeassist/ndk/jni/JniDiagnostics.kt | 189 - .../kotlin/dev/codeassist/ndk/jni/JniIndex.kt | 140 - .../dev/codeassist/ndk/jni/JniNavigation.kt | 161 - .../codeassist/ndk/jni/NativeMethodScanner.kt | 433 - .../src/main/res/raw/codeassist_plugin.toml | 24 - .../src/main/res/values/strings.xml | 4 - .../codeassist/ndk/ClangCompletionsTest.kt | 216 - .../codeassist/ndk/ClangDaemonDeviceTest.kt | 201 - .../dev/codeassist/ndk/ClangDaemonTest.kt | 122 - .../codeassist/ndk/ClangDiagnosticsTest.kt | 187 - .../dev/codeassist/ndk/ClangPreambleTest.kt | 82 - .../codeassist/ndk/ClangSemanticTokensTest.kt | 55 - .../dev/codeassist/ndk/CppNewFilesTest.kt | 48 - .../codeassist/ndk/NativeIncrementalTest.kt | 132 - .../kotlin/dev/codeassist/ndk/NdkAbiTest.kt | 70 - .../kotlin/dev/codeassist/ndk/NdkFacetTest.kt | 155 - .../dev/codeassist/ndk/NdkRunDeviceTest.kt | 160 - .../kotlin/dev/codeassist/ndk/NdkRunTest.kt | 111 - .../dev/codeassist/ndk/NdkTemplatesTest.kt | 430 - .../dev/codeassist/ndk/PreambleCacheTest.kt | 131 - .../codeassist/ndk/ToolCancellationTest.kt | 67 - .../kotlin/dev/codeassist/ndk/jni/JniTest.kt | 210 - .../ndk/jni/KotlinNativeLayoutTest.kt | 40 - samples/swift-plugin/build.gradle.kts | 153 - .../swift-plugin/src/main/AndroidManifest.xml | 32 - .../src/main/assets/fonts/Inter-LICENSE.txt | 92 - .../assets/fonts/InterVariable-Italic.ttf | Bin 910252 -> 0 bytes .../src/main/assets/fonts/InterVariable.ttf | Bin 879708 -> 0 bytes .../src/main/assets/glass-params.json | 236 - .../symbols/MaterialSymbols-LICENSE.txt | 202 - .../symbols/MaterialSymbolsRounded-subset.ttf | Bin 325908 -> 0 bytes .../src/main/assets/symbols/sf-symbols.map | 337 - .../codeassist/swift/PluginInfoActivity.kt | 49 - .../dev/codeassist/swift/ProcessSupport.kt | 112 - .../dev/codeassist/swift/SwiftAppRunner.kt | 126 - .../codeassist/swift/SwiftConsoleTemplate.kt | 109 - .../dev/codeassist/swift/SwiftFileIcons.kt | 26 - .../kotlin/dev/codeassist/swift/SwiftGlass.kt | 303 - .../codeassist/swift/SwiftLanguageServer.kt | 102 - .../dev/codeassist/swift/SwiftPlugin.kt | 60 - .../codeassist/swift/SwiftPreviewPainter.kt | 306 - .../dev/codeassist/swift/SwiftPreviewPane.kt | 236 - .../codeassist/swift/SwiftPreviewSession.kt | 269 - .../codeassist/swift/SwiftPreviewSource.kt | 240 - .../dev/codeassist/swift/SwiftProject.kt | 116 - .../kotlin/dev/codeassist/swift/SwiftRun.kt | 221 - .../dev/codeassist/swift/SwiftSymbols.kt | 99 - .../dev/codeassist/swift/SwiftTextEngine.kt | 233 - .../dev/codeassist/swift/SwiftToolchain.kt | 278 - .../dev/codeassist/swift/SwiftUiPlugin.kt | 65 - .../src/main/res/raw/codeassist_plugin.toml | 21 - .../src/main/res/values/strings.xml | 4 - .../dev/codeassist/swift/SwiftPackagesTest.kt | 55 - .../swift/SwiftPreviewSourceTest.kt | 90 - .../swift-plugin/swiftui/Sources/App.swift | 134 - .../swift-plugin/swiftui/Sources/Chrome.swift | 850 -- .../swift-plugin/swiftui/Sources/Compat.swift | 1106 -- .../swiftui/Sources/Containers.swift | 346 - .../swiftui/Sources/Controls.swift | 763 -- .../swift-plugin/swiftui/Sources/Core.swift | 198 - .../swiftui/Sources/DisplayList.swift | 163 - .../swiftui/Sources/Environment.swift | 245 - .../swift-plugin/swiftui/Sources/Glass.swift | 116 - .../swift-plugin/swiftui/Sources/Layout.swift | 828 -- .../swiftui/Sources/Modifiers.swift | 351 - .../swiftui/Sources/MoreViews.swift | 1164 --- .../swiftui/Sources/Navigation.swift | 287 - .../swiftui/Sources/NavigationStack.swift | 278 - .../swiftui/Sources/Platform.swift | 29 - .../swiftui/Sources/Preview.swift | 235 - .../swift-plugin/swiftui/Sources/Shapes.swift | 414 - .../swift-plugin/swiftui/Sources/State.swift | 416 - .../swift-plugin/swiftui/Sources/Style.swift | 529 - .../swift-plugin/swiftui/Sources/Text.swift | 307 - .../swift-plugin/swiftui/symbol-metrics.tsv | 9185 ----------------- settings.gradle.kts | 13 +- tools/dart-sdk/README.md | 147 - tools/dart-sdk/build-gen-snapshot.sh | 84 - tools/dart-sdk/fetch-dart-android.sh | 147 - tools/dart-sdk/fetch-flutter-release.sh | 117 - tools/dart-sdk/fetch-flutter.sh | 146 - tools/dart-sdk/flutter-player/main.dart | 23 - tools/dart-sdk/flutter-player/pubspec.yaml | 8 - tools/dotnet-toolchain/README.md | 41 - .../dotnet-toolchain/build-dotnet-android.sh | 220 - .../dotnet-toolchain/launcher/dotnetlaunch.c | 138 - tools/dotnet-toolchain/smoke-test-device.sh | 88 - tools/ndk-toolchain/README.md | 183 - tools/ndk-toolchain/build-llvm-android.sh | 542 - tools/ndk-toolchain/daemon/ndkclangd.c | 566 - tools/ndk-toolchain/daemon/ndkrun.c | 162 - tools/ndk-toolchain/smoke-test-device.sh | 96 - tools/ndk-toolchain/toolchain-key.sh | 11 - tools/swift-sdk/build_swiftui.sh | 81 - tools/swift-sdk/packages.lock | 62 - tools/swift-sdk/stage_swift.py | 482 - tools/swift-sdk/symbols/build_symbols.sh | 53 - tools/swift-sdk/symbols/sf-to-material.tsv | 340 - tools/swiftui-parity/ApiCases.swift | 202 - tools/swiftui-parity/Cases.swift | 177 - tools/swiftui-parity/ChromeCases.swift | 211 - tools/swiftui-parity/GlassCases.swift | 211 - tools/swiftui-parity/GlassModel.swift | 303 - tools/swiftui-parity/Ours.swift | 625 -- tools/swiftui-parity/Probe.swift | 170 - tools/swiftui-parity/RefApp.swift | 76 - tools/swiftui-parity/SymbolProbe.swift | 38 - tools/swiftui-parity/glass-params.json | 236 - tools/swiftui-parity/run.sh | 59 - 319 files changed, 21 insertions(+), 62740 deletions(-) delete mode 100644 .github/workflows/dart-gen-snapshot.yml delete mode 100644 .github/workflows/dart-plugin.yml delete mode 100644 .github/workflows/dotnet-plugin.yml delete mode 100644 .github/workflows/ndk-plugin.yml delete mode 100644 .github/workflows/ndk-toolchain.yml delete mode 100644 .github/workflows/swift-plugin.yml delete mode 100644 samples/dart-plugin/build.gradle.kts delete mode 100644 samples/dart-plugin/src/main/AndroidManifest.xml delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartConsoleTemplate.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartFileIcons.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartLanguageServer.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartLex.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartPlugin.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartPreviews.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartProject.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartRun.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartSdk.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartTests.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartUiPlugin.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterAndroidFiles.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterApk.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterAppTemplate.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterAssets.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPlayerActivity.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPlayerLauncher.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPlugins.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPreviewController.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPreviewPane.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPreviewService.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterRun.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterRunParticipant.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterSdk.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterSession.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FrontendServer.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/PackageWatcher.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/PluginInfoActivity.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/Pub.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/PubImporter.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/ToolCancellation.kt delete mode 100644 samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/VmService.kt delete mode 100644 samples/dart-plugin/src/main/res/raw/codeassist_plugin.toml delete mode 100644 samples/dart-plugin/src/main/res/values/strings.xml delete mode 100644 samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartLanguageServerTest.kt delete mode 100644 samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartPackagesTest.kt delete mode 100644 samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartPreviewsTest.kt delete mode 100644 samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartTestsTest.kt delete mode 100644 samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterApkTest.kt delete mode 100644 samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterImportTest.kt delete mode 100644 samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterPluginsTest.kt delete mode 100644 samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterRunParticipantTest.kt delete mode 100644 samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterTest.kt delete mode 100644 samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/PackageWatcherTest.kt delete mode 100644 samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/PubImporterTest.kt delete mode 100644 samples/dart-plugin/src/test/resources/flutter-create/AndroidManifest.xml.txt delete mode 100644 samples/dart-plugin/src/test/resources/flutter-create/app.build.gradle.kts.txt delete mode 100644 samples/dotnet-plugin/README.md delete mode 100644 samples/dotnet-plugin/build.gradle.kts delete mode 100644 samples/dotnet-plugin/src/main/AndroidManifest.xml delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/CSharpPlugin.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/PluginInfoActivity.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/CsBuildPlugin.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsCompileTask.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRestoreTask.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRunIds.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRunProgramTask.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRunTaskProvider.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/RunSupport.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tests/CsTestProvider.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tests/CsTestRunner.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tests/CsTestScan.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsCompletionContributor.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsCompletionItems.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsDocText.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsKeywords.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsNavigationLines.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSemanticCompletion.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSignatureLines.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSymbolTable.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSymbols.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsWords.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsprojCompletionContributor.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsDeclarationProvider.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsFileNames.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsLanguageBackend.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsModules.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsReferenceProviders.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsRunGutter.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsSignatureHelp.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsUsingCleanup.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsWorkspace.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsprojAnalyzer.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnosticProvider.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnosticTags.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnostics.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsLineOffsets.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsMaskedErrors.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/quickfixes/CsUsingFix.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/quickfixes/CsUsingFixProvider.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsMainScan.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsMains.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsNewFiles.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsProject.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsRunConfig.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojCheck.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojCompleter.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojCondition.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojExtras.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojGraph.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojProject.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojReferences.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojSchema.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojText.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/CsPackageRestorer.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/CsPackageWatcher.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/NuGet.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/NuGetVersion.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/templates/CsConsoleTemplate.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/templates/CsLibraryTemplate.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/templates/CsTemplateSupport.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsChecker.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsCompilerHost.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsCompleter.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsFormatter.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsNavigator.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsServer.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/DotnetSdk.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/ResidentProgram.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/RuntimeConfig.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/ui/CsFileIcons.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/ui/CsUiPlugin.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/util/Logging.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/util/ProcessOutput.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/util/RestoreNotice.kt delete mode 100644 samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/util/ToolCancellation.kt delete mode 100644 samples/dotnet-plugin/src/main/res/raw/codeassist_plugin.toml delete mode 100644 samples/dotnet-plugin/src/main/res/values/strings.xml delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/FakeHost.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/TestFiles.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/build/CsRunIdsTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/build/tests/CsTestScanTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/completion/CsCompletionItemsTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/completion/CsDocTextTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/completion/CsNavigationLinesTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/completion/CsSignatureLinesTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/completion/CsSymbolTableTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/completion/CsWordsTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/editor/CsFileNamesTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/editor/CsUsingCleanupTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnosticTagsTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnosticsTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/editor/diagnostics/CsLineOffsetsTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/editor/diagnostics/CsMaskedErrorsTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/editor/quickfixes/CsUsingFixTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/project/CsMainScanTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/project/CsMainsTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/project/CsProjectTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/project/CsRunConfigTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/project/csproj/CsprojCheckTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/project/csproj/CsprojCompleterTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/project/csproj/CsprojExtrasTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/project/csproj/CsprojGraphTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/project/csproj/CsprojTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/project/csproj/CsprojTextTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/project/nuget/NuGetTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/project/nuget/NuGetVersionTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/sdk/CsFormatEditsTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/sdk/DotnetSdkTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/sdk/RuntimeConfigTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/util/ProcessOutputTest.kt delete mode 100644 samples/dotnet-plugin/src/test/kotlin/dev/codeassist/csharp/util/RestoreNoticeTest.kt delete mode 100644 samples/dotnet-plugin/src/test/resources/assets/dotnet-sdk.zip delete mode 100644 samples/dotnet-plugin/src/test/resources/assets/test.txt delete mode 100644 samples/ndk-plugin/README.md delete mode 100644 samples/ndk-plugin/build.gradle.kts delete mode 100755 samples/ndk-plugin/run-tests-on-device.sh delete mode 100644 samples/ndk-plugin/src/main/AndroidManifest.xml delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/ClangCompletions.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/ClangDaemon.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/ClangDiagnostics.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/ClangPreamble.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/CppNewFiles.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NativeActivityTemplate.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NativeAppTemplate.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NativeConsoleTemplate.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NativeCppTemplate.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NativeIncremental.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkAbi.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkBuildPlugin.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkCompletionContributor.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkDiagnosticProvider.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkFacet.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkFileIcons.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkFlags.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkLanguageBackend.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkModuleActions.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkPlugin.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkRun.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkSourceRoots.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkTemplateSupport.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkToolchain.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/NdkUiPlugin.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/PluginInfoActivity.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/PreambleCache.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/ToolCancellation.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/jni/CppJniScanner.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/jni/Jni.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/jni/JniDiagnostics.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/jni/JniIndex.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/jni/JniNavigation.kt delete mode 100644 samples/ndk-plugin/src/main/kotlin/dev/codeassist/ndk/jni/NativeMethodScanner.kt delete mode 100644 samples/ndk-plugin/src/main/res/raw/codeassist_plugin.toml delete mode 100644 samples/ndk-plugin/src/main/res/values/strings.xml delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/ClangCompletionsTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/ClangDaemonDeviceTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/ClangDaemonTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/ClangDiagnosticsTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/ClangPreambleTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/ClangSemanticTokensTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/CppNewFilesTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/NativeIncrementalTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/NdkAbiTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/NdkFacetTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/NdkRunDeviceTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/NdkRunTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/NdkTemplatesTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/PreambleCacheTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/ToolCancellationTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/jni/JniTest.kt delete mode 100644 samples/ndk-plugin/src/test/kotlin/dev/codeassist/ndk/jni/KotlinNativeLayoutTest.kt delete mode 100644 samples/swift-plugin/build.gradle.kts delete mode 100644 samples/swift-plugin/src/main/AndroidManifest.xml delete mode 100644 samples/swift-plugin/src/main/assets/fonts/Inter-LICENSE.txt delete mode 100644 samples/swift-plugin/src/main/assets/fonts/InterVariable-Italic.ttf delete mode 100644 samples/swift-plugin/src/main/assets/fonts/InterVariable.ttf delete mode 100644 samples/swift-plugin/src/main/assets/glass-params.json delete mode 100644 samples/swift-plugin/src/main/assets/symbols/MaterialSymbols-LICENSE.txt delete mode 100644 samples/swift-plugin/src/main/assets/symbols/MaterialSymbolsRounded-subset.ttf delete mode 100644 samples/swift-plugin/src/main/assets/symbols/sf-symbols.map delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/PluginInfoActivity.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/ProcessSupport.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftAppRunner.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftConsoleTemplate.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftFileIcons.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftGlass.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftLanguageServer.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftPlugin.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftPreviewPainter.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftPreviewPane.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftPreviewSession.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftPreviewSource.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftProject.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftRun.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftSymbols.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftTextEngine.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftToolchain.kt delete mode 100644 samples/swift-plugin/src/main/kotlin/dev/codeassist/swift/SwiftUiPlugin.kt delete mode 100644 samples/swift-plugin/src/main/res/raw/codeassist_plugin.toml delete mode 100644 samples/swift-plugin/src/main/res/values/strings.xml delete mode 100644 samples/swift-plugin/src/test/kotlin/dev/codeassist/swift/SwiftPackagesTest.kt delete mode 100644 samples/swift-plugin/src/test/kotlin/dev/codeassist/swift/SwiftPreviewSourceTest.kt delete mode 100644 samples/swift-plugin/swiftui/Sources/App.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Chrome.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Compat.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Containers.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Controls.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Core.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/DisplayList.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Environment.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Glass.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Layout.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Modifiers.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/MoreViews.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Navigation.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/NavigationStack.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Platform.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Preview.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Shapes.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/State.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Style.swift delete mode 100644 samples/swift-plugin/swiftui/Sources/Text.swift delete mode 100644 samples/swift-plugin/swiftui/symbol-metrics.tsv delete mode 100644 tools/dart-sdk/README.md delete mode 100755 tools/dart-sdk/build-gen-snapshot.sh delete mode 100755 tools/dart-sdk/fetch-dart-android.sh delete mode 100755 tools/dart-sdk/fetch-flutter-release.sh delete mode 100755 tools/dart-sdk/fetch-flutter.sh delete mode 100644 tools/dart-sdk/flutter-player/main.dart delete mode 100644 tools/dart-sdk/flutter-player/pubspec.yaml delete mode 100644 tools/dotnet-toolchain/README.md delete mode 100755 tools/dotnet-toolchain/build-dotnet-android.sh delete mode 100644 tools/dotnet-toolchain/launcher/dotnetlaunch.c delete mode 100755 tools/dotnet-toolchain/smoke-test-device.sh delete mode 100644 tools/ndk-toolchain/README.md delete mode 100755 tools/ndk-toolchain/build-llvm-android.sh delete mode 100644 tools/ndk-toolchain/daemon/ndkclangd.c delete mode 100644 tools/ndk-toolchain/daemon/ndkrun.c delete mode 100755 tools/ndk-toolchain/smoke-test-device.sh delete mode 100755 tools/ndk-toolchain/toolchain-key.sh delete mode 100755 tools/swift-sdk/build_swiftui.sh delete mode 100644 tools/swift-sdk/packages.lock delete mode 100644 tools/swift-sdk/stage_swift.py delete mode 100755 tools/swift-sdk/symbols/build_symbols.sh delete mode 100644 tools/swift-sdk/symbols/sf-to-material.tsv delete mode 100644 tools/swiftui-parity/ApiCases.swift delete mode 100644 tools/swiftui-parity/Cases.swift delete mode 100644 tools/swiftui-parity/ChromeCases.swift delete mode 100644 tools/swiftui-parity/GlassCases.swift delete mode 100644 tools/swiftui-parity/GlassModel.swift delete mode 100644 tools/swiftui-parity/Ours.swift delete mode 100644 tools/swiftui-parity/Probe.swift delete mode 100644 tools/swiftui-parity/RefApp.swift delete mode 100644 tools/swiftui-parity/SymbolProbe.swift delete mode 100644 tools/swiftui-parity/glass-params.json delete mode 100755 tools/swiftui-parity/run.sh diff --git a/.github/workflows/dart-gen-snapshot.yml b/.github/workflows/dart-gen-snapshot.yml deleted file mode 100644 index 4741748a68..0000000000 --- a/.github/workflows/dart-gen-snapshot.yml +++ /dev/null @@ -1,90 +0,0 @@ -name: Dart gen_snapshot - -# Builds the Dart SDK's gen_snapshot as an Android executable (tools/dart-sdk/build-gen-snapshot.sh), one per device -# ABI, for the Dart plugin's Flutter release (AOT) builds. A Dart checkout with the NDK is several GB, more than a -# laptop may spare, and the build is the same every time for a given Dart version, so it runs here and publishes -# the executables as the prerelease `dart-gen-snapshot-`: -# gen_snapshot- the executable for a device of that ABI (arm64-v8a, x86_64, armeabi-v7a) -# SHA256SUMS their checksums, which tools/dart-sdk/fetch-flutter-release.sh pins - -on: - push: - branches: [ main ] - paths: - - tools/dart-sdk/build-gen-snapshot.sh - - .github/workflows/dart-gen-snapshot.yml - workflow_dispatch: - inputs: - dart_version: - description: Dart tag (the Dart of the Flutter the plugin pins) - default: "3.13.7" - -permissions: - contents: read - -# One publish at a time: two runs replacing the same release's assets would leave it half one, half the other. -concurrency: - group: dart-gen-snapshot - cancel-in-progress: false - -jobs: - build: - name: gen_snapshot ${{ matrix.arch }} - runs-on: ubuntu-24.04 - timeout-minutes: 180 - strategy: - fail-fast: false - matrix: - arch: [ arm64c, x64c, arm ] - steps: - - uses: actions/checkout@v4 - with: - sparse-checkout: tools/dart-sdk - - # The checkout, toolchains and NDK need more than the runner leaves free by default. - - name: Free disk space - run: | - sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL /usr/local/share/boost - df -h / - - - name: Build - env: - ARCH: ${{ matrix.arch }} - DART_VERSION: ${{ inputs.dart_version || '3.13.7' }} - WORK: ${{ runner.temp }}/gen-snapshot - run: tools/dart-sdk/build-gen-snapshot.sh - - - uses: actions/upload-artifact@v4 - with: - name: gen_snapshot-${{ matrix.arch }} - path: tools/dart-sdk/build/out/gen-snapshot - if-no-files-found: error - - publish: - name: Publish - needs: build - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - uses: actions/download-artifact@v4 - with: - path: artifacts - - name: Release - env: - GH_TOKEN: ${{ github.token }} - DART_VERSION: ${{ inputs.dart_version || '3.13.7' }} - run: | - mkdir assets - for dir in artifacts/gen_snapshot-*/*/; do - abi="$(basename "$dir")" - cp "$dir/gen_snapshot" "assets/gen_snapshot-$abi" - done - (cd assets && sha256sum gen_snapshot-* > SHA256SUMS && cat SHA256SUMS) - tag="dart-gen-snapshot-$DART_VERSION" - if ! gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then - gh release create "$tag" --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --prerelease \ - --title "Dart $DART_VERSION gen_snapshot for Android" \ - --notes "gen_snapshot from Dart $DART_VERSION, built for Android (product mode; compressed pointers on 64-bit) by .github/workflows/dart-gen-snapshot.yml. The Dart plugin uses it to compile Flutter apps ahead of time on the device." - fi - gh release upload "$tag" assets/* --repo "$GITHUB_REPOSITORY" --clobber diff --git a/.github/workflows/dart-plugin.yml b/.github/workflows/dart-plugin.yml deleted file mode 100644 index cc28ffaaa5..0000000000 --- a/.github/workflows/dart-plugin.yml +++ /dev/null @@ -1,285 +0,0 @@ -name: Dart plugin release - -# Builds the Dart plugin (samples/dart-plugin) as one release-signed APK per ABI and attaches them to a CodeAssist -# release as CodeAssist-Dart-Plugin--.apk. apk.yml only builds the IDE. -# -# The plugin carries a Dart SDK and Flutter that run ON the device, and neither is in the repository, so: -# 1. sdk: tools/dart-sdk/fetch-dart-android.sh once per ABI (downloads Termux's Dart package for it) -# 2. flutter: tools/dart-sdk/fetch-flutter.sh once (the debug engine for every ABI Flutter ships one for, plus the -# ABI-independent framework files), from a Flutter SDK pinned to the Dart version, then -# fetch-flutter-release.sh (the release engine, our gen_snapshot from the dart-gen-snapshot- -# prerelease, and the product platform), so the plugin can build release (AOT) Flutter APKs -# 3. plugin: gather the results and run assembleRelease, which makes dart-plugin--release.apk for every ABI -# that has something staged -# -# Three ABIs: Termux publishes no Dart package for x86 (32-bit), so there is no x86 plugin. Every download is -# checked against a pinned checksum. A failed SDK job leaves its ABI without an APK and the plugin job builds with -# the others; arm64-v8a is required. -# -# Runs when a release is published (tags v*), and by hand: with a tag it attaches to that release, without one it -# only builds, and the APKs are this run's artifacts. By hand it builds the branch it was started on (see REF). -# -# Signing uses the IDE's upload key, from the repository secrets RELEASE_KEYSTORE_BASE64, RELEASE_STORE_PASSWORD, -# RELEASE_KEY_ALIAS and RELEASE_KEY_PASSWORD. This workflow never runs for a pull request. - -on: - release: - types: [ published ] - workflow_dispatch: - inputs: - tag: - description: Release tag to attach the APKs to (e.g. v3.49.0); empty to only build - type: string - default: "" - -permissions: - contents: write - -env: - JAVA_VERSION: "25" - FLUTTER_VERSION: "3.47.9" - # A published release builds from its own commit, so the plugin matches the app it ships with. A run by hand - # builds from the branch it was started on and attaches to `tag`: a fix to this workflow or the fetch scripts - # can then ship for a release that is already out, without moving its tag. - REF: ${{ github.event.release.tag_name || github.ref }} - -concurrency: - group: dart-plugin-${{ github.event.release.tag_name || inputs.tag || github.ref }} - cancel-in-progress: false - -jobs: - sdk: - name: Dart SDK ${{ matrix.abi }} - # An app release only: prereleases created by other workflows (dart-gen-snapshot-*) are not app versions. - if: github.event_name == 'workflow_dispatch' || startsWith(github.event.release.tag_name, 'v') - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - # Dart 3.13.7 survives only as our aarch64 mirror (see fetch-dart-android.sh): Termux dropped it for every - # ABI before arm and x86_64 were mirrored. Add them back with the next Dart (and Flutter) the plugin pins. - abi: [ arm64-v8a ] - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ env.REF }} - - - name: Fetch the ${{ matrix.abi }} Dart SDK - working-directory: tools/dart-sdk - env: - ABI: ${{ matrix.abi }} - run: ./fetch-dart-android.sh - - - name: Upload the ${{ matrix.abi }} executables - uses: actions/upload-artifact@v4 - with: - name: dart-host-${{ matrix.abi }} - path: tools/dart-sdk/build/out/jniLibs/${{ matrix.abi }} - if-no-files-found: error - retention-days: 7 - - # The SDK's libraries are the same whichever ABI produced them. - - name: Upload the shared SDK libraries - if: matrix.abi == 'arm64-v8a' - uses: actions/upload-artifact@v4 - with: - name: dart-assets - path: | - tools/dart-sdk/build/out/assets - tools/dart-sdk/build/out/DART_VERSION - if-no-files-found: error - retention-days: 7 - - flutter: - name: Flutter engines and framework - if: github.event_name == 'workflow_dispatch' || startsWith(github.event.release.tag_name, 'v') - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ env.REF }} - - - name: Set up Flutter ${{ env.FLUTTER_VERSION }} - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2 - with: - flutter-version: ${{ env.FLUTTER_VERSION }} - channel: stable - - # llvm-objcopy, to strip the engines, comes from the runner's preinstalled NDK (ANDROID_NDK_HOME). - - name: Stage Flutter - working-directory: tools/dart-sdk - env: - FLUTTER_HOME: ${{ env.FLUTTER_ROOT }} - run: ./fetch-flutter.sh - - # The release engine, gen_snapshot and product platform go beside the debug engine staged above. - - name: Stage Flutter release mode - working-directory: tools/dart-sdk - run: ./fetch-flutter-release.sh - - - name: Check release mode was staged - run: | - out=tools/dart-sdk/build/out/flutter - test -d "$out/product/flutter_patched_sdk_product" - for abi in $(ls "$out/jniLibs"); do - test -f "$out/jniLibs/$abi/libflutter_release.so" - test -x "$out/jniLibs/$abi/libgen_snapshot.so" - done - - - name: Upload Flutter - uses: actions/upload-artifact@v4 - with: - name: dart-flutter - path: tools/dart-sdk/build/out/flutter - if-no-files-found: error - retention-days: 7 - - plugin: - name: Release APKs - needs: [ sdk, flutter ] - # Carry on with whichever ABIs got an SDK; the check below insists on arm64-v8a. - if: ${{ !cancelled() && (github.event_name == 'workflow_dispatch' || startsWith(github.event.release.tag_name, 'v')) }} - runs-on: ubuntu-latest - env: - TAG: ${{ github.event.release.tag_name || inputs.tag }} - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ env.REF }} - - - name: Fetch the SDK libraries and Flutter - uses: actions/download-artifact@v4 - with: - name: dart-assets - path: tools/dart-sdk/build/out - - uses: actions/download-artifact@v4 - with: - name: dart-flutter - path: tools/dart-sdk/build/out/flutter - - - name: Fetch the per-ABI executables - uses: actions/download-artifact@v4 - with: - name: dart-host-arm64-v8a - path: tools/dart-sdk/build/out/jniLibs/arm64-v8a - - uses: actions/download-artifact@v4 - with: - name: dart-host-armeabi-v7a - path: tools/dart-sdk/build/out/jniLibs/armeabi-v7a - continue-on-error: true - - uses: actions/download-artifact@v4 - with: - name: dart-host-x86_64 - path: tools/dart-sdk/build/out/jniLibs/x86_64 - continue-on-error: true - - - name: Set up JDK ${{ env.JAVA_VERSION }} - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: ${{ env.JAVA_VERSION }} - - - name: Set up Gradle - uses: gradle/actions/setup-gradle@v4 - - - name: Set up Android SDK - uses: android-actions/setup-android@v3 - with: - packages: "platform-tools platforms;android-36 platforms;android-36.1 build-tools;36.0.0" - - - name: Disable Kotlin incremental compilation (CI) - run: | - mkdir -p ~/.gradle - echo "kotlin.incremental=false" >> ~/.gradle/gradle.properties - - - name: What was staged - run: | - find tools/dart-sdk/build/out -maxdepth 3 -type d | sort - test -f tools/dart-sdk/build/out/jniLibs/arm64-v8a/libdartvm.so - - - name: Run the plugin's unit tests - run: ./gradlew :samples:dart-plugin:testDebugUnitTest --console=plain --stacktrace - - # download-artifact drops the executable bit; the plugin marks its jniLibs executable on the device anyway. - - name: Restore gen_snapshot's executable bit - run: chmod +x tools/dart-sdk/build/out/flutter/jniLibs/*/libgen_snapshot.so - - # The keystore is written outside the checkout and only for the build step's lifetime. - - name: Build the release APKs - env: - RELEASE_KEYSTORE_BASE64: ${{ secrets.RELEASE_KEYSTORE_BASE64 }} - RELEASE_STORE_PASSWORD: ${{ secrets.RELEASE_STORE_PASSWORD }} - RELEASE_KEY_ALIAS: ${{ secrets.RELEASE_KEY_ALIAS }} - RELEASE_KEY_PASSWORD: ${{ secrets.RELEASE_KEY_PASSWORD }} - run: | - [[ -n "$RELEASE_KEYSTORE_BASE64" ]] || { echo "RELEASE_KEYSTORE_BASE64 is not set: the APKs would be unsigned" >&2; exit 1; } - export RELEASE_STORE_FILE="$RUNNER_TEMP/upload.jks" - echo "$RELEASE_KEYSTORE_BASE64" | base64 -d > "$RELEASE_STORE_FILE" - trap 'rm -f "$RELEASE_STORE_FILE"' EXIT - ./gradlew :samples:dart-plugin:assembleRelease --console=plain --stacktrace - - - name: Check and name the APKs - id: apks - run: | - apksigner="$(ls -d "$ANDROID_HOME"/build-tools/*/ | sort -V | tail -1)apksigner" - version="$(sed -n 's/^version = "\(.*\)"/\1/p' samples/dart-plugin/src/main/res/raw/codeassist_plugin.toml | head -1)" - [[ -n "$version" ]] || { echo "no version in codeassist_plugin.toml" >&2; exit 1; } - mkdir -p dist - abis="" - for apk in samples/dart-plugin/build/outputs/apk/release/dart-plugin-*-release.apk; do - abi="$(basename "$apk")"; abi="${abi#dart-plugin-}"; abi="${abi%-release.apk}" - "$apksigner" verify "$apk" - # Release mode has to be inside: the engine, gen_snapshot and the product platform. - unzip -l "$apk" "lib/$abi/libflutter_release.so" "lib/$abi/libgen_snapshot.so" >/dev/null \ - || { echo "$apk has no release-mode Flutter for $abi" >&2; exit 1; } - unzip -l "$apk" | grep -q 'flutter-product.zip' || { echo "$apk has no flutter-product.zip" >&2; exit 1; } - cp "$apk" "dist/CodeAssist-Dart-Plugin-$version-$abi.apk" - abis="$abis $abi" - done - test -f "dist/CodeAssist-Dart-Plugin-$version-arm64-v8a.apk" || { echo "no arm64-v8a APK" >&2; exit 1; } - "$apksigner" verify --print-certs "dist/CodeAssist-Dart-Plugin-$version-arm64-v8a.apk" | grep -m1 SHA-256 - ls -la dist - echo "version=$version" >> "$GITHUB_OUTPUT" - echo "abis=${abis# }" >> "$GITHUB_OUTPUT" - - - uses: actions/upload-artifact@v4 - with: - name: dart-plugin-release - path: dist/*.apk - if-no-files-found: error - retention-days: 30 - - - name: Attach to ${{ env.TAG }} - if: env.TAG != '' - env: - GH_TOKEN: ${{ github.token }} - VERSION: ${{ steps.apks.outputs.version }} - ABIS: ${{ steps.apks.outputs.abis }} - run: | - gh release upload "$TAG" dist/*.apk --clobber - base="https://github.com/${GITHUB_REPOSITORY}/releases/download/$TAG" - # The catalog row the Get plugins page reads (Supabase public.plugin_catalog): every ABI's build, and - # the plain link (what older apps read) on arm64. - json="{" - for abi in $ABIS; do - f="dist/CodeAssist-Dart-Plugin-$VERSION-$abi.apk" - json="$json\"$abi\": {\"url\": \"$base/$(basename "$f")\", \"size\": $(stat -c %s "$f")}," - done - json="${json%,}}" - arm64="dist/CodeAssist-Dart-Plugin-$VERSION-arm64-v8a.apk" - { - echo "Attached to [$TAG](https://github.com/${GITHUB_REPOSITORY}/releases/tag/$TAG)." - echo - echo "Catalog update (Supabase SQL editor):" - echo - echo '```sql' - echo "update public.plugin_catalog set" - echo " version = '$VERSION'," - echo " download_url = '$base/$(basename "$arm64")'," - echo " size_bytes = $(stat -c %s "$arm64")," - echo " page_url = 'https://github.com/${GITHUB_REPOSITORY}/releases/tag/$TAG'," - echo " abi_downloads = '$json'::jsonb," - echo " updated_at = now()" - echo "where id = 'dev.codeassist.dart';" - echo '```' - } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/dotnet-plugin.yml b/.github/workflows/dotnet-plugin.yml deleted file mode 100644 index 28e3805979..0000000000 --- a/.github/workflows/dotnet-plugin.yml +++ /dev/null @@ -1,161 +0,0 @@ -name: C# plugin release - -# Builds the C# plugin (samples/dotnet-plugin) as one release-signed APK per ABI and attaches them to a CodeAssist -# release as CodeAssist-CSharp-Plugin--.apk. -# -# The .NET runtime and compiler inside it are assembled here, by tools/dotnet-toolchain/build-dotnet-android.sh: -# Microsoft's published packages, each checked against the SHA-256 recorded in that script, plus OpenSSL and -# the launcher built from source with the NDK. That takes a few minutes, so there is no separate toolchain -# workflow or prerelease to keep in step. -# -# Runs when a release is published (tags v*), and by hand: with a tag it attaches to that release, without one -# it only builds, and the APKs are this run's artifacts. -# -# Signing uses the IDE's upload key, from the repository secrets RELEASE_KEYSTORE_BASE64, RELEASE_STORE_PASSWORD, -# RELEASE_KEY_ALIAS and RELEASE_KEY_PASSWORD. This workflow never runs for a pull request. - -on: - release: - types: [ published ] - workflow_dispatch: - inputs: - tag: - description: Release tag to attach the APKs to (e.g. v3.47.0); empty to only build - type: string - default: "" - -permissions: - contents: write - -concurrency: - group: dotnet-plugin-${{ github.event.release.tag_name || inputs.tag || github.ref }} - cancel-in-progress: false - -env: - JAVA_VERSION: "25" - # The ABIs Microsoft publishes an Android runtime for. There is none for 32-bit devices. - ABIS: "arm64-v8a x86_64" - -jobs: - plugin: - name: Release APKs - # An app release only: prereleases created by other workflows are not app versions. - if: github.event_name == 'workflow_dispatch' || startsWith(github.event.release.tag_name, 'v') - runs-on: ubuntu-latest - env: - TAG: ${{ github.event.release.tag_name || inputs.tag }} - steps: - - uses: actions/checkout@v4 - with: - # The release's own commit, so the plugin matches the app it ships with. - ref: ${{ github.event.release.tag_name || inputs.tag || github.ref }} - - - name: Set up JDK ${{ env.JAVA_VERSION }} - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: ${{ env.JAVA_VERSION }} - - - name: Set up Gradle - uses: gradle/actions/setup-gradle@v4 - - - name: Set up Android SDK - uses: android-actions/setup-android@v3 - with: - packages: "platform-tools platforms;android-36 platforms;android-36.1 build-tools;36.0.0" - - - name: Assemble the .NET toolchain - run: | - for abi in $ABIS; do - HOST_ABI="$abi" tools/dotnet-toolchain/build-dotnet-android.sh - out="tools/dotnet-toolchain/build/out/$abi" - test -f "$out/jniLibs/$abi/libdotnetlaunch.so" || { echo "no launcher for $abi" >&2; exit 1; } - test -f "$out/assets/dotnet-sdk.zip" || { echo "no .NET tree for $abi" >&2; exit 1; } - done - - - name: Disable Kotlin incremental compilation (CI) - run: | - mkdir -p ~/.gradle - echo "kotlin.incremental=false" >> ~/.gradle/gradle.properties - - - name: Run the plugin's unit tests - run: ./gradlew :samples:dotnet-plugin:testDebugUnitTest --console=plain --stacktrace - - # The keystore is written outside the checkout and only for the build step's lifetime. One build per ABI: - # the runtime's native libraries are in the asset archive, so an APK serves exactly one ABI. - - name: Build the release APKs - env: - RELEASE_KEYSTORE_BASE64: ${{ secrets.RELEASE_KEYSTORE_BASE64 }} - RELEASE_STORE_PASSWORD: ${{ secrets.RELEASE_STORE_PASSWORD }} - RELEASE_KEY_ALIAS: ${{ secrets.RELEASE_KEY_ALIAS }} - RELEASE_KEY_PASSWORD: ${{ secrets.RELEASE_KEY_PASSWORD }} - run: | - [[ -n "$RELEASE_KEYSTORE_BASE64" ]] || { echo "RELEASE_KEYSTORE_BASE64 is not set: the APKs would be unsigned" >&2; exit 1; } - export RELEASE_STORE_FILE="$RUNNER_TEMP/upload.jks" - echo "$RELEASE_KEYSTORE_BASE64" | base64 -d > "$RELEASE_STORE_FILE" - trap 'rm -f "$RELEASE_STORE_FILE"' EXIT - mkdir -p "$RUNNER_TEMP/apks" - for abi in $ABIS; do - ./gradlew :samples:dotnet-plugin:assembleRelease "-Pdotnet.abi=$abi" --console=plain --stacktrace - cp samples/dotnet-plugin/build/outputs/apk/release/dotnet-plugin-release.apk "$RUNNER_TEMP/apks/$abi.apk" - done - - - name: Check and name the APKs - id: apks - run: | - apksigner="$(ls -d "$ANDROID_HOME"/build-tools/*/ | sort -V | tail -1)apksigner" - version="$(sed -n 's/^version = "\(.*\)"/\1/p' samples/dotnet-plugin/src/main/res/raw/codeassist_plugin.toml | head -1)" - [[ -n "$version" ]] || { echo "no version in codeassist_plugin.toml" >&2; exit 1; } - mkdir -p dist - for abi in $ABIS; do - apk="$RUNNER_TEMP/apks/$abi.apk" - "$apksigner" verify "$apk" - unzip -l "$apk" | grep -q "lib/$abi/libdotnetlaunch.so" || { echo "the $abi APK has no launcher" >&2; exit 1; } - unzip -l "$apk" | grep -q "assets/dotnet-sdk.zip" || { echo "the $abi APK has no .NET tree" >&2; exit 1; } - cp "$apk" "dist/CodeAssist-CSharp-Plugin-$version-$abi.apk" - done - "$apksigner" verify --print-certs "dist/CodeAssist-CSharp-Plugin-$version-arm64-v8a.apk" | grep -m1 SHA-256 - ls -la dist - echo "version=$version" >> "$GITHUB_OUTPUT" - - - uses: actions/upload-artifact@v4 - with: - name: dotnet-plugin-release - path: dist/*.apk - if-no-files-found: error - retention-days: 30 - - - name: Attach to ${{ env.TAG }} - if: env.TAG != '' - env: - GH_TOKEN: ${{ github.token }} - VERSION: ${{ steps.apks.outputs.version }} - run: | - gh release upload "$TAG" dist/*.apk --clobber - base="https://github.com/${GITHUB_REPOSITORY}/releases/download/$TAG" - # The catalog row the Get plugins page reads (Supabase public.plugin_catalog): every ABI's build, and - # the plain link (what older apps read) on arm64. - json="{" - for abi in $ABIS; do - f="dist/CodeAssist-CSharp-Plugin-$VERSION-$abi.apk" - json="$json\"$abi\": {\"url\": \"$base/$(basename "$f")\", \"size\": $(stat -c %s "$f")}," - done - json="${json%,}}" - arm64="dist/CodeAssist-CSharp-Plugin-$VERSION-arm64-v8a.apk" - { - echo "Attached to [$TAG](https://github.com/${GITHUB_REPOSITORY}/releases/tag/$TAG)." - echo - echo "Catalog update (Supabase SQL editor; the row comes from the plugin_catalog_csharp migration):" - echo - echo '```sql' - echo "update public.plugin_catalog set" - echo " version = '$VERSION'," - echo " download_url = '$base/$(basename "$arm64")'," - echo " size_bytes = $(stat -c %s "$arm64")," - echo " page_url = 'https://github.com/${GITHUB_REPOSITORY}/releases/tag/$TAG'," - echo " abi_downloads = '$json'::jsonb," - echo " visible = true," - echo " updated_at = now()" - echo "where id = 'dev.codeassist.csharp';" - echo '```' - } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/ndk-plugin.yml b/.github/workflows/ndk-plugin.yml deleted file mode 100644 index 8c53ca15c1..0000000000 --- a/.github/workflows/ndk-plugin.yml +++ /dev/null @@ -1,167 +0,0 @@ -name: NDK plugin release - -# Builds the NDK plugin (samples/ndk-plugin) as one release-signed APK per ABI and attaches them to a CodeAssist -# release as CodeAssist-NDK-Plugin--.apk. -# -# The compiler inside it is not built here: it comes from the `ndk-toolchain-` prerelease the NDK toolchain -# workflow published for this commit's toolchain sources (tools/ndk-toolchain/toolchain-key.sh). With no such -# prerelease the job stops and says so; run the NDK toolchain workflow, then this one by hand for the tag. -# -# Runs when a release is published (tags v*), and by hand: with a tag it attaches to that release, without one -# it only builds, and the APKs are this run's artifacts. -# -# Signing uses the IDE's upload key, from the repository secrets RELEASE_KEYSTORE_BASE64, RELEASE_STORE_PASSWORD, -# RELEASE_KEY_ALIAS and RELEASE_KEY_PASSWORD. This workflow never runs for a pull request. - -on: - release: - types: [ published ] - workflow_dispatch: - inputs: - tag: - description: Release tag to attach the APKs to (e.g. v3.41.0); empty to only build - type: string - default: "" - -permissions: - contents: write - -concurrency: - group: ndk-plugin-${{ github.event.release.tag_name || inputs.tag || github.ref }} - cancel-in-progress: false - -env: - JAVA_VERSION: "25" - ABIS: "arm64-v8a armeabi-v7a x86 x86_64" - -jobs: - plugin: - name: Release APKs - # An app release only: the toolchain's own prereleases are created by a workflow and are not app versions. - if: github.event_name == 'workflow_dispatch' || startsWith(github.event.release.tag_name, 'v') - runs-on: ubuntu-latest - env: - TAG: ${{ github.event.release.tag_name || inputs.tag }} - steps: - - uses: actions/checkout@v4 - with: - # The release's own commit, so the plugin matches the app it ships with. - ref: ${{ github.event.release.tag_name || inputs.tag || github.ref }} - - - name: Fetch the toolchain - env: - GH_TOKEN: ${{ github.token }} - run: | - key="$(tools/ndk-toolchain/toolchain-key.sh)" - if ! gh release download "ndk-toolchain-$key" -p 'ndk-toolchain-*.tar.gz' -D "$RUNNER_TEMP/toolchain"; then - { - echo "No toolchain for key $key (prerelease ndk-toolchain-$key)." - echo "Run the NDK toolchain workflow on this commit, then this workflow again for ${TAG:-this ref}." - } | tee -a "$GITHUB_STEP_SUMMARY" >&2 - exit 1 - fi - out=tools/ndk-toolchain/build/out - mkdir -p "$out/assets" - tar -C "$out/assets" -xzf "$RUNNER_TEMP/toolchain/ndk-toolchain-assets.tar.gz" - for abi in $ABIS; do - mkdir -p "$out/jniLibs/$abi" - tar -C "$out/jniLibs/$abi" -xzf "$RUNNER_TEMP/toolchain/ndk-toolchain-$abi.tar.gz" - for lib in libllvmtools.so libndkclangd.so libndkrun.so; do - test -f "$out/jniLibs/$abi/$lib" || { echo "the toolchain has no $lib for $abi" >&2; exit 1; } - done - done - echo "Toolchain: ndk-toolchain-$key" >> "$GITHUB_STEP_SUMMARY" - - - name: Set up JDK ${{ env.JAVA_VERSION }} - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: ${{ env.JAVA_VERSION }} - - - name: Set up Gradle - uses: gradle/actions/setup-gradle@v4 - - - name: Set up Android SDK - uses: android-actions/setup-android@v3 - with: - packages: "platform-tools platforms;android-36 platforms;android-36.1 build-tools;36.0.0" - - - name: Disable Kotlin incremental compilation (CI) - run: | - mkdir -p ~/.gradle - echo "kotlin.incremental=false" >> ~/.gradle/gradle.properties - - - name: Run the plugin's unit tests - run: ./gradlew :samples:ndk-plugin:testDebugUnitTest --console=plain --stacktrace - - # The keystore is written outside the checkout and only for the build step's lifetime. - - name: Build the release APKs - env: - RELEASE_KEYSTORE_BASE64: ${{ secrets.RELEASE_KEYSTORE_BASE64 }} - RELEASE_STORE_PASSWORD: ${{ secrets.RELEASE_STORE_PASSWORD }} - RELEASE_KEY_ALIAS: ${{ secrets.RELEASE_KEY_ALIAS }} - RELEASE_KEY_PASSWORD: ${{ secrets.RELEASE_KEY_PASSWORD }} - run: | - [[ -n "$RELEASE_KEYSTORE_BASE64" ]] || { echo "RELEASE_KEYSTORE_BASE64 is not set: the APKs would be unsigned" >&2; exit 1; } - export RELEASE_STORE_FILE="$RUNNER_TEMP/upload.jks" - echo "$RELEASE_KEYSTORE_BASE64" | base64 -d > "$RELEASE_STORE_FILE" - trap 'rm -f "$RELEASE_STORE_FILE"' EXIT - ./gradlew :samples:ndk-plugin:assembleRelease --console=plain --stacktrace - - - name: Check and name the APKs - id: apks - run: | - apksigner="$(ls -d "$ANDROID_HOME"/build-tools/*/ | sort -V | tail -1)apksigner" - version="$(sed -n 's/^version = "\(.*\)"/\1/p' samples/ndk-plugin/src/main/res/raw/codeassist_plugin.toml | head -1)" - [[ -n "$version" ]] || { echo "no version in codeassist_plugin.toml" >&2; exit 1; } - mkdir -p dist - for abi in $ABIS; do - apk="samples/ndk-plugin/build/outputs/apk/release/ndk-plugin-$abi-release.apk" - test -f "$apk" || { echo "no release APK for $abi" >&2; ls samples/ndk-plugin/build/outputs/apk/release >&2; exit 1; } - "$apksigner" verify "$apk" - cp "$apk" "dist/CodeAssist-NDK-Plugin-$version-$abi.apk" - done - "$apksigner" verify --print-certs "dist/CodeAssist-NDK-Plugin-$version-arm64-v8a.apk" | grep -m1 SHA-256 - ls -la dist - echo "version=$version" >> "$GITHUB_OUTPUT" - - - uses: actions/upload-artifact@v4 - with: - name: ndk-plugin-release - path: dist/*.apk - if-no-files-found: error - retention-days: 30 - - - name: Attach to ${{ env.TAG }} - if: env.TAG != '' - env: - GH_TOKEN: ${{ github.token }} - VERSION: ${{ steps.apks.outputs.version }} - run: | - gh release upload "$TAG" dist/*.apk --clobber - base="https://github.com/${GITHUB_REPOSITORY}/releases/download/$TAG" - # The catalog row the Get plugins page reads (Supabase public.plugin_catalog): every ABI's build, and - # the plain link (what older apps read) on arm64. - json="{" - for abi in $ABIS; do - f="dist/CodeAssist-NDK-Plugin-$VERSION-$abi.apk" - json="$json\"$abi\": {\"url\": \"$base/$(basename "$f")\", \"size\": $(stat -c %s "$f")}," - done - json="${json%,}}" - arm64="dist/CodeAssist-NDK-Plugin-$VERSION-arm64-v8a.apk" - { - echo "Attached to [$TAG](https://github.com/${GITHUB_REPOSITORY}/releases/tag/$TAG)." - echo - echo "Catalog update (Supabase SQL editor):" - echo - echo '```sql' - echo "update public.plugin_catalog set" - echo " version = '$VERSION'," - echo " download_url = '$base/$(basename "$arm64")'," - echo " size_bytes = $(stat -c %s "$arm64")," - echo " page_url = 'https://github.com/${GITHUB_REPOSITORY}/releases/tag/$TAG'," - echo " abi_downloads = '$json'::jsonb," - echo " updated_at = now()" - echo "where id = 'dev.codeassist.ndk';" - echo '```' - } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/ndk-toolchain.yml b/.github/workflows/ndk-toolchain.yml deleted file mode 100644 index 92884968e8..0000000000 --- a/.github/workflows/ndk-toolchain.yml +++ /dev/null @@ -1,159 +0,0 @@ -name: NDK toolchain - -# Builds the NDK plugin's on-device compiler (clang + lld + the resident daemon and Run launcher, see -# tools/ndk-toolchain) for each HOST ABI, and publishes it as the prerelease `ndk-toolchain-`, where is -# tools/ndk-toolchain/toolchain-key.sh's hash of the build's sources. The NDK plugin release workflow packages -# that prerelease into the plugin, so a release takes minutes instead of rebuilding LLVM four times. -# -# Each host is a full LLVM build, one to two hours on a hosted runner, so this runs only when the toolchain's -# sources change on main, or by hand. A key that already has a complete build is not built again unless forced. -# -# Assets of the prerelease: -# ndk-toolchain-.tar.gz the executables for a device of that ABI (jniLibs//), one per host ABI -# ndk-toolchain-assets.tar.gz headers, runtime archives and link libraries for all four targets (assets/), -# the same whichever host built them - -on: - push: - branches: [ main ] - paths: - - tools/ndk-toolchain/build-llvm-android.sh - - tools/ndk-toolchain/daemon/** - - tools/ndk-toolchain/toolchain-key.sh - workflow_dispatch: - inputs: - force: - description: Rebuild even if this key already has a complete toolchain - type: boolean - default: false - -permissions: - contents: write - -# One at a time, and never cancelled: a half-published toolchain is the one outcome to avoid. -concurrency: - group: ndk-toolchain - cancel-in-progress: false - -env: - HOST_ABIS: "arm64-v8a armeabi-v7a x86 x86_64" - -jobs: - key: - name: Toolchain key - runs-on: ubuntu-latest - outputs: - key: ${{ steps.key.outputs.key }} - build: ${{ steps.key.outputs.build }} - steps: - - uses: actions/checkout@v4 - - id: key - env: - GH_TOKEN: ${{ github.token }} - FORCE: ${{ inputs.force }} - run: | - key="$(tools/ndk-toolchain/toolchain-key.sh)" - echo "key=$key" >> "$GITHUB_OUTPUT" - have="$(gh release view "ndk-toolchain-$key" --json assets --jq '[.assets[].name] | join(" ")' 2>/dev/null || true)" - missing="" - for abi in $HOST_ABIS assets; do - [[ " $have " == *" ndk-toolchain-$abi.tar.gz "* ]] || missing="$missing $abi" - done - if [[ -z "$missing" && "$FORCE" != "true" ]]; then - echo "build=false" >> "$GITHUB_OUTPUT" - echo "ndk-toolchain-$key is complete; nothing to build." >> "$GITHUB_STEP_SUMMARY" - else - echo "build=true" >> "$GITHUB_OUTPUT" - echo "Building ndk-toolchain-$key (missing:${missing:- none, forced})." >> "$GITHUB_STEP_SUMMARY" - fi - - build: - name: LLVM host ${{ matrix.abi }} - needs: key - if: needs.key.outputs.build == 'true' - runs-on: ubuntu-latest - timeout-minutes: 360 - strategy: - fail-fast: true - matrix: - abi: [ arm64-v8a, armeabi-v7a, x86, x86_64 ] - steps: - - uses: actions/checkout@v4 - - # A hosted runner has about 14 GB free and the LLVM tree plus two build directories want about 13. - - name: Free disk space - run: | - sudo rm -rf /usr/share/dotnet /opt/ghc /usr/local/lib/android /opt/hostedtoolcache/CodeQL - df -h / - - - name: Install the build tools - run: sudo apt-get update -q && sudo apt-get install -y -q ninja-build - - - name: Cache downloads (LLVM source, NDK) - uses: actions/cache@v4 - with: - path: tools/ndk-toolchain/build/dl - key: ndk-toolchain-dl-${{ hashFiles('tools/ndk-toolchain/build-llvm-android.sh') }} - - # `daemon` builds the resident clang (completion, errors, semantic colours) and the Run launcher, a few - # seconds of C against the libclang that `package` staged. - - name: Build LLVM for a ${{ matrix.abi }} host - working-directory: tools/ndk-toolchain - env: - HOST_ABI: ${{ matrix.abi }} - run: ./build-llvm-android.sh deps native cross package daemon - - - name: Check what was built - working-directory: tools/ndk-toolchain/build/out - run: | - for lib in libllvmtools.so libld-gnu-lld.so libLLVM.so libclang.so libc++_shared.so libndkclangd.so libndkrun.so; do - test -f "jniLibs/${{ matrix.abi }}/$lib" || { echo "no $lib for ${{ matrix.abi }}"; exit 1; } - done - test -f assets/toolchain/sysroot/usr/lib/aarch64-linux-android/26/libc.so - du -sh jniLibs/${{ matrix.abi }} assets - - - name: Pack - working-directory: tools/ndk-toolchain/build/out - run: | - mkdir -p "$RUNNER_TEMP/pack" - tar -C "jniLibs/${{ matrix.abi }}" -czf "$RUNNER_TEMP/pack/ndk-toolchain-${{ matrix.abi }}.tar.gz" . - if [[ "${{ matrix.abi }}" == arm64-v8a ]]; then - tar -C assets -czf "$RUNNER_TEMP/pack/ndk-toolchain-assets.tar.gz" . - fi - ls -la "$RUNNER_TEMP/pack" - - - uses: actions/upload-artifact@v4 - with: - name: ndk-toolchain-${{ matrix.abi }} - path: ${{ runner.temp }}/pack/*.tar.gz - if-no-files-found: error - retention-days: 3 - - publish: - name: Publish ndk-toolchain-${{ needs.key.outputs.key }} - needs: [ key, build ] - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/download-artifact@v4 - with: - pattern: ndk-toolchain-* - merge-multiple: true - path: pack - - - name: Publish the prerelease - env: - GH_TOKEN: ${{ github.token }} - TAG: ndk-toolchain-${{ needs.key.outputs.key }} - run: | - ls -la pack - for abi in $HOST_ABIS assets; do test -f "pack/ndk-toolchain-$abi.tar.gz" || { echo "no $abi"; exit 1; }; done - if ! gh release view "$TAG" >/dev/null 2>&1; then - # A prerelease, and never "latest": the app's update check and the README read the latest release. - gh release create "$TAG" --target "$GITHUB_SHA" --prerelease --latest=false \ - --title "NDK toolchain ${{ needs.key.outputs.key }}" \ - --notes "The NDK plugin's on-device compiler, built by the NDK toolchain workflow from $GITHUB_SHA (key ${{ needs.key.outputs.key }}). Not an app release: the NDK plugin release workflow packages these into the plugin." - fi - gh release upload "$TAG" pack/*.tar.gz --clobber - echo "Published $TAG." >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/swift-plugin.yml b/.github/workflows/swift-plugin.yml deleted file mode 100644 index f7093a4ada..0000000000 --- a/.github/workflows/swift-plugin.yml +++ /dev/null @@ -1,201 +0,0 @@ -name: Swift plugin release - -# Builds the Swift plugin (samples/swift-plugin) as one release-signed APK per ABI and attaches them to a CodeAssist -# release as CodeAssist-Swift-Plugin--.apk. -# -# The plugin carries a Swift toolchain that runs ON the device and CodeAssist's SwiftUI engine built for it; neither is -# in the repository, so per ABI: -# 1. toolchain (in the swift:6.4.3 image, the device compiler's own release): tools/swift-sdk/stage_swift.py stages -# Termux's Swift from the packages pinned in packages.lock (our swift-sdk- mirror first), then -# build_swiftui.sh builds libSwiftUI.so and the SwiftUI module against it -# 2. plugin: assembleRelease -Pswift.abi= packages them -# -# Runs when a release is published (tags v*), and by hand: with a tag it attaches to that release, without one it only -# builds, and the APKs are this run's artifacts. By hand it builds the branch it was started on. -# -# Signing uses the IDE's upload key, from the repository secrets RELEASE_KEYSTORE_BASE64, RELEASE_STORE_PASSWORD, -# RELEASE_KEY_ALIAS and RELEASE_KEY_PASSWORD. This workflow never runs for a pull request. - -on: - release: - types: [ published ] - workflow_dispatch: - inputs: - tag: - description: Release tag to attach the APKs to (e.g. v3.50.0); empty to only build - type: string - default: "" - -permissions: - contents: write - -env: - JAVA_VERSION: "25" - REF: ${{ github.event.release.tag_name || github.ref }} - -concurrency: - group: swift-plugin-${{ github.event.release.tag_name || inputs.tag || github.ref }} - cancel-in-progress: false - -jobs: - toolchain: - name: Toolchain ${{ matrix.abi }} - # An app release only: tool mirrors (swift-sdk-*, dart-sdk-*, ...) are prereleases too. - if: github.event_name == 'workflow_dispatch' || startsWith(github.event.release.tag_name, 'v') - runs-on: ubuntu-latest - container: swift:6.4.3 - strategy: - fail-fast: false - matrix: - abi: [ arm64-v8a, armeabi-v7a, x86_64 ] - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ env.REF }} - - # The image has the compiler and ld.lld; the stager needs Python. - - name: Install Python - run: apt-get update -qq && apt-get install -y -qq python3 >/dev/null - - - name: Stage the ${{ matrix.abi }} toolchain - run: python3 -I tools/swift-sdk/stage_swift.py ${{ matrix.abi }} - - - name: Build the SwiftUI engine for ${{ matrix.abi }} - env: - SWIFTUI_IN_CONTAINER: "1" - run: bash tools/swift-sdk/build_swiftui.sh ${{ matrix.abi }} - - - name: Pack - run: tar -C tools/swift-sdk/build/out -cf swift-${{ matrix.abi }}.tar ${{ matrix.abi }} - - - uses: actions/upload-artifact@v4 - with: - name: swift-${{ matrix.abi }} - path: swift-${{ matrix.abi }}.tar - if-no-files-found: error - retention-days: 7 - - plugin: - name: Release APKs - needs: [ toolchain ] - if: ${{ !cancelled() && (github.event_name == 'workflow_dispatch' || startsWith(github.event.release.tag_name, 'v')) }} - runs-on: ubuntu-latest - env: - TAG: ${{ github.event.release.tag_name || inputs.tag }} - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ env.REF }} - - - uses: actions/download-artifact@v4 - with: - pattern: swift-* - path: dl - merge-multiple: true - - - name: Unpack the toolchains - run: | - mkdir -p tools/swift-sdk/build/out - for t in dl/swift-*.tar; do tar -C tools/swift-sdk/build/out -xf "$t"; done - ls tools/swift-sdk/build/out - test -f tools/swift-sdk/build/out/arm64-v8a/jniLibs/arm64-v8a/libSwiftUI.so - - - name: Set up JDK ${{ env.JAVA_VERSION }} - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: ${{ env.JAVA_VERSION }} - - - name: Set up Gradle - uses: gradle/actions/setup-gradle@v4 - - - name: Set up Android SDK - uses: android-actions/setup-android@v3 - with: - packages: "platform-tools platforms;android-36 platforms;android-36.1 build-tools;36.0.0" - - - name: Disable Kotlin incremental compilation (CI) - run: | - mkdir -p ~/.gradle - echo "kotlin.incremental=false" >> ~/.gradle/gradle.properties - - - name: Run the plugin's unit tests - run: ./gradlew :samples:swift-plugin:testDebugUnitTest --console=plain --stacktrace - - # The keystore is written outside the checkout and only for the build step's lifetime. One build per ABI: each - # carries its own toolchain assets, which an ABI split cannot separate. - - name: Build the release APKs - env: - RELEASE_KEYSTORE_BASE64: ${{ secrets.RELEASE_KEYSTORE_BASE64 }} - RELEASE_STORE_PASSWORD: ${{ secrets.RELEASE_STORE_PASSWORD }} - RELEASE_KEY_ALIAS: ${{ secrets.RELEASE_KEY_ALIAS }} - RELEASE_KEY_PASSWORD: ${{ secrets.RELEASE_KEY_PASSWORD }} - run: | - [[ -n "$RELEASE_KEYSTORE_BASE64" ]] || { echo "RELEASE_KEYSTORE_BASE64 is not set: the APKs would be unsigned" >&2; exit 1; } - export RELEASE_STORE_FILE="$RUNNER_TEMP/upload.jks" - echo "$RELEASE_KEYSTORE_BASE64" | base64 -d > "$RELEASE_STORE_FILE" - trap 'rm -f "$RELEASE_STORE_FILE"' EXIT - for abi in $(ls tools/swift-sdk/build/out); do - ./gradlew :samples:swift-plugin:assembleRelease -Pswift.abi="$abi" --console=plain --stacktrace - mkdir -p built && cp samples/swift-plugin/build/outputs/apk/release/swift-plugin-"$abi"-release.apk built/ - done - - - name: Check and name the APKs - id: apks - run: | - apksigner="$(ls -d "$ANDROID_HOME"/build-tools/*/ | sort -V | tail -1)apksigner" - version="$(sed -n 's/^version = "\(.*\)"/\1/p' samples/swift-plugin/src/main/res/raw/codeassist_plugin.toml | head -1)" - [[ -n "$version" ]] || { echo "no version in codeassist_plugin.toml" >&2; exit 1; } - mkdir -p dist - abis="" - for apk in built/swift-plugin-*-release.apk; do - abi="$(basename "$apk")"; abi="${abi#swift-plugin-}"; abi="${abi%-release.apk}" - "$apksigner" verify "$apk" - unzip -l "$apk" "lib/$abi/libswiftfrontend.so" "lib/$abi/libSwiftUI.so" >/dev/null \ - || { echo "$apk lacks the compiler or the SwiftUI engine for $abi" >&2; exit 1; } - cp "$apk" "dist/CodeAssist-Swift-Plugin-$version-$abi.apk" - abis="$abis $abi" - done - ls -la dist - echo "version=$version" >> "$GITHUB_OUTPUT" - echo "abis=${abis# }" >> "$GITHUB_OUTPUT" - - - uses: actions/upload-artifact@v4 - with: - name: swift-plugin-release - path: dist/*.apk - if-no-files-found: error - retention-days: 30 - - - name: Attach to ${{ env.TAG }} - if: env.TAG != '' - env: - GH_TOKEN: ${{ github.token }} - VERSION: ${{ steps.apks.outputs.version }} - ABIS: ${{ steps.apks.outputs.abis }} - run: | - gh release upload "$TAG" dist/*.apk --clobber - base="https://github.com/${GITHUB_REPOSITORY}/releases/download/$TAG" - json="{" - for abi in $ABIS; do - f="dist/CodeAssist-Swift-Plugin-$VERSION-$abi.apk" - json="$json\"$abi\": {\"url\": \"$base/$(basename "$f")\", \"size\": $(stat -c %s "$f")}," - done - json="${json%,}}" - arm64="dist/CodeAssist-Swift-Plugin-$VERSION-arm64-v8a.apk" - { - echo "Attached to [$TAG](https://github.com/${GITHUB_REPOSITORY}/releases/tag/$TAG)." - echo - echo "Catalog row (Supabase SQL editor; insert the first time, update after):" - echo - echo '```sql' - echo "update public.plugin_catalog set" - echo " version = '$VERSION'," - echo " download_url = '$base/$(basename "$arm64")'," - echo " size_bytes = $(stat -c %s "$arm64")," - echo " page_url = 'https://github.com/${GITHUB_REPOSITORY}/releases/tag/$TAG'," - echo " abi_downloads = '$json'::jsonb," - echo " updated_at = now()" - echo "where id = 'dev.codeassist.swift';" - echo '```' - } >> "$GITHUB_STEP_SUMMARY" diff --git a/app/ide-android-e2e/build.gradle.kts b/app/ide-android-e2e/build.gradle.kts index dd4a7fa79f..8f6aac9df1 100644 --- a/app/ide-android-e2e/build.gradle.kts +++ b/app/ide-android-e2e/build.gradle.kts @@ -65,16 +65,13 @@ val stageHelloPlugin = tasks.register("stageHelloPluginApk") { into(layout.buildDirectory.dir("plugin-asset")) } -// CsPluginTest installs the C# plugin the same way. Its .NET toolchain is built outside Gradle -// (tools/dotnet-toolchain), so without one there is nothing worth installing and the test skips itself. -val dotnetToolchainBuilt = rootProject.file("tools/dotnet-toolchain/build/out/arm64-v8a/assets/dotnet-sdk.zip").isFile +// CsPluginTest installs the C# plugin the same way. The plugin lives in tyron12233/codeassist-dotnet-plugin, so +// pass the debug APK built there (with its .NET toolchain) as -Pe2e.dotnetPluginApk=; without one there is +// nothing worth installing and the test skips itself. +val dotnetPluginApk: File? = providers.gradleProperty("e2e.dotnetPluginApk").orNull?.let(::File)?.takeIf { it.isFile } val stageDotnetPlugin = tasks.register("stageDotnetPluginApk") { - onlyIf { dotnetToolchainBuilt } - if (dotnetToolchainBuilt) dependsOn(":samples:dotnet-plugin:assembleDebug") - from(project(":samples:dotnet-plugin").layout.buildDirectory.dir("outputs/apk/debug")) { - include("*.apk") - rename { "dotnet-plugin.apk" } - } + onlyIf { dotnetPluginApk != null } + if (dotnetPluginApk != null) from(dotnetPluginApk) { rename { "dotnet-plugin.apk" } } into(layout.buildDirectory.dir("plugin-asset")) } android.sourceSets.getByName("main").assets.srcDir(layout.buildDirectory.dir("plugin-asset").get().asFile) diff --git a/app/ide-android-e2e/src/main/kotlin/dev/ide/android/e2e/CsPluginTest.kt b/app/ide-android-e2e/src/main/kotlin/dev/ide/android/e2e/CsPluginTest.kt index 0534a7af7d..4c64795124 100644 --- a/app/ide-android-e2e/src/main/kotlin/dev/ide/android/e2e/CsPluginTest.kt +++ b/app/ide-android-e2e/src/main/kotlin/dev/ide/android/e2e/CsPluginTest.kt @@ -10,7 +10,7 @@ import org.junit.Test import org.junit.runner.RunWith /** - * The C# plugin (:samples:dotnet-plugin, bundled into this test APK when its .NET toolchain has been built) + * The C# plugin (tyron12233/codeassist-dotnet-plugin, bundled into this test APK when -Pe2e.dotnetPluginApk names its APK) * compiles and runs a program inside the IDE: the plugin's process launches, the runtime unpacked into the * IDE's storage, Roslyn, and the Run console, none of which a unit test or a shell on the device reaches. */ @@ -38,7 +38,7 @@ class CsPluginTest : E2eTest() { @Test fun consoleAppCompilesAndRuns() { - assumeTrue("needs tools/dotnet-toolchain/build-dotnet-android.sh to have been run", bundled) + assumeTrue("needs -Pe2e.dotnetPluginApk=", bundled) val name = uniqueName("CsCon") createProject("C# Console App", name) @@ -62,7 +62,7 @@ class CsPluginTest : E2eTest() { */ @Test fun editorCompletesAndReportsErrors() { - assumeTrue("needs tools/dotnet-toolchain/build-dotnet-android.sh to have been run", bundled) + assumeTrue("needs -Pe2e.dotnetPluginApk=", bundled) val name = uniqueName("CsEdit") createProject("C# Console App", name) val program = "${projectDir(name)}/Program.cs" @@ -90,7 +90,7 @@ class CsPluginTest : E2eTest() { /** A package named in the project file is fetched from nuget.org, compiled against, and found at run time. */ @Test fun nugetPackageIsRestoredAndUsed() { - assumeTrue("needs tools/dotnet-toolchain/build-dotnet-android.sh to have been run", bundled) + assumeTrue("needs -Pe2e.dotnetPluginApk=", bundled) val name = uniqueName("CsPkg") createProject("C# Console App", name) val dir = projectDir(name) @@ -114,7 +114,7 @@ class CsPluginTest : E2eTest() { */ @Test fun referencedProjectIsBuiltAndUsed() { - assumeTrue("needs tools/dotnet-toolchain/build-dotnet-android.sh to have been run", bundled) + assumeTrue("needs -Pe2e.dotnetPluginApk=", bundled) val name = uniqueName("CsRef") createProject("C# Console App", name) val dir = projectDir(name) @@ -142,7 +142,7 @@ class CsPluginTest : E2eTest() { */ @Test fun xunitTestsRunAndReport() { - assumeTrue("needs tools/dotnet-toolchain/build-dotnet-android.sh to have been run", bundled) + assumeTrue("needs -Pe2e.dotnetPluginApk=", bundled) val name = uniqueName("CsTest") createProject("C# Console App", name) val dir = projectDir(name) @@ -166,7 +166,7 @@ class CsPluginTest : E2eTest() { /** The editor marks a test class in the gutter, and the mark runs the class's tests. */ @Test fun gutterMarkRunsATestClass() { - assumeTrue("needs tools/dotnet-toolchain/build-dotnet-android.sh to have been run", bundled) + assumeTrue("needs -Pe2e.dotnetPluginApk=", bundled) val name = uniqueName("CsMark") createProject("C# Console App", name) val dir = projectDir(name) @@ -193,7 +193,7 @@ class CsPluginTest : E2eTest() { */ @Test fun editorReformatsAndGoesToDeclaration() { - assumeTrue("needs tools/dotnet-toolchain/build-dotnet-android.sh to have been run", bundled) + assumeTrue("needs -Pe2e.dotnetPluginApk=", bundled) val name = uniqueName("CsNav") createProject("C# Console App", name) val dir = projectDir(name) @@ -236,7 +236,7 @@ class CsPluginTest : E2eTest() { */ @Test fun secondProgramInAModuleHasItsOwnRunRow() { - assumeTrue("needs tools/dotnet-toolchain/build-dotnet-android.sh to have been run", bundled) + assumeTrue("needs -Pe2e.dotnetPluginApk=", bundled) val name = uniqueName("CsTwo") createProject("C# Console App", name) val dir = projectDir(name) diff --git a/docs/custom-build-plugins.md b/docs/custom-build-plugins.md index 35ab65268b..c03de7b617 100644 --- a/docs/custom-build-plugins.md +++ b/docs/custom-build-plugins.md @@ -514,7 +514,7 @@ inference and cycle detection. task that runs the program reads `console.io` and streams through it (`stdout`, `stdin`, `started`, `exited`). It is a property, not a constructor parameter, so `RunAction`'s constructor is unchanged; on an older host the setter throws a `LinkageError` and the plugin can fall back to its build log. The NDK plugin's C/C++ Run -(`samples/ndk-plugin`, `NdkRun.kt`) is the worked example. +([codeassist-ndk-plugin](https://github.com/tyron12233/codeassist-ndk-plugin), `NdkRun.kt`) is the worked example. A `BuildSystem` bound to a project offers the same pair through `runTasks(project)` and `actionFor(spec, project, ctx)`, for targets that belong to the pipeline rather than to a module. diff --git a/docs/writing-plugins.md b/docs/writing-plugins.md index 6c926dfb26..fad46ccdb8 100644 --- a/docs/writing-plugins.md +++ b/docs/writing-plugins.md @@ -995,7 +995,7 @@ it is unavailable), and the project model if your language has one (a module typ it look like your language's project: declare its directories as content roots under a `ContentRole` of your own and the Project view shows them (a plugin's roles are surfaced there like the built-in code roots), and a module type no build system builds offers its own Run rows rather than a Build row that cannot work. The -Dart plugin (`samples/dart-plugin`) is a complete example. +Dart plugin ([codeassist-dart-plugin](https://github.com/tyron12233/codeassist-dart-plugin)) is a complete example. How it behaves, so you can plan around it: @@ -1098,7 +1098,7 @@ your provider), then `queued` / `started` / `passed` / `failed` / `skipped` per end, to the console's `ProgramIo.stdout`. Everything else the run prints stays in the console as output. A re-run hands `run` the targets as `suite#test` (or a bare suite), in the names your records used. The Calc sample (`samples/lsp-plugin`, `CalcTestProvider`) is a complete one; the Dart plugin's `DartTestProvider` -(`samples/dart-plugin`) is one for a real test framework. +([codeassist-dart-plugin](https://github.com/tyron12233/codeassist-dart-plugin)) is one for a real test framework. ### Language servers without a plugin diff --git a/samples/dart-plugin/build.gradle.kts b/samples/dart-plugin/build.gradle.kts deleted file mode 100644 index f57abd62ad..0000000000 --- a/samples/dart-plugin/build.gradle.kts +++ /dev/null @@ -1,199 +0,0 @@ -// The Dart plugin: Dart on the device, shipped as its own Android app. -// -// It carries a Dart SDK that RUNS on Android (tools/dart-sdk), one set of executables per ABI. Those bytes are -// NOT in this repository: `tools/dart-sdk/fetch-dart-android.sh` stages them, once per ABI, and this module -// packages whatever that left behind, as one APK per ABI that has anything staged. -// Building the plugin without them produces an APK that installs and reports "no Dart SDK for this device", -// which is what a user on an unsupported ABI sees too. -import java.util.Properties - -plugins { - alias(libs.plugins.android.application) - // The UI facet's Flutter preview pane is a @Composable. - alias(libs.plugins.kotlin.compose) -} - -/** Where `fetch-dart-android.sh` put its output. Override with `-Pdart.sdk.dir=...`. */ -val sdkOut: File = - (providers.gradleProperty("dart.sdk.dir").orNull?.let(::File) ?: rootProject.file("tools/dart-sdk/build/out")) - -val sdkLibs: File = File(sdkOut, "jniLibs") -val sdkAssets: File = File(sdkOut, "assets/dart-sdk") -val generatedAssetsDir: File = layout.buildDirectory.dir("generated/dart-sdk/assets").get().asFile - -/** - * Flutter, from `fetch-flutter.sh`: the engine, the player's bundle, a FLUTTER_ROOT and the base assets. Without - * them the plugin still builds and runs Dart; a Flutter app's Run then says the plugin carries no Flutter. - */ -val flutterOut: File = File(sdkOut, "flutter") - -/** - * The ABIs a Dart SDK was staged for (its `jniLibs/` directories); a Flutter engine alone is no use without - * one. x86 (32-bit) is absent: Termux publishes no Dart for it. - * - * One APK is built for each (see `splits` below), carrying only that ABI's executables, instead of one APK with - * all of them. `-Pdart.abis=arm64-v8a,x86_64` narrows the set; `-Pdart.universalApk` adds the single APK with - * every ABI as well. - */ -val allAbis = listOf("arm64-v8a", "armeabi-v7a", "x86_64") -val stagedAbis: List = (providers.gradleProperty("dart.abis").orNull - ?.split(',')?.map { it.trim() }?.filter { it.isNotEmpty() } ?: allAbis) - .filter { File(sdkLibs, it).isDirectory } - -/** The engine the staged Flutter was built on, which the player's Java embedding has to match. */ -val flutterEngine: String = File(flutterOut, "ENGINE").takeIf { it.isFile }?.readText()?.trim() - ?: "89c39edfdfae2949f6806e4a315c0c08522238b7" // Flutter 3.47.9 - -/** - * Pack the SDK's libraries into ONE archive. The plugin reads it back through its classloader, over the - * installed APK, and a classloader can open a named entry but cannot list a directory, so ~500 loose files - * would be unreachable for want of a way to enumerate them. - */ -val packSdkAssets by tasks.registering(Zip::class) { - from(sdkAssets) - archiveFileName.set("dart-sdk.zip") - destinationDirectory.set(generatedAssetsDir) - // Stored: the APK compresses its own entries, and compressing twice costs build time for nothing. - entryCompression = ZipEntryCompression.STORED - onlyIf { - sdkAssets.isDirectory.also { - if (!it) logger.warn( - "No Dart SDK at $sdkAssets -- the plugin will build without one. Run tools/dart-sdk/fetch-dart-android.sh first." - ) - } - } -} - -/** Pack a staged Flutter directory into one stored asset archive (the classloader can only open named entries). */ -fun packFlutter(taskName: String, dir: String, archive: String) = tasks.register(taskName) { - from(File(flutterOut, dir)) - archiveFileName.set(archive) - destinationDirectory.set(generatedAssetsDir) - entryCompression = ZipEntryCompression.STORED - onlyIf { File(flutterOut, dir).isDirectory } -} -val packFlutterRoot = packFlutter("packFlutterRoot", "root", "flutter-root.zip") -val packFlutterBaseAssets = packFlutter("packFlutterBaseAssets", "base-assets", "flutter-base-assets.zip") -// Release builds' product platform, from fetch-flutter-release.sh, which also stages the release engine and -// gen_snapshot into the jniLibs below. Without them the plugin still builds debug APKs; a release build says why not. -val packFlutterProduct = packFlutter("packFlutterProduct", "product", "flutter-product.zip") - -android { - namespace = "dev.codeassist.dart" - compileSdk = 36 - - defaultConfig { - applicationId = "dev.codeassist.dart" - // The IDE's own floor: this code runs inside the IDE's process. - minSdk = 26 - targetSdk = 36 - versionCode = 4 - versionName = "0.4.0" - } - - // Signed with the IDE's upload key when one is configured (a gitignored keystore.properties at the repo - // root), as the NDK plugin is; with none the release variant is left unsigned. - signingConfigs { - val keystoreProps = Properties().apply { - val f = rootProject.file("keystore.properties") - if (f.exists()) f.inputStream().use { load(it) } - } - fun signingValue(key: String, prop: String, env: String): String? = - keystoreProps.getProperty(key) ?: (findProperty(prop) as String?) ?: System.getenv(env) - - val storeFileResolved = signingValue("storeFile", "RELEASE_STORE_FILE", "RELEASE_STORE_FILE") - ?.let { rootProject.file(it) } - if (storeFileResolved != null && storeFileResolved.exists()) { - create("release") { - storeFile = storeFileResolved - storePassword = signingValue("storePassword", "RELEASE_STORE_PASSWORD", "RELEASE_STORE_PASSWORD") - keyAlias = signingValue("keyAlias", "RELEASE_KEY_ALIAS", "RELEASE_KEY_ALIAS") - keyPassword = signingValue("keyPassword", "RELEASE_KEY_PASSWORD", "RELEASE_KEY_PASSWORD") - } - } - } - - buildTypes { - // Never minify a plugin: the IDE loads the entry points by the names in the packaged manifest. - getByName("debug") { isMinifyEnabled = false } - getByName("release") { - isMinifyEnabled = false - signingConfig = signingConfigs.findByName("release") - } - } - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - // A separate APK for each ABI that has something staged, named like `dart-plugin-arm64-v8a-debug.apk`. - // With nothing staged there is nothing to split, and the build stays a single SDK-less APK. - splits { - abi { - isEnable = stagedAbis.isNotEmpty() - reset() - include(*stagedAbis.toTypedArray()) - isUniversalApk = providers.gradleProperty("dart.universalApk").isPresent - } - } - - sourceSets["main"].jniLibs.srcDir(sdkLibs) - // The engine (libflutter.so), and the player's own bundle as the APK's `flutter_assets`, where the - // Flutter embedding looks for it. - sourceSets["main"].jniLibs.srcDir(File(flutterOut, "jniLibs")) - sourceSets["main"].assets.srcDir(File(flutterOut, "player")) - // Produced by `packSdkAssets`. AGP refuses a Provider here, so the directory is a plain File and the - // ordering is an explicit task dependency below. - sourceSets["main"].assets.srcDir(generatedAssetsDir) - - packaging { - jniLibs { - // The executables have to exist as FILES to be run: left in the APK they are mapped straight out - // of the archive, which serves System.loadLibrary and gives a child process nothing to exec. - useLegacyPackaging = true - // Three of these are AOT snapshots, ELF files the Dart VM loads itself. Stripping them as if they - // were ordinary shared libraries would break them. - keepDebugSymbols += "**/*.so" - } - } -} - -tasks.named("preBuild") { dependsOn(packSdkAssets, packFlutterRoot, packFlutterBaseAssets, packFlutterProduct) } - -// JUnit 5, like the rest of this build. AGP defaults a unit test task to JUnit 4. -tasks.withType().configureEach { useJUnitPlatform() } - -dependencies { - // Compiled against, never bundled: the IDE's classloader is the parent of the plugin's. - compileOnly(project(":plugin-api")) - compileOnly(project(":plugin-ui-api")) - compileOnly(project(":build-api")) - compileOnly(project(":language-api")) - compileOnly(project(":lsp-api")) - compileOnly(project(":project-model-api")) - compileOnly(libs.kotlinx.coroutines.core) - // Reading the test runner's JSON events. Bundled, as the Calc sample bundles it, rather than borrowed - // from the IDE. - implementation(libs.kotlinx.serialization.json) - // The Flutter player (FlutterPlayerActivity), which runs in this plugin's own process, never the IDE's. - implementation("io.flutter:flutter_embedding_debug:1.0.0-$flutterEngine") - - // The IDE's Compose, which the preview pane is composed by. Never bundled. - compileOnly(libs.androidx.compose.runtime) - compileOnly(libs.androidx.compose.foundation) - compileOnly(libs.androidx.compose.ui) - compileOnly(libs.androidx.compose.material3) - - testImplementation(platform(libs.junit.bom)) - testImplementation(libs.junit.jupiter) - testRuntimeOnly(libs.junit.platform.launcher) - testImplementation(project(":plugin-api")) - testImplementation(project(":build-api")) - testImplementation(project(":language-api")) - testImplementation(project(":lsp-api")) - testImplementation(project(":project-model-api")) - testImplementation(libs.kotlinx.coroutines.core) - // The Compose compiler insists on a runtime wherever it compiles, test sources included. - testImplementation(libs.androidx.compose.runtime) -} diff --git a/samples/dart-plugin/src/main/AndroidManifest.xml b/samples/dart-plugin/src/main/AndroidManifest.xml deleted file mode 100644 index 8e1a0f4605..0000000000 --- a/samples/dart-plugin/src/main/AndroidManifest.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartConsoleTemplate.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartConsoleTemplate.kt deleted file mode 100644 index c7c857cb55..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartConsoleTemplate.kt +++ /dev/null @@ -1,97 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.model.BuildSystemId -import dev.ide.model.template.ProjectScaffold -import dev.ide.model.template.ProjectTemplate -import dev.ide.model.template.TemplateArgs -import dev.ide.model.template.TemplateCategory -import dev.ide.model.template.TemplateId -import dev.ide.model.template.TemplateParameter - -/** - * A Dart command-line app, laid out as `dart create -t console` lays one out: the package at the project - * root, `bin/` holding the program, `lib/` the code it imports, `test/` for tests. - * - * It has no dependencies, so the first Run works offline. The program asks a question and waits for the - * answer, on purpose: a prompt that shows before the program reads its input is the thing a console run most - * often gets wrong, and the first run is where to see it work. - */ -class DartConsoleTemplate : ProjectTemplate { - - override val id = TemplateId("dart-console") - override val displayName = "Dart Console App" - override val description = "A Dart command-line program, run on the device with Run. Errors, completion and " + - "quick fixes come from Dart's own analysis server." - override val category = TemplateCategory.OTHER - override val iconId = DartFileIcons.DART - - override fun parameters(): List = emptyList() - - override fun generate(scaffold: ProjectScaffold, args: TemplateArgs) { - val pkg = DartPackages.packageName(args.name) - scaffold.workspace.beginModification().apply { - addProject(args.name, BuildSystemId.NATIVE, scaffold.rootDir) - commit() - } - scaffold.workspace.projects.first { it.name == args.name }.beginModification().apply { - addModule(pkg, scaffold.moduleType(DartModuleType.ID)).apply { - // The package is the project root, where Dart tools (and `git clone` of a Dart repo) put it. - dirRelPath = "" - languageLevel = scaffold.languageLevel - for (dir in listOf("lib", "bin")) addContentRoot("main", dir, setOf(DartModuleType.DART_SOURCE)) - // No test yet (package:test would need the network for the first Run), but where they go. - addContentRoot("test", "test", setOf(DartModuleType.DART_SOURCE)) - } - commit() - } - scaffold.writeText(DartPackages.PUBSPEC, pubspec(pkg)) - scaffold.writeText("bin/$pkg.dart", program(pkg)) - scaffold.writeText("lib/$pkg.dart", library()) - scaffold.writeText(".gitignore", ".dart_tool/\nbuild/\n") - scaffold.writeText("README.md", readme(pkg)) - } - - private fun pubspec(pkg: String) = """ - name: $pkg - description: A command-line application. - version: 1.0.0 - publish_to: none - - environment: - sdk: ^3.9.0 - """.trimIndent() + "\n" - - private fun program(pkg: String) = """ - import 'dart:io'; - - import 'package:$pkg/$pkg.dart'; - - void main(List arguments) { - stdout.write('What is your name? '); - final name = stdin.readLineSync()?.trim() ?? ''; - if (name.isEmpty) { - print('No name given.'); - exitCode = 1; - return; - } - print(greet(name)); - } - """.trimIndent() + "\n" - - private fun library() = """ - /// The greeting for [name]. - String greet(String name) => 'Hello, ${'$'}name! This program ran on your device.'; - """.trimIndent() + "\n" - - private fun readme(pkg: String) = """ - # $pkg - - A Dart program, run on the device by the Dart SDK inside the Dart plugin. - - - `bin/$pkg.dart` is the program. Press Run: its output appears in the Run console, and what you type - there is its standard input. Every `.dart` file in `bin/` gets a Run entry of its own. - - `lib/` holds the code the program imports as `package:$pkg/...`. - - Add packages in `pubspec.yaml`, then pick `pub get` in the Run menu (Run also does it when the - pubspec changed). - """.trimIndent() + "\n" -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartFileIcons.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartFileIcons.kt deleted file mode 100644 index 09b6046bca..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartFileIcons.kt +++ /dev/null @@ -1,26 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.model.FileIconProvider -import dev.ide.model.IconTarget - -/** - * What a `.dart` file looks like in the tree, on tabs and in breadcrumbs. The tree asks the engine - * ([DartFileIconProvider]); tabs and breadcrumbs resolve the id in the UI layer, which [DartUiPlugin] - * registers the art for. Without both, a Dart file is drawn as the generic grey document. - */ -object DartFileIcons { - const val DART = "dart.file" - val SUFFIXES = listOf(".dart") - - fun idFor(fileName: String): String? = if (SUFFIXES.any { fileName.lowercase().endsWith(it) }) DART else null -} - -/** The engine half. Above the built-in fallback (0), below android-support (100). */ -object DartFileIconProvider : FileIconProvider { - override val priority: Int get() = 50 - - override fun iconFor(target: IconTarget): String? = when (target) { - is IconTarget.File -> DartFileIcons.idFor(target.fileName) - else -> null - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartLanguageServer.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartLanguageServer.kt deleted file mode 100644 index 00e45df4ef..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartLanguageServer.kt +++ /dev/null @@ -1,76 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.lang.LanguageId -import dev.ide.lsp.LanguageServerConnection -import dev.ide.lsp.LanguageServerContext -import dev.ide.lsp.LanguageServerDefinition -import dev.ide.platform.log.Logger -import java.nio.file.Files -import java.nio.file.Path - -/** - * Dart's analysis server, the one `dart language-server` starts, run straight from its snapshot. - * - * One server per package ([rootFor] is the directory holding the nearest `pubspec.yaml`), which is how the - * Dart tools scope analysis. A package that never had `pub get` gets one before the server starts, because - * without its package config every `package:` import is an error. - */ -class DartLanguageServer(private val sdk: DartSdk, private val pub: Pub, private val log: Logger) : LanguageServerDefinition { - override val id = "dart" - override val displayName = "Dart analysis server" - override val languages = setOf(LanguageId(DartPlugin.LANGUAGE)) - - override fun start(context: LanguageServerContext): LanguageServerConnection? { - val status = sdk.prepare() - if (status is DartSdk.Status.Unavailable) { - log.warn(status.reason) - return null - } - val runtime = sdk.runtime ?: return null - val server = sdk.analysisServer ?: return null - if (Files.isRegularFile(context.root.resolve(DartPackages.PUBSPEC)) && DartPackages.needsPubGet(context.root)) { - // Best effort: offline, or a dependency that does not resolve, still leaves a server worth having. - val result = pub.run(context.root, "get", timeoutSeconds = 120) { line -> context.logger.info("pub: $line") } - if (result != 0) context.logger.warn("pub get exited with $result; package imports may not resolve") - } - return LanguageServerConnection.process( - listOf(runtime.toString()) + DartSdk.VM_TUNING + listOf( - server.toString(), - "--protocol=lsp", - "--dart-sdk=${sdk.sdkDir}", - "--client-id=codeassist", - "--cache=${sdk.home.resolve("analysis-cache")}", - ), - context.root, - sdk.environment(), - ) - } - - /** - * Only the packages with an open file are analysed, which is what keeps the server's memory proportional - * to what the user is looking at on a phone. Completion offers what is not imported yet, with the import. - */ - override fun initializationOptions(context: LanguageServerContext): String = - """{"onlyAnalyzeProjectsWithOpenFiles":true,"suggestFromUnimportedLibraries":true,"closingLabels":false,"outline":false,"flutterOutline":false}""" - - /** - * The server's client settings, which it asks for (`workspace/configuration`, section `dart`) once it is up. - * `completeFunctionCalls` makes completing a function insert its call, `print(object)`, with the arguments as - * snippet placeholders, rather than the bare name. It is off unless the client turns it on. - */ - override fun configuration(section: String?, context: LanguageServerContext): String? = settings(section) - - override fun rootFor(file: Path, context: LanguageServerContext): Path? = - DartPackages.packageRootOf(file, context.projectRoot) - - companion object { - private const val DART_SETTINGS = """{"completeFunctionCalls":true}""" - - /** The answer for [section]: the `dart` settings, all of them for no section, nothing for any other. */ - fun settings(section: String?): String? = when (section) { - "dart" -> DART_SETTINGS - null -> """{"dart":$DART_SETTINGS}""" - else -> null - } - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartLex.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartLex.kt deleted file mode 100644 index 55df5e58e7..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartLex.kt +++ /dev/null @@ -1,74 +0,0 @@ -package dev.codeassist.dart - -/** - * Just enough of Dart's lexical structure to scan source for declarations without a parser: where comments - * and strings end, so a `test(` or an `@Preview` inside one is not taken for code, and matching brackets. - */ -internal object DartLex { - /** Past a comment or string starting at [i], or [i] itself when neither starts there. */ - fun skipNonCode(text: String, i: Int): Int { - if (text.startsWith("//", i)) return text.indexOf('\n', i).let { if (it < 0) text.length else it } - if (text.startsWith("/" + "*", i)) { - var depth = 0 - var j = i - while (j < text.length) { - if (text.startsWith("/" + "*", j)) { depth++; j += 2; continue } - if (text.startsWith("*" + "/", j)) { depth--; j += 2; if (depth == 0) return j; continue } - j++ - } - return text.length - } - val raw = text[i] == 'r' && i + 1 < text.length && (text[i + 1] == '\'' || text[i + 1] == '"') && - (i == 0 || !(text[i - 1].isLetterOrDigit() || text[i - 1] == '_')) - val q = if (raw) i + 1 else i - if (q >= text.length || (text[q] != '\'' && text[q] != '"')) return i - return stringEnd(text, q, raw) - } - - /** The index past the string literal whose opening quote is at [q]. */ - fun stringEnd(text: String, q: Int, raw: Boolean): Int { - val quote = text[q] - val triple = text.startsWith("$quote$quote$quote", q) - val close = if (triple) "$quote$quote$quote" else "$quote" - var j = q + close.length - while (j < text.length) { - if (!raw && text[j] == '\\') { j += 2; continue } - if (text.startsWith(close, j)) return j + close.length - if (!triple && text[j] == '\n') return j // unterminated: stop at the line's end - j++ - } - return text.length - } - - /** The index of the `)` matching the `(` at [open], skipping strings and comments; the text's end if none. */ - fun matchParen(text: String, open: Int): Int { - var depth = 0 - var i = open - while (i < text.length) { - val skipped = skipNonCode(text, i) - if (skipped != i) { i = skipped; continue } - when (text[i]) { - '(' -> depth++ - ')' -> { depth--; if (depth == 0) return i } - } - i++ - } - return text.length - } - - /** The index of the `}` matching the `{` at [open], skipping strings and comments; the text's end if none. */ - fun matchBrace(text: String, open: Int): Int { - var depth = 0 - var i = open - while (i < text.length) { - val skipped = skipNonCode(text, i) - if (skipped != i) { i = skipped; continue } - when (text[i]) { - '{' -> depth++ - '}' -> { depth--; if (depth == 0) return i } - } - i++ - } - return text.length - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartPlugin.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartPlugin.kt deleted file mode 100644 index 772506c006..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartPlugin.kt +++ /dev/null @@ -1,79 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.build.ANDROID_RUN_PARTICIPANT_EP -import dev.ide.build.BUILD_PLUGIN_EP -import dev.ide.build.RUN_TASK_PROVIDER_EP -import dev.ide.build.TEST_PROVIDER_EP -import dev.ide.lang.FILE_TYPE_EP -import dev.ide.lang.FileTypeMapping -import dev.ide.lang.LanguageId -import dev.ide.lsp.LANGUAGE_SERVER_EP -import dev.ide.model.FACET_CODEC_EP -import dev.ide.model.FileIconExtensionPoint -import dev.ide.model.ModuleTypeExtensionPoint -import dev.ide.model.sync.PROJECT_IMPORTER_EP -import dev.ide.model.template.ProjectTemplateExtensionPoint -import dev.ide.platform.notify.USER_MESSAGES -import dev.ide.plugin.Plugin -import dev.ide.plugin.PluginRegistration - -/** - * The engine facet: Dart as a language (the analysis server), as a kind of project (a pub package), and as - * something to run. - * - * `register` runs at startup and does not touch the SDK: unpacking it is for the first thing that needs - * Dart (opening a `.dart` file, or Run), not for the way to the IDE's first frame. - */ -class DartPlugin : Plugin { - - override fun register(reg: PluginRegistration) { - val log = reg.logger("DartPlugin") - val sdk = DartSdk(reg, log, reg.appServices.getServiceOrNull(USER_MESSAGES)) - val flutter = FlutterSdk(reg, sdk, reg.logger("Flutter")) - val pub = Pub(sdk, flutter) - tools = Tools(sdk, flutter, pub, reg.logger("FlutterPreview"), reg.messageBus) - - reg.register(FILE_TYPE_EP, FileTypeMapping(DartFileIcons.SUFFIXES, LanguageId(LANGUAGE))) - reg.register(LANGUAGE_SERVER_EP, DartLanguageServer(sdk, pub, reg.logger("DartServer"))) - - reg.register(ModuleTypeExtensionPoint, DartModuleType) - reg.register(ProjectTemplateExtensionPoint, DartConsoleTemplate()) - reg.register(ProjectTemplateExtensionPoint, FlutterAppTemplate()) - reg.register(PROJECT_IMPORTER_EP, PubImporter) - reg.register(FileIconExtensionPoint, DartFileIconProvider) - - reg.register(RUN_TASK_PROVIDER_EP, DartRunTaskProvider(sdk, pub, flutter)) - reg.register(TEST_PROVIDER_EP, DartTestProvider(sdk, pub)) - - // A Flutter app's APK: its `android/app` module carries a [flutter] table naming the package, and the - // module's ordinary Android build compiles that package and packages it with the engine. - reg.register(FACET_CODEC_EP, FlutterFacetCodec) - reg.register(BUILD_PLUGIN_EP, FlutterBuildPlugin(sdk, flutter, pub, reg.logger("FlutterBuild"))) - // Run Debug on that module is `flutter run`: the app's own APK, attached for hot reload. - reg.register(ANDROID_RUN_PARTICIPANT_EP, FlutterRunParticipant(sdk, flutter, pub)) - log.info("registered; the Dart SDK is prepared on first use") - } - - /** What the UI facet's preview pane and the Flutter runs share: the SDKs the engine facet prepared, the bus. */ - class Tools( - val sdk: DartSdk, - val flutter: FlutterSdk, - val pub: Pub, - val log: dev.ide.platform.log.Logger, - /** The app's bus, where editor saves are announced ([PackageWatcher]). */ - val bus: dev.ide.platform.MessageBus, - ) - - companion object { - /** - * Set by [register], read by the UI facet ([FlutterPreviewPane]). The two facets are loaded by one - * classloader, so they share this. - */ - @Volatile - var tools: Tools? = null - private set - - /** The language id, shared by the file-type mapping, the editor profile and the language server. */ - const val LANGUAGE = "dart" - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartPreviews.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartPreviews.kt deleted file mode 100644 index 098aca277e..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartPreviews.kt +++ /dev/null @@ -1,298 +0,0 @@ -package dev.codeassist.dart - -import java.nio.file.Files -import java.nio.file.Path -import java.util.stream.Collectors - -/** - * Flutter's `@Preview` widgets (`package:flutter/widget_previews.dart`) in an app's `lib/`, and the gallery - * app that shows them all, which the preview Run starts in the player and hot-reloads like the app itself. - * - * A preview is what Flutter's own previewer takes: a public top-level function, static method, or widget - * constructor (or factory) with no required arguments, returning a `Widget` or a `WidgetBuilder`, annotated - * `@Preview(...)`. Its arguments are copied into the gallery as they are written, which is sound because - * they must be constants and public references. - */ -object DartPreviews { - - /** One preview: where it is, how to call it, its annotation's arguments as written. */ - data class Found( - /** The library, `package:app/widgets/card.dart`. */ - val library: String, - /** The call that builds it, without a prefix: `cardPreview()`, `Card.preview()`, `Card()`. */ - val call: String, - /** What it is called in the gallery when the annotation names nothing. */ - val label: String, - /** The annotation's arguments, the text between its parentheses. */ - val arguments: String, - /** It returns a `WidgetBuilder`, to be called with a context. */ - val builder: Boolean, - /** The line it is declared on, 1-based. */ - val line: Int, - ) - - /** Every preview under [pkg]'s `lib/`, for the package named [name]. */ - fun find(pkg: Path, name: String): List { - val lib = pkg.resolve("lib") - if (!Files.isDirectory(lib)) return emptyList() - val files = Files.walk(lib).use { w -> - w.filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(".dart") }.collect(Collectors.toList()) - }.sorted() - return files.flatMap { file -> - val text = runCatching { String(Files.readAllBytes(file)) }.getOrDefault("") - if (!isLibraryWithPreviews(text)) return@flatMap emptyList() - val library = "package:$name/" + lib.relativize(file).joinToString("/") { it.toString() } - scan(text).map { it.copy(library = library) } - } - } - - /** Whether [text] can hold previews the gallery can import: it mentions one and is a library, not a `part`. */ - fun isLibraryWithPreviews(text: String): Boolean = - text.contains("@Preview") && !Regex("""(?m)^\s*part\s+of\b""").containsMatchIn(text) - - /** The previews declared in one library's [text] (their [Found.library] is left blank). */ - fun scan(text: String): List { - val classes = classRanges(text) - val out = ArrayList() - var i = 0 - while (i < text.length) { - val skipped = DartLex.skipNonCode(text, i) - if (skipped != i) { i = skipped; continue } - if (text.startsWith("@Preview", i) && !isIdent(text.getOrNull(i + 8)) && !isIdent(text.getOrNull(i - 1))) { - var k = skipSpace(text, i + 8) - if (k < text.length && text[k] == '(') { - val close = DartLex.matchParen(text, k) - val arguments = text.substring(k + 1, close.coerceAtMost(text.length)).trim() - declaration(text, close + 1, classes)?.let { (call, label, builder, at) -> - out += Found("", call, label, arguments, builder, text.substring(0, at).count { it == '\n' } + 1) - } - i = close + 1 - continue - } - } - i++ - } - return out - } - - /** - * The declaration an annotation ending before [from] annotates: past any other annotations, the header up - * to its parameter list. Null when it is not something a preview can be (private, or not recognisable). - */ - private fun declaration(text: String, from: Int, classes: List>): Quad? { - var i = from - while (true) { - i = skipSpace(text, i) - val skipped = DartLex.skipNonCode(text, i) - if (skipped != i) { i = skipped; continue } - if (i < text.length && text[i] == '@') { - // Another annotation: its name, and its arguments if it has any. - i++ - while (i < text.length && (isIdent(text[i]) || text[i] == '.')) i++ - val k = skipSpace(text, i) - if (k < text.length && text[k] == '(') i = DartLex.matchParen(text, k) + 1 - continue - } - break - } - val paren = text.indexOf('(', i).takeIf { it > 0 } ?: return null - val header = text.substring(i, paren).trim() - if (header.isEmpty() || header.contains('{') || header.contains(';') || header.contains('=')) return null - val words = header.split(Regex("\\s+")).filter { it !in MODIFIERS } - val owner = classes.lastOrNull { (_, range) -> i in range }?.first - val name = words.lastOrNull() ?: return null - if (name.split('.').any { it.startsWith("_") }) return null - return when { - // A constructor or factory: the class's own name, or its name and a constructor name. - words.size == 1 && owner != null && name.substringBefore('.') == owner -> - Quad("$name()", name, false, i) - words.size >= 2 -> { - val returnType = words.dropLast(1).joinToString(" ").removeSuffix("?") - val builder = returnType == "WidgetBuilder" - if (returnType != "Widget" && !builder) return null - val isStatic = header.split(Regex("\\s+")).contains("static") - when { - owner == null -> Quad("$name()", name, builder, i) - isStatic && !owner.startsWith("_") -> Quad("$owner.$name()", "$owner.$name", builder, i) - else -> null // an instance method: not something a preview can be - } - } - else -> null - } - } - - private data class Quad(val call: String, val label: String, val builder: Boolean, val at: Int) - - /** Each class (mixin, extension type) declared in [text] and the range of its body. */ - private fun classRanges(text: String): List> { - val out = ArrayList>() - val decl = Regex("""\b(?:class|mixin)\s+([A-Za-z_$][A-Za-z0-9_$]*)""") - var i = 0 - while (i < text.length) { - val skipped = DartLex.skipNonCode(text, i) - if (skipped != i) { i = skipped; continue } - val m = decl.matchAt(text, i) - if (m != null && !isIdent(text.getOrNull(i - 1))) { - val open = text.indexOf('{', m.range.last) - if (open > 0) { - out += m.groupValues[1] to (open..DartLex.matchBrace(text, open)) - i = open + 1 - continue - } - } - i++ - } - return out - } - - private fun skipSpace(text: String, from: Int): Int { - var i = from - while (i < text.length && text[i].isWhitespace()) i++ - return i - } - - private fun isIdent(c: Char?) = c != null && (c.isLetterOrDigit() || c == '_' || c == '$') - - private val MODIFIERS = setOf("static", "const", "factory", "external") - - /** - * The gallery app: every preview, grouped as their annotations say, each sized and themed as Flutter's - * previewer would (half the screen's height unless the preview gives a size), on a list. - * - * [pane] is the editor's preview pane, which has a title of its own, so the gallery drops its app bar. - * [dark] is the scheme to show it in, when it should not follow the device's. [empty] is what it says - * when there is nothing to show. - */ - fun gallery( - previews: List, - pane: Boolean = false, - dark: Boolean? = null, - empty: String = "No @Preview widgets in lib/ yet.", - ): String = buildString { - appendLine("// Generated by CodeAssist from the app's @Preview widgets. Do not edit: it is rewritten on every save.") - appendLine("import 'package:flutter/material.dart';") - appendLine("import 'package:flutter/widget_previews.dart';") - val libraries = previews.map { it.library }.distinct() - // Unprefixed, so an annotation's arguments resolve as they did where they were written; prefixed for - // the calls, so two libraries' previews of the same name do not collide. - libraries.forEachIndexed { n, lib -> appendLine("import ${quote(lib)};"); appendLine("import ${quote(lib)} as p$n;") } - appendLine() - // A getter, not a final: a hot reload keeps a global's value once it has been read, so a list built once - // would show the previews as they were when the gallery started. - appendLine("List<_Entry> get _previews => <_Entry>[") - for (p in previews) { - val prefix = "p${libraries.indexOf(p.library)}" - val build = if (p.builder) "(context) => $prefix.${p.call}(context)" else "(context) => $prefix.${p.call}" - appendLine(" _Entry(${quote(p.label)}, ${quote(p.library.substringAfter('/'))}, ${p.line}, const Preview(${p.arguments}), $build),") - } - appendLine("];") - // Getters for the same reason: a hot reload has to see these change. - appendLine("bool get _inPane => $pane;") - appendLine("Brightness? get _brightness => ${when (dark) { true -> "Brightness.dark"; false -> "Brightness.light"; null -> "null" }};") - appendLine("String get _empty => ${quote(empty)};") - append(GALLERY) - } - - /** Write a gallery's [source] to [file] unless it already holds exactly that. Answers whether it changed. */ - fun write(file: Path, source: String): Boolean { - Files.createDirectories(file.parent) - val before = runCatching { String(Files.readAllBytes(file)) }.getOrNull() - if (before == source) return false - Files.write(file, source.toByteArray()) - return true - } - - private fun quote(s: String) = "'" + s.replace("\\", "\\\\").replace("'", "\\'").replace("$", "\\$") + "'" - - private val GALLERY = """ - - void main() => runApp(const _Gallery()); - - class _Entry { - const _Entry(this.label, this.file, this.line, this.preview, this.build); - final String label; - final String file; - final int line; - final Preview preview; - final WidgetBuilder build; - } - - class _Gallery extends StatelessWidget { - const _Gallery(); - - @override - Widget build(BuildContext context) { - final groups = >{}; - for (final e in _previews) { - groups.putIfAbsent(e.preview.group, () => <_Entry>[]).add(e); - } - return MaterialApp( - debugShowCheckedModeBanner: false, - title: 'Previews', - theme: ThemeData(colorSchemeSeed: Colors.blueGrey, brightness: _brightness ?? MediaQuery.platformBrightnessOf(context)), - home: Scaffold( - appBar: _inPane ? null : AppBar(title: Text('Previews (${'$'}{_previews.length})')), - body: _previews.isEmpty - ? Center(child: Padding(padding: const EdgeInsets.all(24), child: Text(_empty, textAlign: TextAlign.center))) - : ListView( - padding: const EdgeInsets.all(12), - children: [ - for (final group in groups.entries) ...[ - if (groups.length > 1) - Padding( - padding: const EdgeInsets.fromLTRB(4, 12, 4, 4), - child: Text(group.key, style: Theme.of(context).textTheme.titleMedium), - ), - for (final e in group.value) _PreviewCard(entry: e), - ], - ], - ), - ), - ); - } - } - - class _PreviewCard extends StatelessWidget { - const _PreviewCard({required this.entry}); - final _Entry entry; - - @override - Widget build(BuildContext context) { - final preview = entry.preview; - final screen = MediaQuery.sizeOf(context); - Widget child = Builder(builder: entry.build); - if (preview.wrapper != null) child = preview.wrapper!(child); - if (preview.theme != null) { - final theme = preview.theme!(); - child = Builder(builder: (context) => theme.apply(context, child)); - } - final media = MediaQuery.of(context); - child = MediaQuery( - data: media.copyWith( - platformBrightness: preview.brightness ?? _brightness ?? media.platformBrightness, - textScaler: preview.textScaleFactor == null ? media.textScaler : TextScaler.linear(preview.textScaleFactor!), - ), - child: child, - ); - final size = preview.size; - final width = size?.width == double.infinity ? null : size?.width; - final height = size?.height == double.infinity ? null : (size?.height ?? screen.height / 2); - return Card( - clipBehavior: Clip.antiAlias, - margin: const EdgeInsets.symmetric(vertical: 6), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - ListTile( - dense: true, - title: Text(preview.name ?? entry.label), - subtitle: Text('${'$'}{entry.file}:${'$'}{entry.line}'), - ), - ClipRect(child: Center(child: SizedBox(width: width, height: height, child: child))), - ], - ), - ); - } - } - """.trimIndent() + "\n" -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartProject.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartProject.kt deleted file mode 100644 index 2b76d7f61b..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartProject.kt +++ /dev/null @@ -1,136 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.model.BuildSystemId -import dev.ide.model.ContentRole -import dev.ide.model.DependencyScope -import dev.ide.model.FacetTemplate -import dev.ide.model.ModuleType -import dev.ide.model.PlatformKind -import dev.ide.model.SourceSetTemplate -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.contentOrNull -import kotlinx.serialization.json.jsonObject -import java.net.URI -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths -import java.util.stream.Collectors - -/** - * A Dart package as a module: its directory is the package (where `pubspec.yaml` is), and its content roots - * are the directories Dart tools give a meaning to (`lib/`, `bin/`, `test/`, and `example/` and `tool/` when - * they exist), under one role of this plugin's own. The Project view shows them with the pubspec beside - * them, as Dart tools lay a package out, rather than as JVM source roots it does not have. - */ -object DartModuleType : ModuleType { - const val ID = "dart-package" - - override val id = ID - override val displayName = "Dart package" - override val platform: PlatformKind get() = DART_PLATFORM - override fun defaultSourceSets(): List = listOf( - SourceSetTemplate("main", DependencyScope.IMPLEMENTATION, mapOf("lib" to setOf(DART_SOURCE), "bin" to setOf(DART_SOURCE))), - SourceSetTemplate("test", DependencyScope.TEST_IMPLEMENTATION, mapOf("test" to setOf(DART_SOURCE))), - ) - override fun defaultFacets(): List = emptyList() - override fun supportedBuildSystems(): Set = setOf(BuildSystemId.NATIVE, PUB) - - /** A directory of Dart code in a package. Not a Java source root: nothing JVM-shaped reads it. */ - val DART_SOURCE = ContentRole("dart-source") - - /** Dart compiles against its own SDK, never android.jar or a JDK. */ - val DART_PLATFORM = PlatformKind("DART") - - /** The build system an imported pub package is read by ([PubImporter]). */ - val PUB = BuildSystemId("pub") -} - -/** What the plugin needs to know about a package on disk. Pure file reads; nothing here runs Dart. */ -object DartPackages { - const val PUBSPEC = "pubspec.yaml" - const val PACKAGE_CONFIG = ".dart_tool/package_config.json" - - /** The nearest directory at or above [file] holding a `pubspec.yaml`, stopping at [limit]. */ - fun packageRootOf(file: Path, limit: Path): Path? { - var dir: Path? = if (Files.isDirectory(file)) file else file.parent - while (dir != null && dir.startsWith(limit)) { - if (Files.isRegularFile(dir.resolve(PUBSPEC))) return dir - dir = dir.parent - } - return null - } - - /** The package's `name:` from its pubspec text, or null when it has none. */ - fun nameOf(pubspec: String): String? = - Regex("""(?m)^name:\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*(?:#.*)?$""").find(pubspec)?.groupValues?.get(1) - - /** - * A valid package name made from a free-form project name: lowercase words joined by underscores, as pub - * requires (`My App` -> `my_app`), never starting with a digit. - */ - fun packageName(raw: String): String { - val words = Regex("[A-Za-z0-9]+").findAll( - // Split camelCase too: `HelloWorld` -> `hello_world`. - raw.replace(Regex("([a-z0-9])([A-Z])"), "$1 $2"), - ).map { it.value.lowercase() }.toList() - val name = words.joinToString("_").ifEmpty { "app" } - return if (name.first().isDigit()) "app_$name" else name - } - - /** - * Whether `pub get` has to run before [pkg] can be compiled or analysed: it never has, `pubspec.yaml` or - * `pubspec.lock` changed since it last did, or a package the config names is no longer on disk. A package - * importing itself (`package:name/...`) needs the package config even with no dependencies at all. - */ - fun needsPubGet(pkg: Path): Boolean { - val config = pkg.resolve(PACKAGE_CONFIG) - if (!Files.isRegularFile(config)) return true - val configAt = Files.getLastModifiedTime(config).toMillis() - val changed = listOf(PUBSPEC, "pubspec.lock").any { name -> - val f = pkg.resolve(name) - Files.isRegularFile(f) && Files.getLastModifiedTime(f).toMillis() > configAt - } - // The config names packages by their folder in the pub cache. With that folder gone (the cache or the - // plugin's data cleared) a newer config still compiled against nothing: thousands of errors inside - // Flutter itself, its `meta` and `vector_math` missing. - return changed || packages(pkg).any { (_, root) -> !Files.isDirectory(root) } - } - - /** Package name to root directory, from `.dart_tool/package_config.json`. */ - fun packages(pkg: Path): List> { - val configFile = pkg.resolve(PACKAGE_CONFIG) - val text = runCatching { String(Files.readAllBytes(configFile)) }.getOrNull() ?: return emptyList() - val config = runCatching { Json.parseToJsonElement(text).jsonObject }.getOrNull() ?: return emptyList() - val base = configFile.parent.toUri() - return (config["packages"] as? JsonArray).orEmpty().mapNotNull { e -> - val o = e as? JsonObject ?: return@mapNotNull null - val name = (o["name"] as? JsonPrimitive)?.contentOrNull ?: return@mapNotNull null - val rootUri = (o["rootUri"] as? JsonPrimitive)?.contentOrNull ?: return@mapNotNull null - val resolved = runCatching { Paths.get(base.resolve(URI(if (rootUri.endsWith("/")) rootUri else "$rootUri/"))) } - .getOrNull() ?: return@mapNotNull null - name to resolved.normalize() - } - } - - /** - * The content roots of the package at [pkg], by source set: `lib/` and `test/` always (where a package's - * code and tests go, so the Project view shows them as soon as they exist; it skips a root that does not), - * the other conventional directories when they are there. - */ - fun contentRoots(pkg: Path): Map> { - val main = listOf("lib") + listOf("bin", "example", "tool").filter { Files.isDirectory(pkg.resolve(it)) } - return linkedMapOf("main" to main, "test" to listOf("test")) - } - - /** The programs a package offers to run: the `.dart` files directly in `bin/`, as pub does, sorted. */ - fun executables(pkg: Path): List { - val bin = pkg.resolve("bin") - if (!Files.isDirectory(bin)) return emptyList() - return Files.list(bin).use { s -> - s.filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(".dart") }.collect(Collectors.toList()) - }.sortedBy { it.fileName.toString() } - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartRun.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartRun.kt deleted file mode 100644 index e3a646fc85..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartRun.kt +++ /dev/null @@ -1,315 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.build.AlwaysRun -import dev.ide.build.BuildContext -import dev.ide.build.ProgramIo -import dev.ide.build.RunAction -import dev.ide.build.RunConsole -import dev.ide.build.RunTaskProvider -import dev.ide.build.RunTaskSpec -import dev.ide.build.Task -import dev.ide.build.TaskContext -import dev.ide.build.TaskGraph -import dev.ide.build.TaskInputs -import dev.ide.build.TaskInputsImpl -import dev.ide.build.TaskName -import dev.ide.build.TaskOutputs -import dev.ide.build.TaskOutputsImpl -import dev.ide.build.TaskResult -import dev.ide.model.Module -import dev.ide.model.Project -import java.io.IOException -import java.io.InputStream -import java.io.OutputStream -import java.nio.ByteBuffer -import java.nio.CharBuffer -import java.nio.charset.CodingErrorAction -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths - -/** - * The Run picker's Dart rows: "Run " for each `.dart` file directly in a Dart package's `bin/`, and `pub get` / - * `pub upgrade`. - * - * A run is three steps: `pub get` when the package config is missing or older than the pubspec, compile the - * program to kernel with the SDK's kernel compiler, and run that on the JIT VM in the Run console. It is not - * `dart run`, which cannot work from an installed app: it looks for its compilers beside the runtime's real - * path, the read-only native library directory. - */ -class DartRunTaskProvider(private val sdk: DartSdk, private val pub: Pub, private val flutter: FlutterSdk) : RunTaskProvider { - - override fun tasksFor(module: Module): List { - if (module.type.id != DartModuleType.ID) return emptyList() - val pkg = Paths.get(module.dir.path) - // A Flutter app runs in the player, hot-reloading; its bin/ (if any) is not what Run means. - val runs = if (FlutterSdk.isFlutterPackage(pkg)) { - listOf( - RunTaskSpec("$FLUTTER_PREFIX${module.name}", "Run Flutter app · ${module.name}", "run"), - RunTaskSpec("$PREVIEW_PREFIX${module.name}", "Preview widgets · ${module.name}", "run"), - ) - } else DartPackages.executables(pkg).map { file -> - RunTaskSpec("$RUN_PREFIX${module.name}:${pkg.relativize(file)}", "Run ${file.fileName}", "run") - } - return runs + listOf( - RunTaskSpec("$PUB_PREFIX${module.name}:get", "pub get · ${module.name}", "build"), - RunTaskSpec("$PUB_PREFIX${module.name}:upgrade", "pub upgrade · ${module.name}", "build"), - ) - } - - override fun actionFor(spec: RunTaskSpec, project: Project, module: Module, ctx: BuildContext): RunAction? { - val pkg = Paths.get(module.dir.path) - if (spec.id.startsWith("$PUB_PREFIX${module.name}:")) { - val command = spec.id.substringAfterLast(':').takeIf { it == "get" || it == "upgrade" } ?: return null - val task = PubTask(TaskName(":${module.name}:pub${command.replaceFirstChar(Char::uppercaseChar)}"), pkg, pub, command, onlyIfNeeded = false) - return RunAction("> dart pub $command", LinearGraph(listOf(task))) - } - if (spec.id == "$PREVIEW_PREFIX${module.name}") { - val console = RunConsole("${module.name} previews") - val task = FlutterRunTask(TaskName(":${module.name}:flutterPreview"), pkg, sdk, flutter, pub, console, preview = true) - return RunAction("> Flutter previews ${module.name}", LinearGraph(listOf(task))).also { it.console = console } - } - if (spec.id == "$FLUTTER_PREFIX${module.name}") { - val console = RunConsole("${module.name} (Flutter)") - val task = FlutterRunTask(TaskName(":${module.name}:flutterRun"), pkg, sdk, flutter, pub, console) - return RunAction("> Flutter ${module.name}", LinearGraph(listOf(task))).also { it.console = console } - } - val prefix = "$RUN_PREFIX${module.name}:" - if (!spec.id.startsWith(prefix)) return null - val entry = pkg.resolve(spec.id.removePrefix(prefix)).normalize() - if (!entry.startsWith(pkg) || !Files.isRegularFile(entry)) return null - - val stem = entry.fileName.toString().removeSuffix(".dart") - val dill = pkg.resolve(".dart_tool/codeassist/run/$stem.dill") - val console = RunConsole("${entry.fileName}") - val tasks = listOf( - PubTask(TaskName(":${module.name}:pubGet"), pkg, pub, "get", onlyIfNeeded = true, console = console), - CompileTask(TaskName(":${module.name}:compileDart"), pkg, entry, dill, sdk, console), - RunProgramTask(TaskName(":${module.name}:runDart"), pkg, dill, "${entry.fileName}", sdk, console), - ) - return RunAction("> Run ${pkg.relativize(entry)}", LinearGraph(tasks)).also { it.console = console } - } - - companion object { - const val RUN_PREFIX = "dartRun:" - const val PUB_PREFIX = "dartPub:" - const val FLUTTER_PREFIX = "flutterRun:" - const val PREVIEW_PREFIX = "flutterPreview:" - } -} - -/** A line logger that also writes to [console]'s output, when the Run opened one. */ -internal fun alsoToConsole(log: (String) -> Unit, console: RunConsole?): (String) -> Unit = { line -> - log(line) - console?.io?.stdout(line + "\n") -} - -/** Tasks run one after another, each depending on the one before. */ -internal class LinearGraph(override val tasks: List) : TaskGraph { - override fun dependencies(t: Task): List = tasks.indexOf(t).let { i -> if (i > 0) listOf(tasks[i - 1]) else emptyList() } - override fun topologicalLevels(): List> = tasks.map { listOf(it) } -} - -/** - * `dart pub `, its output in the build log, and in the Run [console] too when it is a step of a Run. - * With [onlyIfNeeded], skipped while the package config is current. - */ -internal class PubTask( - override val name: TaskName, - private val pkg: Path, - private val pub: Pub, - private val command: String, - private val onlyIfNeeded: Boolean, - private val console: RunConsole? = null, -) : Task, AlwaysRun { - override val inputs: TaskInputs get() = TaskInputsImpl() - override val outputs: TaskOutputs get() = TaskOutputsImpl() - - override suspend fun execute(ctx: TaskContext): TaskResult { - if (onlyIfNeeded && !DartPackages.needsPubGet(pkg)) return TaskResult.Success - val log = alsoToConsole(ctx.logger(), console) - // As a step of a Run the header names the program, so say what this step is; run on its own, the - // run's header already did. - if (onlyIfNeeded) log("> dart pub $command") - val code = killableTool { cancellation -> pub.run(pkg, command, cancellation = cancellation, out = log) } - return if (code == 0) TaskResult.Success else TaskResult.Failed("pub $command failed (exit code $code)") - } -} - -/** - * Compile [entry] to kernel at [dill] with the SDK's kernel compiler. The platform libraries are not linked - * in (the VM carries its own), so the output is the program alone: a few hundred kilobytes, not nine MB. - * - * What the compiler says goes to the Run [console] as well as the build log: a Run that stops at a compile - * error otherwise opened a console reading "(no output)", with the reason in a log the user was not looking at. - */ -internal class CompileTask( - override val name: TaskName, - private val pkg: Path, - private val entry: Path, - private val dill: Path, - private val sdk: DartSdk, - private val console: RunConsole? = null, -) : Task, AlwaysRun { - override val inputs: TaskInputs get() = TaskInputsImpl() - override val outputs: TaskOutputs get() = TaskOutputsImpl() - - override suspend fun execute(ctx: TaskContext): TaskResult { - val status = sdk.prepare() - if (status is DartSdk.Status.Unavailable) return TaskResult.Failed(status.reason) - val log = alsoToConsole(ctx.logger(), console) - val code = killableTool { cancellation -> compileKernel(sdk, pkg, entry, dill, cancellation, log) } - if (code != 0 || !Files.isRegularFile(dill)) return TaskResult.Failed("${entry.fileName} did not compile") - return TaskResult.Success - } -} - -/** - * Compile [entry] of the package at [pkg] to kernel at [dill], passing each line the compiler prints to [out]. - * The exit code, or -1 when the SDK is missing. Blocking; [cancellation] kills the compiler. - */ -internal fun compileKernel( - sdk: DartSdk, - pkg: Path, - entry: Path, - dill: Path, - cancellation: ToolCancellation?, - out: (String) -> Unit, -): Int { - val runtime = sdk.runtime ?: return -1 - val compiler = sdk.genKernel ?: return -1 - Files.createDirectories(dill.parent) - Files.deleteIfExists(dill) - val config = pkg.resolve(DartPackages.PACKAGE_CONFIG) - val command = buildList { - add(runtime.toString()); add(compiler.toString()) - add("--platform=${sdk.platformDill}") - if (Files.isRegularFile(config)) add("--packages=$config") - add("--no-link-platform") - add("-o"); add(dill.toString()) - add(entry.toString()) - } - val process = ProcessBuilder(command).directory(pkg.toFile()).redirectErrorStream(true) - .apply { environment().putAll(sdk.environment()) }.start() - cancellation?.attach(process) - runCatching { process.outputStream.close() } - process.inputStream.bufferedReader().forEachLine(out) - return process.waitFor() -} - -/** Run [dill] on the JIT VM in the Run console: its output there, what is typed there as its stdin. */ -internal class RunProgramTask( - override val name: TaskName, - private val pkg: Path, - private val dill: Path, - private val title: String, - private val sdk: DartSdk, - private val console: RunConsole, -) : Task, AlwaysRun { - override val inputs: TaskInputs get() = TaskInputsImpl() - override val outputs: TaskOutputs get() = TaskOutputsImpl() - - override suspend fun execute(ctx: TaskContext): TaskResult { - val vm = sdk.vm ?: return TaskResult.Failed(DartSdk.NO_SDK) - val io: ProgramIo? = console.io - val lines = LineSplitter(ctx.logger()) - val write: (String) -> Unit = io?.let { it::stdout } ?: lines::append - val code = killableTool { cancellation -> - val process = ProcessBuilder(listOf(vm.toString(), dill.toString())) - .directory(pkg.toFile()) - .redirectErrorStream(true) - .apply { environment().putAll(sdk.environment()) } - .start() - cancellation.attach(process) - io?.started() - val stdin = io?.stdin - if (stdin == null) runCatching { process.outputStream.close() } else pumpInput(stdin, process.outputStream) - val decoder = Utf8Chunks() - val buffer = ByteArray(8192) - try { - while (true) { - val n = process.inputStream.read(buffer) - if (n < 0) break - decoder.decode(buffer, n).takeIf { it.isNotEmpty() }?.let(write) - } - } catch (e: IOException) { - // Killed by Stop: the read ends with the stream, which is how this run is meant to end. - if (!cancellation.isCancelled) throw e - } - decoder.finish().takeIf { it.isNotEmpty() }?.let(write) - process.waitFor() - } - lines.flush() - if (io != null) io.exited(code) else ctx.logger()("Process finished with exit code $code") - return if (code == 0) TaskResult.Success else TaskResult.Failed("$title exited with code $code") - } - - /** Copy what the console sends into the program's stdin on a thread of its own, since both ends block. */ - private fun pumpInput(from: InputStream, to: OutputStream) { - Thread({ - try { - val buffer = ByteArray(4096) - while (true) { - val n = from.read(buffer) - if (n < 0) break - to.write(buffer, 0, n) - to.flush() - } - } catch (_: IOException) { - // The program exited and its stdin closed under us. - } finally { - runCatching { to.close() } - } - }, "dart-run-stdin").apply { isDaemon = true }.start() - } -} - -/** Decodes UTF-8 arriving in arbitrary chunks, carrying a character split across two of them. */ -internal class Utf8Chunks { - private val decoder = Charsets.UTF_8.newDecoder() - .onMalformedInput(CodingErrorAction.REPLACE) - .onUnmappableCharacter(CodingErrorAction.REPLACE) - private var pending = ByteArray(0) - - fun decode(bytes: ByteArray, length: Int): String { - val input = ByteBuffer.allocate(pending.size + length).put(pending).put(bytes, 0, length) - input.flip() - val out = CharBuffer.allocate(input.remaining() + 1) - decoder.decode(input, out, false) - pending = ByteArray(input.remaining()).also { input.get(it) } - out.flip() - return out.toString() - } - - fun finish(): String { - val input = ByteBuffer.wrap(pending) - val out = CharBuffer.allocate(pending.size + 1) - decoder.decode(input, out, true) - decoder.flush(out) - pending = ByteArray(0) - out.flip() - return out.toString() - } -} - -/** Re-splits raw program output into lines for the build log, when there is no console to stream to. */ -internal class LineSplitter(private val log: (String) -> Unit) { - private val pending = StringBuilder() - - @Synchronized - fun append(text: String) { - pending.append(text) - var nl = pending.indexOf("\n") - while (nl >= 0) { - log(pending.substring(0, nl).trimEnd('\r')) - pending.delete(0, nl + 1) - nl = pending.indexOf("\n") - } - } - - @Synchronized - fun flush() { - if (pending.isNotEmpty()) log(pending.toString().trimEnd('\r')) - pending.setLength(0) - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartSdk.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartSdk.kt deleted file mode 100644 index 21a6258f09..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartSdk.kt +++ /dev/null @@ -1,232 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.platform.log.Logger -import dev.ide.platform.notify.UserMessages -import dev.ide.plugin.PluginRegistration -import java.io.InputStream -import java.io.RandomAccessFile -import java.nio.file.Files -import java.nio.file.LinkOption -import java.nio.file.Path -import java.nio.file.Paths -import java.nio.file.StandardCopyOption -import java.util.zip.ZipInputStream - -/** - * The Dart SDK this plugin carries, and the layout it is run from. - * - * It arrives in two halves (see tools/dart-sdk/fetch-dart-android.sh). What is executed, the runtimes and - * the AOT snapshots, is in this package's native library directory, the one place Android lets an app run a - * file from. What is only read, the SDK's libraries, is `assets/dart-sdk.zip`, unpacked here on first use. - * - * The unpacked SDK lives in the IDE's INTERNAL storage, [PluginRegistration.privateDataDir], not - * [PluginRegistration.dataDir]. `dart pub` finds its SDK by walking up from the path it was started by, so - * [launcher] is a symlink at `/bin/dart` pointing at the runtime in the native library directory, and - * shared storage cannot hold a symlink. Being the plugin's own directory, the IDE offers to delete it once the - * plugin is uninstalled; the path this plugin picked for itself before (`files/dart-plugin`) outlived it. - * - * Safe to use from several processes at once: the IDE's (the language server) and `:build`'s (Run) both - * prepare it, and a file lock makes one of them unpack while the other waits. - */ -class DartSdk( - private val reg: PluginRegistration, - private val log: Logger, - private val messages: UserMessages?, -) { - sealed interface Status { - data class Ready(val version: String) : Status - data class Unavailable(val reason: String) : Status - } - - /** - * Where everything this plugin writes for itself lives: the SDK, the pub cache, a home and a temp dir. The - * plugin's [PluginRegistration.privateDataDir]; on a host older than SPI 3.4.0, which has none, the path - * this plugin used before it existed. - */ - val home: Path by lazy { privateHome() ?: internalHome() ?: reg.dataDir } - - private fun privateHome(): Path? { - // NoSuchMethodError (or AbstractMethodError) on a host from before the property. - val dir = try { reg.privateDataDir } catch (e: LinkageError) { return null } - internalHome()?.let { legacy -> - runCatching { adoptLegacyHome(legacy, dir) } - .onFailure { log.warn("could not move the Dart SDK from $legacy to $dir; it stays there", it) } - } - return dir - } - - /** - * Moves [legacy], where an earlier version of this plugin kept everything, into [dir], once, and leaves a link - * in its place. The link matters: a project's `.dart_tool/package_config.json` names its packages by their - * absolute path in the pub cache, so the old path has to keep resolving until the next `pub get` rewrites it. - * A rename within one file system, so it is instant whatever the pub cache holds. Under a lock, since the IDE - * and `:build` may both get here first; whichever is second finds the link and does nothing. - */ - private fun adoptLegacyHome(legacy: Path, dir: Path) { - if (!Files.isDirectory(legacy, LinkOption.NOFOLLOW_LINKS)) return - val root = dir.parent ?: return - withFileLock(root.resolve(".dart-plugin-move.lock")) { - if (!Files.isDirectory(legacy, LinkOption.NOFOLLOW_LINKS)) return@withFileLock - // Something already here means the move happened another way; the old copy is left for the IDE to - // offer rather than merged into a directory that is in use. - val empty = Files.newDirectoryStream(dir).use { !it.iterator().hasNext() } - if (!empty) return@withFileLock - Files.delete(dir) - Files.move(legacy, dir, StandardCopyOption.ATOMIC_MOVE) - Files.createSymbolicLink(legacy, dir) - log.info("moved the Dart SDK and pub cache from $legacy to $dir") - } - } - - val sdkDir: Path get() = home.resolve("sdk") - val pubCache: Path get() = home.resolve("pub-cache") - - private fun native(name: String): Path? = reg.nativeLibrary(name)?.takeIf { Files.isRegularFile(it) } - - /** Runs the AOT snapshots: the analysis server, the kernel compiler, `dart` itself. */ - val runtime: Path? get() = native("dartaotruntime") - - /** The JIT VM a program runs in. */ - val vm: Path? get() = native("dartvm") - val analysisServer: Path? get() = native("analysis_server") - val genKernel: Path? get() = native("gen_kernel") - val dartdev: Path? get() = native("dartdev") - - /** The incremental compiler behind Flutter's hot reload. */ - val frontendServer: Path? get() = native("frontend_server") - - /** `/bin/dart`: the runtime, by a path two levels below the SDK root, which is how `dart` finds it. */ - val launcher: Path get() = sdkDir.resolve("bin").resolve("dart") - - /** The core libraries in kernel form, which the kernel compiler links against. */ - val platformDill: Path get() = sdkDir.resolve("lib/_internal/vm_platform_strong.dill") - - @Volatile - private var ready: Status.Ready? = null - - /** - * Make the SDK usable: unpack the libraries if this version has not been, and point the launcher links - * at this install's native library directory (which moves with every update of the plugin). Cheap after - * the first call in a process. - */ - @Synchronized - fun prepare(): Status { - ready?.let { if (linksCurrent()) return it } - val runtime = runtime ?: return Status.Unavailable(NO_SDK) - if (vm == null || analysisServer == null || genKernel == null || dartdev == null) return Status.Unavailable(NO_SDK) - return try { - Files.createDirectories(home) - withFileLock(home.resolve(".lock")) { - unpackIfNeeded() - link(launcher, runtime) - link(sdkDir.resolve("bin/snapshots/dartdev_aot.dart.snapshot"), dartdev!!) - } - for (dir in listOf("home", "tmp")) Files.createDirectories(home.resolve(dir)) - Files.createDirectories(pubCache) - Status.Ready("Dart $VERSION").also { ready = it } - } catch (e: Exception) { - log.warn("could not prepare the Dart SDK", e) - Status.Unavailable("The Dart SDK could not be prepared: ${e.message}") - } - } - - /** The environment every Dart process gets: a home, a temp dir and a pub cache of the plugin's own. */ - fun environment(): Map = mapOf( - "HOME" to home.resolve("home").toString(), - "TMPDIR" to home.resolve("tmp").toString(), - "PUB_CACHE" to pubCache.toString(), - // pub's user agent names the client it runs under. - "PUB_ENVIRONMENT" to "codeassist", - // A program's output goes to a console that shows text, not a terminal that draws escape codes. - "TERM" to "dumb", - ) - - private fun linksCurrent(): Boolean { - val runtime = runtime ?: return false - return runCatching { Files.readSymbolicLink(launcher) == runtime }.getOrDefault(false) - } - - private fun unpackIfNeeded() { - val stamp = sdkDir.resolve(".unpacked") - if (Files.isRegularFile(stamp) && runCatching { String(Files.readAllBytes(stamp)).trim() }.getOrNull() == VERSION) return - val stream: InputStream = javaClass.classLoader?.getResourceAsStream(ASSET) - ?: throw IllegalStateException("$ASSET is not packaged in this plugin") - val progress = messages?.startProgress("Preparing the Dart SDK") - val started = System.nanoTime() - try { - // A partial unpack from an interrupted run must not read as complete: the stamp is written last, and - // a previous attempt is dropped rather than merged into. - if (Files.exists(sdkDir)) sdkDir.toFile().deleteRecursively() - Files.createDirectories(sdkDir) - var files = 0 - ZipInputStream(stream.buffered()).use { zip -> - while (true) { - val entry = zip.nextEntry ?: break - val target = sdkDir.resolve(entry.name).normalize() - require(target.startsWith(sdkDir)) { "entry escapes the SDK directory: ${entry.name}" } - if (entry.isDirectory) { - Files.createDirectories(target) - } else { - Files.createDirectories(target.parent) - Files.copy(zip, target, StandardCopyOption.REPLACE_EXISTING) - files++ - if (files % 100 == 0) progress?.detail = entry.name.substringAfterLast('/') - } - zip.closeEntry() - } - } - Files.write(stamp, VERSION.toByteArray()) - log.info("unpacked $files SDK files in ${(System.nanoTime() - started) / 1_000_000} ms") - } finally { - progress?.finish() - } - } - - /** Make [at] a symlink to [target], replacing whatever is there unless it already is exactly that. */ - private fun link(at: Path, target: Path) { - if (runCatching { Files.readSymbolicLink(at) == target }.getOrDefault(false)) return - Files.createDirectories(at.parent) - Files.deleteIfExists(at) - Files.createSymbolicLink(at, target) - } - - private inline fun withFileLock(file: Path, block: () -> T): T = - RandomAccessFile(file.toFile(), "rw").use { raf -> raf.channel.lock().use { block() } } - - /** - * `/files/dart-plugin`. ART points `java.io.tmpdir` at the app's own cache directory in every - * process of the app, so its parent is the app's data directory. Null off Android (or anywhere that is not - * internal storage), where the plugin's own data directory serves. - */ - private fun internalHome(): Path? { - val tmp = System.getProperty("java.io.tmpdir")?.takeIf { it.startsWith("/data/") } ?: return null - val appData = Paths.get(tmp).parent ?: return null - return appData.resolve("files").resolve("dart-plugin").takeIf { Files.isDirectory(appData, LinkOption.NOFOLLOW_LINKS) } - } - - companion object { - /** - * Dart VM flags for the long-running tools (the analysis server, the Flutter compiler): a heap that grows more - * gently, is compacted, gives freed pages back, and is collected while the tool waits for its next request. - * Measured on the device with a Flutter app open, 30 edits and a completion: the analysis server settles at - * ~250 MB instead of ~320 MB (peak ~320 instead of ~340), the compiler at ~350 instead of ~375; request times - * unchanged. A capped heap (`--old_gen_heap_size`) is NOT among them: the compiler crashed at 256 MB. - * - * The VM refuses to start on a flag it does not know, so these are tied to the SDK this plugin carries. - */ - val VM_TUNING = listOf( - "--old_gen_growth_space_ratio=10", - "--old_gen_growth_rate=60", - "--use_compactor", - "--dontneed_on_sweep", - "--mark_when_idle", - "--idle_timeout_micros=200000", - "--idle_duration_micros=200000", - ) - - /** The SDK version staged by tools/dart-sdk; also the unpack stamp, so a new SDK unpacks afresh. */ - const val VERSION = "3.13.7" - private const val ASSET = "assets/dart-sdk.zip" - const val NO_SDK = "This plugin has no Dart SDK for this device's ABI. Install the plugin build made for it (arm64-v8a, armeabi-v7a or x86_64; there is none for x86)." - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartTests.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartTests.kt deleted file mode 100644 index cf02834119..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartTests.kt +++ /dev/null @@ -1,388 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.build.AlwaysRun -import dev.ide.build.BuildContext -import dev.ide.build.RunAction -import dev.ide.build.RunConsole -import dev.ide.build.Task -import dev.ide.build.TaskContext -import dev.ide.build.TaskInputs -import dev.ide.build.TaskInputsImpl -import dev.ide.build.TaskName -import dev.ide.build.TaskOutputs -import dev.ide.build.TaskOutputsImpl -import dev.ide.build.TaskResult -import dev.ide.build.TestDeclaration -import dev.ide.build.TestProvider -import dev.ide.build.TestReport -import dev.ide.lang.LanguageId -import dev.ide.model.Module -import dev.ide.model.Project -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.booleanOrNull -import kotlinx.serialization.json.contentOrNull -import kotlinx.serialization.json.intOrNull -import kotlinx.serialization.json.jsonObject -import kotlinx.serialization.json.longOrNull -import java.io.IOException -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths -import java.util.stream.Collectors - -/** - * Dart tests (package:test) in the gutter, the Run picker and the Run screen's Tests tab. - * - * `dart test` cannot run from an installed app (it looks for its compilers beside the runtime's real path), - * so a run is the plugin's own: one generated entry point imports every test file it runs and hands each - * file's `main` to package:test's engine through `directRunTests`, the entry point test_core keeps for other - * runners, with the JSON reporter `dart test --reporter json` uses. That is compiled to kernel and run on the - * VM like a program, and its events become [TestReport] records. - * - * A suite is a test file's path in the package, dotted and without `.dart` (`test.parser_test`); a target is a - * suite, or `suite#name` for one test or group by its full name (group names and test name, space separated), - * which is what package:test calls a test and what a re-run sends back. - */ -class DartTestProvider(private val sdk: DartSdk, private val pub: Pub) : TestProvider { - override val id = ID - override val displayName = "Dart tests" - override val languages = setOf(LanguageId(DartPlugin.LANGUAGE)) - - // A Flutter package's tests are widget tests (flutter_test), which need Flutter's host test engine: not here. - override fun appliesTo(module: Module): Boolean = - module.type.id == DartModuleType.ID && testFiles(Paths.get(module.dir.path)).isNotEmpty() && - !FlutterSdk.isFlutterPackage(Paths.get(module.dir.path)) - - override fun tests(module: Module, path: String, text: String): List { - if (!path.endsWith(TEST_SUFFIX)) return emptyList() - val pkg = Paths.get(module.dir.path) - val file = Paths.get(path) - if (!file.startsWith(pkg.resolve("test")) || FlutterSdk.isFlutterPackage(pkg)) return emptyList() - val calls = DartTestScanner.scan(text) - if (calls.isEmpty()) return emptyList() - val suite = suiteOf(pkg, file) - return listOf(TestDeclaration(file.fileName.toString(), mainOffset(text), suite, group = true)) + - calls.map { TestDeclaration(it.fullName, it.offset, "$suite#${it.fullName}", group = it.group) } - } - - override fun run(module: Module, targets: List, project: Project, ctx: BuildContext): RunAction { - val console = RunConsole("Dart tests · ${module.name}") - val task = RunDartTests(TaskName(":${module.name}:dartTest"), Paths.get(module.dir.path), targets, sdk, pub, console) - return RunAction("> Dart tests ${module.name}", LinearGraph(listOf(task))).also { it.console = console } - } - - companion object { - const val ID = "dartTest" - const val TEST_SUFFIX = "_test.dart" - - /** The test files `dart test` would run: every `*_test.dart` under `test/`, sorted. */ - fun testFiles(pkg: Path): List { - val dir = pkg.resolve("test") - if (!Files.isDirectory(dir)) return emptyList() - return Files.walk(dir).use { w -> - w.filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(TEST_SUFFIX) }.collect(Collectors.toList()) - }.sorted() - } - - /** Where the file's own mark goes: its `main`, else the top. Never the blank line above `main`. */ - fun mainOffset(text: String): Int = - Regex("""(?m)^[ \t]*(?:void\s+|Future\s+)?main\s*\(""").find(text)?.range?.first ?: 0 - - /** [file]'s suite name: its path in the package, dotted, without `.dart`. */ - fun suiteOf(pkg: Path, file: Path): String = - pkg.relativize(file).joinToString(".") { it.toString() }.removeSuffix(".dart") - } -} - -/** - * Finds the `test(...)` and `group(...)` calls in a test file and their full names, for the gutter. - * - * Not a parser: a scan that skips comments and strings, matches each call's parentheses to know which tests a - * group encloses, and takes a name only when it is a plain string literal. A name built at runtime - * (`test('adds $x', ...)`), or anything inside a group so named, gets no mark rather than a wrong one. - */ -object DartTestScanner { - class Call(val fullName: String, val offset: Int, val group: Boolean) - - private class Raw(val name: String?, val offset: Int, val end: Int, val group: Boolean) - - fun scan(text: String): List { - val raws = ArrayList() - var i = 0 - while (i < text.length) { - val skipped = DartLex.skipNonCode(text, i) - if (skipped != i) { i = skipped; continue } - val c = text[i] - if (c.isLetter() || c == '_') { - var j = i - while (j < text.length && (text[j].isLetterOrDigit() || text[j] == '_')) j++ - val word = text.substring(i, j) - val prev = text.substring(0, i).trimEnd().lastOrNull() - if ((word == "test" || word == "group") && prev != '.') { - var k = j - while (k < text.length && text[k].isWhitespace()) k++ - if (k < text.length && text[k] == '(') { - val end = DartLex.matchParen(text, k) - raws += Raw(literalAt(text, k + 1), i, end, word == "group") - } - } - i = j - continue - } - i++ - } - val groups = raws.filter { it.group } - return raws.mapNotNull { call -> - val enclosing = groups.filter { it !== call && it.offset < call.offset && call.offset < it.end }.sortedBy { it.offset } - if (call.name == null || enclosing.any { it.name == null }) return@mapNotNull null - Call((enclosing.map { it.name!! } + call.name).joinToString(" "), call.offset, call.group) - } - } - - /** The value of the plain string literal at the start of [from] (after whitespace), or null. */ - private fun literalAt(text: String, from: Int): String? { - var i = from - while (i < text.length && text[i].isWhitespace()) i++ - val raw = i < text.length && text[i] == 'r' - val q = if (raw) i + 1 else i - if (q >= text.length || (text[q] != '\'' && text[q] != '"')) return null - val quote = text[q] - if (text.startsWith("$quote$quote$quote", q)) return null - val sb = StringBuilder() - var j = q + 1 - while (j < text.length && text[j] != quote) { - val c = text[j] - if (c == '\n') return null - if (!raw && c == '$') return null // interpolated: only known at runtime - if (!raw && c == '\\' && j + 1 < text.length) { - val e = text[j + 1] - sb.append(when (e) { 'n' -> '\n'; 't' -> '\t'; else -> e }) - j += 2 - continue - } - sb.append(c) - j++ - } - return sb.toString() - } -} - -/** The generated entry point that runs test files through package:test without `dart test`. */ -object DartTestRunnerSource { - /** - * Dart source importing each of [suites] (suite name to the file's URI relative to the runner) and running - * them in order. Its arguments are targets (`suite` or `suite#name`); none runs everything. - */ - fun generate(suites: Map): String = buildString { - appendLine("// Generated by CodeAssist to run tests without `dart test`, which cannot run on Android.") - appendLine("import 'dart:convert';") - appendLine("import 'dart:io';") - appendLine() - appendLine("import 'package:test_core/src/direct_run.dart';") - appendLine("import 'package:test_core/src/runner/reporter/json.dart';") - appendLine() - suites.values.forEachIndexed { i, uri -> appendLine("import ${dartString(uri)} as s$i;") } - appendLine() - appendLine("final suites = {") - suites.keys.forEachIndexed { i, suite -> appendLine(" ${dartString(suite)}: () => s$i.main(),") } - appendLine("};") - append( - """ - - Future main(List args) async { - var ok = true; - for (final entry in suites.entries) { - final wanted = [for (final a in args) if (a == entry.key || a.startsWith('${'$'}{entry.key}#')) a]; - if (args.isNotEmpty && wanted.isEmpty) continue; - stdout.writeln(jsonEncode({'type': 'codeassist.suite', 'suite': entry.key})); - reporter(e) => JsonReporter.watch(e, stdout, isDebugRun: false); - try { - if (wanted.isEmpty || wanted.contains(entry.key)) { - ok = await directRunTests(entry.value, reporterFactory: reporter) && ok; - } else { - final names = await enumerateTestCases(entry.value); - final only = [for (final w in wanted) w.substring(entry.key.length + 1)]; - for (final name in names.where((n) => only.any((o) => n == o || n.startsWith('${'$'}o ')))) { - ok = await directRunSingleTest(entry.value, name, reporterFactory: reporter) && ok; - } - } - } catch (e, st) { - ok = false; - stdout.writeln(jsonEncode({'type': 'codeassist.error', 'error': '${'$'}e', 'stackTrace': '${'$'}st'})); - } - } - exitCode = ok ? 0 : 1; - } - """.trimIndent(), - ) - appendLine() - } - - private fun dartString(s: String): String = "'" + s.replace("\\", "\\\\").replace("'", "\\'").replace("$", "\\$") + "'" -} - -/** - * Turns the runner's output into [TestReport] records for the Tests tab, and everything else (a test's - * prints, anything that is not an event) into console text. One instance per run. - */ -class DartTestEvents(private val out: (String) -> Unit) { - var ran = 0 - private set - var failed = 0 - private set - - private var suite = "" - private val names = HashMap() - private val startedAt = HashMap() - private val skipReasons = HashMap() - private val errors = HashMap() - - fun line(text: String) { - val event = if (text.startsWith("{")) runCatching { Json.parseToJsonElement(text).jsonObject }.getOrNull() else null - val type = event?.string("type") - if (event == null || type == null) { - out(text + "\n") - return - } - when (type) { - "codeassist.suite" -> suite = event.string("suite").orEmpty() - "codeassist.error" -> { - failed++ - out(TestReport.suiteFailed(suite, listOfNotNull(event.string("error"), event.string("stackTrace")).joinToString("\n"))) - } - // Each engine numbers its tests from scratch, and a filtered run starts one engine per test. - "start" -> { names.clear(); startedAt.clear(); skipReasons.clear(); errors.clear() } - "testStart" -> { - val test = event["test"] as? JsonObject ?: return - val id = test.int("id") ?: return - val name = test.string("name") ?: return - names[id] = name - startedAt[id] = event.long("time") ?: 0 - (test["metadata"] as? JsonObject)?.string("skipReason")?.let { skipReasons[id] = it } - out(TestReport.started(suite, name)) - } - "print" -> event.string("message")?.let { out(it + "\n") } - "error" -> { - val id = event.int("testID") - val message = listOfNotNull(event.string("error"), event.string("stackTrace")).joinToString("\n") - if (id == null || id !in names) { - failed++ - out(TestReport.suiteFailed(suite, message)) - } else { - errors.getOrPut(id) { StringBuilder() }.apply { if (isNotEmpty()) append("\n") }.append(message) - } - } - "testDone" -> { - val id = event.int("testID") ?: return - val name = names[id] ?: return - if (event.bool("hidden") == true) return - val millis = (event.long("time") ?: 0) - (startedAt[id] ?: 0) - when { - event.bool("skipped") == true -> out(TestReport.skipped(suite, name, skipReasons[id].orEmpty())) - event.string("result") == "success" -> { ran++; out(TestReport.passed(suite, name, millis)) } - else -> { - ran++ - failed++ - out(TestReport.failed(suite, name, millis, errors[id]?.toString() ?: "Failed (${event.string("result")})")) - } - } - } - } - } - - private fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull - private fun JsonObject.int(key: String): Int? = (this[key] as? JsonPrimitive)?.intOrNull - private fun JsonObject.long(key: String): Long? = (this[key] as? JsonPrimitive)?.longOrNull - private fun JsonObject.bool(key: String): Boolean? = (this[key] as? JsonPrimitive)?.booleanOrNull -} - -/** One test run: pub get if needed, generate and compile the runner, run it, report. */ -private class RunDartTests( - override val name: TaskName, - private val pkg: Path, - private val targets: List, - private val sdk: DartSdk, - private val pub: Pub, - private val console: RunConsole, -) : Task, AlwaysRun { - override val inputs: TaskInputs get() = TaskInputsImpl() - override val outputs: TaskOutputs get() = TaskOutputsImpl() - - override suspend fun execute(ctx: TaskContext): TaskResult { - val io = console.io - val out: (String) -> Unit = io?.let { it::stdout } ?: { text -> ctx.logger()(text.trimEnd()) } - val outLine: (String) -> Unit = { out(it + "\n") } - io?.started() - out(TestReport.run(DartTestProvider.ID)) - val code = runTests(out, outLine) - io?.exited(code) - return if (code == 0) TaskResult.Success else TaskResult.Failed("Dart tests failed") - } - - private suspend fun runTests(out: (String) -> Unit, outLine: (String) -> Unit): Int { - fun failAll(suites: Collection, message: String): Int { - outLine(message) - suites.forEach { out(TestReport.suiteFailed(it, message)) } - out(TestReport.finished()) - return 1 - } - - val status = sdk.prepare() - if (status is DartSdk.Status.Unavailable) return failAll(emptyList(), status.reason) - - val files = DartTestProvider.testFiles(pkg).associateBy { DartTestProvider.suiteOf(pkg, it) } - val wantedSuites = if (targets.isEmpty()) files.keys.toList() else targets.map { it.substringBefore('#') }.distinct() - val missing = wantedSuites.filter { it !in files } - missing.forEach { out(TestReport.suiteFailed(it, "No test file in this package is $it")) } - val suites = wantedSuites.filter { it in files } - if (suites.isEmpty()) { - out(TestReport.finished(noTests = missing.isEmpty())) - return if (missing.isEmpty()) 0 else 1 - } - - if (DartPackages.needsPubGet(pkg)) { - outLine("> dart pub get") - val got = killableTool { c -> pub.run(pkg, "get", cancellation = c, out = outLine) } - if (got != 0) return failAll(suites, "pub get failed (exit code $got)") - } - val config = pkg.resolve(DartPackages.PACKAGE_CONFIG) - if (!String(Files.readAllBytes(config)).contains("\"test_core\"")) { - return failAll(suites, "This package does not depend on package:test. Add it under dev_dependencies in pubspec.yaml (test: ^1.25.0), then run pub get.") - } - - val dir = pkg.resolve(".dart_tool/codeassist/test") - Files.createDirectories(dir) - val runner = dir.resolve("runner.dart") - val imports = suites.associateWith { suite -> dir.relativize(files.getValue(suite)).joinToString("/") { it.toString() } } - Files.write(runner, DartTestRunnerSource.generate(imports).toByteArray()) - val dill = dir.resolve("runner.dill") - val compileOutput = StringBuilder() - val compiled = killableTool { c -> compileKernel(sdk, pkg, runner, dill, c) { compileOutput.appendLine(it) } } - if (compiled != 0 || !Files.isRegularFile(dill)) { - out(compileOutput.toString()) - return failAll(suites, "The tests did not compile:\n$compileOutput".trimEnd()) - } - - val vm = sdk.vm ?: return failAll(suites, DartSdk.NO_SDK) - val events = DartTestEvents(out) - val exit = killableTool { cancellation -> - val process = ProcessBuilder(listOf(vm.toString(), dill.toString()) + targets) - .directory(pkg.toFile()) - .redirectErrorStream(true) - .apply { environment().putAll(sdk.environment()) } - .start() - cancellation.attach(process) - runCatching { process.outputStream.close() } - try { - process.inputStream.bufferedReader().forEachLine(events::line) - } catch (e: IOException) { - if (!cancellation.isCancelled) throw e - } - process.waitFor() - } - out(TestReport.finished(noTests = events.ran == 0 && events.failed == 0)) - return if (exit == 0 && events.failed == 0 && missing.isEmpty()) 0 else 1 - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartUiPlugin.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartUiPlugin.kt deleted file mode 100644 index a4d143d278..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/DartUiPlugin.kt +++ /dev/null @@ -1,63 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.plugin.ui.EditorLanguage -import dev.ide.plugin.ui.EditorPreview -import dev.ide.plugin.ui.FileIcon -import dev.ide.plugin.ui.SyntaxStyle -import dev.ide.plugin.ui.UiPlugin -import dev.ide.plugin.ui.UiRegistration - -/** - * The UI facet: how a Dart file looks while it is being typed (keywords, strings, comments, brackets), drawn - * on every keystroke before the analysis server's semantic colours arrive and wherever it is unavailable, - * the icon a `.dart` file gets, and the preview pane for a Flutter file's `@Preview` widgets. - */ -class DartUiPlugin : UiPlugin { - - override val id = "dev.codeassist.dart" - - override fun contribute(ui: UiRegistration) { - ui.editorLanguage( - EditorLanguage( - id = DartPlugin.LANGUAGE, - suffixes = DartFileIcons.SUFFIXES, - syntax = SyntaxStyle.C_FAMILY, - keywords = KEYWORDS, - lineComment = "//", - blockCommentOpen = BLOCK_OPEN, - blockCommentClose = BLOCK_CLOSE, - ) - ) - // Dart's own blue. - ui.fileIcon(FileIcon(DartFileIcons.DART, DartFileIcons.SUFFIXES, badge = "D", color = 0xFF40C4FF)) - // A Flutter file's @Preview widgets, live and hot-reloading, in the editor's preview pane. - ui.editorPreview( - EditorPreview( - id = "dev.codeassist.dart.flutterPreview", - title = "Flutter", - appliesTo = FlutterPreviewFiles::appliesTo, - ) { ctx -> FlutterPreviewPane(ctx) }, - ) - } - - private companion object { - // Spelled rather than written literally: a `*` followed by a `/` inside a comment ends it. - const val BLOCK_OPEN = "/*" - const val BLOCK_CLOSE = "*" + "/" - - /** - * Dart's reserved words, built-in identifiers and contextual keywords. Type names (`int`, `String`) - * are absent on purpose: a capitalized word already colours as a type, and the server colours the - * rest. - */ - val KEYWORDS = setOf( - "abstract", "as", "assert", "async", "await", "base", "break", "case", "catch", "class", "const", - "continue", "covariant", "default", "deferred", "do", "dynamic", "else", "enum", "export", "extends", - "extension", "external", "factory", "false", "final", "finally", "for", "Function", "get", "hide", - "if", "implements", "import", "in", "interface", "is", "late", "library", "mixin", "new", "null", - "of", "on", "operator", "part", "required", "rethrow", "return", "sealed", "set", "show", "static", - "super", "switch", "sync", "this", "throw", "true", "try", "type", "typedef", "var", "void", "when", - "while", "with", "yield", - ) - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterAndroidFiles.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterAndroidFiles.kt deleted file mode 100644 index f1235eb4e8..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterAndroidFiles.kt +++ /dev/null @@ -1,153 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.model.template.ProjectScaffold - -/** - * The Android side of a Flutter app, as `flutter create` writes it into `android/app`: what an APK needs that is - * not Flutter's. Java rather than Kotlin, because the IDE compiles Java on the device in a fraction of the time. - */ -object FlutterAndroidFiles { - - fun write(scaffold: ProjectScaffold, dir: String, appId: String, label: String) { - val main = "$dir/src/main" - scaffold.writeText("$main/AndroidManifest.xml", manifest(label)) - scaffold.writeText("$main/java/${appId.replace('.', '/')}/MainActivity.java", mainActivity(appId)) - scaffold.writeText("$main/java/io/flutter/plugins/GeneratedPluginRegistrant.java", PLUGIN_REGISTRANT) - scaffold.writeText("$main/res/values/styles.xml", styles("@android:style/Theme.Light.NoTitleBar")) - scaffold.writeText("$main/res/values-night/styles.xml", styles("@android:style/Theme.Black.NoTitleBar")) - scaffold.writeText("$main/res/values/colors.xml", COLORS) - scaffold.writeText("$main/res/drawable/launch_background.xml", LAUNCH_BACKGROUND) - scaffold.writeText("$main/res/drawable/ic_launcher_foreground.xml", ICON_FOREGROUND) - scaffold.writeText("$main/res/mipmap-anydpi-v26/ic_launcher.xml", ADAPTIVE_ICON) - } - - /** - * `flutter create`'s manifest, less the `${applicationName}` its Gradle plugin fills in. INTERNET is in the - * main manifest (`flutter create` keeps it in the debug one, which this build does not merge): the debug - * engine serves its Dart VM service on a local socket, and most apps reach the network anyway. - */ - fun manifest(label: String): String = """ - - - - - - - - - - - - - - - - - - - - - - - - - - - """.trimIndent() + "\n" - - fun mainActivity(appId: String): String = """ - package $appId; - - import io.flutter.embedding.android.FlutterActivity; - - /** The app's one Activity. Flutter draws all of it; lib/main.dart is the app. */ - public class MainActivity extends FlutterActivity { - } - """.trimIndent() + "\n" - - /** - * What `FlutterActivity` registers the app's Flutter plugins through. `flutter` generates it from the - * pubspec's plugins; with none that have Android code (the only kind the IDE can build yet) it is empty, - * and having it keeps the engine from warning on every start that it is missing. - */ - private val PLUGIN_REGISTRANT = """ - package io.flutter.plugins; - - import androidx.annotation.Keep; - import androidx.annotation.NonNull; - import io.flutter.embedding.engine.FlutterEngine; - - /** Registers the app's Flutter plugins that have Android code. It has none. */ - @Keep - public final class GeneratedPluginRegistrant { - public static void registerWith(@NonNull FlutterEngine flutterEngine) { - } - } - """.trimIndent() + "\n" - - private fun styles(parent: String): String = """ - - - - - - - - """.trimIndent() + "\n" - - private val COLORS = """ - - - #3F51B5 - - """.trimIndent() + "\n" - - private val LAUNCH_BACKGROUND = """ - - - - - - """.trimIndent() + "\n" - - private val ICON_FOREGROUND = """ - - - - - """.trimIndent() + "\n" - - private val ADAPTIVE_ICON = """ - - - - - - """.trimIndent() + "\n" - - private fun xml(s: String) = s.replace("&", "&").replace("<", "<").replace("\"", """) -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterApk.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterApk.kt deleted file mode 100644 index 176a81c0a9..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterApk.kt +++ /dev/null @@ -1,480 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.build.AlwaysRun -import dev.ide.build.BuildConfiguration -import dev.ide.build.BuildDiagnostic -import dev.ide.build.BuildGoal -import dev.ide.build.BuildPlugin -import dev.ide.build.BuildSeverity -import dev.ide.build.Lifecycle -import dev.ide.build.Task -import dev.ide.build.TaskContext -import dev.ide.build.TaskInputs -import dev.ide.build.TaskInputsImpl -import dev.ide.build.TaskName -import dev.ide.build.TaskOutputs -import dev.ide.build.TaskOutputsImpl -import dev.ide.build.TaskResult -import dev.ide.model.Facet -import dev.ide.model.FacetCodec -import dev.ide.model.FacetKey -import dev.ide.platform.log.Logger -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.runInterruptible -import kotlinx.coroutines.withContext -import java.io.IOException -import java.io.InputStream -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths -import java.nio.file.StandardCopyOption -import java.util.stream.Collectors - -/** - * Marks an Android app module as the Android side of a Flutter app, as the `flutter { source = "../.." }` - * block of a Flutter project's `android/app/build.gradle` does: [source] is the Flutter package, relative to - * the module. The module's build then compiles that package and packages it with the engine - * ([FlutterBuildPlugin]). - */ -data class FlutterFacet(val source: String = DEFAULT_SOURCE) : Facet { - override val key get() = KEY - - companion object { - val KEY = FacetKey("flutter") - - /** `android/app` inside the package, where `flutter create` puts it. */ - const val DEFAULT_SOURCE = "../.." - } -} - -/** The `[flutter]` table of an Android module's `module.toml`. */ -object FlutterFacetCodec : FacetCodec { - override val key = FlutterFacet.KEY - override val tomlTable = "flutter" - - override fun encode(facet: FlutterFacet): Map = mapOf("source" to facet.source) - - override fun decode(values: Map): FlutterFacet = - FlutterFacet((values["source"] as? String)?.takeIf { it.isNotBlank() } ?: FlutterFacet.DEFAULT_SOURCE) -} - -/** - * Builds a Flutter app into its Android app's APK, as the Flutter Gradle plugin's `compileFlutterBuild` - * does: for each module with a [FlutterFacet], one task that compiles the Flutter package and lays out what - * the APK needs from it. The Android build packages the result like any module's own assets and native - * libraries, so signing, installing and Run are the ordinary Android ones. - * - * A debug variant is what `flutter build apk --debug` makes: the program as kernel, run by the debug engine's - * JIT. A release variant is `flutter build apk --release`: the program compiled ahead of time to machine code - * (`libapp.so`) by gen_snapshot, run by the release engine, with no kernel in the APK. - */ -class FlutterBuildPlugin( - private val sdk: DartSdk, - private val flutter: FlutterSdk, - private val pub: Pub, - private val log: Logger, -) : BuildPlugin { - - override val id = "flutter" - - override fun appliesTo(config: BuildConfiguration): Boolean = - config.request.goal != BuildGoal.CLEAN && config.project.modules.any { it.facets.get(FlutterFacet.KEY) != null } - - override fun apply(config: BuildConfiguration) { - val variant = config.request.variant.name - for (module in config.project.modules) { - val facet = module.facets.get(FlutterFacet.KEY) ?: continue - val pkg = Paths.get(module.dir.path).resolve(facet.source).normalize() - val out = config.env.buildDir(module).resolve("intermediates").resolve("flutter").resolve(variant) - val taskName = TaskName(":${module.name}:compileFlutterBuild${variant.cap()}") - val assets = out.resolve("assets") - val libs = out.resolve("lib") - - // Both declarations need SPI 3.8.0 (assets) and 3.1.0 (native libraries). On an older host the - // task is still registered, to fail with the reason instead of packaging an app with no Flutter in it. - val declared = try { - config.addAssets(module, assets, taskName) - config.addNativeLibraries(module, libs, taskName) - true - } catch (e: LinkageError) { - log.info("this IDE cannot package a build directory's assets; Flutter APKs need a newer CodeAssist") - false - } - - val moduleNames = config.project.modules.mapTo(HashSet()) { it.name } - // The modules whose C/C++ something builds: their `[ndk]` table decodes only when the NDK plugin, - // which registers its codec, is installed and on. - val nativeModules = config.project.modules.filter { m -> m.facets.all.any { it.key.id == NDK_FACET } }.mapTo(HashSet()) { it.name } - config.tasks.register(taskName) { - FlutterApkTask(taskName, pkg, out, release = isRelease(variant), hostCanPackage = declared, sdk, flutter, pub, moduleNames, nativeModules) - } - config.tasks.named(Lifecycle.assemble(module.name)).configure { dependsOn(taskName) } - config.tasks.named(Lifecycle.assemble(module.name, variant)).configure { dependsOn(taskName) } - } - } - - private fun String.cap(): String = replaceFirstChar { it.uppercase() } - - companion object { - /** - * Whether [variant] is a release build. The Android facet that says which build types are debuggable - * belongs to another plugin, so this goes by the name AGP gives a variant: `release`, `freeRelease`. - */ - fun isRelease(variant: String): Boolean = variant.endsWith("release", ignoreCase = true) - - /** The NDK plugin's facet id (its `[ndk]` table). */ - const val NDK_FACET = "ndk" - } -} - -/** - * Compiles the Flutter package at [pkg] and writes, under [out]: - * - `assets/flutter_assets/`: the asset bundle (fonts, shaders, images, the manifests the framework reads them - * by), and for a debug build the program (`kernel_blob.bin`) and the VM snapshots the debug engine starts from; - * - `lib//libflutter.so`: the engine (debug or release), for the ABI the plugin carries it for; - * - `lib//libapp.so`, for a release build: the program as machine code. - * - * A debug build compiles with the incremental compiler Run uses ([FrontendServer]), started from the kernel it - * wrote last time, so a build after an edit recompiles only what changed. A release build compiles the whole - * program to kernel against the product platform with tree shaking (`--aot --tfa`), then gen_snapshot compiles - * that to an ELF library, as `flutter build apk --release` does. - */ -internal class FlutterApkTask( - override val name: TaskName, - private val pkg: Path, - private val out: Path, - private val release: Boolean, - private val hostCanPackage: Boolean, - private val sdk: DartSdk, - private val flutter: FlutterSdk, - private val pub: Pub, - /** The project's modules as this build sees them, to tell when the app's plugins have none yet. */ - private val moduleNames: Set = emptySet(), - /** The modules whose native code a plugin builds (see [FlutterBuildPlugin.NDK_FACET]). */ - private val nativeModules: Set = emptySet(), -) : Task, AlwaysRun { - override val inputs: TaskInputs get() = TaskInputsImpl() - override val outputs: TaskOutputs get() = TaskOutputsImpl() - - /** - * The build, with its reason for failing (an app that does not compile, a missing NDK plugin) also filed under - * Problems: the log line alone is easy to miss among a build's hundreds. - */ - override suspend fun execute(ctx: TaskContext): TaskResult { - val result = build(ctx) - if (result is TaskResult.Failed) { - runCatching { ctx.diagnostics.report(BuildDiagnostic(BuildSeverity.ERROR, result.message, source = "flutter")) } - } - return result - } - - private suspend fun build(ctx: TaskContext): TaskResult = withContext(Dispatchers.IO) { - val log = ctx.logger() - if (!hostCanPackage) return@withContext TaskResult.Failed(TOO_OLD) - (sdk.prepare() as? DartSdk.Status.Unavailable)?.let { return@withContext TaskResult.Failed(it.reason) } - val prepared = if (release) flutter.prepareRelease() else flutter.prepare() - (prepared as? FlutterSdk.Status.Unavailable)?.let { return@withContext TaskResult.Failed(it.reason) } - val pubspec = pkg.resolve(DartPackages.PUBSPEC) - if (!Files.isRegularFile(pubspec)) return@withContext TaskResult.Failed("No Flutter package at $pkg (no pubspec.yaml).") - val name = DartPackages.nameOf(String(Files.readAllBytes(pubspec))) - ?: return@withContext TaskResult.Failed("$pubspec has no name.") - if (!Files.isRegularFile(pkg.resolve("lib/main.dart"))) return@withContext TaskResult.Failed("A Flutter app needs lib/main.dart.") - val engine = (if (release) flutter.releaseEngine else flutter.engine) - ?: return@withContext TaskResult.Failed(if (release) FlutterSdk.NO_RELEASE else FlutterSdk.NO_FLUTTER) - val abi = abiOf(engine.parent) - ?: return@withContext TaskResult.Failed("Could not tell which ABI the Flutter engine at $engine is for.") - - if (DartPackages.needsPubGet(pkg)) { - log("> dart pub get") - val code = killableTool { cancellation -> pub.run(pkg, "get", cancellation = cancellation, out = log) } - // `dart pub get` can exit 0 after "version solving failed"; what matters is the package config it writes. - if (code != 0 || DartPackages.needsPubGet(pkg)) return@withContext TaskResult.Failed("pub get failed: see its output above.") - } - - // A plugin pub just brought in (here, or since the last sync) has no module in this build: its Android - // code would be missing from the APK. The project syncs before the next build, which then has it. - val plugins = FlutterPlugins.discover(pkg) - val missing = plugins.filter { it.hasAndroidCode && it.name !in moduleNames }.map { it.name } - if (missing.isNotEmpty() && moduleNames.isNotEmpty()) { - return@withContext TaskResult.Failed( - "The app's Flutter plugins changed (${missing.joinToString()}), and this build started before the " + - "project took them in. Build again: the project syncs them first.", - ) - } - // An FFI plugin's C code is built by the NDK plugin. Without it the APK would install and crash the first - // time the app reaches that code, so this fails the build and says what to install instead. - val unbuilt = plugins.filter { it.ffi && it.hasAndroidCode && it.name in moduleNames && it.name !in nativeModules }.map { it.name } - if (unbuilt.isNotEmpty()) return@withContext TaskResult.Failed(noNativeBuild(unbuilt)) - - val entry = "package:$name/main.dart" - val libs = out.resolve("lib").resolve(abi) - val registrant = try { - writeDartRegistrant() - } catch (e: IOException) { - return@withContext TaskResult.Failed("Could not write the Dart plugin registrant: ${e.message}") - } - if (registrant.isNotEmpty()) log("Registering the Dart side of the app's Flutter plugins.") - if (release) return@withContext buildRelease(entry, engine, abi, libs, registrant, log) - - log("Compiling $entry ...") - val started = System.nanoTime() - val compiled = compile(entry, registrant) - compiled.messages.forEach(log) - val dill = compiled.dill - if (!compiled.ok || dill == null) { - return@withContext TaskResult.Failed("The Flutter app did not compile (${compiled.errors.coerceAtLeast(1)} error(s)).") - } - log("Compiled in ${(System.nanoTime() - started) / 1_000_000} ms.") - - try { - writeBundle(kernel = dill) - copyIfChanged(engine, libs.resolve(ENGINE)) - } catch (e: IOException) { - return@withContext TaskResult.Failed("Could not lay out the Flutter app for packaging: ${e.message}") - } - log("Flutter $abi debug engine and ${name}'s bundle ready for packaging.") - TaskResult.Success - } - - /** The release build: kernel ahead of time, gen_snapshot to `libapp.so`, the release engine, no kernel. */ - private suspend fun buildRelease( - entry: String, engine: Path, abi: String, libs: Path, registrant: List, log: (String) -> Unit, - ): TaskResult { - val runtime = sdk.runtime ?: return TaskResult.Failed(DartSdk.NO_SDK) - val compiler = sdk.frontendServer ?: return TaskResult.Failed(DartSdk.NO_SDK) - val genSnapshot = flutter.genSnapshot ?: return TaskResult.Failed(FlutterSdk.NO_RELEASE) - val work = out.resolve("compile") - val dill = work.resolve("app.dill") - Files.createDirectories(work) - Files.deleteIfExists(dill) - - log("Compiling $entry ahead of time ...") - var started = System.nanoTime() - val kernel = killableTool { c -> - runTool( - aotKernelCommand(runtime, compiler, flutter.productPlatformDir, pkg.resolve(DartPackages.PACKAGE_CONFIG), dill, entry, registrant), - c, log, - ) - } - if (kernel.exitCode != 0 || kernel.errors > 0 || !Files.isRegularFile(dill)) { - return TaskResult.Failed("The Flutter app did not compile (${kernel.errors.coerceAtLeast(1)} error(s)).") - } - log("Kernel in ${ms(started)} ms. Compiling to $abi machine code ...") - - started = System.nanoTime() - Files.createDirectories(libs) - // Written beside the real name and moved into place, so a failed or cancelled run never leaves a - // half-written library for the packaging to pick up. - val partial = libs.resolve("$APP_LIBRARY.partial") - val snapshot = killableTool { c -> runTool(genSnapshotCommand(genSnapshot, abi, dill, partial), c, log) } - if (snapshot.exitCode != 0 || !Files.isRegularFile(partial)) { - Files.deleteIfExists(partial) - return TaskResult.Failed("gen_snapshot could not compile the app to machine code (exit code ${snapshot.exitCode}).") - } - Files.move(partial, libs.resolve(APP_LIBRARY), StandardCopyOption.REPLACE_EXISTING) - log("Machine code in ${ms(started)} ms (${Files.size(libs.resolve(APP_LIBRARY)) / 1024} KB).") - - try { - writeBundle(kernel = null) - copyIfChanged(engine, libs.resolve(ENGINE)) - } catch (e: IOException) { - return TaskResult.Failed("Could not lay out the Flutter app for packaging: ${e.message}") - } - log("Flutter $abi release engine and the app's machine code ready for packaging.") - return TaskResult.Success - } - - /** What a tool run came to: its exit code, and the error count the compiler reported (0 for other tools). */ - class ToolRun(val exitCode: Int, val errors: Int) - - /** - * Run [command] in the package, its output to [log] (less the compiler's list of the files it read), and - * answer how it went. Blocking; [cancellation] kills it. - */ - private fun runTool(command: List, cancellation: ToolCancellation, log: (String) -> Unit): ToolRun { - val process = ProcessBuilder(command).directory(pkg.toFile()).redirectErrorStream(true) - .apply { environment().putAll(sdk.environment()) } - .start() - cancellation.attach(process) - var errors = 0 - // The compiler frames its messages with `result ` and `` lines, which say nothing to a reader. - var key: String? = null - process.inputStream.bufferedReader().forEachLine { line -> - val result = compileErrors(line) - when { - result != null -> errors = result - line.startsWith("result ") -> key = line.removePrefix("result ").trim() - line == key -> Unit - line.startsWith("+") || line.startsWith("-") -> Unit - else -> log(line) - } - } - return ToolRun(process.waitFor(), errors) - } - - private fun ms(since: Long) = (System.nanoTime() - since) / 1_000_000 - - /** - * Write the Dart plugin registrant for the app's plugins and answer the compiler arguments that include it, - * or none when no plugin registers a Dart class (the file is then removed, so a dropped plugin's stays out). - */ - private fun writeDartRegistrant(): List { - val file = FlutterPlugins.dartRegistrantFile(pkg) - val text = FlutterPlugins.dartRegistrant(FlutterPlugins.discover(pkg), FlutterPlugins.directDependencies(pkg)) - if (text == null) { - Files.deleteIfExists(file) - return emptyList() - } - if (!Files.isRegularFile(file) || String(Files.readAllBytes(file)) != text) { - Files.createDirectories(file.parent) - Files.write(file, text.toByteArray()) - } - return FlutterPlugins.dartRegistrantArgs(file) - } - - private suspend fun compile(entry: String, registrant: List): FrontendServer.Result { - val seeds = listOf( - FlutterSession.runWork(pkg).resolve("app.dill"), - FlutterSession.paneWork(pkg).resolve("app.dill"), - FlutterSession.seed(sdk), - ) - val compiler = FrontendServer(sdk, flutter, pkg, out.resolve("compile").resolve("app.dill"), seeds, registrant) - // Cancelling interrupts the wait for the compiler's answer; closing it then ends its process. - return runInterruptible { - try { - compiler.start() - compiler.compile(entry) - } finally { - compiler.close() - } - } - } - - /** - * `flutter_assets`, rewritten whole except for the files that did not change: a stale asset from a previous - * build (one the pubspec no longer lists) must not reach the APK, and an unchanged 40 MB kernel need not be - * copied again. - */ - private fun writeBundle(kernel: Path?) { - val root = out.resolve("assets").resolve(BUNDLE) - val bundle = FlutterAssets.build(pkg, flutter.baseAssets) - val wanted = HashSet() - - fun keep(relative: String): Path = root.resolve(relative).normalize().also { - require(it.startsWith(root)) { "asset path escapes the bundle: $relative" } - wanted.add(it) - } - - // A debug build's program and the snapshots its JIT starts from. A release build's program is libapp.so. - if (kernel != null) { - copyIfChanged(kernel, keep(KERNEL)) - for (snapshot in SNAPSHOTS) { - val target = keep(snapshot) - val stream = flutter.vmSnapshot(snapshot) ?: throw IOException("this build of the Dart plugin has no $snapshot") - stream.use { writeIfChanged(it, target) } - } - } - for ((relative, file) in bundle.files) copyIfChanged(file, keep(relative)) - for ((relative, bytes) in bundle.generated) writeIfChanged(bytes.inputStream(), keep(relative)) - - if (Files.isDirectory(root)) { - val all = Files.walk(root).use { s -> s.sorted(Comparator.reverseOrder()).collect(Collectors.toList()) } - for (p in all) { - if (Files.isRegularFile(p) && p !in wanted) Files.delete(p) - else if (Files.isDirectory(p) && p != root && Files.list(p).use { !it.findFirst().isPresent }) Files.delete(p) - } - } - } - - internal companion object { - const val BUNDLE = "flutter_assets" - const val KERNEL = "kernel_blob.bin" - val SNAPSHOTS = listOf("vm_snapshot_data", "isolate_snapshot_data") - - const val ENGINE = "libflutter.so" - const val APP_LIBRARY = "libapp.so" - - /** - * The error count on the compiler's last line for a compile, ` `, or null - * for any other line. - */ - fun compileErrors(line: String): Int? { - val parts = line.split(' ') - if (parts.size != 3 || !parts[1].endsWith(".dill")) return null - return parts[2].toIntOrNull() - } - - /** - * The release kernel: the whole program and the platform, tree-shaken (`--tfa`) for ahead-of-time - * compilation, against the product platform, as flutter_tools compiles one for `flutter build --release`. - */ - fun aotKernelCommand( - runtime: Path, compiler: Path, platformDir: Path, packages: Path, dill: Path, entry: String, - extraArgs: List = emptyList(), - ): List = - listOf(runtime.toString()) + DartSdk.VM_TUNING + listOf( - compiler.toString(), - "--sdk-root", "$platformDir/", - "--target=flutter", - "--aot", - "--tfa", - "-Ddart.vm.product=true", - "-Ddart.vm.profile=false", - "--no-print-incremental-dependencies", - "--packages=$packages", - "--output-dill=$dill", - ) + extraArgs + entry - - /** - * gen_snapshot from the release kernel to an ELF library the release engine loads, as flutter_tools - * runs it for Android. 32-bit ARM leaves integer division out: not every ARMv7 CPU has the instruction. - */ - fun genSnapshotCommand(genSnapshot: Path, abi: String, dill: Path, elf: Path): List = buildList { - add(genSnapshot.toString()) - add("--deterministic") - add("--snapshot_kind=app-aot-elf") - add("--elf=$elf") - add("--strip") - if (abi == "armeabi-v7a") add("--no-use-integer-division") - add(dill.toString()) - } - - /** What to do when [plugins] have C/C++ that nothing builds. */ - fun noNativeBuild(plugins: List): String = - "The Flutter plugin${if (plugins.size == 1) "" else "s"} ${plugins.joinToString()} " + - "${if (plugins.size == 1) "has" else "have"} C code, which the NDK (C/C++) plugin compiles, and it is " + - "not installed or not turned on. Install it from Settings > Plugins > Get plugins (and allow it), " + - "then build again." - - const val TOO_OLD = "This version of CodeAssist cannot package a Flutter app. Update CodeAssist to build its APK." - - /** - * The Android ABI a native library directory holds: an app's extracted `lib/arm64` names its instruction - * set rather than the ABI, an APK's `lib/arm64-v8a` the ABI itself. - */ - fun abiOf(libraryDir: Path?): String? = when (libraryDir?.fileName?.toString()) { - "arm64", "arm64-v8a" -> "arm64-v8a" - "arm", "armeabi-v7a" -> "armeabi-v7a" - "x86_64" -> "x86_64" - "x86" -> "x86" - else -> null - } - - /** Copy [from] over [to] unless [to] already has its size and time, which is how a copy made here is left. */ - fun copyIfChanged(from: Path, to: Path) { - val time = Files.getLastModifiedTime(from) - if (Files.isRegularFile(to) && Files.size(to) == Files.size(from) && Files.getLastModifiedTime(to) == time) return - Files.createDirectories(to.parent) - Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING) - Files.setLastModifiedTime(to, time) - } - - /** Write [content] to [to] unless it already holds exactly that, so its time (and the APK's inputs) stay put. */ - fun writeIfChanged(content: InputStream, to: Path) { - val bytes = content.readBytes() - if (Files.isRegularFile(to) && Files.size(to) == bytes.size.toLong() && Files.readAllBytes(to).contentEquals(bytes)) return - Files.createDirectories(to.parent) - Files.write(to, bytes) - } - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterAppTemplate.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterAppTemplate.kt deleted file mode 100644 index 295da66e8d..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterAppTemplate.kt +++ /dev/null @@ -1,207 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.model.BuildSystemId -import dev.ide.model.DependencyScope -import dev.ide.model.FacetData -import dev.ide.model.LibraryDependency -import dev.ide.model.LibraryRef -import dev.ide.model.template.ProjectScaffold -import dev.ide.model.template.ProjectTemplate -import dev.ide.model.template.TemplateArgs -import dev.ide.model.template.TemplateCategory -import dev.ide.model.template.TemplateDependency -import dev.ide.model.template.TemplateId -import dev.ide.model.template.TemplateParameter - -/** - * A Flutter app: the package at the project root, `lib/main.dart` the app. Run starts it in the Flutter player - * on this device and hot-reloads it as files are saved. - * - * Beside it, `android/app` is the app's Android side, as `flutter create` lays it out: a manifest, a - * `MainActivity` that is a `FlutterActivity`, a theme and an icon. Building that module builds the Flutter app - * into its APK ([FlutterBuildPlugin]), so it installs and runs without the player, and can be shared. - * - * The first `pub get` needs the network: the framework's own dependencies (`characters`, `vector_math`, ...) - * come from pub.dev even though the framework itself comes with the plugin. - */ -class FlutterAppTemplate : ProjectTemplate { - - override val id = TemplateId("flutter-app") - override val displayName = "Flutter App" - override val description = "A Flutter app, run on this device with hot reload and built into an APK. " + - "Flutter ${FlutterSdk.VERSION}; the first pub get and build need the network." - override val category = TemplateCategory.OTHER - override val iconId = DartFileIcons.DART - - override fun parameters(): List = emptyList() - - override fun generate(scaffold: ProjectScaffold, args: TemplateArgs) { - val pkg = DartPackages.packageName(args.name) - val appId = args.packageName - scaffold.workspace.beginModification().apply { - addProject(args.name, BuildSystemId.NATIVE, scaffold.rootDir) - commit() - } - scaffold.workspace.projects.first { it.name == args.name }.beginModification().apply { - addModule(pkg, scaffold.moduleType(DartModuleType.ID)).apply { - dirRelPath = "" - languageLevel = scaffold.languageLevel - addContentRoot("main", "lib", setOf(DartModuleType.DART_SOURCE)) - addContentRoot("test", "test", setOf(DartModuleType.DART_SOURCE)) - } - addModule(ANDROID_MODULE, scaffold.moduleType("android-app")).apply { - dirRelPath = ANDROID_DIR - languageLevel = scaffold.languageLevel - // The Android plugin's own table, written by name: this plugin does not link against it. - putFacetData( - FacetData( - "android", - mapOf( - "namespace" to appId, - "applicationId" to appId, - "compileSdk" to COMPILE_SDK, - "minSdk" to MIN_SDK, - "targetSdk" to COMPILE_SDK, - "versionCode" to 1, - "versionName" to "1.0.0", - ), - ), - ) - putFacetData(FacetData(FlutterFacetCodec.tomlTable, FlutterFacetCodec.encode(FlutterFacet()))) - // The engine's Java half, one per build type as the Flutter Gradle plugin declares it - // (`debugImplementation` / `releaseImplementation`): the debug one runs a kernel, the release one - // loads libapp.so, and a build must have exactly one. - for ((variant, coordinate) in EMBEDDINGS) { - addDependency(LibraryDependency(LibraryRef(coordinate), DependencyScope.IMPLEMENTATION, variant = variant)) - } - } - commit() - } - scaffold.writeText(DartPackages.PUBSPEC, pubspec(pkg)) - scaffold.writeText("lib/main.dart", main(args.name)) - scaffold.writeText(".gitignore", ".dart_tool/\nbuild/\n$ANDROID_DIR/build/\n") - scaffold.writeText("README.md", readme(pkg)) - FlutterAndroidFiles.write(scaffold, ANDROID_DIR, appId, args.name) - // Flutter's engine is on its own Maven repository; the project resolves the embedding from there. - scaffold.writeText(REPOSITORIES_FILE, "Flutter\t${FlutterSdk.MAVEN_REPOSITORY}\n") - } - - /** - * The engine's Java halves, resolved once the project opens like every template's Maven dependencies. - * [generate] has already declared them, scoped to their build types, which a [TemplateDependency] cannot - * say; listing them here is what has them resolved. - */ - override fun dependencies(args: TemplateArgs): List = - EMBEDDINGS.map { (_, coordinate) -> TemplateDependency(module = ANDROID_MODULE, coordinate = coordinate) } - - private fun pubspec(pkg: String) = """ - name: $pkg - description: A Flutter app. - version: 1.0.0 - publish_to: none - - environment: - sdk: ^3.9.0 - - dependencies: - flutter: - sdk: flutter - cupertino_icons: ^1.0.8 - - flutter: - uses-material-design: true - """.trimIndent() + "\n" - - private fun main(title: String) = """ - import 'package:flutter/material.dart'; - import 'package:flutter/widget_previews.dart'; - - void main() => runApp(const App()); - - class App extends StatelessWidget { - const App({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp( - title: ${dartString(title)}, - theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo)), - home: const CounterPage(title: ${dartString(title)}), - ); - } - } - - class CounterPage extends StatefulWidget { - const CounterPage({super.key, required this.title}); - - final String title; - - @override - State createState() => _CounterPageState(); - } - - class _CounterPageState extends State { - int _count = 0; - - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar(title: Text(widget.title)), - body: Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Text('Taps so far:'), - Text('${'$'}_count', style: Theme.of(context).textTheme.displayMedium), - ], - ), - ), - floatingActionButton: FloatingActionButton( - onPressed: () => setState(() => _count++), - tooltip: 'Tap', - child: const Icon(Icons.add), - ), - ); - } - } - - // Previews: pick "Preview widgets" in the Run menu to see these, updating as you save. - @Preview(name: 'Counter page') - Widget counterPagePreview() => const CounterPage(title: 'Preview'); - - @Preview(name: 'Counter page, small phone', size: Size(320, 480), textScaleFactor: 1.3) - Widget smallCounterPagePreview() => const CounterPage(title: 'Small'); - """.trimIndent() + "\n" - - private fun readme(pkg: String) = """ - # $pkg - - A Flutter app, run on this device by the Dart plugin's Flutter player. - - - `lib/main.dart` is the app. Press Run: it starts in the player, and every file you save hot-reloads - into it, keeping its state. In the Run console, type `r` to hot reload, `R` to restart, `q` to quit. - - Functions marked `@Preview` show in "Preview widgets" in the Run menu: every preview in `lib/` in one - gallery, hot-reloading as you save. - - Add packages in `pubspec.yaml`; saving it runs `pub get` and restarts the app. Packages with their own - Android code (plugins) do not work in the player. - - `android/app` is the app's Android side. Run Debug builds an APK that installs and runs without the - player, in Flutter's debug mode; Run Release compiles the app ahead of time to machine code, as - `flutter build apk --release` does, for a smaller, faster APK. Either is for this device's ABI, and - the module's manifest, theme and icon are ordinary Android files. - """.trimIndent() + "\n" - - companion object { - const val ANDROID_MODULE = "app" - const val ANDROID_DIR = "android/app" - const val COMPILE_SDK = 36 - const val MIN_SDK = 26 - - /** Build type to the embedding it compiles and packages. */ - val EMBEDDINGS = listOf("debug" to FlutterSdk.EMBEDDING_DEBUG, "release" to FlutterSdk.EMBEDDING_RELEASE) - - /** The project's extra Maven repositories, one `nameurl` per line, as the Dependencies screen keeps them. */ - const val REPOSITORIES_FILE = ".platform/repositories.txt" - } - - private fun dartString(s: String) = "'" + s.replace("\\", "\\\\").replace("'", "\\'").replace("$", "\\$") + "'" -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterAssets.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterAssets.kt deleted file mode 100644 index a120bd4593..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterAssets.kt +++ /dev/null @@ -1,248 +0,0 @@ -package dev.codeassist.dart - -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.buildJsonArray -import kotlinx.serialization.json.buildJsonObject -import kotlinx.serialization.json.put -import java.io.ByteArrayOutputStream -import java.nio.file.Files -import java.nio.file.Path -import java.util.stream.Collectors - -/** - * A Flutter app's asset bundle (`flutter_assets`), built the way `flutter build bundle` lays one out, for the - * player to run the app with: the assets and fonts the app and its packages declare, the manifests the - * framework reads them by, and the base assets (the Material icons font, the framework's compiled shaders, - * the license notices) that come with the Flutter the plugin carries. - * - * Not implemented: resolution-aware asset variants (`2.0x/`), asset transformers, deferred components. - */ -object FlutterAssets { - - /** The bundle: published path to the file it comes from, plus the generated manifests. */ - class Bundle(val files: Map, val generated: Map) - - /** Build the bundle of the package at [pkg], whose `pub get` has run, with the base assets in [base]. */ - fun build(pkg: Path, base: Path): Bundle { - val files = LinkedHashMap() - val assetKeys = ArrayList() - val fonts = ArrayList() - - val packages = packages(pkg) - val rootName = DartPackages.nameOf(read(pkg.resolve(DartPackages.PUBSPEC))) ?: "" - // The app first, then its packages: the order flutter_tools lists them in. - val ordered = packages.sortedBy { (name, _) -> if (name == rootName) 0 else 1 } - var materialDesign = false - for ((name, dir) in ordered) { - val isRoot = name == rootName - val section = (MiniYaml.parse(read(dir.resolve(DartPackages.PUBSPEC))) as? Map<*, *>)?.get("flutter") as? Map<*, *> - ?: continue - val prefix = if (isRoot) "" else "packages/$name/" - if (isRoot && section["uses-material-design"]?.toString() == "true") materialDesign = true - for (entry in section["assets"] as? List<*> ?: emptyList()) { - val declared = (entry as? Map<*, *>)?.get("path")?.toString() ?: entry?.toString() ?: continue - for (file in expand(dir, declared)) { - val key = prefix + dir.relativize(file).joinToString("/") { it.toString() } - if (files.put(key, file) == null) assetKeys += key - } - } - for (family in section["fonts"] as? List<*> ?: emptyList()) { - val f = family as? Map<*, *> ?: continue - val familyName = f["family"]?.toString() ?: continue - val faces = (f["fonts"] as? List<*>).orEmpty().mapNotNull { face -> - val m = face as? Map<*, *> ?: return@mapNotNull null - val asset = m["asset"]?.toString() ?: return@mapNotNull null - val key = prefix + asset - val file = dir.resolve(asset).normalize() - if (Files.isRegularFile(file) && files.put(key, file) == null) assetKeys += key - buildJsonObject { - put("asset", key) - m["weight"]?.toString()?.toIntOrNull()?.let { put("weight", it) } - m["style"]?.toString()?.let { put("style", it) } - } - } - fonts += buildJsonObject { - put("family", prefix + familyName) - put("fonts", JsonArray(faces)) - } - } - } - - if (materialDesign) { - files["fonts/MaterialIcons-Regular.otf"] = base.resolve("fonts/MaterialIcons-Regular.otf") - fonts.add(0, buildJsonObject { - put("family", "MaterialIcons") - put("fonts", buildJsonArray { add(buildJsonObject { put("asset", "fonts/MaterialIcons-Regular.otf") }) }) - }) - } - listFiles(base.resolve("shaders")).forEach { files["shaders/${it.fileName}"] = it } - base.resolve("NOTICES.Z").takeIf { Files.isRegularFile(it) }?.let { files["NOTICES.Z"] = it } - - val generated = linkedMapOf( - "AssetManifest.bin" to assetManifest(assetKeys), - "FontManifest.json" to Json.encodeToString(JsonArray.serializer(), JsonArray(fonts)).toByteArray(), - "NativeAssetsManifest.json" to """{"format-version":[1,0,0],"native-assets":{}}""".toByteArray(), - ) - return Bundle(files, generated) - } - - /** The asset manifest: each asset to its variants, the only variant being itself (no `2.0x/` support). */ - fun assetManifest(keys: List): ByteArray = - StandardMessageCodec.encode(keys.associateWith { listOf(mapOf("asset" to it)) }) - - /** A declared asset: a file, or a directory (ending in `/`) meaning the files directly in it. */ - private fun expand(dir: Path, declared: String): List { - val target = dir.resolve(declared.removeSuffix("/")).normalize() - if (!target.startsWith(dir)) return emptyList() - return if (declared.endsWith("/")) listFiles(target) else listOfNotNull(target.takeIf { Files.isRegularFile(it) }) - } - - private fun listFiles(dir: Path): List { - if (!Files.isDirectory(dir)) return emptyList() - return Files.list(dir).use { s -> s.filter { Files.isRegularFile(it) && !it.fileName.toString().startsWith(".") }.collect(Collectors.toList()) } - .sortedBy { it.fileName.toString() } - } - - /** Package name to root directory, from `.dart_tool/package_config.json`. */ - fun packages(pkg: Path): List> = DartPackages.packages(pkg) - - private fun read(path: Path): String = runCatching { String(Files.readAllBytes(path)) }.getOrDefault("") -} - -/** - * Flutter's StandardMessageCodec, the encoding of `AssetManifest.bin`: the part of it a manifest uses (null, - * booleans, strings, lists and maps). Sizes are one byte below 254, else a marker and two or four bytes, - * little-endian. - */ -object StandardMessageCodec { - fun encode(value: Any?): ByteArray = ByteArrayOutputStream().also { write(it, value) }.toByteArray() - - private fun write(out: ByteArrayOutputStream, value: Any?) { - when (value) { - null -> out.write(0) - true -> out.write(1) - false -> out.write(2) - is String -> { - out.write(7) - val bytes = value.toByteArray(Charsets.UTF_8) - size(out, bytes.size) - out.write(bytes) - } - is List<*> -> { out.write(12); size(out, value.size); value.forEach { write(out, it) } } - is Map<*, *> -> { out.write(13); size(out, value.size); value.forEach { (k, v) -> write(out, k); write(out, v) } } - else -> error("StandardMessageCodec: cannot encode ${value::class.simpleName}") - } - } - - private fun size(out: ByteArrayOutputStream, n: Int) { - when { - n < 254 -> out.write(n) - n <= 0xffff -> { out.write(254); out.write(n and 0xff); out.write(n ushr 8) } - else -> { out.write(255); for (shift in 0..24 step 8) out.write((n ushr shift) and 0xff) } - } - } -} - -/** - * Enough YAML for a pubspec: block mappings and sequences by indentation, scalars (quoted or not), comments. - * A sequence item that starts a mapping (`- family: Roboto` with more keys under it) is a mapping. Not flow - * collections, anchors or multi-line scalars, which no pubspec section this plugin reads uses. - */ -object MiniYaml { - private class Line(val indent: Int, val text: String) - - fun parse(text: String): Any? { - val lines = text.lineSequence().mapNotNull { raw -> - val stripped = stripComment(raw).trimEnd() - if (stripped.isBlank() || stripped.trim() == "---") null - else Line(stripped.length - stripped.trimStart().length, stripped.trim()) - }.toMutableList() - if (lines.isEmpty()) return null - return Parser(lines).block(lines[0].indent) - } - - private class Parser(val lines: MutableList) { - var i = 0 - - fun block(indent: Int): Any? { - if (i >= lines.size) return null - return if (lines[i].text == "-" || lines[i].text.startsWith("- ")) sequence(indent) else mapping(indent) - } - - fun mapping(indent: Int): Map { - val out = LinkedHashMap() - while (i < lines.size && lines[i].indent == indent && !isItem(lines[i].text)) { - val line = lines[i] - val colon = keyColon(line.text) - if (colon < 0) { i++; continue } - val key = unquote(line.text.substring(0, colon).trim()) - val rest = line.text.substring(colon + 1).trim() - i++ - out[key] = if (rest.isNotEmpty()) { - // A plain scalar may go on over more-indented lines (`description: one\n two`), as - // pub.dev pubspecs' descriptions often do; folded into one, as YAML reads it. Stopping at - // the first of them lost every key after it, the package's dependencies included. - val parts = arrayListOf(rest) - while (i < lines.size && lines[i].indent > indent) { parts += lines[i].text; i++ } - scalar(parts.joinToString(" ")) - } else when { - i < lines.size && lines[i].indent > indent -> block(lines[i].indent) - // `key:` followed by a sequence at the same indent is legal YAML, and common in pubspecs. - i < lines.size && lines[i].indent == indent && isItem(lines[i].text) -> sequence(indent) - else -> null - } - } - return out - } - - fun sequence(indent: Int): List { - val out = ArrayList() - while (i < lines.size && lines[i].indent == indent && isItem(lines[i].text)) { - val content = lines[i].text.removePrefix("-").trimStart() - if (content.isEmpty()) { - i++ - out += if (i < lines.size && lines[i].indent > indent) block(lines[i].indent) else null - } else if (keyColon(content) >= 0) { - // `- key: value` starts a mapping whose keys sit where `key` does. - val inner = indent + (lines[i].text.length - content.length) - lines[i] = Line(inner, content) - out += mapping(inner) - } else { - out += scalar(content) - i++ - } - } - return out - } - - private fun isItem(text: String) = text == "-" || text.startsWith("- ") - } - - /** The colon ending a mapping key on [text], ignoring colons inside quotes; -1 for none. */ - private fun keyColon(text: String): Int { - var quote: Char? = null - for ((index, c) in text.withIndex()) { - if (quote != null) { if (c == quote) quote = null; continue } - if (c == '\'' || c == '"') { if (index == 0) quote = c; continue } - if (c == ':' && (index + 1 == text.length || text[index + 1] == ' ')) return index - } - return -1 - } - - private fun scalar(text: String): String = unquote(text) - - private fun unquote(text: String): String = - if (text.length >= 2 && (text[0] == '"' || text[0] == '\'') && text.last() == text[0]) text.substring(1, text.length - 1) else text - - private fun stripComment(line: String): String { - var quote: Char? = null - for ((index, c) in line.withIndex()) { - if (quote != null) { if (c == quote) quote = null; continue } - if (c == '\'' || c == '"') quote = c - else if (c == '#' && (index == 0 || line[index - 1].isWhitespace())) return line.substring(0, index) - } - return line - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPlayerActivity.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPlayerActivity.kt deleted file mode 100644 index ef46cf2a33..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPlayerActivity.kt +++ /dev/null @@ -1,97 +0,0 @@ -package dev.codeassist.dart - -import android.os.Bundle -import android.os.Handler -import android.os.Looper -import android.os.Messenger -import android.os.Process -import android.os.ResultReceiver -import io.flutter.embedding.android.FlutterActivity -import io.flutter.embedding.engine.FlutterJNI - -/** - * The Flutter player. It starts on a few-kilobyte `dart:ui` program ("Waiting for CodeAssist...") and is then - * handed the real app through its Dart VM service, the way `flutter run` restarts and hot-reloads an app. - * - * Runs in this plugin's own process, started only by [FlutterPlayerLauncher] (it is not exported), which - * passes on the IDE's [ResultReceiver] in [EXTRA_RECEIVER]; the player answers it with its VM service URI - * (auth token included) and its isolate once the engine has them. - */ -class FlutterPlayerActivity : FlutterActivity() { - - /** - * No plugins: an app's Flutter plugins (packages with Android code of their own) are not in the player, so - * there is no GeneratedPluginRegistrant to call, and the default implementation logs its absence as an error. - */ - override fun configureFlutterEngine(flutterEngine: io.flutter.embedding.engine.FlutterEngine) {} - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - reportVmService() - } - - override fun onNewIntent(intent: android.content.Intent) { - super.onNewIntent(intent) - setIntent(intent) - reportVmService() - } - - /** - * The run's way to end the player: [QUIT] closes its task and ends this process, which holds nothing but the - * player (the preview pane's engines are in `:preview`). Not `ext.flutter.exit`, the VM service's own - * exit: with the player in the background it left the VM wedged and the process alive. - */ - private val control = Messenger(Handler(Looper.getMainLooper()) { msg -> - if (msg.what == QUIT) { - finishAndRemoveTask() - Process.killProcess(Process.myPid()) - } - true - }) - - /** Send the VM service URI to whoever started this run, as soon as the engine publishes it. */ - private fun reportVmService() { - val receiver = intent.getParcelableExtra(EXTRA_RECEIVER) ?: return - intent.removeExtra(EXTRA_RECEIVER) - Thread({ - var uri: String? = null - var isolate: String? = null - val deadline = System.currentTimeMillis() + 20_000 - // The isolate only picks the view when a VM has several, so once the VM service is up it is waited - // for briefly, never the whole deadline. - var isolateDeadline = Long.MAX_VALUE - while ((uri == null || isolate == null) && System.currentTimeMillis() < minOf(deadline, isolateDeadline)) { - uri = uri ?: runCatching { FlutterJNI.getVMServiceUri() }.getOrNull()?.takeIf { it.isNotBlank() } - ?.also { isolateDeadline = System.currentTimeMillis() + ISOLATE_GRACE_MS } - isolate = isolate ?: runCatching { flutterEngine?.dartExecutor?.isolateServiceId }.getOrNull() - if (uri == null || isolate == null) Thread.sleep(50) - } - receiver.send(if (uri != null) 0 else 1, Bundle().apply { - putString(EXTRA_URI, uri) - putString(EXTRA_ISOLATE, isolate) - // How the run ends the player. Handed only to the caller FlutterPlayerLauncher let in, so it needs - // no check of its own. - putBinder(EXTRA_CONTROL, control.binder) - }) - }, "flutter-player-vm-service").apply { isDaemon = true }.start() - } - - companion object { - /** How long the isolate id is waited for once the VM service is known. */ - internal const val ISOLATE_GRACE_MS = 1_000L - const val EXTRA_RECEIVER = "dev.codeassist.dart.VM_SERVICE_RECEIVER" - const val EXTRA_URI = "uri" - /** A Messenger binder; [QUIT] sent to it ends the player. */ - const val EXTRA_CONTROL = "control" - const val QUIT = 1 - /** Result codes besides 0 (the VM service) and 1 (none): the launcher let the caller in, or did not. */ - const val RESULT_REACHED = 2 - const val RESULT_REFUSED = 3 - /** A PendingIntent the caller made: its creator says who the caller is, on any Android version. */ - const val EXTRA_IDENTITY = "dev.codeassist.dart.CALLER_IDENTITY" - /** With [RESULT_REFUSED]: the package the launcher took the caller to be. */ - const val EXTRA_CALLER = "caller" - /** The isolate the player's engine started, which picks its view out of the VM's. */ - const val EXTRA_ISOLATE = "isolate" - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPlayerLauncher.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPlayerLauncher.kt deleted file mode 100644 index 759a91e00b..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPlayerLauncher.kt +++ /dev/null @@ -1,68 +0,0 @@ -package dev.codeassist.dart - -import android.app.Activity -import android.app.PendingIntent -import android.content.Intent -import android.content.pm.ApplicationInfo -import android.os.Build -import android.os.Bundle -import android.os.ResultReceiver -import android.util.Log - -/** - * The one way into the Flutter player from outside this app, and the check on who is asking. - * - * The player hands whoever starts it the address of its Dart VM service, auth token included, and the VM - * service runs any code it is given, as this app. So the player is not exported; this Activity is, and starts - * it only for CodeAssist itself ([TRUSTED_HOSTS]), refusing everyone else without starting an engine. - * - * Who is asking: on Android 14 and later the system says, when the caller shares its identity (the IDE does, - * with `ActivityOptions.setShareIdentityEnabled`). Before that, the creator of the PendingIntent the caller passes - * in [FlutterPlayerActivity.EXTRA_IDENTITY], which the system records and no app can forge. The referrer is the - * last resort: Android fills it in only for a start from an Activity, which the IDE's build process has none of, - * and a referrer extra the intent carries itself is what a caller pretending to be someone else would add. - */ -class FlutterPlayerLauncher : Activity() { - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - val caller = callerPackage() - // Answered at once either way, so the IDE can tell a launch the system blocked (nothing answers) from - // one refused here or a player that started and then failed. - val receiver = runCatching { intent.getParcelableExtra(FlutterPlayerActivity.EXTRA_RECEIVER) }.getOrNull() - if (caller != null && trusted(caller)) { - startActivity( - Intent(this, FlutterPlayerActivity::class.java) - .putExtras(intent) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), - ) - receiver?.send(FlutterPlayerActivity.RESULT_REACHED, null) - } else { - val who = caller ?: "an unidentified caller" - Log.w(TAG, "refused to start the Flutter player for $who") - receiver?.send(FlutterPlayerActivity.RESULT_REFUSED, Bundle().apply { putString(FlutterPlayerActivity.EXTRA_CALLER, who) }) - } - finish() - } - - private fun callerPackage(): String? { - if (Build.VERSION.SDK_INT >= 34) launchedFromPackage?.let { return it } - runCatching { intent.getParcelableExtra(FlutterPlayerActivity.EXTRA_IDENTITY)?.creatorPackage } - .getOrNull()?.let { return it } - if (intent.hasExtra(Intent.EXTRA_REFERRER) || intent.hasExtra(Intent.EXTRA_REFERRER_NAME)) return null - return referrer?.takeIf { it.scheme == "android-app" }?.host - } - - private fun trusted(caller: String): Boolean { - if (caller in TRUSTED_HOSTS) return true - // A debuggable build of the plugin also answers adb, which is already a more privileged caller. - return caller == "com.android.shell" && (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0 - } - - companion object { - private const val TAG = "FlutterPlayerLauncher" - - /** The CodeAssist apps the player runs Flutter apps for. */ - val TRUSTED_HOSTS = setOf("com.tyron.code") - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPlugins.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPlugins.kt deleted file mode 100644 index b496b53386..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPlugins.kt +++ /dev/null @@ -1,346 +0,0 @@ -package dev.codeassist.dart - -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.StandardCopyOption -import java.util.stream.Collectors - -/** - * A Flutter plugin the app depends on, as its pubspec's `flutter: plugin:` section describes it for Android. - * - * Three kinds matter here, alone or together: [pluginClass] is Java or Kotlin code under the package's `android/` - * that the app registers with its engine; [ffi] is native code built by CMake and loaded from Dart; and - * [dartPluginClass] is a Dart class registered at startup (a federated plugin's Android implementation, which - * may have no Android code at all and reach Android through `jni` instead). - */ -data class FlutterPlugin( - val name: String, - /** The package's root (where its pubspec is). */ - val root: Path, - val androidPackage: String? = null, - val pluginClass: String? = null, - val dartPluginClass: String? = null, - /** `package:/` the Dart class is in: `dartPluginFile`, else `.dart`. */ - val dartPluginFile: String? = null, - val ffi: Boolean = false, - /** The interface package this implements (`implements:`), for choosing one implementation per interface. */ - val implements: String? = null, - /** The other Android plugins this one depends on, by package name. */ - val dependsOn: List = emptyList(), -) { - /** The package has an Android library to build: code to register, or native code to compile. */ - val hasAndroidCode: Boolean get() = (pluginClass != null || ffi) && Files.isDirectory(root.resolve("android")) -} - -/** What a plugin's `android/build.gradle(.kts)` says, as far as it can be read without running Gradle. */ -data class PluginAndroidBuild( - val namespace: String? = null, - val minSdk: Int? = null, - /** `configuration` to `group:name:version`: implementation, api, compileOnly, runtimeOnly. */ - val dependencies: List> = emptyList(), - /** Declarations that could not be read (a version catalog entry, an interpolated version). */ - val unreadDependencies: List = emptyList(), - /** Java source directories besides `src/main/java`, relative to `android/` (`../java/src/main/java`). */ - val extraJavaDirs: List = emptyList(), - /** `externalNativeBuild { cmake { path } }`, relative to `android/`. */ - val cmakePath: String? = null, -) - -/** - * What a Flutter app's `android/app/build.gradle(.kts)` says. A value written as `flutter.` (the Flutter Gradle - * plugin's default) reads as null: the caller fills in the default, as that plugin would. - */ -data class AppAndroidBuild( - val namespace: String? = null, - val applicationId: String? = null, - val compileSdk: Int? = null, - val minSdk: Int? = null, - val targetSdk: Int? = null, - val versionCode: Int? = null, - val versionName: String? = null, - val dependencies: List> = emptyList(), - val unreadDependencies: List = emptyList(), -) - -/** One `add_library(... SHARED ...)` of a plugin's CMakeLists.txt, which is all a Flutter FFI plugin's usually is. */ -data class CMakeLibrary( - val target: String, - val outputName: String, - /** Source files relative to the CMakeLists' directory. */ - val sources: List, - val definitions: List = emptyList(), - val linkLibraries: List = emptyList(), -) - -object FlutterPlugins { - - /** - * The plugins of the app at [pkg] (whose `pub get` has run), sorted by name as `flutter` lists them: every - * package its non-dev dependencies reach whose pubspec declares an Android plugin. A dev dependency's plugin - * (a test helper) does not belong in the app. - */ - fun discover(pkg: Path): List { - val roots = DartPackages.packages(pkg).toMap() - val pubspecs = HashMap>() - fun pubspec(name: String): Map<*, *>? = pubspecs.getOrPut(name) { - val root = roots[name] ?: return null - (runCatching { MiniYaml.parse(String(Files.readAllBytes(root.resolve(DartPackages.PUBSPEC)))) }.getOrNull() as? Map<*, *>) - ?: emptyMap() - } - fun dependencies(spec: Map<*, *>?): List = - (spec?.get("dependencies") as? Map<*, *>)?.keys?.map { it.toString() }.orEmpty() - - val appSpec = runCatching { MiniYaml.parse(String(Files.readAllBytes(pkg.resolve(DartPackages.PUBSPEC)))) }.getOrNull() as? Map<*, *> - val appName = appSpec?.get("name")?.toString() - // Everything the app's own dependencies reach, dev dependencies left out. - val reached = LinkedHashSet() - val queue = ArrayDeque(dependencies(appSpec)) - while (queue.isNotEmpty()) { - val name = queue.removeFirst() - if (name == appName || name !in roots || !reached.add(name)) continue - queue.addAll(dependencies(pubspec(name))) - } - - val plugins = reached.mapNotNull { name -> describe(name, roots.getValue(name), pubspec(name) ?: return@mapNotNull null) } - val android = plugins.filter { it.hasAndroidCode }.map { it.name }.toSet() - return plugins - .map { p -> p.copy(dependsOn = dependencies(pubspec(p.name)).filter { it in android && it != p.name }.sorted()) } - .sortedBy { it.name } - } - - /** [spec]'s Android plugin, or null when the package is not one (or has nothing for Android). */ - fun describe(name: String, root: Path, spec: Map<*, *>): FlutterPlugin? { - val plugin = (spec["flutter"] as? Map<*, *>)?.get("plugin") as? Map<*, *> ?: return null - val implements = plugin["implements"]?.toString() - val android = (plugin["platforms"] as? Map<*, *>)?.get("android") as? Map<*, *> - if (android == null) { - // The format before `platforms:`, Android only. - val pkg = plugin["androidPackage"]?.toString() ?: return null - return FlutterPlugin(name, root, androidPackage = pkg, pluginClass = plugin["pluginClass"]?.toString(), implements = implements) - } - val pluginClass = android["pluginClass"]?.toString()?.takeIf { it.isNotBlank() && it != "none" } - val dartPluginClass = android["dartPluginClass"]?.toString()?.takeIf { it.isNotBlank() } - val ffi = android["ffiPlugin"]?.toString() == "true" - if (pluginClass == null && dartPluginClass == null && !ffi) return null - return FlutterPlugin( - name, root, - androidPackage = android["package"]?.toString(), - pluginClass = pluginClass, - dartPluginClass = dartPluginClass, - dartPluginFile = android["dartPluginFile"]?.toString(), - ffi = ffi, - implements = implements, - ) - } - - // ---- reading a plugin's Android build ---- - - fun readAndroidBuild(androidDir: Path): PluginAndroidBuild { - val file = listOf("build.gradle.kts", "build.gradle").map { androidDir.resolve(it) }.firstOrNull { Files.isRegularFile(it) } - ?: return PluginAndroidBuild() - return parseAndroidBuild(String(Files.readAllBytes(file))) - } - - private val CONFIGURATIONS = setOf("implementation", "api", "compileOnly", "runtimeOnly") - - fun parseAndroidBuild(text: String): PluginAndroidBuild { - val code = stripComments(text) - val namespace = Regex("""\bnamespace\s*(?:=\s*)?["']([\w.]+)["']""").find(code)?.groupValues?.get(1) - val minSdk = Regex("""\bminSdk(?:Version)?\s*(?:=\s*)?(?:\(\s*)?(\d+)""").find(code)?.groupValues?.get(1)?.toIntOrNull() - val deps = ArrayList>() - val unread = ArrayList() - // `implementation("g:a:v")`, `implementation 'g:a:v'`; anything else on such a line is reported, not guessed. - for (m in Regex("""(?m)^\s*(\w+)\s*\(?\s*(.+?)\s*\)?\s*$""").findAll(code)) { - val configuration = m.groupValues[1] - if (configuration !in CONFIGURATIONS) continue - val argument = m.groupValues[2] - val literal = Regex("""^["']([^"'\s]+:[^"'\s]+:[^"'\s]+)["']$""").find(argument)?.groupValues?.get(1) - if (literal != null && '$' !in literal) deps += configuration to literal - else if (!argument.startsWith("project(") && !argument.startsWith("files(") && !argument.startsWith("fileTree(")) { - unread += "$configuration $argument" - } - } - // `java.srcDirs += '../x'`, `java { srcDirs '../x' }`, `java.srcDir("../x")`. - val javaDirs = Regex("""java[\s\S]{0,40}?srcDirs?\s*(?:\+=|=)?\s*\(?\s*(?:\[|listOf\(|setOf\()?\s*["']([^"']+)["']""") - .findAll(code).map { it.groupValues[1] }.filter { it != "src/main/java" }.distinct().toList() - val cmake = Regex("""cmake\s*\{[\s\S]*?\bpath\s*(?:=\s*)?(?:file\(\s*)?["']([^"']*CMakeLists\.txt)["']""").find(code)?.groupValues?.get(1) - return PluginAndroidBuild(namespace, minSdk, deps, unread, javaDirs, cmake) - } - - fun parseAppBuild(text: String): AppAndroidBuild { - val code = stripComments(text) - val common = parseAndroidBuild(text) - fun int(name: String): Int? = - Regex("""\b$name(?:Version)?\s*(?:=\s*)?(?:\(\s*)?(\d+)""").find(code)?.groupValues?.get(1)?.toIntOrNull() - fun string(name: String): String? = - Regex("""\b$name\s*(?:=\s*)?["']([^"'$]+)["']""").find(code)?.groupValues?.get(1) - return AppAndroidBuild( - namespace = common.namespace, - applicationId = string("applicationId"), - compileSdk = int("compileSdk"), - minSdk = common.minSdk, - targetSdk = int("targetSdk"), - versionCode = int("versionCode"), - versionName = string("versionName"), - dependencies = common.dependencies, - unreadDependencies = common.unreadDependencies, - ) - } - - /** The first SHARED library [text] (a CMakeLists.txt) adds, with what it is compiled and linked with. */ - fun parseCMake(text: String): CMakeLibrary? { - val code = text.lineSequence().map { it.substringBefore('#') }.joinToString("\n") - val lib = Regex("""add_library\s*\(\s*([\w.-]+)\s+SHARED\s+([^)]*)\)""").find(code) ?: return null - val target = lib.groupValues[1] - fun arguments(body: String) = Regex(""""([^"]*)"|(\S+)""").findAll(body).map { it.groupValues[1].ifEmpty { it.groupValues[2] } }.toList() - val sources = arguments(lib.groupValues[2]).filter { !it.startsWith("\${") && it.isNotBlank() } - val outputName = Regex("""set_target_properties\s*\(\s*${Regex.escape(target)}\b[^)]*OUTPUT_NAME\s+"?([\w.-]+)"?""").find(code)?.groupValues?.get(1) ?: target - val keywords = setOf("PUBLIC", "PRIVATE", "INTERFACE") - val definitions = Regex("""target_compile_definitions\s*\(\s*${Regex.escape(target)}\s+([^)]*)\)""").findAll(code) - .flatMap { arguments(it.groupValues[1]) }.filter { it !in keywords && !it.startsWith("\${") }.toList() - // Only the Android branch's libraries count, and only system ones (`log`, `android`, `m`): a CMake - // variable is for the desktop builds the same file serves. - val links = Regex("""target_link_libraries\s*\(\s*${Regex.escape(target)}\s+([^)]*)\)""").findAll(code) - .flatMap { arguments(it.groupValues[1]) }.filter { it !in keywords && Regex("""[a-z0-9_]+""").matches(it) }.distinct().toList() - return CMakeLibrary(target, outputName, sources, definitions, links) - } - - private fun stripComments(text: String): String = - text.replace(Regex("""/\*[\s\S]*?\*/"""), "").lineSequence().map { line -> - val at = Regex("""(^|[^:"'])//""").find(line)?.range?.first - if (at == null) line else line.substring(0, at + if (line[at] == '/') 0 else 1) - }.joinToString("\n") - - // ---- the plugin's Android library, inside the app's project ---- - - /** Where [plugin]'s Android library lives in the project at [pkg]: a copy, laid out as one module. */ - fun moduleDirRel(plugin: FlutterPlugin) = ".dart_tool/codeassist/android-plugins/${plugin.name}" - - /** - * Copy [plugin]'s Android library into [dest], laid out as a plain Android library module: `src/main` from - * `android/src/main`, any extra Java directories its build names merged into `src/main/java`, and its CMake - * library's sources (with every header beside them) under `src/main/cpp`, where the NDK plugin builds it. - * A copy rather than the pub cache in place, because a module lives inside its project, and the pub cache - * is shared by every project and owned by pub. Skipped when [dest] already holds this version. - */ - fun copyAndroidLibrary(plugin: FlutterPlugin, build: PluginAndroidBuild, cmake: CMakeLibrary?, dest: Path) { - val stamp = dest.resolve(".source") - val source = plugin.root.toString() - if (Files.isRegularFile(stamp) && String(Files.readAllBytes(stamp)) == source) return - if (Files.exists(dest)) dest.toFile().deleteRecursively() - val android = plugin.root.resolve("android") - copyTree(android.resolve("src/main"), dest.resolve("src/main")) - for (dir in build.extraJavaDirs) copyTree(android.resolve(dir).normalize(), dest.resolve("src/main/java")) - if (cmake != null && build.cmakePath != null) { - val cmakeDir = android.resolve(build.cmakePath).normalize().parent - val cpp = dest.resolve("src/main/cpp") - for (file in cmake.sources) copyFile(cmakeDir.resolve(file).normalize(), cpp.resolve(file).normalize()) - Files.walk(cmakeDir).use { s -> s.filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(".h") }.collect(Collectors.toList()) } - .forEach { copyFile(it, cpp.resolve(cmakeDir.relativize(it).toString())) } - } - Files.createDirectories(dest) - Files.write(stamp, source.toByteArray()) - } - - private fun copyTree(from: Path, to: Path) { - if (!Files.isDirectory(from)) return - Files.walk(from).use { s -> s.filter { Files.isRegularFile(it) }.collect(Collectors.toList()) } - .forEach { copyFile(it, to.resolve(from.relativize(it).toString())) } - } - - private fun copyFile(from: Path, to: Path) { - if (!Files.isRegularFile(from)) return - Files.createDirectories(to.parent) - Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING) - } - - // ---- registrants ---- - - /** - * `GeneratedPluginRegistrant.java`, which `FlutterActivity` registers the app's plugins through: one `add` per - * plugin with a [FlutterPlugin.pluginClass], each failing alone, as `flutter` writes it. - */ - fun javaRegistrant(plugins: List): String = buildString { - append( - """ - package io.flutter.plugins; - - import androidx.annotation.Keep; - import androidx.annotation.NonNull; - import io.flutter.Log; - - import io.flutter.embedding.engine.FlutterEngine; - - /** - * Generated file. Do not edit. - * CodeAssist writes it from the app's Flutter plugins that support Android, as the Flutter tool does. - */ - @Keep - public final class GeneratedPluginRegistrant { - private static final String TAG = "GeneratedPluginRegistrant"; - public static void registerWith(@NonNull FlutterEngine flutterEngine) { - - """.trimIndent(), - ) - for (p in plugins.filter { it.pluginClass != null && it.androidPackage != null }) { - val cls = "${p.androidPackage}.${p.pluginClass}" - append(" try {\n") - append(" flutterEngine.getPlugins().add(new $cls());\n") - append(" } catch (Exception e) {\n") - append(" Log.e(TAG, \"Error registering plugin ${p.name}, $cls\", e);\n") - append(" }\n") - } - append(" }\n}\n") - } - - /** - * The Dart plugin registrant: the one Android implementation per interface that registers itself in Dart - * (`dartPluginClass`), called by the engine before `main`. The app's direct dependency wins over a default - * implementation, as `flutter` decides it. Null when no plugin has one. - */ - fun dartRegistrant(plugins: List, directDependencies: Set): String? { - val chosen = plugins.filter { it.dartPluginClass != null } - .groupBy { it.implements ?: it.name } - .map { (_, candidates) -> candidates.firstOrNull { it.name in directDependencies } ?: candidates.first() } - .sortedBy { it.name } - if (chosen.isEmpty()) return null - return buildString { - append("// Generated file. Do not edit. CodeAssist writes it from the app's Flutter plugins, as the Flutter tool does.\n") - append("// ignore_for_file: type=lint\n\n") - append("import 'dart:io'; // flutter_ignore: dart_io_import.\n") - for (p in chosen) append("import 'package:${p.name}/${p.dartPluginFile ?: "${p.name}.dart"}' as ${p.name};\n") - append("\n@pragma('vm:entry-point')\nclass _PluginRegistrant {\n\n @pragma('vm:entry-point')\n static void register() {\n") - append(" if (Platform.isAndroid) {\n") - for (p in chosen) { - append(" try {\n") - append(" ${p.name}.${p.dartPluginClass}.registerWith();\n") - append(" } catch (err) {\n") - append(" print('`${p.name}` threw an error: \$err. The app may not function as expected until you remove this plugin from pubspec.yaml');\n") - append(" }\n") - } - append(" }\n }\n}\n") - } - } - - /** Where the Dart registrant is written, as `flutter` places it. */ - fun dartRegistrantFile(pkg: Path): Path = pkg.resolve(".dart_tool/flutter_build/dart_plugin_registrant.dart") - - /** - * The compiler arguments that include [registrant] in the program and tell the engine where it is, as - * `flutter` passes them to the frontend server. - */ - fun dartRegistrantArgs(registrant: Path): List { - val uri = registrant.toUri().toString() - return listOf( - "--source", uri, - "--source", "package:flutter/src/dart_plugin_registrant.dart", - "-Dflutter.dart_plugin_registrant=$uri", - ) - } - - /** The app's direct (non-dev) dependencies, by name. */ - fun directDependencies(pkg: Path): Set { - val spec = runCatching { MiniYaml.parse(String(Files.readAllBytes(pkg.resolve(DartPackages.PUBSPEC)))) }.getOrNull() as? Map<*, *> - return (spec?.get("dependencies") as? Map<*, *>)?.keys?.mapTo(HashSet()) { it.toString() }.orEmpty() - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPreviewController.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPreviewController.kt deleted file mode 100644 index 846b6264d4..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPreviewController.kt +++ /dev/null @@ -1,259 +0,0 @@ -package dev.codeassist.dart - -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.isActive -import kotlinx.coroutines.launch -import java.io.IOException -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths - -/** - * The preview pane's side of a Flutter preview, in the IDE's process: the gallery of ONE file's `@Preview` - * widgets, compiled here and run in an engine the plugin's preview service draws into the pane. - * - * It lives as long as the pane shows a package. Switching to another file of the package rewrites the gallery - * and hot-reloads it; saving any file of the package hot-reloads it, keeping the previews' state, as Run does. - * The engine arrives separately ([engineReady]), from the pane's surface once the service has made one; a new - * engine (the service's process died and the pane bound it again) gets the program restarted in it. - * - * Kept light: its compiler stops after [FlutterSession.IDLE_MS] without a save and starts again (from the kernel it - * left) on the next one, and the whole preview pauses while a Run of the same package is going. - */ -internal class FlutterPreviewController( - val pkg: Path, - private val tools: DartPlugin.Tools, -) { - /** What the pane shows over the previews ([message], when there is one) and in its problem chip. */ - data class State(val message: String?, val problems: List = emptyList()) - - private val _state = MutableStateFlow(State("Preparing the preview ...")) - val state: StateFlow get() = _state - - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - private val engines = Channel(Channel.CONFLATED) - /** Wakes the session loop: a save (through its [PackageWatcher]), another file shown, a new engine. */ - private val wake = Channel(Channel.CONFLATED) - // One place per package, kept: the next pane on this package starts its compiler from the kernel left here. - private val work = FlutterSession.paneWork(pkg) - private val galleryFile = work.resolve("gallery.dart") - - @Volatile private var file: Path? = null - @Volatile private var dark: Boolean? = null - @Volatile private var dirty = true - @Volatile private var session: FlutterSession? = null - private var packageName = "" - private var job: Job? = null - - private class Engine(val uri: String, val isolate: String?) - - /** - * Told when the preview pauses for a Run of the package (true) and resumes after it (false), so the pane can let - * its engine go meanwhile. Called off the main thread. - */ - @Volatile var onPause: (Boolean) -> Unit = {} - - /** Show [path]'s previews in the [dark] or light scheme. Cheap when nothing changed. */ - fun show(path: String, dark: Boolean) { - val p = Paths.get(path) - if (p == file && dark == this.dark) return - file = p - this.dark = dark - dirty = true - wake.trySend(Unit) - if (job == null) job = scope.launch { run() } - } - - /** The service made an engine for the pane and it is listening at [uri]. */ - fun engineReady(uri: String, isolate: String?) { - engines.trySend(Engine(uri, isolate)) - wake.trySend(Unit) - } - - /** The pane's engine could not be had. */ - fun engineFailed(reason: String) { - _state.value = State(reason, listOf(reason)) - } - - fun close() { - scope.cancel() - // The compiler blocks on its answers; closing it is what unblocks a run that is waiting on one. - session?.close() - } - - private suspend fun run() { - try { - session() - } catch (e: IOException) { - if (scope.isActive) _state.value = State(e.message ?: "The preview stopped.", listOf(e.message ?: e.toString())) - } finally { - session?.close() - } - } - - private suspend fun session() { - (tools.sdk.prepare() as? DartSdk.Status.Unavailable)?.let { return fail(it.reason) } - (tools.flutter.prepare() as? FlutterSdk.Status.Unavailable)?.let { return fail(it.reason) } - packageName = DartPackages.nameOf(String(Files.readAllBytes(pkg.resolve(DartPackages.PUBSPEC)))) - ?: return fail("pubspec.yaml has no name") - if (DartPackages.needsPubGet(pkg)) { - _state.value = State("Getting packages ...") - if (!pubGet()) return fail("pub get failed: open pubspec.yaml or Run to see why.") - } - - PackageWatcher(pkg, tools.bus, wake).use { watcher -> - while (scope.isActive) { - if (FlutterSession.runActive(pkg)) pauseWhileRunning(watcher) - live(watcher) - } - } - } - - /** - * A Run of this package holds a compiler and a Flutter engine of its own; the preview gives up both until the - * Run ends, then comes back with a fresh engine and a compiler that starts from the kernel it left. - */ - private suspend fun pauseWhileRunning(watcher: PackageWatcher) { - _state.value = State("Paused while the app runs. The preview comes back when the Run ends.") - onPause(true) - while (engines.tryReceive().isSuccess) { /* engines from before the pause are gone with it */ } - while (scope.isActive && FlutterSession.runActive(pkg)) watcher.await() - watcher.changes() // whatever changed meanwhile is compiled from scratch anyway - dirty = true - onPause(false) - } - - /** The preview, until a Run of the package starts (then it returns, its compiler closed) or the pane goes. */ - private suspend fun live(watcher: PackageWatcher) { - // The first compile, again after every save until there is one that compiles. - var compiled: Path? = null - var app: FlutterSession? = null - while (compiled == null) { - if (FlutterSession.runActive(pkg)) return - writeGallery() - _state.value = State(COMPILING) - app = FlutterSession( - pkg, tools.sdk, tools.flutter, galleryFile.toUri().toString(), work, ::log, ::galleryChanges, - siblings = listOf(FlutterSession.runWork(pkg).resolve("app.dill")), - ) - session = app - // The first compile after the IDE starts races the analysis server's own first pass over the framework - // and can take tens of seconds on a phone; past a few seconds, say why the pane is still waiting. - val slow = scope.launch { - delay(SLOW_COMPILE_MS) - if (_state.value.message == COMPILING) { - _state.value = State("$COMPILING\nThe first compile after opening a project is slow while Dart analyses it.") - } - } - val first = try { app.compile() } finally { slow.cancel() } - if (first.ok) { - compiled = first.dill - } else { - app.close() - _state.value = State("The previews do not compile. Save a fix to try again.", errors(first)) - while (scope.isActive && watcher.changes().isEmpty() && !dirty && !FlutterSession.runActive(pkg)) watcher.await() - dirty = false - } - } - app!! - try { - live(watcher, app, compiled) - } finally { - app.close() - session = null - } - } - - private suspend fun live(watcher: PackageWatcher, app: FlutterSession, compiled: Path) { - _state.value = State("Starting the Flutter engine ...") - var first: Engine? = null - while (first == null) { - first = engines.tryReceive().getOrNull() - if (first == null) { - if (!scope.isActive || FlutterSession.runActive(pkg)) return - watcher.await() - } - } - var engine: Engine = first - app.runIn(FlutterSession.connect(engine.uri), engine.isolate, compiled) - _state.value = State(null) - dirty = false - - while (scope.isActive) { - watcher.await() - if (FlutterSession.runActive(pkg)) return - app.releaseIfIdle() - engines.tryReceive().getOrNull()?.let { next -> - // A new engine: the old one went with its process. Start the program in it from scratch. - engine = next - _state.value = State("Restarting the preview ...") - val full = app.fullKernel(watcher.changes()) - if (!full.ok) { _state.value = State("The previews do not compile.", errors(full)); return@let } - app.runIn(FlutterSession.connect(engine.uri), engine.isolate, full.dill!!) - _state.value = State(null) - dirty = false - } - if (app.engineGone) { - // The pane went (its engine with it) or the engine's process died; the next pane's engine, or - // the rebound one, arrives through [engines]. - _state.value = State("Starting the Flutter engine ...") - continue - } - val changed = watcher.changes() - if (changed.isEmpty() && !dirty) continue - dirty = false - val outcome = if (changed.any { it.fileName.toString() == DartPackages.PUBSPEC }) { - _state.value = State("Getting packages ...") - if (!pubGet()) { _state.value = State(null, listOf("pub get failed")); continue } - app.uploadAssets() - app.restart(emptyList()) - } else { - app.reload(changed.filter { it.toString().endsWith(".dart") && Files.isRegularFile(it) }) - } - _state.value = State(null, outcome.problems) - } - } - - /** The gallery for the file being shown, rewritten when what it holds changed. */ - private fun writeGallery(): Boolean { - val shown = file ?: return false - val lib = pkg.resolve("lib") - // Only the shown file's previews, so only that file is read: not the whole of lib/ on every reload. - val previews = if (shown.startsWith(lib)) { - val library = "package:$packageName/" + lib.relativize(shown).joinToString("/") { it.toString() } - val text = runCatching { String(Files.readAllBytes(shown)) }.getOrDefault("") - if (DartPreviews.isLibraryWithPreviews(text)) DartPreviews.scan(text).map { it.copy(library = library) } else emptyList() - } else emptyList() - val empty = if (shown.startsWith(lib)) "No @Preview widgets in ${shown.fileName} yet." - else "Previews are shown for files in lib/." - return DartPreviews.write(galleryFile, DartPreviews.gallery(previews, pane = true, dark = dark, empty = empty)) - } - - private fun galleryChanges(): List = if (writeGallery()) listOf(galleryFile) else emptyList() - - private fun pubGet(): Boolean = tools.pub.run(pkg, "get", out = ::log) == 0 - - private fun errors(result: FrontendServer.Result): List = - result.messages.filter { ": Error: " in it || it.startsWith("Error: ") } - .map { it.substringAfter("$pkg/") } - .ifEmpty { listOf("${result.errors} compile error(s)") } - - private fun fail(reason: String) { - _state.value = State(reason, listOf(reason)) - } - - private fun log(line: String) = tools.log.info("preview: $line") - - private companion object { - const val COMPILING = "Compiling the previews ..." - const val SLOW_COMPILE_MS = 6_000L - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPreviewPane.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPreviewPane.kt deleted file mode 100644 index d987707641..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPreviewPane.kt +++ /dev/null @@ -1,382 +0,0 @@ -package dev.codeassist.dart - -import android.annotation.SuppressLint -import android.content.ComponentName -import android.content.Context -import android.content.Intent -import android.content.ServiceConnection -import android.os.Build -import android.os.Bundle -import android.os.Handler -import android.os.IBinder -import android.os.Looper -import android.os.Message -import android.os.Messenger -import android.os.RemoteException -import android.view.InputDevice -import android.view.MotionEvent -import android.view.SurfaceControlViewHost -import android.view.SurfaceView -import androidx.annotation.RequiresApi -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.padding -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.SideEffect -import androidx.compose.runtime.collectAsState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.compose.ui.viewinterop.AndroidView -import dev.ide.plugin.ui.EditorPreviewContext -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.atomic.AtomicInteger - -/** - * Which files the Flutter preview pane is for: a `.dart` file of a Flutter package that declares a `@Preview`. - * Asked during composition, so the answer is kept per file until the file changes. - */ -internal object FlutterPreviewFiles { - private class Answer(val stamp: Long, val size: Long, val applies: Boolean) - - private val answers = ConcurrentHashMap() - - fun appliesTo(path: String): Boolean { - if (!path.endsWith(".dart")) return false - val file = Paths.get(path) - val stamp = runCatching { Files.getLastModifiedTime(file).toMillis() }.getOrNull() ?: return false - val size = runCatching { Files.size(file) }.getOrDefault(0L) - answers[path]?.let { if (it.stamp == stamp && it.size == size) return it.applies } - val applies = runCatching { - String(Files.readAllBytes(file)).contains("@Preview") && packageOf(file)?.let(FlutterSdk::isFlutterPackage) == true - }.getOrDefault(false) - answers[path] = Answer(stamp, size, applies) - return applies - } - - fun packageOf(file: Path): Path? = DartPackages.packageRootOf(file, file.root ?: return null) -} - -/** One package's preview: the gallery's compiler and the engine it runs in, outliving the pane that shows them. */ -@RequiresApi(30) -internal class FlutterPreviewSession(val pkg: Path, tools: DartPlugin.Tools) { - val controller = FlutterPreviewController(pkg, tools) - val engine = FlutterPreviewEngine(controller) - internal var refs = 0 - internal var parkedAt = 0L - - init { - val main = Handler(Looper.getMainLooper()) - controller.onPause = { paused -> main.post { engine.pause(paused) } } - } - - fun close() { - engine.close() - controller.close() - } -} - -/** - * The previews panes are showing, and the ones a pane let go of a moment ago. - * - * Switching between Split and Preview, or away from the file and back, recreates the pane. The session is - * not recreated with it: the new pane takes over the one the old pane showed, its compiler and its running - * engine, so the previews carry on exactly as they were, state and scroll position included. Two panes on one - * package share a session; the one that attached last shows it. - * - * What no pane shows is let go in two steps, the engine first: after [ENGINE_KEEP_MS] the engine (and with it the - * preview process), after [KEEP_MS] the compiler too. A pane back in between gets a new engine and the previews - * restarted in it, without a compile. - */ -@RequiresApi(30) -internal object FlutterPreviewSessions { - private const val ENGINE_KEEP_MS = 15_000L - private const val KEEP_MS = 60_000L - private val main = Handler(Looper.getMainLooper()) - private val sessions = HashMap() - - fun acquire(pkg: Path, tools: DartPlugin.Tools): FlutterPreviewSession = synchronized(this) { - sessions.getOrPut(pkg) { FlutterPreviewSession(pkg, tools) }.also { it.refs++ } - } - - fun release(session: FlutterPreviewSession) { - val parkedAt = synchronized(this) { - session.refs-- - if (session.refs > 0) return - System.nanoTime().also { session.parkedAt = it } - } - main.postDelayed({ - val idle = synchronized(this) { session.refs == 0 && session.parkedAt == parkedAt } - if (idle) session.engine.close() - }, ENGINE_KEEP_MS) - main.postDelayed({ - val expired = synchronized(this) { - if (session.refs == 0 && session.parkedAt == parkedAt && sessions[session.pkg] === session) { - sessions.remove(session.pkg) - } else null - } - expired?.close() - }, KEEP_MS) - } -} - -/** - * The editor's Flutter preview: the open file's `@Preview` widgets, live, in the same pane as the built-in - * previews. The Flutter engine runs in the plugin's own app and draws straight into this pane (see - * [FlutterPreviewService]); the gallery it runs is compiled and hot-reloaded from here - * ([FlutterPreviewController]). Android 11 and later; before that the "Preview widgets" Run shows the same - * gallery in the player. - */ -@Composable -internal fun FlutterPreviewPane(ctx: EditorPreviewContext) { - val tools = DartPlugin.tools - val pkg = remember(ctx.path) { FlutterPreviewFiles.packageOf(Paths.get(ctx.path)) } - if (Build.VERSION.SDK_INT < 30 || tools == null || pkg == null) { - val reason = when { - Build.VERSION.SDK_INT < 30 -> "The preview pane needs Android 11 or later. Run \"Preview widgets\" shows them in the player instead." - tools == null -> "The Dart plugin's engine side did not start." - else -> "This file is not in a pub package." - } - SideEffect { ctx.reportProblems(emptyList()) } - Notice(reason) - return - } - val session = remember(pkg) { FlutterPreviewSessions.acquire(pkg, tools) } - DisposableEffect(session) { onDispose { FlutterPreviewSessions.release(session) } } - LaunchedEffect(session, ctx.path, ctx.dark) { session.controller.show(ctx.path, ctx.dark) } - val state by session.controller.state.collectAsState() - SideEffect { ctx.reportProblems(state.problems) } - - Box(Modifier.fillMaxSize()) { - AndroidView( - factory = { context -> FlutterPreviewSurface(context, session.engine) }, - modifier = Modifier.fillMaxSize(), - ) - state.message?.let { Notice(it) } - } -} - -@Composable -private fun Notice(text: String) { - Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surface), contentAlignment = Alignment.Center) { - Text( - text, - Modifier.padding(24.dp), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - } -} - -/** - * A session's engine in [FlutterPreviewService]: the binding, the engine's id there, and which pane surface - * shows it now. It outlives surfaces. A surface that attaches asks for the engine; the service makes one the - * first time and from then on hands the same running engine a new surface, so a recreated pane does not - * restart the previews. Only [close] (the session expiring) ends the engine. All on the main thread. - */ -@RequiresApi(30) -internal class FlutterPreviewEngine(private val controller: FlutterPreviewController) { - private val id = ids.incrementAndGet() - private var service: Messenger? = null - private var bound = false - private var context: Context? = null - private var surface: FlutterPreviewSurface? = null - private var requested = false - private var showing = false - /** Paused for a Run of the package ([FlutterPreviewController.onPause]): no engine wanted until it ends. */ - private var paused = false - - private val replies = Messenger(Handler(Looper.getMainLooper()) { msg -> onReply(msg); true }) - - private val connection = object : ServiceConnection { - override fun onServiceConnected(name: ComponentName, binder: IBinder) { - service = Messenger(binder) - requested = false - open() - } - - override fun onServiceDisconnected(name: ComponentName) { - // Its process died, and the engine with it. Android binds it again by itself, and - // onServiceConnected asks for a new engine, which the controller restarts the previews in. - service = null - requested = false - showing = false - controller.engineFailed("The preview engine stopped; starting it again ...") - } - } - - /** [view] is the pane's surface now (a newer pane's takes over from an older one). */ - fun attach(view: FlutterPreviewSurface) { - surface = view - requested = false - showing = false - if (!bound) { - val ctx = view.context.applicationContext.also { context = it } - val intent = Intent().setClassName(FlutterPlayer.PACKAGE, FlutterPreviewService.CLASS) - bound = runCatching { ctx.bindService(intent, connection, Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT) } - .getOrDefault(false) - if (!bound) controller.engineFailed("The Dart plugin's preview service could not be reached. ${FlutterPlayer.blockedHint()}") - } - open() - } - - /** Let the engine go while the preview is [paused] (a Run of the package is going), and ask for a new one after. */ - fun pause(paused: Boolean) { - if (this.paused == paused) return - this.paused = paused - if (paused) { - send(FlutterPreviewService.CLOSE) - requested = false - showing = false - } else { - open() - } - } - - /** [view] left its window. The engine keeps running for whichever surface attaches next. */ - fun detach(view: FlutterPreviewSurface) { - if (surface !== view) return - surface = null - requested = false - showing = false - } - - fun sized(view: FlutterPreviewSurface) { - if (surface !== view) return - if (requested) send(FlutterPreviewService.RESIZE, size(view)) else open() - } - - /** Whether [view] is the surface the engine draws into, so its touches are the engine's. */ - fun shows(view: FlutterPreviewSurface): Boolean = surface === view && showing - - fun input(view: FlutterPreviewSurface, event: MotionEvent) { - if (!shows(view)) return - send(FlutterPreviewService.INPUT, Bundle().apply { putParcelable(FlutterPreviewService.KEY_EVENT, MotionEvent.obtain(event)) }) - } - - /** - * End the engine and the binding (the preview process goes once nothing else holds it). A surface that attaches - * afterwards binds again and gets a new engine. - */ - fun close() { - send(FlutterPreviewService.CLOSE) - if (bound) runCatching { context?.unbindService(connection) } - bound = false - service = null - requested = false - showing = false - } - - private fun open() { - if (paused) return - val view = surface ?: return - if (requested || service == null || view.width <= 0 || view.height <= 0) return - val token = view.hostToken ?: return - val display = view.display ?: return - requested = true - send(FlutterPreviewService.OPEN, size(view).apply { - putBinder(FlutterPreviewService.KEY_HOST_TOKEN, token) - putInt(FlutterPreviewService.KEY_DISPLAY, display.displayId) - }) - } - - private fun size(view: SurfaceView) = Bundle().apply { - putInt(FlutterPreviewService.KEY_WIDTH, view.width) - putInt(FlutterPreviewService.KEY_HEIGHT, view.height) - } - - private fun onReply(msg: Message) { - if (msg.arg1 != id) return - when (msg.what) { - FlutterPreviewService.OPENED -> { - @Suppress("DEPRECATION") - val pkg = msg.data.getParcelable(FlutterPreviewService.KEY_SURFACE) - val uri = msg.data.getString(FlutterPreviewService.KEY_URI) - val view = surface - if (pkg == null || uri == null) { - controller.engineFailed("The preview engine sent no surface.") - return - } - if (view == null) { pkg.release(); return } - view.setChildSurfacePackage(pkg) - showing = true - // The size may have changed while the engine was starting. - send(FlutterPreviewService.RESIZE, size(view)) - // The same engine handed to a new surface is already running the previews. - if (!msg.data.getBoolean(FlutterPreviewService.KEY_REUSED)) { - controller.engineReady(uri, msg.data.getString(FlutterPreviewService.KEY_ISOLATE)) - } - } - FlutterPreviewService.FAILED -> - controller.engineFailed(msg.data.getString(FlutterPreviewService.KEY_REASON) ?: "The preview engine did not start.") - } - } - - private fun send(what: Int, data: Bundle = Bundle()) { - val to = service ?: return - try { - to.send(Message.obtain(null, what, id, 0).apply { - this.data = data - replyTo = replies - }) - } catch (_: RemoteException) { - // The service died; onServiceDisconnected follows. - } - } - - private companion object { - val ids = AtomicInteger() - } -} - -/** - * The pane's window into the preview engine: a [SurfaceView] whose child surface the plugin's process draws. - * What it shows, and the binding behind it, belong to the session's [FlutterPreviewEngine]; this view only - * says when it is attached and how big it is, and passes on what it is touched with. - */ -@SuppressLint("ViewConstructor") -@RequiresApi(30) -internal class FlutterPreviewSurface(context: Context, private val engine: FlutterPreviewEngine) : SurfaceView(context) { - - override fun onAttachedToWindow() { - super.onAttachedToWindow() - engine.attach(this) - } - - override fun onDetachedFromWindow() { - engine.detach(this) - super.onDetachedFromWindow() - } - - override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { - super.onSizeChanged(w, h, oldw, oldh) - engine.sized(this) - } - - // The IDE's window is above this surface, so its input arrives here; it is the embedded view's, so pass it on. - @SuppressLint("ClickableViewAccessibility") - override fun onTouchEvent(event: MotionEvent): Boolean { - if (!engine.shows(this)) return false - if (event.actionMasked == MotionEvent.ACTION_DOWN) parent?.requestDisallowInterceptTouchEvent(true) - engine.input(this, event) - return true - } - - override fun onGenericMotionEvent(event: MotionEvent): Boolean { - if (!engine.shows(this) || !event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) return false - engine.input(this, event) - return true - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPreviewService.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPreviewService.kt deleted file mode 100644 index 8f13ddf18b..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterPreviewService.kt +++ /dev/null @@ -1,280 +0,0 @@ -package dev.codeassist.dart - -import android.app.Service -import android.content.Intent -import android.content.pm.ApplicationInfo -import android.hardware.display.DisplayManager -import android.os.Build -import android.os.Bundle -import android.os.Handler -import android.os.IBinder -import android.os.Looper -import android.os.Message -import android.os.Messenger -import android.os.Process -import android.os.RemoteException -import android.util.Log -import android.view.InputDevice -import android.view.MotionEvent -import android.view.SurfaceControlViewHost -import androidx.annotation.RequiresApi -import io.flutter.embedding.android.FlutterTextureView -import io.flutter.embedding.android.FlutterView -import io.flutter.embedding.engine.FlutterEngine -import io.flutter.embedding.engine.FlutterJNI -import io.flutter.embedding.engine.dart.DartExecutor - -/** - * Flutter engines for the editor's preview pane, drawn INTO the IDE's window. - * - * The pane is a `SurfaceView` in CodeAssist; it sends its host token, display and size, and gets back a - * `SurfacePackage`: a [FlutterView] rendered here, in this plugin's process, by a [SurfaceControlViewHost], - * which the pane attaches to its surface. The pane forwards its touches ([INPUT]). Android 11 and later. - * - * Each engine starts on the player's stub program, and the reply carries its Dart VM service URI and isolate, - * through which the IDE runs the gallery in it and hot-reloads it. That is why only CodeAssist may ask: a VM - * service runs any code it is given, as this app. A message's sender is checked by its uid, which Binder - * supplies and the sender cannot choose. - * - * Runs in its own process (`:preview`), apart from the player: an engine exiting (`ext.flutter.exit`) ends its - * process, and the Run's player and the pane must not take each other down, or share a VM with its prints. - * - * Protocol (a [Messenger]; `arg1` is the pane's own id throughout): - * - [OPEN]: `data` {[KEY_HOST_TOKEN], [KEY_DISPLAY], [KEY_WIDTH], [KEY_HEIGHT]}, `replyTo` set. Answered by - * [OPENED] {[KEY_SURFACE], [KEY_URI], [KEY_ISOLATE], [KEY_REUSED]} or [FAILED] {[KEY_REASON]}. An OPEN for an - * id whose engine is running hands that engine to the new surface ([KEY_REUSED]) rather than starting one. - * - [RESIZE]: `data` {[KEY_WIDTH], [KEY_HEIGHT]}. - * - [INPUT]: `data` {[KEY_EVENT]}, a MotionEvent in the view's coordinates. - * - [CLOSE]: the engine is destroyed. Unbinding closes every engine the client opened. - */ -class FlutterPreviewService : Service() { - - private val main = Handler(Looper.getMainLooper()) - private val engines = HashMap() - private val messenger = Messenger(Handler(Looper.getMainLooper()) { msg -> handle(msg); true }) - - /** Whether a pane is bound: the process ends itself shortly after the last one unbinds. */ - private var clients = false - - override fun onBind(intent: Intent): IBinder { - clients = true - return messenger.binder - } - - override fun onRebind(intent: Intent) { - clients = true - } - - /** - * The last pane let go (its preview parked long enough, or the IDE went). Its engines go, and so does this - * process soon after: without an engine it still holds the Flutter library and a Dart VM, some 80 MB, for - * nothing. A pane that binds again in the meantime keeps it. - */ - override fun onUnbind(intent: Intent): Boolean { - clients = false - closeAll() - main.postDelayed({ if (!clients && engines.isEmpty()) Process.killProcess(Process.myPid()) }, 2_000) - return true - } - - override fun onDestroy() { - closeAll() - super.onDestroy() - } - - private fun handle(msg: Message) { - val caller = msg.sendingUid - if (!trusted(caller)) { - Log.w(TAG, "refused a preview for uid $caller") - reply(msg.replyTo, FAILED, msg.arg1, Bundle().apply { putString(KEY_REASON, "Not CodeAssist.") }) - return - } - when (msg.what) { - OPEN -> if (Build.VERSION.SDK_INT >= 30) open(msg) else { - reply(msg.replyTo, FAILED, msg.arg1, Bundle().apply { putString(KEY_REASON, "The preview pane needs Android 11 or later.") }) - } - RESIZE -> if (Build.VERSION.SDK_INT >= 30) engines[msg.arg1]?.resize(msg.data.getInt(KEY_WIDTH), msg.data.getInt(KEY_HEIGHT)) - CLOSE -> engines.remove(msg.arg1)?.close() - INPUT -> if (Build.VERSION.SDK_INT >= 30) { - @Suppress("DEPRECATION") - val event = msg.data.apply { classLoader = MotionEvent::class.java.classLoader }.getParcelable(KEY_EVENT) - if (event != null) { - engines[msg.arg1]?.input(event) - event.recycle() - } - } - } - } - - @RequiresApi(30) - private fun open(msg: Message) { - val id = msg.arg1 - val replyTo = msg.replyTo ?: return - val data = msg.data - val failed = { reason: String -> reply(replyTo, FAILED, id, Bundle().apply { putString(KEY_REASON, reason) }) } - val token = data.getBinder(KEY_HOST_TOKEN) ?: return failed("No host window.") - val display = getSystemService(DisplayManager::class.java).getDisplay(data.getInt(KEY_DISPLAY)) - ?: return failed("No such display.") - val width = data.getInt(KEY_WIDTH).coerceAtLeast(1) - val height = data.getInt(KEY_HEIGHT).coerceAtLeast(1) - // A pane recreated (Split to Preview and back): the same engine, still running, for its new surface. - engines[id]?.takeIf { it.uri != null }?.let { running -> - try { - running.rehost(token, display, width, height) - } catch (e: Exception) { - Log.w(TAG, "could not move a preview to its new surface", e) - engines.remove(id)?.close() - return failed("The preview could not move to the new pane: ${e.message}") - } - reply(replyTo, OPENED, id, Bundle().apply { - putParcelable(KEY_SURFACE, running.host.surfacePackage) - putString(KEY_URI, running.uri) - putString(KEY_ISOLATE, running.isolate) - putBoolean(KEY_REUSED, true) - }) - return - } - engines.remove(id)?.close() - val embedded = try { - Embedded(token, display, width, height) - } catch (e: Exception) { - Log.w(TAG, "could not start a preview engine", e) - return failed("The Flutter engine did not start: ${e.message}") - } - engines[id] = embedded - // The VM service and the isolate arrive a moment after the engine starts; wait for them off the main thread. - Thread({ - val deadline = System.currentTimeMillis() + 20_000 - var uri: String? = null - var isolate: String? = null - var isolateDeadline = Long.MAX_VALUE - while ((uri == null || isolate == null) && System.currentTimeMillis() < minOf(deadline, isolateDeadline)) { - uri = uri ?: runCatching { FlutterJNI.getVMServiceUri() }.getOrNull()?.takeIf { it.isNotBlank() } - ?.also { isolateDeadline = System.currentTimeMillis() + FlutterPlayerActivity.ISOLATE_GRACE_MS } - isolate = isolate ?: embedded.isolate - if (uri == null || isolate == null) Thread.sleep(30) - } - main.post { - if (engines[id] !== embedded) return@post - if (uri == null) { failed("The Flutter engine started without a VM service."); return@post } - embedded.uri = uri - reply(replyTo, OPENED, id, Bundle().apply { - putParcelable(KEY_SURFACE, embedded.host.surfacePackage) - putString(KEY_URI, uri) - putString(KEY_ISOLATE, isolate) - }) - } - }, "flutter-preview-start").apply { isDaemon = true }.start() - } - - private fun closeAll() { - engines.values.forEach { it.close() } - engines.clear() - } - - private fun reply(to: Messenger?, what: Int, id: Int, data: Bundle) { - to ?: return - try { - to.send(Message.obtain(null, what, id, 0).apply { this.data = data }) - } catch (_: RemoteException) { - // The pane is gone; its unbinding closes the engine. - } - } - - private fun trusted(uid: Int): Boolean { - if (uid == Process.myUid()) return true - val packages = packageManager.getPackagesForUid(uid).orEmpty() - if (packages.any { it in FlutterPlayerLauncher.TRUSTED_HOSTS }) return true - return uid == SHELL_UID && (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0 - } - - /** One pane's engine and the view it draws into the IDE's window. */ - @RequiresApi(30) - private inner class Embedded(private var token: IBinder, private var display: android.view.Display, width: Int, height: Int) { - // No plugin registrant: an app's Flutter plugins (packages with Android code) are not in the player. - val engine = FlutterEngine(this@FlutterPreviewService, null, false) - private val view = FlutterView(this@FlutterPreviewService, FlutterTextureView(this@FlutterPreviewService)) - var host = SurfaceControlViewHost(this@FlutterPreviewService, display, token) - private set - - /** The engine's VM service, once it has one. */ - var uri: String? = null - - val isolate: String? get() = engine.dartExecutor.isolateServiceId - - /** - * Show the same running view on a new pane surface. In the same window (the usual case: the pane was - * recreated) the view host stays and only its size changes; each surface gets its own package of it. - * In another window the view moves to a new host there. - */ - fun rehost(token: IBinder, display: android.view.Display, width: Int, height: Int) { - if (token == this.token && display.displayId == this.display.displayId) { - host.relayout(width, height) - return - } - host.release() - host = SurfaceControlViewHost(this@FlutterPreviewService, display, token) - host.setView(view, width, height) - this.token = token - this.display = display - } - - init { - engine.dartExecutor.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault()) - view.attachToFlutterEngine(engine) - host.setView(view, width, height) - engine.lifecycleChannel.appIsResumed() - } - - /** - * A touch or mouse event the pane received. The pane's surface is below the IDE's window, as a - * `SurfaceView` is unless it is put on top (which would hide the IDE's own chrome over the pane), so the - * IDE's window gets the input and the pane forwards it here, in the view's own coordinates. - */ - fun input(event: MotionEvent) { - if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER) && event.actionMasked in POINTER_ONLY) view.dispatchGenericMotionEvent(event) - else view.dispatchTouchEvent(event) - } - - fun resize(width: Int, height: Int) { - if (width > 0 && height > 0) host.relayout(width, height) - } - - fun close() { - runCatching { engine.lifecycleChannel.appIsDetached() } - runCatching { view.detachFromFlutterEngine() } - runCatching { host.release() } - runCatching { engine.destroy() } - } - } - - companion object { - private const val TAG = "FlutterPreviewService" - /** adb's uid (android.os.Process.SHELL_UID, which the SDK does not expose). */ - private const val SHELL_UID = 2000 - const val CLASS = "dev.codeassist.dart.FlutterPreviewService" - - const val OPEN = 1 - const val RESIZE = 2 - const val CLOSE = 3 - const val INPUT = 4 - const val OPENED = 10 - const val FAILED = 11 - - const val KEY_HOST_TOKEN = "hostToken" - const val KEY_DISPLAY = "display" - const val KEY_WIDTH = "width" - const val KEY_HEIGHT = "height" - const val KEY_SURFACE = "surface" - const val KEY_URI = "uri" - const val KEY_ISOLATE = "isolate" - const val KEY_REASON = "reason" - const val KEY_EVENT = "event" - const val KEY_REUSED = "reused" - - /** Pointer events that are not touches: hover and the mouse wheel. */ - private val POINTER_ONLY = setOf( - MotionEvent.ACTION_HOVER_ENTER, MotionEvent.ACTION_HOVER_MOVE, MotionEvent.ACTION_HOVER_EXIT, MotionEvent.ACTION_SCROLL, - ) - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterRun.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterRun.kt deleted file mode 100644 index c5ffb5368e..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterRun.kt +++ /dev/null @@ -1,374 +0,0 @@ -package dev.codeassist.dart - -import android.content.Context -import android.content.Intent -import android.os.Bundle -import android.os.ResultReceiver -import dev.codeassist.dart.FlutterSession.Companion.string -import dev.ide.build.AlwaysRun -import dev.ide.build.ProgramIo -import dev.ide.build.RunConsole -import dev.ide.build.Task -import dev.ide.build.TaskContext -import dev.ide.build.TaskInputs -import dev.ide.build.TaskInputsImpl -import dev.ide.build.TaskName -import dev.ide.build.TaskOutputs -import dev.ide.build.TaskOutputsImpl -import dev.ide.build.TaskResult -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.currentCoroutineContext -import kotlinx.coroutines.ensureActive -import kotlinx.coroutines.isActive -import kotlinx.coroutines.withContext -import kotlinx.serialization.json.JsonObject -import java.io.IOException -import java.nio.file.Files -import java.nio.file.Path -import java.util.Base64 -import java.util.concurrent.CompletableFuture -import java.util.concurrent.LinkedBlockingQueue -import java.util.concurrent.TimeUnit - -/** - * Starts the Flutter player (FlutterPlayerActivity, in this plugin's own app) and answers its Dart VM service - * URI and the isolate its engine started, which the player sends back once its engine has them. - */ -object FlutterPlayer { - const val PACKAGE = "dev.codeassist.dart" - /** The player's gate, which checks that CodeAssist is the caller (see FlutterPlayerLauncher). */ - private const val ACTIVITY = "dev.codeassist.dart.FlutterPlayerLauncher" - - /** The identity token's intent: never sent, only its PendingIntent's creator is read. */ - private const val IDENTITY_ACTION = "dev.codeassist.dart.PLAYER_CALLER" - private const val IDENTITY_REQUEST = 0x5EED - - class Started(val uri: String, val isolate: String?, private val control: android.os.IBinder?) { - /** End the player: its task closed, its process gone. Safe to call again, or once it is already gone. */ - fun quit() { - val binder = control ?: return - runCatching { android.os.Messenger(binder).send(android.os.Message.obtain(null, FlutterPlayerActivity.QUIT)) } - } - } - - /** - * Start the player and wait for its VM service: [reachTimeoutMs] for the launcher to answer, which only a - * launch the system blocked leaves unanswered, then [timeoutMs] for the engine. - */ - fun launch(reachTimeoutMs: Long = 8_000, timeoutMs: Long = 20_000): Started { - val context = appContext() ?: throw IOException("No Android context to start the Flutter player from.") - val reached = CompletableFuture() - val answer = CompletableFuture() - val receiver = object : ResultReceiver(null) { - override fun onReceiveResult(resultCode: Int, resultData: Bundle?) { - when (resultCode) { - FlutterPlayerActivity.RESULT_REACHED -> reached.complete(Unit) - FlutterPlayerActivity.RESULT_REFUSED -> { - val caller = resultData?.getString(FlutterPlayerActivity.EXTRA_CALLER) ?: "an unidentified caller" - val e = IOException("The Flutter player refused to start: it took the caller to be $caller, not CodeAssist.") - reached.completeExceptionally(e) - answer.completeExceptionally(e) - } - else -> { - reached.complete(Unit) - val uri = resultData?.getString(FlutterPlayerActivity.EXTRA_URI) - if (resultCode == 0 && uri != null) answer.complete(Started(uri, resultData.getString(FlutterPlayerActivity.EXTRA_ISOLATE), resultData.getBinder(FlutterPlayerActivity.EXTRA_CONTROL))) - else answer.completeExceptionally(IOException("The Flutter player started without a VM service.")) - } - } - } - } - val intent = Intent() - .setClassName(PACKAGE, ACTIVITY) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - .putExtra(FlutterPlayerActivity.EXTRA_RECEIVER, receiver) - // Who is asking, before Android 14: a PendingIntent's creator is recorded by the system and cannot be - // forged, and this one is made for the player alone. (The referrer the launcher used to read is only - // filled in for a start from an Activity, and this one comes from the build process: it was always - // empty there, and every run below Android 14 was refused.) - .putExtra( - FlutterPlayerActivity.EXTRA_IDENTITY, - android.app.PendingIntent.getBroadcast( - context, IDENTITY_REQUEST, - Intent(IDENTITY_ACTION).setPackage(context.packageName), - android.app.PendingIntent.FLAG_IMMUTABLE, - ), - ) - // Android 14 and later tell the player who is starting it only when the caller agrees to say. - val options = if (android.os.Build.VERSION.SDK_INT >= 34) { - android.app.ActivityOptions.makeBasic().setShareIdentityEnabled(true).toBundle() - } else null - try { - context.startActivity(intent, options) - } catch (e: RuntimeException) { - // ActivityNotFoundException, SecurityException: the plugin's app is missing or out of reach. - throw IOException("Could not open the Flutter player: ${e.message}. ${blockedHint()}") - } - await(reached, reachTimeoutMs) { - // Some systems drop a launch into another app without a word (startActivity returns as if it worked). - "Android did not open the Flutter player (the CodeAssist Dart app). ${blockedHint()}" - } - return await(answer, timeoutMs) { - "The Flutter player opened, but its engine did not start within ${timeoutMs / 1000} seconds. " + - "If it closed by itself it crashed; its logcat (tag \"flutter\") says why." - } - } - - private fun await(future: CompletableFuture, timeoutMs: Long, timedOut: () -> String): T = try { - future.get(timeoutMs, TimeUnit.MILLISECONDS) - } catch (e: java.util.concurrent.TimeoutException) { - throw IOException(timedOut()) - } catch (e: java.util.concurrent.ExecutionException) { - throw e.cause ?: e - } - - /** - * What to do when the system keeps CodeAssist from starting the plugin's app. Xiaomi's systems (MIUI, - * HyperOS) block it unless the app has Autostart; other makers have their own versions of the switch. - */ - internal fun blockedHint(): String { - val maker = "${android.os.Build.MANUFACTURER} ${android.os.Build.BRAND}".lowercase() - return if (listOf("xiaomi", "redmi", "poco").any { it in maker }) { - "On Xiaomi, Redmi and POCO phones, open Settings > Apps > Manage apps > CodeAssist Dart, turn on " + - "Autostart, and run again." - } else { - "Some phones stop one app from starting another: allow CodeAssist Dart to start in the background " + - "(often called Autostart) in the system settings, and run again." - } - } - - /** - * The IDE's application context. A plugin is handed none (its engine facet has no Android API), but this - * code runs inside the IDE's process, the IDE's or its `:build` one, and the process has an application. - */ - internal fun appContext(): Context? = runCatching { - Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null) as Context? - }.getOrNull() -} - -/** - * `flutter run` for the device itself: compile the app, run it in the player, and keep it hot-reloading. - * - * The run lasts as long as the app: every save of a `.dart` file in the package hot-reloads it (state kept), - * a pubspec change gets `pub get` and a hot restart, and the console takes `r` (reload), `R` (restart) and `q` - * (quit), as `flutter run` does. What the app prints shows in the console. Stop, `q` or closing the app ends it. - * - * With [preview], what runs is not the app but a gallery of its `@Preview` widgets ([DartPreviews]), rewritten - * before every reload so a preview added, removed or changed shows on the next save. - */ -internal class FlutterRunTask( - override val name: TaskName, - private val pkg: Path, - private val sdk: DartSdk, - private val flutter: FlutterSdk, - private val pub: Pub, - private val console: RunConsole, - private val preview: Boolean = false, -) : Task, AlwaysRun { - override val inputs: TaskInputs get() = TaskInputsImpl() - override val outputs: TaskOutputs get() = TaskOutputsImpl() - - private lateinit var out: (String) -> Unit - - /** - * Set for a run of the app's own APK ([attach]): the VM service of the app the host just launched, and the - * Dart plugin registrant the APK was compiled with. Null for a run in the player. - */ - private var attachUri: String? = null - private var registrantArgs: List = emptyList() - - /** - * Run in the app's own debug APK rather than the player, as `flutter run` does: the host has installed and - * launched it with the VM service on [vmUri] ([FlutterRunParticipant]). The app keeps its plugins, which the - * player has none of; reloads, restarts and the console work as in the player. - */ - suspend fun attach(io: ProgramIo, vmUri: String, registrant: List): TaskResult = withContext(Dispatchers.IO) { - attachUri = vmUri - registrantArgs = registrant - out = { line: String -> io.stdout(line + "\n") } - io.started() - val result = try { - session(io) - } catch (e: kotlinx.coroutines.CancellationException) { - throw e - } catch (e: Exception) { - out(e.message ?: e.toString()) - TaskResult.Failed(e.message ?: "The Flutter run failed") - } - io.exited(if (result is TaskResult.Success) 0 else 1) - result - } - private var packageName = "" - private val galleryFile: Path get() = pkg.resolve(".dart_tool/codeassist/preview/main.dart") - - override suspend fun execute(ctx: TaskContext): TaskResult = withContext(Dispatchers.IO) { - val io: ProgramIo? = console.io - out = io?.let { c -> { line: String -> c.stdout(line + "\n") } } ?: ctx.logger() - io?.started() - val result = try { - session(io) - } catch (e: kotlinx.coroutines.CancellationException) { - throw e - } catch (e: Exception) { - // Anything else ends the run with its reason in the console, never silently. - out(e.message ?: e.toString()) - TaskResult.Failed(e.message ?: "The Flutter run failed") - } - io?.exited(if (result is TaskResult.Success) 0 else 1) - result - } - - private suspend fun session(io: ProgramIo?): TaskResult { - (sdk.prepare() as? DartSdk.Status.Unavailable)?.let { return TaskResult.Failed(it.reason).also { _ -> out(it.reason) } } - (flutter.prepare() as? FlutterSdk.Status.Unavailable)?.let { return TaskResult.Failed(it.reason).also { _ -> out(it.reason) } } - val name = DartPackages.nameOf(String(Files.readAllBytes(pkg.resolve(DartPackages.PUBSPEC)))) - ?: return fail("pubspec.yaml has no name") - packageName = name - val entry = if (preview) { - writeGallery() - galleryFile.toUri().toString() - } else { - if (!Files.isRegularFile(pkg.resolve("lib/main.dart"))) return fail("A Flutter app needs lib/main.dart.") - "package:$name/main.dart" - } - if (DartPackages.needsPubGet(pkg) && !pubGet()) return fail("pub get failed") - - heartbeat() - val app = FlutterSession( - pkg, sdk, flutter, entry, FlutterSession.runWork(pkg), out, - alsoChanged = { if (preview && writeGallery()) listOf(galleryFile) else emptyList() }, - siblings = listOf(FlutterSession.paneWork(pkg).resolve("app.dill")), - extraArgs = registrantArgs, - ) - var player: FlutterPlayer.Started? = null - var watching: PackageWatcher? = null - try { - out("Compiling $entry ...") - val started = System.nanoTime() - val first = app.compile() - first.messages.forEach(out) - if (!first.ok) return fail("The app did not compile (${first.errors} error(s)).") - out("Compiled in ${ms(started)} ms.") - - val launched = System.nanoTime() - val target = attachUri - val vm = if (target != null) { - out("Connecting to the app ...") - connectWhenUp(target) - } else { - out("Starting the Flutter player ...") - player = FlutterPlayer.launch() - FlutterSession.connect(player.uri) - } - vm.onEvent = { stream, event -> if (stream == "Stdout" || stream == "Stderr") printed(event) } - for (stream in listOf("Stdout", "Stderr")) runCatching { vm.call("streamListen", mapOf("streamId" to stream)) } - out(if (target != null) "The app answered in ${ms(launched)} ms." else "The player answered in ${ms(launched)} ms.") - val uploaded = System.nanoTime() - app.runIn(vm, player?.isolate, first.dill!!) - out("Running in ${ms(uploaded)} ms. Saving a file hot-reloads it; type r (reload), R (restart) or q (quit).") - - val watcher = PackageWatcher(pkg, DartPlugin.tools?.bus).also { watching = it } - vm.onClosed = { watcher.wake.trySend(Unit) } - val commands = LinkedBlockingQueue() - io?.stdin?.let { readCommands(it, commands) { watcher.wake.trySend(Unit) } } - while (currentCoroutineContext().isActive && !app.engineGone) { - heartbeat() - // A save, a command or the app closing wakes this at once; otherwise the watcher's walk is due. - if (commands.isEmpty()) watcher.await() - app.releaseIfIdle() - when (commands.poll()?.trim()) { - "r" -> app.reload(dartFiles(watcher.changes())) - "R" -> app.restart(dartFiles(watcher.changes())) - "q" -> break - else -> { - val changed = watcher.changes() - if (changed.isEmpty()) continue - if (changed.any { it.fileName.toString() == DartPackages.PUBSPEC }) { - out("pubspec.yaml changed: pub get and a hot restart.") - if (pubGet()) { app.uploadAssets(); app.restart(emptyList()) } - } else { - app.reload(dartFiles(changed)) - } - } - } - } - if (app.engineGone) out("The app was closed.") - return TaskResult.Success - } finally { - // A run that stopped should not leave its player behind. - player?.quit() - watching?.close() - runCatching { Files.deleteIfExists(FlutterSession.runMarker(pkg)) } - app.close() - } - } - - /** Rewrite the preview gallery from the app's previews as they are now. Answers whether its text changed. */ - private fun writeGallery(): Boolean { - val previews = DartPreviews.find(pkg, packageName) - val changed = DartPreviews.write(galleryFile, DartPreviews.gallery(previews)) - if (changed) out("${previews.size} preview(s): ${previews.joinToString(", ") { it.label }.ifEmpty { "none yet" }}") - return changed - } - - /** - * Tells a preview pane on this package that a Run is going ([FlutterSession.runMarker]), so it lets its own - * compiler and engine go until the Run ends. Called before the compile and on every pass of the loop. - */ - private fun heartbeat() { - val marker = FlutterSession.runMarker(pkg) - runCatching { - Files.createDirectories(marker.parent) - if (Files.exists(marker)) Files.setLastModifiedTime(marker, java.nio.file.attribute.FileTime.fromMillis(System.currentTimeMillis())) - else Files.write(marker, ByteArray(0)) - } - } - - /** - * The VM service at [uri], retried while the app comes up: the host only asked for the launch, the system may - * still be showing the install confirmation, and the engine opens its service a moment after the app starts. - */ - private suspend fun connectWhenUp(uri: String, timeoutMs: Long = 180_000): VmService { - val deadline = System.nanoTime() + timeoutMs * 1_000_000 - var last: Exception? = null - while (System.nanoTime() < deadline) { - currentCoroutineContext().ensureActive() - try { - return FlutterSession.connect(uri) - } catch (e: Exception) { - last = e - kotlinx.coroutines.delay(500) - } - } - throw IOException("The app's Dart VM service did not answer at $uri: ${last?.message}. If the app is not open, open it and run again.") - } - - private fun pubGet(): Boolean { - out("> dart pub get") - return pub.run(pkg, "get", out = out) == 0 - } - - private fun fail(message: String): TaskResult { - out(message) - return TaskResult.Failed(message) - } - - /** What the app printed (a `print`, an uncaught error), from the VM's Stdout and Stderr streams. */ - private fun printed(event: JsonObject) { - val bytes = event.string("bytes") ?: return - val text = runCatching { String(Base64.getDecoder().decode(bytes)) }.getOrNull() ?: return - text.trimEnd('\n').split('\n').forEach(out) - } - - private fun readCommands(stdin: java.io.InputStream, into: LinkedBlockingQueue, arrived: () -> Unit) { - Thread({ - runCatching { stdin.bufferedReader().forEachLine { into.put(it); arrived() } } - }, "flutter-run-commands").apply { isDaemon = true }.start() - } - - /** The Dart files among [changed] that still exist: what a reload recompiles. */ - private fun dartFiles(changed: List): List = - changed.filter { it.toString().endsWith(".dart") && Files.isRegularFile(it) } - - private fun ms(since: Long) = (System.nanoTime() - since) / 1_000_000 -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterRunParticipant.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterRunParticipant.kt deleted file mode 100644 index 70e768c83b..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterRunParticipant.kt +++ /dev/null @@ -1,78 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.build.AndroidRunParticipant -import dev.ide.build.ProgramIo -import dev.ide.build.RunConsole -import dev.ide.build.TaskName -import dev.ide.build.TaskResult -import dev.ide.model.Module -import java.io.IOException -import java.net.ServerSocket -import java.nio.file.Files -import java.nio.file.Paths -import java.util.concurrent.ConcurrentHashMap - -/** - * Makes the Run of a Flutter app's Android module what `flutter run` is: the app's own debug APK, with its - * plugins, hot-reloading as its Dart files are saved. The host builds, installs and launches the APK; the launch - * asks the debug engine for a VM service on a port picked here, with no auth code, so the run can find it; then - * the run attaches the same compiler, file watcher and r/R/q console the player uses ([FlutterRunTask.attach]). - * - * Release builds are left alone: their engine is ahead-of-time compiled, with no VM service to attach to. - */ -class FlutterRunParticipant( - private val sdk: DartSdk, - private val flutter: FlutterSdk, - private val pub: Pub, -) : AndroidRunParticipant { - - override val consoleTitle = "Flutter" - - /** The VM service port each module's current run asked for, from [launchExtras] to [afterLaunch]. */ - private val ports = ConcurrentHashMap() - - override fun launchExtras(module: Module, variant: String): Map? { - module.facets.get(FlutterFacet.KEY) ?: return null - if (FlutterBuildPlugin.isRelease(variant)) return null - val port = freePort() - ports[module.name] = port - return extras(port) - } - - override suspend fun afterLaunch(module: Module, variant: String, io: ProgramIo, log: (String) -> Unit) { - val facet = module.facets.get(FlutterFacet.KEY) ?: return - val port = ports.remove(module.name) ?: return - val pkg = Paths.get(module.dir.path).resolve(facet.source).normalize() - // The APK was compiled with the app's Dart plugin registrant; a restart's kernel has to carry it too, or the - // plugins' Dart side stops registering after the first `R`. - val registrant = FlutterPlugins.dartRegistrantFile(pkg).takeIf { Files.isRegularFile(it) } - ?.let { FlutterPlugins.dartRegistrantArgs(it) }.orEmpty() - val task = FlutterRunTask( - TaskName(":${module.name}:flutterRun"), pkg, sdk, flutter, pub, RunConsole(consoleTitle), - ) - val result = task.attach(io, serviceUri(port), registrant) - if (result is TaskResult.Failed) log(result.message) - } - - private fun freePort(): Int = try { - ServerSocket(0).use { it.localPort } - } catch (e: IOException) { - // Any port: the engine picks another if it is taken, and the run then says it could not connect. - 40_000 + (System.nanoTime() % 20_000).toInt() - } - - internal companion object { - const val VM_SERVICE_PORT = "vm-service-port" - const val DISABLE_AUTH_CODES = "disable-service-auth-codes" - - /** - * The launch extras asking the debug engine for a VM service on [port] with no auth code: the keys - * FlutterActivity reads into the engine's shell arguments (FlutterShellArgs), as `flutter run` passes - * them with `am start`. - */ - fun extras(port: Int): Map = mapOf(VM_SERVICE_PORT to port, DISABLE_AUTH_CODES to true) - - /** The VM service's HTTP root on [port]; VmService opens its WebSocket under it (`ws`). */ - fun serviceUri(port: Int): String = "http://127.0.0.1:$port/" - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterSdk.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterSdk.kt deleted file mode 100644 index 25c2f7a5db..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterSdk.kt +++ /dev/null @@ -1,183 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.platform.log.Logger -import dev.ide.plugin.PluginRegistration -import java.io.RandomAccessFile -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.StandardCopyOption -import java.util.zip.ZipInputStream - -/** - * The Flutter this plugin carries (tools/dart-sdk/fetch-flutter.sh): a FLUTTER_ROOT the framework packages - * resolve from, the assets every app's bundle starts with, and, in the plugin's own APK, the engine and the - * player that runs apps. One Flutter version, the one whose Dart the plugin carries: the kernel the IDE - * compiles must match the Dart VM inside the engine. - */ -class FlutterSdk(private val reg: PluginRegistration, private val dart: DartSdk, private val log: Logger) { - - sealed interface Status { - data class Ready(val root: Path) : Status - data class Unavailable(val reason: String) : Status - } - - /** `FLUTTER_ROOT`: `packages/flutter`, `bin/cache/pkg/sky_engine`, the patched platform, the version files. */ - val root: Path get() = dart.home.resolve("flutter").resolve(VERSION) - val baseAssets: Path get() = dart.home.resolve("flutter").resolve("base-assets-$VERSION") - - /** The core libraries in kernel form, patched for Flutter, that an app compiles against. */ - val platformDir: Path get() = root.resolve("bin/cache/artifacts/engine/common/flutter_patched_sdk") - - /** Whether this build of the plugin carries Flutter at all (the stage is optional at build time). */ - val packaged: Boolean - get() = javaClass.classLoader?.getResource(ROOT_ASSET) != null && reg.nativeLibrary("flutter") != null - - /** - * The debug engine this plugin carries for the device's ABI (`libflutter.so`), which an app built here - * packages as its own, or null when the plugin carries none. - */ - val engine: Path? get() = reg.nativeLibrary("flutter") - - /** - * One of the Dart VM's snapshots that every debug app's `flutter_assets` holds beside its program - * (`vm_snapshot_data`, `isolate_snapshot_data`). The player's bundle has them, made by this same engine. - */ - fun vmSnapshot(name: String): java.io.InputStream? = - javaClass.classLoader?.getResourceAsStream("assets/flutter_assets/$name") - - /** The release engine (`libflutter_release.so`), which a release build packages as the app's `libflutter.so`. */ - val releaseEngine: Path? get() = reg.nativeLibrary("flutter_release") - - /** - * Dart's gen_snapshot built for this device (`libgen_snapshot.so`): a release build's kernel to machine code. - * Built like the release engine's own VM (product mode, compressed pointers on 64-bit), or the engine refuses - * the snapshot (tools/dart-sdk/build-gen-snapshot.sh). - */ - val genSnapshot: Path? get() = reg.nativeLibrary("gen_snapshot") - - /** The core libraries in kernel form for product mode, which a release build's kernel compiles against. */ - val productPlatformDir: Path - get() = dart.home.resolve("flutter").resolve("product-$VERSION").resolve("flutter_patched_sdk_product") - - @Volatile - private var ready: Status.Ready? = null - - @Volatile - private var releaseReady: Status.Ready? = null - - /** Unpack the Flutter root and the base assets once per version. Safe across the IDE's processes. */ - @Synchronized - fun prepare(): Status { - ready?.let { return it } - if (!packaged) return Status.Unavailable(NO_FLUTTER) - return try { - locked { - unpack(ROOT_ASSET, root) - unpack(BASE_ASSETS, baseAssets) - } - Status.Ready(root).also { ready = it } - } catch (e: Exception) { - log.warn("could not prepare Flutter", e) - Status.Unavailable("Flutter could not be prepared: ${e.message}") - } - } - - /** - * [prepare], plus what a release build needs besides: the release engine, gen_snapshot and the product - * platform, which a build of the plugin made without fetch-flutter-release.sh does not carry. - */ - @Synchronized - fun prepareRelease(): Status { - releaseReady?.let { return it } - (prepare() as? Status.Unavailable)?.let { return it } - if (releaseEngine == null || genSnapshot == null || javaClass.classLoader?.getResource(PRODUCT_ASSET) == null) { - return Status.Unavailable(NO_RELEASE) - } - return try { - locked { unpack(PRODUCT_ASSET, productPlatformDir.parent) } - Status.Ready(root).also { releaseReady = it } - } catch (e: Exception) { - log.warn("could not prepare Flutter release builds", e) - Status.Unavailable("Flutter release builds could not be prepared: ${e.message}") - } - } - - /** Run [block] holding the file lock the IDE's processes share, so two never unpack into one directory. */ - private fun locked(block: () -> Unit) { - Files.createDirectories(root.parent) - RandomAccessFile(root.parent.resolve(".lock").toFile(), "rw").use { raf -> - raf.channel.lock().use { block() } - } - } - - private fun unpack(asset: String, into: Path) { - val stamp = into.resolve(".unpacked") - // The version alone is not enough: a plugin update can change what a version's archive holds (the SDK - // packages added to the root), and an install that unpacked the old one must unpack again. - val expected = "$VERSION/$LAYOUT" - if (Files.isRegularFile(stamp) && String(Files.readAllBytes(stamp)) == expected) return - val stream = javaClass.classLoader?.getResourceAsStream(asset) ?: error("$asset is not packaged") - val started = System.nanoTime() - if (Files.exists(into)) into.toFile().deleteRecursively() - Files.createDirectories(into) - var files = 0 - ZipInputStream(stream.buffered()).use { zip -> - while (true) { - val entry = zip.nextEntry ?: break - val target = into.resolve(entry.name).normalize() - require(target.startsWith(into)) { "entry escapes $into: ${entry.name}" } - if (entry.isDirectory) Files.createDirectories(target) else { - Files.createDirectories(target.parent) - Files.copy(zip, target, StandardCopyOption.REPLACE_EXISTING) - files++ - } - zip.closeEntry() - } - } - Files.write(stamp, expected.toByteArray()) - log.info("unpacked $files files of $asset in ${(System.nanoTime() - started) / 1_000_000} ms") - } - - companion object { - /** The Flutter release staged by fetch-flutter.sh; its Dart is [DartSdk.VERSION]. */ - const val VERSION = "3.47.9" - - /** - * What the staged archives hold, beyond the version: bump it when fetch-flutter.sh stages more, so an - * install that unpacked an older plugin's archives unpacks them again. 2: flutter_web_plugins and - * flutter_localizations in the root. - */ - private const val LAYOUT = 2 - - /** - * The engine revision of [VERSION], which names the engine's Java embedding on Flutter's Maven repository - * ([MAVEN_REPOSITORY], `io.flutter:flutter_embedding_debug:1.0.0-`). fetch-flutter.sh writes the - * same value into its ENGINE file; the plugin's own build resolves its embedding by it. - */ - const val ENGINE = "89c39edfdfae2949f6806e4a315c0c08522238b7" - - /** Where Flutter publishes its engine's Maven artifacts. Neither Maven Central nor Google has them. */ - const val MAVEN_REPOSITORY = "https://storage.googleapis.com/download.flutter.io" - - /** The Java half of the debug engine, which an app's `MainActivity` extends `FlutterActivity` from. */ - const val EMBEDDING_DEBUG = "io.flutter:flutter_embedding_debug:1.0.0-$ENGINE" - - /** The Java half of the release engine: the same classes, loading the app's `libapp.so` instead of a kernel. */ - const val EMBEDDING_RELEASE = "io.flutter:flutter_embedding_release:1.0.0-$ENGINE" - private const val ROOT_ASSET = "assets/flutter-root.zip" - private const val BASE_ASSETS = "assets/flutter-base-assets.zip" - private const val PRODUCT_ASSET = "assets/flutter-product.zip" - const val NO_RELEASE = "This build of the Dart plugin cannot build Flutter apps in release mode " + - "(tools/dart-sdk/fetch-flutter-release.sh was not run). Build the debug variant." - const val NO_FLUTTER = "This build of the Dart plugin carries no Flutter (tools/dart-sdk/fetch-flutter.sh was not run)." - - /** Whether the package whose pubspec is [pubspec] is a Flutter app or package: it depends on the SDK's `flutter`. */ - fun isFlutter(pubspec: String): Boolean = - // `flutter:` with `sdk: flutter` under it: the dependency on the framework itself (flutter_test's - // entry is `flutter_test:`, and the `flutter:` section at the top level has no `sdk:`). - Regex("""(?m)^[ \t]+flutter:[ \t]*\r?\n[ \t]+sdk:[ \t]*flutter\b""").containsMatchIn(pubspec) - - fun isFlutterPackage(pkg: Path): Boolean = - runCatching { isFlutter(String(Files.readAllBytes(pkg.resolve(DartPackages.PUBSPEC)))) }.getOrDefault(false) - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterSession.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterSession.kt deleted file mode 100644 index 79fd4470e8..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FlutterSession.kt +++ /dev/null @@ -1,330 +0,0 @@ -package dev.codeassist.dart - -import kotlinx.coroutines.delay -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.booleanOrNull -import kotlinx.serialization.json.contentOrNull -import java.io.IOException -import java.net.URI -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths - -/** - * One Flutter program kept running and hot-reloading: its incremental compiler and, once it has an engine to - * run in, that engine's VM service and DevFS. What `flutter run` keeps between reloads, shared by the Run - * console ([FlutterRunTask]) and the editor's preview pane ([FlutterPreviewController]). - * - * Blocking throughout: every call talks to the compiler or the VM and waits for its answer. - */ -internal class FlutterSession( - private val pkg: Path, - private val sdk: DartSdk, - private val flutter: FlutterSdk, - /** What runs: `package:app/main.dart`, or a generated gallery's file URI. */ - private val entry: String, - /** The compiler's working directory. A Run and a preview pane each have their own. */ - work: Path, - private val out: (String) -> Unit, - /** Files a reload must recompile besides the ones that were edited: a gallery rewritten just now. */ - private val alsoChanged: () -> List = { emptyList() }, - /** Other compiles of this package whose kernels a cold compiler can start from (see [FrontendServer.warm]). */ - siblings: List = emptyList(), - /** More compiler arguments: the Dart plugin registrant, for the app's own APK ([FlutterPlugins.dartRegistrantArgs]). */ - extraArgs: List = emptyList(), -) : AutoCloseable { - /** What a reload or restart came to, and the compiler's errors when it did not happen. */ - class Outcome(val ok: Boolean, val problems: List = emptyList()) - - private val frontend = FrontendServer(sdk, flutter, pkg, work.resolve("app.dill"), siblings + seed(sdk), extraArgs) - private var vm: VmService? = null - private var fsUri = "" - private var lastUsed = System.nanoTime() - - /** The compiler was stopped for being idle ([releaseIfIdle]); the next reload or restart starts it again. */ - @Volatile var released = false - private set - private var viewId: String? = null - private var isolateHint: String? = null - - /** Whether the engine the program ran in has gone (closed, or killed with its process). */ - val engineGone: Boolean get() = vm?.isClosed ?: true - - /** - * Start the compiler and compile the whole program. Accepted when it compiled, so reloads build on it. - * - * A compiler that had no kernel to start from is replaced at once by one that starts from what it just wrote: - * a second or so, once, for about 200 MB less for the rest of the session. Its kernel also becomes the - * plugin-wide seed when there is none, so no later compile of any Flutter app starts cold. - */ - fun compile(): FrontendServer.Result { - lastUsed = System.nanoTime() - frontend.start() - val first = frontend.compile(entry) - if (!first.ok) return first - frontend.accept() - if (frontend.warm) return first - val compiled = first.dill!! - saveSeed(compiled) - frontend.close() - frontend.start() - val again = frontend.compile(entry) - if (again.ok) frontend.accept() - return again - } - - private fun saveSeed(dill: Path) { - val target = seed(sdk) - if (Files.isRegularFile(target)) return - runCatching { - Files.createDirectories(target.parent) - val partial = target.resolveSibling(target.fileName.toString() + ".partial") - Files.copy(dill, partial, java.nio.file.StandardCopyOption.REPLACE_EXISTING) - Files.move(partial, target, java.nio.file.StandardCopyOption.REPLACE_EXISTING, java.nio.file.StandardCopyOption.ATOMIC_MOVE) - } - } - - /** - * Run the program in the engine whose VM service is [vm]: a DevFS for its files, then the kernel [dill] - * started in the engine's view. [isolate] names the isolate the engine started with, which picks its view - * when the VM has several (two engines in one process share one VM). - */ - fun runIn(vm: VmService, isolate: String?, dill: Path) { - this.vm?.takeIf { it !== vm }?.close() - this.vm = vm - viewId = null - isolateHint = isolate - runCatching { vm.call("_deleteDevFS", mapOf("fsName" to FS)) } - fsUri = vm.call("_createDevFS", mapOf("fsName" to FS)).string("uri") ?: throw IOException("the app made no DevFS") - val started = System.nanoTime() - uploadAssets() - val assets = System.nanoTime() - vm.upload(FS, "app.dill", dill) - val kernel = System.nanoTime() - runInView("app.dill") - out("Started: assets ${(assets - started) / 1_000_000} ms, kernel ${(kernel - assets) / 1_000_000} ms, run ${ms(kernel)} ms.") - } - - /** A full kernel of the program as it is now, for an engine that has not run it yet. */ - fun fullKernel(edited: List = emptyList()): FrontendServer.Result { - lastUsed = System.nanoTime() - if (released) return revive() - val full = frontend.recompileFull(entry, (edited + alsoChanged()).map { it.toUri().toString() }) - if (full.ok) frontend.accept() else frontend.reject() - return full - } - - /** - * Stop the compiler if nothing was compiled for [idleMs]: it holds some 350 MB doing nothing. Answers whether it - * stopped. The next reload starts a compiler from the kernel it left (about a second, see [FrontendServer.warm]). - */ - fun releaseIfIdle(idleMs: Long = IDLE_MS): Boolean { - if (released || (System.nanoTime() - lastUsed) / 1_000_000 < idleMs) return false - frontend.close() - released = true - out("The compiler was stopped after ${idleMs / 60_000} idle minutes; the next save starts it again.") - return true - } - - /** - * A compiler again after [releaseIfIdle], and a full kernel of the program as it is now: it starts from the kernel - * the last one wrote and checks that against the sources, so whatever was saved meanwhile is in it. It is - * accepted as the base for the reloads after it. Left released when the program does not compile. - */ - private fun revive(): FrontendServer.Result { - alsoChanged() // a gallery brought up to date before it is compiled - frontend.start() - val full = frontend.compile(entry) - if (full.ok) { - frontend.accept() - released = false - } else { - frontend.close() - } - return full - } - - /** The app's assets, its fonts and the framework's own, into the DevFS where the engine reads them. */ - fun uploadAssets() { - val vm = vm ?: return - val bundle = FlutterAssets.build(pkg, flutter.baseAssets) - for ((path, file) in bundle.files) vm.upload(FS, "flutter_assets/$path", file) - val staged = pkg.resolve(".dart_tool/codeassist/flutter/generated") - Files.createDirectories(staged) - for ((path, bytes) in bundle.generated) { - val file = staged.resolve(path) - Files.write(file, bytes) - vm.upload(FS, "flutter_assets/$path", file) - } - } - - /** Hot reload: recompile what changed, hand the VM the delta, and rebuild the widget tree. State is kept. */ - fun reload(edited: List): Outcome { - val vm = vm ?: throw IOException("the app is not running") - lastUsed = System.nanoTime() - if (released) return reloadRevived(vm) - val changed = edited + alsoChanged() - if (changed.isEmpty()) { out("Nothing changed."); return Outcome(true) } - val started = System.nanoTime() - val delta = frontend.recompile(entry, changed.map { it.toUri().toString() }) - delta.messages.forEach(out) - if (!delta.ok) { - frontend.reject() - out("Not reloaded: ${delta.errors} compile error(s).") - return Outcome(false, errors(delta)) - } - val compiled = System.nanoTime() - vm.upload(FS, "app.dill.incremental.dill", delta.dill!!) - val uploaded = System.nanoTime() - val isolate = (view()["isolate"] as? JsonObject)?.string("id") ?: throw IOException("the app has no isolate") - val report = vm.call("reloadSources", mapOf("isolateId" to isolate, "rootLibUri" to fsUri + "app.dill.incremental.dill")) - val reloaded = System.nanoTime() - if ((report["success"] as? JsonPrimitive)?.booleanOrNull != true) { - frontend.reject() - val notices = (report["notices"] as? JsonArray).orEmpty().mapNotNull { (it as? JsonObject)?.string("message") } - val why = notices.joinToString("; ").ifEmpty { "the VM refused the change" } - out("Hot reload was rejected: $why. Type R to restart.") - return Outcome(false, listOf("Hot reload was rejected: $why")) - } - frontend.accept() - vm.call("ext.flutter.reassemble", mapOf("isolateId" to isolate)) - val details = report["details"] as? JsonObject - out("Reloaded ${details?.string("loadedLibraryCount") ?: "?"} of ${details?.string("finalLibraryCount") ?: "?"} libraries in ${ms(started)} ms " + - "(compile ${(compiled - started) / 1_000_000}, upload ${(uploaded - compiled) / 1_000_000}, " + - "reload ${(reloaded - uploaded) / 1_000_000}, rebuild ${ms(reloaded)}).") - return Outcome(true) - } - - /** - * The first reload after [releaseIfIdle]: the new compiler has no delta to give, so the VM gets the whole - * program, which it reloads like any other change (state kept). Should it refuse, the app restarts instead. - */ - private fun reloadRevived(vm: VmService): Outcome { - val started = System.nanoTime() - val full = revive() - full.messages.forEach(out) - if (!full.ok) { - out("Not reloaded: ${full.errors} compile error(s).") - return Outcome(false, errors(full)) - } - vm.upload(FS, "app.dill", full.dill!!) - val isolate = (view()["isolate"] as? JsonObject)?.string("id") ?: throw IOException("the app has no isolate") - val report = vm.call("reloadSources", mapOf("isolateId" to isolate, "rootLibUri" to fsUri + "app.dill")) - if ((report["success"] as? JsonPrimitive)?.booleanOrNull == true) { - vm.call("ext.flutter.reassemble", mapOf("isolateId" to isolate)) - out("Reloaded with a new compiler in ${ms(started)} ms.") - } else { - runInView("app.dill") - out("Restarted with a new compiler in ${ms(started)} ms (the VM would not reload the whole program).") - } - return Outcome(true) - } - - /** Hot restart: the whole program recompiled and started again in the same view. State is lost. */ - fun restart(edited: List): Outcome { - val vm = vm ?: throw IOException("the app is not running") - val started = System.nanoTime() - val full = fullKernel(edited) - full.messages.forEach(out) - if (!full.ok) { - out("Not restarted: ${full.errors} compile error(s).") - return Outcome(false, errors(full)) - } - val compiled = System.nanoTime() - vm.upload(FS, "app.dill", full.dill!!) - val uploaded = System.nanoTime() - runInView("app.dill") - out("Restarted in ${ms(started)} ms (compile ${(compiled - started) / 1_000_000}, upload ${(uploaded - compiled) / 1_000_000}, start ${ms(uploaded)}).") - return Outcome(true) - } - - override fun close() { - vm?.close() - vm = null - frontend.close() - } - - private fun runInView(dill: String) { - val vm = vm ?: return - vm.call("_flutter.runInView", mapOf( - "viewId" to view().string("id"), - "mainScript" to fsUri + dill, - "assetDirectory" to Paths.get(URI(fsUri + "flutter_assets")).toString(), - )) - } - - /** - * This program's Flutter view. The first time, the one whose isolate is [isolateHint] (or the only one); after - * that the same view by its id, since running a program in a view gives the view a new isolate. - */ - private fun view(timeoutMs: Long = 60_000): JsonObject { - val vm = vm ?: throw IOException("the app is not running") - val views = (vm.call("_flutter.listViews", timeoutMs = timeoutMs)["views"] as? JsonArray).orEmpty() - .filterIsInstance() - val chosen = viewId?.let { id -> - views.firstOrNull { it.string("id") == id } ?: throw IOException("the app's Flutter view is gone") - } ?: isolateHint?.let { iso -> views.firstOrNull { (it["isolate"] as? JsonObject)?.string("id") == iso } } - ?: views.firstOrNull() - ?: throw IOException("the app has no Flutter view") - viewId = chosen.string("id") - return chosen - } - - private fun errors(result: FrontendServer.Result): List { - val errors = result.messages.filter { ": Error: " in it || it.startsWith("Error: ") } - .map { line -> line.substringAfter(pkg.toString() + "/").removePrefix(pkg.toUri().toString()) } - return errors.ifEmpty { listOf("${result.errors} compile error(s)") } - } - - private fun ms(since: Long) = (System.nanoTime() - since) / 1_000_000 - - companion object { - private const val FS = "codeassist" - - /** How long a compiler may sit unused before [releaseIfIdle] stops it. */ - const val IDLE_MS = 2 * 60_000L - - /** - * The plugin-wide seed: a kernel of some Flutter app built with this Flutter, which a compiler with nothing - * better starts from. Mostly the framework, which every app shares; its app libraries are checked against - * the sources like any other and simply recompiled. - */ - fun seed(sdk: DartSdk): Path = sdk.home.resolve("flutter-seed-${FlutterSdk.VERSION}.dill") - - /** Where the Run compiles a package. */ - fun runWork(pkg: Path): Path = pkg.resolve(".dart_tool/codeassist/flutter") - - /** - * A Run's heartbeat: present while a Run of the package is going, its time moved on every couple of seconds. - * A file and not a flag in memory because the Run may be in the build process, not the IDE's; a time and not - * just presence because a Run whose process died leaves the file behind. - */ - fun runMarker(pkg: Path): Path = runWork(pkg).resolve("running") - - /** Whether a Run of [pkg] is going now (its [runMarker] was touched in the last ten seconds). */ - fun runActive(pkg: Path): Boolean = runCatching { - System.currentTimeMillis() - Files.getLastModifiedTime(runMarker(pkg)).toMillis() < 10_000 - }.getOrDefault(false) - - /** Where the preview pane compiles a package. */ - fun paneWork(pkg: Path): Path = pkg.resolve(".dart_tool/codeassist/pane") - - /** The VM service answers a moment after the engine reports it; try a few times. */ - suspend fun connect(uri: String): VmService { - var last: IOException? = null - repeat(20) { - try { - return VmService.connect(uri) - } catch (e: IOException) { - last = e - delay(250) - } - } - throw IOException("Could not reach the Flutter engine's VM service at $uri: ${last?.message}") - } - - internal fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.contentOrNull - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FrontendServer.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FrontendServer.kt deleted file mode 100644 index 48da64c64e..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/FrontendServer.kt +++ /dev/null @@ -1,165 +0,0 @@ -package dev.codeassist.dart - -import java.io.IOException -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths -import java.util.UUID -import java.util.concurrent.LinkedBlockingQueue -import java.util.concurrent.TimeUnit - -/** - * The Dart SDK's `frontend_server` for one Flutter app: the incremental compiler behind `flutter run`. It - * stays running for the length of a run, so a hot reload recompiles only the libraries that changed. - * - * Spoken to over stdin, one command at a time (pkg/frontend_server/lib/frontend_server.dart): `compile ` - * for the first, full compile; `recompile ` then the changed files' URIs and `` for a delta; - * `accept` once the VM took a delta, `reject` when it did not; `reset` so the next recompile writes a full - * kernel, which is how a hot restart gets one (`recompile-restart` is the web compiler's, and on the VM it - * writes a delta, whose program has no `main` of its own). Each compile answers with `result `, the - * compiler's messages, and ` `. - */ -class FrontendServer( - private val sdk: DartSdk, - private val flutter: FlutterSdk, - private val pkg: Path, - val outputDill: Path, - /** - * Kernels to start from when [outputDill] does not exist yet, best first: another compile of this package - * (the Run's, the preview pane's), then a plugin-wide one. See [warm]. - */ - private val seeds: List = emptyList(), - /** More arguments for the compiler: an APK build's Dart plugin registrant ([FlutterPlugins.dartRegistrantArgs]). */ - private val extraArgs: List = emptyList(), -) : AutoCloseable { - /** A compile's outcome: the kernel file (null when it failed outright), its error count, what it said. */ - class Result(val dill: Path?, val errors: Int, val messages: List) { - val ok: Boolean get() = dill != null && errors == 0 - } - - private var process: Process? = null - private var lines = LinkedBlockingQueue() - - /** - * Whether this compiler started from a kernel ([outputDill] from a previous run, or a seed) rather than from - * sources alone. It matters for memory far more than for time: a warm compiler of a Flutter app settles - * around 375 MB, a cold one around 590 MB, and it keeps that for as long as it runs. Starting warm is safe - * with any kernel of the same Flutter: the compiler checks each library it reuses against its source and - * compiles again the ones that changed. - */ - var warm = false - private set - - fun start() { - val runtime = sdk.runtime ?: throw IOException(DartSdk.NO_SDK) - val compiler = sdk.frontendServer ?: throw IOException(DartSdk.NO_SDK) - Files.createDirectories(outputDill.parent) - // The compiler initializes from its own output when there is one; failing that, from a seed. - val seed = if (Files.isRegularFile(outputDill)) null else seeds.firstOrNull { Files.isRegularFile(it) } - warm = Files.isRegularFile(outputDill) || seed != null - lines = LinkedBlockingQueue() - val p = ProcessBuilder( - listOf(runtime.toString()) + DartSdk.VM_TUNING + listOfNotNull( - compiler.toString(), - "--sdk-root", flutter.platformDir.toString() + "/", - "--target=flutter", - "--incremental", - "--track-widget-creation", - "--enable-asserts", - "--packages=${pkg.resolve(DartPackages.PACKAGE_CONFIG)}", - "--output-dill=$outputDill", - "-Ddart.vm.profile=false", - "-Ddart.vm.product=false", - "--no-print-incremental-dependencies", - seed?.let { "--initialize-from-dill=$it" }, - ) + extraArgs, - ).directory(pkg.toFile()).redirectErrorStream(true) - .apply { environment().putAll(sdk.environment()) } - .start() - process = p - val into = lines - Thread({ - try { - p.inputStream.bufferedReader().forEachLine { into.put(it) } - } catch (_: IOException) { - // Closed by close(). - } - into.put(EOF) - }, "flutter-frontend-server").apply { isDaemon = true }.start() - } - - /** The first, full compile of [entry] (`package:app/main.dart`). */ - fun compile(entry: String): Result { - send("compile $entry\n") - return result() - } - - /** Recompile [entry] with [changed] (file URIs) invalidated: a delta holding only what changed. */ - fun recompile(entry: String, changed: List): Result { - val key = UUID.randomUUID().toString() - send("recompile $entry $key\n" + changed.joinToString("") { "$it\n" } + "$key\n") - return result() - } - - /** A full kernel of the program as it is now, for a hot restart: `reset`, then a recompile. */ - fun recompileFull(entry: String, changed: List): Result { - send("reset\n") - return recompile(entry, changed) - } - - /** The VM took the last delta: it becomes the base of the next. */ - fun accept() = send("accept\n") - - /** The VM refused the last delta: the next recompile includes its changes again. */ - fun reject() { - send("reject\n") - result(expectDill = false) - } - - override fun close() { - val p = process ?: return - runCatching { send("quit\n") } - if (!p.waitFor(2, TimeUnit.SECONDS)) p.destroyForcibly() - process = null - } - - private fun send(text: String) { - val p = process ?: throw IOException("the compiler is not running") - p.outputStream.write(text.toByteArray()) - p.outputStream.flush() - } - - /** - * Read one answer: everything up to `result ` is noise, then the messages until the key, then (for a - * compile) ` `. - */ - private fun result(expectDill: Boolean = true, timeoutSeconds: Long = 600): Result { - val messages = ArrayList() - var key: String? = null - while (true) { - val line = lines.poll(timeoutSeconds, TimeUnit.SECONDS) ?: throw IOException("the compiler stopped answering") - if (line === EOF) throw IOException("the compiler exited: ${messages.joinToString("\n").take(2000)}") - if (key == null) { - val at = line.indexOf("result ") - if (at >= 0) key = line.substring(at + "result ".length).trim() else messages += line - continue - } - if (line == key) { - if (!expectDill) return Result(null, 0, messages) - continue - } - if (line.startsWith("$key ")) { - val rest = line.substring(key.length + 1) - val space = rest.lastIndexOf(' ') - val errors = rest.substring(space + 1).trim().toIntOrNull() ?: 1 - val dill = rest.substring(0, space.coerceAtLeast(0)).trim().takeIf { it.isNotEmpty() }?.let { Paths.get(it) } - return Result(dill?.takeIf { Files.isRegularFile(it) }, errors, messages) - } - if (!line.startsWith("+") && !line.startsWith("-")) messages += line - } - } - - private companion object { - val EOF = String(charArrayOf('\u0000')) - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/PackageWatcher.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/PackageWatcher.kt deleted file mode 100644 index cebf3e18fd..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/PackageWatcher.kt +++ /dev/null @@ -1,136 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.platform.MessageBus -import dev.ide.vfs.FileMoved -import dev.ide.vfs.VfsEvent -import dev.ide.vfs.VfsListener -import dev.ide.vfs.VfsTopics -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.withTimeoutOrNull -import java.io.IOException -import java.nio.file.FileVisitResult -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths -import java.nio.file.SimpleFileVisitor -import java.nio.file.attribute.BasicFileAttributes -import java.util.concurrent.ConcurrentHashMap - -/** - * Which of a package's Dart files and pubspec changed: what a hot-reloading run or preview reloads. - * - * Two sources. The IDE's own file events ([VfsTopics.CHANGES], published on every editor save) are immediate and - * cost nothing, and they [wake] whoever waits. They only reach the IDE's process; a Run in the separate build - * process never sees them, and an edit made outside the IDE never makes one. So the package is also walked, every - * [POLL_MS] rather than continuously, and never into `.dart_tool`, `build` or a dot directory: the projects live on - * shared storage, where every file looked at is a round trip through Android's FUSE layer. - */ -internal class PackageWatcher( - private val pkg: Path, - bus: MessageBus?, - /** Signalled when there is something to look at. Shared, so other wake-ups (a console command) use it too. */ - val wake: Channel = Channel(Channel.CONFLATED), - /** How often the package is walked; [POLL_MS] but in tests. */ - private val walkEveryMs: Long = POLL_MS, -) : AutoCloseable { - private val edited = ConcurrentHashMap.newKeySet() - private val seen = HashMap() - private var lastWalk = 0L - - private val connection = bus?.connect()?.also { c -> - c.subscribe(VfsTopics.CHANGES, VfsListener { events -> onEvents(events) }) - } - - init { - seen.putAll(walk()) - lastWalk = System.nanoTime() - } - - /** Wait until something may have changed, or [timeoutMs] passed (when the walk is due). */ - suspend fun await(timeoutMs: Long = walkEveryMs) { - withTimeoutOrNull(timeoutMs) { wake.receive() } - } - - /** The files changed since the last call: what the events named at once, and what a due walk found. */ - fun changes(): List { - val out = LinkedHashSet() - if (edited.isNotEmpty()) { - val batch = edited.toList() - edited.removeAll(batch.toSet()) - for (p in batch) { - val stamp = stamp(p) - // An event for a file the walk already took in (or a save that changed nothing on disk) is not a change. - if (stamp == seen[p]) continue - if (stamp == null) seen.remove(p) else seen[p] = stamp - out.add(p) - } - } - if (System.nanoTime() - lastWalk >= walkEveryMs * 1_000_000) { - val now = walk() - for (p in now.keys + seen.keys) if (now[p] != seen[p]) out.add(p) - seen.clear() - seen.putAll(now) - lastWalk = System.nanoTime() - } - return out.toList() - } - - override fun close() { - connection?.dispose() - } - - private fun onEvents(events: List) { - // On the publisher's thread (the editor's save): only note the paths and wake the waiter. - var any = false - for (e in events) { - val paths = if (e is FileMoved) listOf(e.from, e.to) else listOf(e.file.path) - for (raw in paths) { - val p = runCatching { Paths.get(raw).normalize() }.getOrNull() ?: continue - if (watched(p)) { - edited.add(p) - any = true - } - } - } - if (any) wake.trySend(Unit) - } - - private fun watched(p: Path): Boolean { - if (!p.startsWith(pkg) || p == pkg) return false - val rel = pkg.relativize(p) - if ((0 until rel.nameCount - 1).any { skipped(rel.getName(it).toString(), it == 0) }) return false - val name = p.fileName.toString() - return name.endsWith(".dart") || (rel.nameCount == 1 && name == DartPackages.PUBSPEC) - } - - /** The modification time of each watched file, found without entering the directories nothing is watched in. */ - private fun walk(): Map { - val out = HashMap() - try { - Files.walkFileTree(pkg, object : SimpleFileVisitor() { - override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult = - if (dir != pkg && skipped(dir.fileName.toString(), dir.parent == pkg)) FileVisitResult.SKIP_SUBTREE - else FileVisitResult.CONTINUE - - override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { - if (attrs.isRegularFile && watched(file)) out[file] = attrs.lastModifiedTime().toMillis() - return FileVisitResult.CONTINUE - } - - override fun visitFileFailed(file: Path, exc: IOException): FileVisitResult = FileVisitResult.CONTINUE - }) - } catch (_: IOException) { - // The package went away mid-walk; what was found stands. - } - return out - } - - private fun stamp(p: Path): Long? = runCatching { Files.getLastModifiedTime(p).toMillis() }.getOrNull() - - private fun skipped(name: String, topLevel: Boolean) = name.startsWith(".") || (topLevel && name == "build") - - companion object { - /** How often the package is walked for changes no event announced. */ - const val POLL_MS = 2_000L - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/PluginInfoActivity.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/PluginInfoActivity.kt deleted file mode 100644 index b826f53565..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/PluginInfoActivity.kt +++ /dev/null @@ -1,112 +0,0 @@ -package dev.codeassist.dart - -import android.app.Activity -import android.os.Bundle -import android.view.View -import android.view.ViewGroup -import android.widget.BaseAdapter -import android.widget.ListView -import android.widget.TextView -import java.io.InputStream -import java.util.zip.GZIPInputStream -import java.util.zip.ZipInputStream - -/** - * What the user sees if they launch this app directly: what the plugin is, and the licenses of everything it - * carries. A plugin app exists to be discovered by CodeAssist; saying so is better than a blank screen, which - * reads as a broken install. - * - * The licenses are read from the assets the plugin ships rather than copied into the app: the Dart SDK's and - * Flutter's own `LICENSE`, and Flutter's `NOTICES` (every library inside the engine and the framework, Skia, - * ICU, HarfBuzz, BoringSSL, ...), so they are always the ones for the exact bytes on the device. - */ -class PluginInfoActivity : Activity() { - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - val entries = ArrayList() - entries += INTRO - entries += section("The Dart SDK ${DartSdk.VERSION}", "Built for Android by the Termux project (termux-packages, Apache License 2.0).") + - (zipEntry(DART_ASSET, "LICENSE") ?: MISSING) - entries += section("Flutter ${FlutterSdk.VERSION}", null) + (zipEntry(FLUTTER_ROOT_ASSET, "LICENSE") ?: MISSING) - entries += section("kotlinx.serialization", null) + APACHE_2 - // Flutter's notices: one entry per library or group of libraries, separated by a line of dashes. - val notices = zipEntry(FLUTTER_BASE_ASSET, "NOTICES.Z", gzipped = true) - if (notices != null) { - entries += section("Inside the Flutter engine and framework", null).trimEnd() - entries += notices.split(NOTICE_SEPARATOR).map { it.trim() }.filter { it.isNotEmpty() } - } - setContentView(ListView(this).apply { - divider = null - adapter = Entries(entries) - }) - } - - /** One text block per row, so the ~1 MB of notices is laid out a screen at a time, never all at once. */ - private inner class Entries(private val items: List) : BaseAdapter() { - override fun getCount() = items.size - override fun getItem(position: Int) = items[position] - override fun getItemId(position: Int) = position.toLong() - override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View = - ((convertView as? TextView) ?: TextView(this@PluginInfoActivity).apply { - setPadding(48, 24, 48, 24) - setTextIsSelectable(true) - }).apply { - text = items[position] - textSize = if (position == 0) 16f else 12f - } - } - - /** The text of [name] inside the stored archive [asset], or null when this build does not carry it. */ - private fun zipEntry(asset: String, name: String, gzipped: Boolean = false): String? = runCatching { - ZipInputStream(assets.open(asset).buffered()).use { zip -> - var entry = zip.nextEntry - while (entry != null && entry.name != name) entry = zip.nextEntry - if (entry == null) return@use null - val stream: InputStream = if (gzipped) GZIPInputStream(zip) else zip - String(stream.readBytes()) - } - }.getOrNull() - - private fun section(title: String, note: String?) = buildString { - appendLine(title) - appendLine("=".repeat(title.length)) - if (note != null) appendLine(note) - appendLine() - } - - private companion object { - const val DART_ASSET = "dart-sdk.zip" - const val FLUTTER_ROOT_ASSET = "flutter-root.zip" - const val FLUTTER_BASE_ASSET = "flutter-base-assets.zip" - const val MISSING = "(not in this build)" - val NOTICE_SEPARATOR = Regex("(?m)^-{20,}$") - - val INTRO = """ - CodeAssist Dart - - A plugin for CodeAssist, not an app of its own. - - It adds Dart and Flutter: errors, completion and quick fixes from Dart's analysis server, Run for - command-line programs and Flutter apps (with hot reload), live @Preview widgets in the editor, tests, - and pub, with a Dart SDK and Flutter for this device's ABI inside. - - Open CodeAssist, then Settings and tools > Plugins to allow it to run. - - Below: the licenses of the software this plugin carries. - """.trimIndent() - - val APACHE_2 = """ - kotlinx.serialization, by JetBrains and its contributors (github.com/Kotlin/kotlinx.serialization). - - Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in - compliance with the License. You may obtain a copy of the License at - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software distributed under the License is - distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied. See the License for the specific language governing permissions and limitations under the - License. - """.trimIndent() - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/Pub.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/Pub.kt deleted file mode 100644 index ef3b552612..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/Pub.kt +++ /dev/null @@ -1,97 +0,0 @@ -package dev.codeassist.dart - -import java.io.IOException -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.attribute.FileTime -import java.util.concurrent.TimeUnit - -/** - * `dart pub`, run through the `dart` tool's own snapshot. - * - * It is started by [DartSdk.launcher], the `/bin/dart` symlink, and not by the runtime's real path: - * `dart` locates its SDK two directories above the path it was started by, and the real one is the native - * library directory, which has no SDK around it. pub's `get`, `upgrade`, `add` and `outdated` work this way; - * `dart run` and `dart test` do not (they look for compilers beside the runtime's resolved path), which is - * why Run compiles and runs a program itself ([DartRun]). - */ -class Pub(private val sdk: DartSdk, private val flutter: FlutterSdk? = null) { - - /** - * Run `dart pub ` in [pkg], passing each line of its output to [out], and answer its exit - * code, or -1 when it could not run or took longer than [timeoutSeconds]. Blocking. - */ - fun run( - pkg: Path, - command: String, - vararg args: String, - timeoutSeconds: Long = 300, - cancellation: ToolCancellation? = null, - out: (String) -> Unit, - ): Int { - val status = sdk.prepare() - if (status is DartSdk.Status.Unavailable) { - out(status.reason) - return -1 - } - val dartdev = sdk.dartdev ?: return -1 - // A Flutter package's `flutter: sdk: flutter` dependencies resolve from FLUTTER_ROOT. - val env = sdk.environment().toMutableMap() - if (FlutterSdk.isFlutterPackage(pkg)) { - when (val f = flutter?.prepare() ?: FlutterSdk.Status.Unavailable(FlutterSdk.NO_FLUTTER)) { - is FlutterSdk.Status.Ready -> env["FLUTTER_ROOT"] = f.root.toString() - is FlutterSdk.Status.Unavailable -> { out(f.reason); return -1 } - } - } - val process = try { - ProcessBuilder(listOf(sdk.launcher.toString(), dartdev.toString(), "--suppress-analytics", "pub", command) + args) - .directory(pkg.toFile()) - .redirectErrorStream(true) - .apply { environment().putAll(env) } - .start() - } catch (e: IOException) { - out("Could not start pub: ${e.message}") - return -1 - } - cancellation?.attach(process) - runCatching { process.outputStream.close() } - // pub can wait on the network for a long time; the reader runs beside the timeout rather than in its way. - var solveFailed = false - val reader = Thread({ - try { - process.inputStream.bufferedReader().forEachLine { line -> - if (FAILURES.any { it in line }) solveFailed = true - out(line) - } - } catch (_: IOException) { - // Killed: the stream ended with the process. - } - }, "dart-pub-output").apply { isDaemon = true; start() } - if (!process.waitFor(timeoutSeconds, TimeUnit.SECONDS)) { - process.destroyForcibly() - reader.join(1_000) - out("pub $command did not finish within $timeoutSeconds seconds") - return -1 - } - reader.join(5_000) - // `dart pub get` has been seen to exit 0 after "version solving failed": the output decides. - val code = process.exitValue().let { if (it == 0 && solveFailed) 1 else it } - if (code == 0 && command in RESOLVING) markResolved(pkg) - return code - } - - /** - * Record that [pkg]'s package config answers its pubspec as it is now. pub leaves an unchanged config - * untouched, so after a save that changed nothing pub cares about, the pubspec stays newer than the config - * and [DartPackages.needsPubGet] would ask for another `pub get` on every run and build. - */ - private fun markResolved(pkg: Path) { - val config = pkg.resolve(DartPackages.PACKAGE_CONFIG) - if (Files.isRegularFile(config)) runCatching { Files.setLastModifiedTime(config, FileTime.fromMillis(System.currentTimeMillis())) } - } - - private companion object { - val RESOLVING = setOf("get", "upgrade", "downgrade") - val FAILURES = listOf("version solving failed", "Failed to update packages") - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/PubImporter.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/PubImporter.kt deleted file mode 100644 index 3ebf44846f..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/PubImporter.kt +++ /dev/null @@ -1,278 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.model.BuildSystemId -import dev.ide.model.DependencyScope -import dev.ide.model.sync.Detection -import dev.ide.model.sync.ExternalDependency -import dev.ide.model.sync.ExternalFacet -import dev.ide.model.sync.ExternalLibrary -import dev.ide.model.sync.ExternalModule -import dev.ide.model.sync.ExternalModuleRef -import dev.ide.model.sync.ExternalProjectModel -import dev.ide.model.sync.ExternalRepository -import dev.ide.model.sync.ExternalSourceSet -import dev.ide.model.sync.ModelOwnership -import dev.ide.model.sync.ProjectImporter -import dev.ide.model.sync.SyncMessage -import dev.ide.model.sync.SyncOutcome -import dev.ide.model.sync.SyncRequest -import dev.ide.model.sync.SyncSeverity -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import java.nio.file.Files -import java.nio.file.Path - -/** - * Opens a pub package as a Dart project: the package as a module, rooted where its `pubspec.yaml` is. - * - * A Flutter app with an Android side (`android/app`, as `flutter create` and the Flutter App template lay it - * out) also gets that as an Android app module, built with the Flutter app in it ([FlutterBuildPlugin]), and - * one Android library module per Flutter plugin with Android code its dependencies reach, as the Flutter Gradle - * plugin includes each one as a Gradle subproject. Which plugins there are is decided by `pub get`, not by - * anything the user edits, so this syncs before a build whenever the package config changed - * ([syncBeforeBuild]), and a sync removes only the modules an earlier sync produced. - * - * The IDE owns the model once the package is adopted ([ModelOwnership.IDE]): a dependency the user adds to the - * app module in the IDE survives the syncs that keep its plugin modules current. - */ -object PubImporter : ProjectImporter { - override val id: BuildSystemId = DartModuleType.PUB - override val displayName = "Dart (pub)" - override val ownership: ModelOwnership get() = ModelOwnership.IDE - override val syncBeforeBuild: Boolean get() = true - - /** The Android app module of a Flutter app, where `flutter create` puts it. */ - const val ANDROID_APP_DIR = "android/app" - const val ANDROID_APP_MODULE = "app" - - override fun detect(root: Path): Detection? { - val pubspec = root.resolve(DartPackages.PUBSPEC) - if (!Files.isRegularFile(pubspec)) return null - return Detection(nameOf(root, pubspec), listOf(pubspec), confidence = 10) - } - - /** What changes the modules: the package config (`pub get`, so the plugins), and an Android app's build file. */ - override fun syncFiles(): List = listOf( - DartPackages.PUBSPEC, - DartPackages.PACKAGE_CONFIG, - "$ANDROID_APP_DIR/build.gradle", - "$ANDROID_APP_DIR/build.gradle.kts", - ) - - override suspend fun resolve(request: SyncRequest): SyncOutcome = withContext(Dispatchers.IO) { - val root = request.root - val pubspec = root.resolve(DartPackages.PUBSPEC) - if (!Files.isRegularFile(pubspec)) return@withContext SyncOutcome.failed("No pubspec.yaml at ${root}") - val name = nameOf(root, pubspec) - val messages = ArrayList() - val dart = ExternalModule( - name = name, - // The project root, written as "." because the host reads a blank path as "a directory named after - // the module": an imported package's module then sat in `//`, where there is no pubspec. - dirRelPath = ".", - typeId = DartModuleType.ID, - sourceSets = DartPackages.contentRoots(root).map { (set, dirs) -> - ExternalSourceSet( - set, - scope = if (set == "test") DependencyScope.TEST_IMPLEMENTATION else DependencyScope.IMPLEMENTATION, - roots = dirs.associateWith { setOf(DartModuleType.DART_SOURCE) }, - ) - }, - ) - val android = if (isFlutterApp(root)) androidModules(root, messages) else emptyList() - val repositories = if (android.isEmpty()) emptyList() - else listOf(ExternalRepository("Flutter", FlutterSdk.MAVEN_REPOSITORY)) - SyncOutcome(ExternalProjectModel(name, DartModuleType.PUB, modules = listOf(dart) + android, repositories = repositories), messages) - } - - private fun isFlutterApp(root: Path): Boolean = - FlutterSdk.isFlutterPackage(root) && Files.isRegularFile(root.resolve("$ANDROID_APP_DIR/src/main/AndroidManifest.xml")) - - /** - * The Android app module and its plugins' library modules. Runs `pub get` first when the package config is - * missing or stale, since which plugins there are is what it decides; without one, the app module comes - * without plugins and a message says why. - */ - private fun androidModules(root: Path, messages: MutableList): List { - if (DartPackages.needsPubGet(root)) { - val pub = DartPlugin.tools?.pub - val output = StringBuilder() - val code = pub?.run(root, "get", out = { output.appendLine(it) }) ?: -1 - if (code != 0 || DartPackages.needsPubGet(root)) { - messages += SyncMessage( - SyncSeverity.WARNING, - "pub get failed, so the app's Flutter plugins are not known yet: ${output.toString().trim().takeLast(600)}", - ) - } - } - val plugins = runCatching { FlutterPlugins.discover(root) }.getOrDefault(emptyList()) - val withCode = plugins.filter { it.hasAndroidCode } - val abi = FlutterApkTask.abiOf(DartPlugin.tools?.flutter?.engine?.parent) - - val libraries = withCode.mapNotNull { plugin -> - runCatching { pluginModule(root, plugin, abi, messages) } - .onFailure { messages += SyncMessage(SyncSeverity.WARNING, "The Flutter plugin ${plugin.name} could not be set up: ${it.message}") } - .getOrNull() - } - // The Java registrant names exactly the plugins whose modules exist. - val registered = withCode.filter { p -> libraries.any { it.name == p.name } } - runCatching { - val file = root.resolve("$ANDROID_APP_DIR/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java") - val text = FlutterPlugins.javaRegistrant(registered) - if (!Files.isRegularFile(file) || String(Files.readAllBytes(file)) != text) { - Files.createDirectories(file.parent) - Files.write(file, text.toByteArray()) - } - }.onFailure { messages += SyncMessage(SyncSeverity.WARNING, "GeneratedPluginRegistrant.java could not be written: ${it.message}") } - - val appBuildText = appBuildFile(root)?.let { String(Files.readAllBytes(it)) } - val appBuild = appBuildText?.let { FlutterPlugins.parseAppBuild(it) } - val appDependencies = FlutterAppTemplate.EMBEDDINGS.map { (variant, coordinate) -> - ExternalLibrary(coordinate, DependencyScope.IMPLEMENTATION, variant) - } + libraries.map { ExternalModuleRef(it.name, DependencyScope.IMPLEMENTATION) } + - appBuild?.dependencies.orEmpty().map { (configuration, coordinate) -> ExternalLibrary(coordinate, scopeOf(configuration)) } - appBuild?.unreadDependencies?.forEach { - messages += SyncMessage(SyncSeverity.WARNING, "android/app: could not read the dependency '$it' in its build file.") - } - val facets = ArrayList() - facets += ExternalFacet(FlutterFacetCodec.tomlTable, FlutterFacetCodec.encode(FlutterFacet())) - // A project `flutter create` made has its Android settings in its Gradle build file; one the Flutter App - // template made has them in the module itself, which a sync then leaves as they are. - // Only when the build file changed since the settings were last taken from it (or never were): a change - // made since in Module Settings then stands until the build file is edited again, whichever was edited - // last wins, rather than every sync (each pub get) quietly putting the build file's values back. - if (appBuild != null && appBuildChanged(root, appBuildText!!)) facets += ExternalFacet("android", androidSettings(root, appBuild)) - val app = ExternalModule( - name = ANDROID_APP_MODULE, - dirRelPath = ANDROID_APP_DIR, - typeId = "android-app", - dependencies = appDependencies, - facets = facets, - ) - return listOf(app) + libraries - } - - /** - * Whether [text], the app's build file, differs from the one whose settings the last sync applied, recording - * it as applied. True the first time, and whenever the stamp is unreadable: better a settings refresh than - * settings that never came from the build file at all. - */ - private fun appBuildChanged(root: Path, text: String): Boolean { - val stamp = root.resolve(".dart_tool/codeassist/android-app-build.sha256") - val digest = java.security.MessageDigest.getInstance("SHA-256").digest(text.toByteArray()) - .joinToString("") { "%02x".format(it) } - val previous = runCatching { String(Files.readAllBytes(stamp)).trim() }.getOrNull() - if (previous == digest) return false - runCatching { - Files.createDirectories(stamp.parent) - Files.write(stamp, digest.toByteArray()) - } - return true - } - - private fun appBuildFile(root: Path): Path? = - listOf("build.gradle.kts", "build.gradle").map { root.resolve("$ANDROID_APP_DIR/$it") }.firstOrNull { Files.isRegularFile(it) } - - /** - * The `[android]` table for an app whose build file says it, with what the Flutter Gradle plugin supplies - * filled in: its default SDK levels for `flutter.compileSdkVersion` and the like, the version from the - * pubspec for `flutter.versionCode` / `flutter.versionName`, and the `applicationName` placeholder the - * manifest of every `flutter create` app names. - */ - internal fun androidSettings(root: Path, build: AppAndroidBuild): Map { - val version = runCatching { - (MiniYaml.parse(String(Files.readAllBytes(root.resolve(DartPackages.PUBSPEC)))) as? Map<*, *>)?.get("version")?.toString() - }.getOrNull() - val namespace = build.namespace ?: build.applicationId ?: "com.example.${nameOf(root, root.resolve(DartPackages.PUBSPEC))}" - return mapOf( - "namespace" to namespace, - "applicationId" to (build.applicationId ?: namespace), - "compileSdk" to (build.compileSdk ?: FLUTTER_COMPILE_SDK), - "minSdk" to (build.minSdk ?: FLUTTER_MIN_SDK), - "targetSdk" to (build.targetSdk ?: FLUTTER_TARGET_SDK), - "versionCode" to (build.versionCode ?: versionCode(version)), - "versionName" to (build.versionName ?: versionName(version)), - "manifestPlaceholders" to listOf("applicationName=android.app.Application"), - ) - } - - /** `1.2.0+7` gives version code 7, as Flutter reads a pubspec's version; no build number gives 1. */ - internal fun versionCode(version: String?): Int = version?.substringAfter('+', "")?.toIntOrNull() ?: 1 - - /** `1.2.0+7` gives version name `1.2.0`. */ - internal fun versionName(version: String?): String = version?.substringBefore('+')?.takeIf { it.isNotBlank() } ?: "1.0.0" - - /** The Flutter Gradle plugin's defaults for Flutter [FlutterSdk.VERSION] (its FlutterExtension). */ - const val FLUTTER_COMPILE_SDK = 36 - const val FLUTTER_MIN_SDK = 24 - const val FLUTTER_TARGET_SDK = 36 - - private fun scopeOf(configuration: String) = when (configuration) { - "api" -> DependencyScope.API - "compileOnly" -> DependencyScope.COMPILE_ONLY - "runtimeOnly" -> DependencyScope.RUNTIME_ONLY - else -> DependencyScope.IMPLEMENTATION - } - - /** [plugin]'s Android library as a module: its code copied into the project, its build read for the rest. */ - private fun pluginModule(root: Path, plugin: FlutterPlugin, abi: String?, messages: MutableList): ExternalModule { - val androidDir = plugin.root.resolve("android") - val build = FlutterPlugins.readAndroidBuild(androidDir) - val cmake = build.cmakePath?.let { path -> - val file = androidDir.resolve(path).normalize() - runCatching { FlutterPlugins.parseCMake(String(Files.readAllBytes(file))) }.getOrNull() - } - if (plugin.ffi && cmake == null) { - messages += SyncMessage(SyncSeverity.WARNING, "${plugin.name} has native code whose build could not be read, so it is not built.") - } - val dirRel = FlutterPlugins.moduleDirRel(plugin) - FlutterPlugins.copyAndroidLibrary(plugin, build, cmake, root.resolve(dirRel)) - for (unread in build.unreadDependencies) { - messages += SyncMessage(SyncSeverity.WARNING, "${plugin.name}: could not read the dependency '$unread' in its build file.") - } - - val dependencies = ArrayList() - for ((configuration, coordinate) in build.dependencies) dependencies += ExternalLibrary(coordinate, scopeOf(configuration)) - // The engine's Java half to compile against; the app packages its own, debug or release. - dependencies += ExternalLibrary(FlutterSdk.EMBEDDING_DEBUG, DependencyScope.COMPILE_ONLY) - plugin.dependsOn.forEach { dependencies += ExternalModuleRef(it, DependencyScope.IMPLEMENTATION) } - - val namespace = build.namespace ?: plugin.androidPackage ?: "io.flutter.plugins.${plugin.name}" - val facets = ArrayList() - facets += ExternalFacet( - "android", - mapOf( - "namespace" to namespace, - "compileSdk" to FlutterAppTemplate.COMPILE_SDK, - "minSdk" to (build.minSdk ?: 21).coerceAtMost(FlutterAppTemplate.MIN_SDK), - "targetSdk" to FlutterAppTemplate.COMPILE_SDK, - "isApplication" to false, - ), - ) - if (cmake != null) { - // The NDK plugin's table, by name: compiled by its on-device clang, packaged by the app's build. - facets += ExternalFacet( - "ndk", - mapOf( - "sourceDirs" to listOf("src/main/cpp"), - "libraryName" to cmake.outputName, - "abis" to listOfNotNull(abi).ifEmpty { listOf("arm64-v8a") }, - "minSdk" to FlutterAppTemplate.MIN_SDK, - "compilerFlags" to cmake.definitions.map { "-D$it" }, - "linkLibraries" to cmake.linkLibraries.ifEmpty { listOf("log") }, - ), - ) - } - return ExternalModule( - name = plugin.name, - dirRelPath = dirRel, - typeId = "android-lib", - dependencies = dependencies, - facets = facets, - ) - } - - private fun nameOf(root: Path, pubspec: Path): String = - runCatching { DartPackages.nameOf(String(Files.readAllBytes(pubspec))) }.getOrNull() - ?: DartPackages.packageName(root.fileName?.toString() ?: "dart") -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/ToolCancellation.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/ToolCancellation.kt deleted file mode 100644 index 99a9418d6e..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/ToolCancellation.kt +++ /dev/null @@ -1,74 +0,0 @@ -package dev.codeassist.dart - -import kotlinx.coroutines.CoroutineStart -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.awaitCancellation -import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -/** - * Lets a coroutine that is cancelled stop the process it is waiting on, instead of letting it run on. - * - * Stop on a run cancels the coroutine that drives it. Without this the coroutine was cancelled but the - * compiler or the program it had launched kept going, with nothing left to read its output. - * - * Blocking code (a pub, compiler or program run) [attach]es the process it starts; the coroutine side - * [cancel]s it. Both orders are handled: a cancel that arrives before the process exists kills it as soon as - * it is attached. The same helper as the NDK plugin's: plugins load on classloaders of their own and cannot - * share code. - */ -class ToolCancellation { - private var process: Process? = null - private var cancelled = false - private var finished = false - - /** True once the request was cancelled; its output is then incomplete and must not be used. */ - val isCancelled: Boolean - @Synchronized get() = cancelled - - /** Record [process] as the one to kill. Kills it at once when the request was already cancelled. */ - @Synchronized - fun attach(process: Process) { - if (cancelled) process.destroyForcibly() else this.process = process - } - - /** Kill the attached process, if any. A no-op once the request has [finish]ed. */ - @Synchronized - fun cancel() { - if (finished) return - cancelled = true - process?.destroyForcibly() - } - - /** The request is over: nothing is attached any more, and a late cancel must not mark it cancelled. */ - @Synchronized - fun finish() { - finished = true - process = null - } -} - -/** - * Run the blocking [block] on the IO dispatcher, killing whatever process it [ToolCancellation.attach]es - * when the calling coroutine is cancelled. Throws [kotlinx.coroutines.CancellationException] in that case, - * like any other cancelled suspend call, so a cancelled result never reaches a cache. - */ -internal suspend fun killableTool(block: (ToolCancellation) -> T): T = coroutineScope { - val cancellation = ToolCancellation() - // UNDISPATCHED so the watcher is registered before the block starts: a cancel that lands in between - // must still reach the process. - val watcher = launch(Dispatchers.Default, start = CoroutineStart.UNDISPATCHED) { - try { - awaitCancellation() - } finally { - cancellation.cancel() - } - } - try { - withContext(Dispatchers.IO) { block(cancellation) } - } finally { - cancellation.finish() - watcher.cancel() - } -} diff --git a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/VmService.kt b/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/VmService.kt deleted file mode 100644 index a3185f5c3d..0000000000 --- a/samples/dart-plugin/src/main/kotlin/dev/codeassist/dart/VmService.kt +++ /dev/null @@ -1,317 +0,0 @@ -package dev.codeassist.dart - -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonElement -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.buildJsonObject -import kotlinx.serialization.json.contentOrNull -import kotlinx.serialization.json.jsonObject -import kotlinx.serialization.json.put -import java.io.BufferedInputStream -import java.io.ByteArrayOutputStream -import java.io.EOFException -import java.io.IOException -import java.io.InputStream -import java.io.OutputStream -import java.net.HttpURLConnection -import java.net.InetSocketAddress -import java.net.Socket -import java.net.URI -import java.net.URL -import java.nio.file.Files -import java.nio.file.Path -import java.security.MessageDigest -import java.security.SecureRandom -import java.util.Base64 -import java.util.concurrent.CompletableFuture -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicLong -import java.util.zip.Deflater -import java.util.zip.GZIPOutputStream - -/** A VM service call the VM refused or failed. */ -class VmServiceException(val code: Int, message: String, val data: JsonElement?) : IOException(message) - -/** - * A client for the Dart VM service of a running Flutter app: JSON-RPC 2.0 over a WebSocket, which is how - * `flutter run` restarts and hot-reloads an app, plus the DevFS upload that puts files where the app can read - * them. The VM service only listens on localhost, so this is a plain socket to 127.0.0.1. - * - * A WebSocket client of its own (RFC 6455, the little of it a localhost JSON-RPC peer needs) rather than a - * library, because a plugin cannot count on one in the IDE and should not carry one for two hundred lines. - */ -class VmService private constructor(private val httpBase: String, private val socket: Socket) : AutoCloseable { - private val input = BufferedInputStream(socket.getInputStream()) - private val output: OutputStream = socket.getOutputStream() - private val nextId = AtomicLong(1) - private val pending = ConcurrentHashMap>() - private val writeLock = Any() - private val random = SecureRandom() - - /** Stream events (`streamListen`): the stream id and the event object. Called on the reader thread. */ - @Volatile var onEvent: (stream: String, event: JsonObject) -> Unit = { _, _ -> } - - /** Runs once when the connection ends: the app exited or was killed. */ - @Volatile var onClosed: () -> Unit = {} - - @Volatile var isClosed = false - private set - - private val reader = Thread({ readLoop() }, "flutter-vm-service").apply { isDaemon = true } - - /** Call [method] and wait for its result. Throws [VmServiceException] for an error answer. */ - fun call(method: String, params: Map = emptyMap(), timeoutMs: Long = 60_000): JsonObject { - val id = nextId.getAndIncrement().toString() - val future = CompletableFuture() - pending[id] = future - val message = buildJsonObject { - put("jsonrpc", "2.0") - put("id", id) - put("method", method) - put("params", toJson(params)) - } - try { - sendText(Json.encodeToString(JsonElement.serializer(), message)) - return try { - future.get(timeoutMs, TimeUnit.MILLISECONDS) - } catch (e: java.util.concurrent.ExecutionException) { - throw e.cause ?: e - } catch (e: java.util.concurrent.TimeoutException) { - // An IOException like every other way a call fails, so the run reports it rather than dying of it. - throw IOException("the app did not answer $method within ${timeoutMs / 1000} s") - } - } finally { - pending.remove(id) - } - } - - /** - * Write [file] into the DevFS [fsName] at [path] (relative to the DevFS root), the way `flutter run` - * uploads: an HTTP PUT of the gzipped bytes to the VM service, naming the file in two headers. - */ - fun upload(fsName: String, path: String, file: Path) { - val connection = URL(httpBase).openConnection() as HttpURLConnection - try { - connection.requestMethod = "PUT" - connection.doOutput = true - connection.setChunkedStreamingMode(64 * 1024) - // Without these a VM service that stops answering holds the run forever, past Stop. - connection.connectTimeout = 10_000 - connection.readTimeout = UPLOAD_TIMEOUT_MS - // A fresh socket for every upload. Reusing a pooled one now and then sends the request down a - // connection the VM service has finished with, and it never answers: the run hung on a reload. - connection.setRequestProperty("Connection", "close") - connection.setRequestProperty("dev_fs_name", fsName) - connection.setRequestProperty("dev_fs_uri_b64", Base64.getEncoder().encodeToString(path.toByteArray())) - // The fastest level: the kernel is tens of megabytes, compressed on the phone for a socket to localhost, - // where the default level costs seconds and saves nothing that matters. - object : GZIPOutputStream(connection.outputStream, 64 * 1024) { - init { def.setLevel(Deflater.BEST_SPEED) } - }.use { gz -> Files.copy(file, gz) } - val code = connection.responseCode - if (code != 200) throw IOException("uploading $path to the app failed: HTTP $code") - } finally { - connection.disconnect() - } - } - - override fun close() { - if (isClosed) return - isClosed = true - runCatching { sendFrame(OP_CLOSE, ByteArray(0)) } - runCatching { socket.close() } - } - - // ------------------------------------------------------------------------------------------- the socket - - private fun handshake(path: String, host: String, port: Int) { - val key = Base64.getEncoder().encodeToString(ByteArray(16).also(random::nextBytes)) - val request = "GET $path HTTP/1.1\r\nHost: $host:$port\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + - "Sec-WebSocket-Key: $key\r\nSec-WebSocket-Version: 13\r\n\r\n" - output.write(request.toByteArray(Charsets.US_ASCII)) - output.flush() - val status = readLine() - if (!status.startsWith("HTTP/1.1 101")) throw IOException("the VM service refused the WebSocket: $status") - var accept: String? = null - while (true) { - val line = readLine() - if (line.isEmpty()) break - val colon = line.indexOf(':') - if (colon > 0 && line.substring(0, colon).trim().equals("Sec-WebSocket-Accept", ignoreCase = true)) { - accept = line.substring(colon + 1).trim() - } - } - val expected = Base64.getEncoder().encodeToString( - MessageDigest.getInstance("SHA-1").digest((key + WS_GUID).toByteArray(Charsets.US_ASCII)), - ) - if (accept != expected) throw IOException("the VM service answered the WebSocket handshake wrongly") - } - - private fun readLine(): String { - val buf = ByteArrayOutputStream() - while (true) { - val b = input.read() - if (b < 0) throw EOFException("the VM service closed the connection") - if (b == '\n'.code) break - if (b != '\r'.code) buf.write(b) - } - return buf.toString("US-ASCII") - } - - private fun sendText(text: String) = sendFrame(OP_TEXT, text.toByteArray(Charsets.UTF_8)) - - /** One masked, unfragmented frame: what a client sends (RFC 6455 section 5.3). */ - private fun sendFrame(opcode: Int, payload: ByteArray) { - synchronized(writeLock) { - output.write(WsFrames.encode(opcode, payload, ByteArray(4).also(random::nextBytes))) - output.flush() - } - } - - private fun readLoop() { - val message = ByteArrayOutputStream() - try { - while (!isClosed) { - val frame = WsFrames.read(input) - when (frame.opcode) { - OP_TEXT, OP_BINARY, OP_CONTINUATION -> { - message.write(frame.payload) - if (frame.fin) { - handle(message.toString("UTF-8")) - message.reset() - } - } - OP_PING -> sendFrame(OP_PONG, frame.payload) - OP_CLOSE -> break - } - } - } catch (_: IOException) { - // The app went away, or close() was called. - } finally { - isClosed = true - runCatching { socket.close() } - val gone = IOException("the app's VM service connection closed") - pending.values.forEach { it.completeExceptionally(gone) } - runCatching { onClosed() } - } - } - - private fun handle(text: String) { - val message = runCatching { Json.parseToJsonElement(text).jsonObject }.getOrNull() ?: return - val id = (message["id"] as? JsonPrimitive)?.contentOrNull - if (id != null) { - val future = pending[id] ?: return - val error = message["error"] as? JsonObject - if (error != null) { - val code = (error["code"] as? JsonPrimitive)?.contentOrNull?.toIntOrNull() ?: -1 - val text2 = (error["message"] as? JsonPrimitive)?.contentOrNull ?: "error $code" - future.completeExceptionally(VmServiceException(code, text2, error["data"])) - } else { - future.complete(message["result"] as? JsonObject ?: JsonObject(emptyMap())) - } - return - } - if ((message["method"] as? JsonPrimitive)?.contentOrNull == "streamNotify") { - val params = message["params"] as? JsonObject ?: return - val stream = (params["streamId"] as? JsonPrimitive)?.contentOrNull ?: return - val event = params["event"] as? JsonObject ?: return - runCatching { onEvent(stream, event) } - } - } - - companion object { - private const val UPLOAD_TIMEOUT_MS = 120_000 - private const val WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" - const val OP_CONTINUATION = 0 - const val OP_TEXT = 1 - const val OP_BINARY = 2 - const val OP_CLOSE = 8 - const val OP_PING = 9 - const val OP_PONG = 10 - - /** - * Connect to the VM service at [httpUri] (what the engine prints: `http://127.0.0.1:PORT/TOKEN=/`). Its - * WebSocket is the same path plus `ws`. - */ - fun connect(httpUri: String, timeoutMs: Int = 10_000): VmService { - val base = if (httpUri.endsWith("/")) httpUri else "$httpUri/" - val uri = URI(base) - val socket = Socket() - socket.connect(InetSocketAddress(uri.host, uri.port), timeoutMs) - socket.tcpNoDelay = true - val service = VmService(base, socket) - try { - service.handshake("${uri.rawPath}ws", uri.host, uri.port) - } catch (e: IOException) { - runCatching { socket.close() } - throw e - } - service.reader.start() - return service - } - - private fun toJson(value: Any?): JsonElement = when (value) { - null -> kotlinx.serialization.json.JsonNull - is JsonElement -> value - is String -> JsonPrimitive(value) - is Number -> JsonPrimitive(value) - is Boolean -> JsonPrimitive(value) - is Map<*, *> -> JsonObject(value.entries.associate { (k, v) -> k.toString() to toJson(v) }) - is List<*> -> kotlinx.serialization.json.JsonArray(value.map(::toJson)) - else -> JsonPrimitive(value.toString()) - } - } -} - -/** WebSocket framing (RFC 6455 section 5.2), separate so it can be tested without a socket. */ -object WsFrames { - class Frame(val fin: Boolean, val opcode: Int, val payload: ByteArray) - - /** A client frame: FIN set, masked with [mask]. */ - fun encode(opcode: Int, payload: ByteArray, mask: ByteArray): ByteArray { - val out = ByteArrayOutputStream(payload.size + 14) - out.write(0x80 or opcode) - val n = payload.size - when { - n < 126 -> out.write(0x80 or n) - n < 65536 -> { out.write(0x80 or 126); out.write(n ushr 8); out.write(n and 0xff) } - else -> { - out.write(0x80 or 127) - for (shift in 56 downTo 0 step 8) out.write(((n.toLong() ushr shift) and 0xff).toInt()) - } - } - out.write(mask) - for (i in payload.indices) out.write(payload[i].toInt() xor mask[i % 4].toInt()) - return out.toByteArray() - } - - /** The next frame on [input], unmasking it when it is masked (a server's frames are not). */ - fun read(input: InputStream): Frame { - val b0 = readByte(input) - val b1 = readByte(input) - var length = (b1 and 0x7f).toLong() - if (length == 126L) length = ((readByte(input) shl 8) or readByte(input)).toLong() - else if (length == 127L) { - length = 0 - repeat(8) { length = (length shl 8) or readByte(input).toLong() } - } - if (length > Int.MAX_VALUE) throw IOException("a WebSocket frame of $length bytes") - val mask = if (b1 and 0x80 != 0) ByteArray(4).also { readFully(input, it) } else null - val payload = ByteArray(length.toInt()).also { readFully(input, it) } - if (mask != null) for (i in payload.indices) payload[i] = (payload[i].toInt() xor mask[i % 4].toInt()).toByte() - return Frame(b0 and 0x80 != 0, b0 and 0x0f, payload) - } - - private fun readByte(input: InputStream): Int = input.read().also { if (it < 0) throw EOFException("WebSocket closed") } - - private fun readFully(input: InputStream, into: ByteArray) { - var read = 0 - while (read < into.size) { - val n = input.read(into, read, into.size - read) - if (n < 0) throw EOFException("WebSocket closed inside a frame") - read += n - } - } -} diff --git a/samples/dart-plugin/src/main/res/raw/codeassist_plugin.toml b/samples/dart-plugin/src/main/res/raw/codeassist_plugin.toml deleted file mode 100644 index 8d516d8576..0000000000 --- a/samples/dart-plugin/src/main/res/raw/codeassist_plugin.toml +++ /dev/null @@ -1,31 +0,0 @@ -[plugin] -id = "dev.codeassist.dart" -name = "Dart" -version = "0.4.0" -apiVersion = 4 -description = "Dart on the device, with a bundled Dart SDK for Android (arm64-v8a, armeabi-v7a or x86_64: one plugin APK per ABI). Dart's analysis server gives errors, completion, quick fixes, navigation, rename and formatting. Run compiles and runs bin/*.dart in the Run console, package:test tests run from the gutter with results in the Tests tab, pub get fetches packages, and there are Dart Console App and Flutter App templates. Flutter apps (Flutter 3.47.9, debug mode) run on this device in a built-in player with hot reload on save, build into an APK through the app's android/app module (debug, or release compiled ahead of time to machine code) with their Flutter plugins (Java and Kotlin, and C through the NDK plugin), and their @Preview widgets show live in the editor's preview pane (Android 11 and later) or in a hot-reloading gallery. Existing pub packages open as Dart projects." -entryPoints = ["dev.codeassist.dart.DartPlugin"] -uiEntryPoints = ["dev.codeassist.dart.DartUiPlugin"] -capabilities = [ - "lang.server", - "model.moduleType", - "build.runTask", - "build.task", - "model.facet", - "ui.editorLanguage", - "ui.editorPreview", - "fs.read", - "fs.write", - "net", -] -# Language servers arrived with SPI 3.3.0, first released in CodeAssist 3.40.0. An older IDE refuses the plugin -# with "requires CodeAssist 3.40.0 or newer" instead of failing on a missing class. -# 3.49.0: EditorLanguage grew parameters (SPI 3.8.0), so the UI facet, compiled against it, calls a constructor -# older IDEs lack. (Language servers needed only 3.40.0.) -minHostVersion = "3.49.0" -# Building a Flutter APK packages a build directory's assets, which SPI 3.8.0 added; on an older IDE that build -# fails and says to update, and everything else works. - -# Flutter plugins that ship C code through dart:ffi build with the NDK plugin. Everything else works without it, -# so it is optional: when it is installed it loads first, and when it is not the Plugins screen offers it. -optionalDependsOn = ["dev.codeassist.ndk"] diff --git a/samples/dart-plugin/src/main/res/values/strings.xml b/samples/dart-plugin/src/main/res/values/strings.xml deleted file mode 100644 index 1f58ee8b6c..0000000000 --- a/samples/dart-plugin/src/main/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - CodeAssist Dart - diff --git a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartLanguageServerTest.kt b/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartLanguageServerTest.kt deleted file mode 100644 index 36a6fa7c1f..0000000000 --- a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartLanguageServerTest.kt +++ /dev/null @@ -1,20 +0,0 @@ -package dev.codeassist.dart - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertNull -import org.junit.jupiter.api.Test - -class DartLanguageServerTest { - - @Test - fun completingAFunctionInsertsItsCall() { - // Off unless the client turns it on: completing `print` then inserted the bare name, no parentheses. - assertEquals("""{"completeFunctionCalls":true}""", DartLanguageServer.settings("dart")) - assertEquals("""{"dart":{"completeFunctionCalls":true}}""", DartLanguageServer.settings(null)) - } - - @Test - fun otherSectionsHaveNoSettings() { - assertNull(DartLanguageServer.settings("editor")) - } -} diff --git a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartPackagesTest.kt b/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartPackagesTest.kt deleted file mode 100644 index 67fc024775..0000000000 --- a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartPackagesTest.kt +++ /dev/null @@ -1,105 +0,0 @@ -package dev.codeassist.dart - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Assertions.assertNull -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.attribute.FileTime - -class DartPackagesTest { - - @TempDir - lateinit var dir: Path - - private fun write(rel: String, text: String = ""): Path = - dir.resolve(rel).also { Files.createDirectories(it.parent); Files.write(it, text.toByteArray()) } - - @Test - fun theNameComesFromThePubspec() { - assertEquals("my_app", DartPackages.nameOf("name: my_app\nversion: 1.0.0\n")) - assertEquals("quoted", DartPackages.nameOf("description: x\nname: 'quoted' # a comment\n")) - // A nested `name:` (a dependency's) is not the package's. - assertNull(DartPackages.nameOf("dependencies:\n foo:\n name: other\n")) - } - - @Test - fun projectNamesBecomeValidPackageNames() { - assertEquals("my_app", DartPackages.packageName("My App")) - assertEquals("hello_world", DartPackages.packageName("HelloWorld")) - assertEquals("app_2048", DartPackages.packageName("2048")) - assertEquals("app", DartPackages.packageName("!!!")) - } - - @Test - fun pubGetIsNeededUntilTheConfigIsNewerThanThePubspec() { - val pubspec = write("pubspec.yaml", "name: p\n") - assertTrue(DartPackages.needsPubGet(dir), "never fetched") - val config = write(DartPackages.PACKAGE_CONFIG, "{}") - Files.setLastModifiedTime(pubspec, FileTime.fromMillis(1_000_000)) - Files.setLastModifiedTime(config, FileTime.fromMillis(2_000_000)) - assertFalse(DartPackages.needsPubGet(dir)) - Files.setLastModifiedTime(pubspec, FileTime.fromMillis(3_000_000)) - assertTrue(DartPackages.needsPubGet(dir), "the pubspec changed since") - Files.setLastModifiedTime(pubspec, FileTime.fromMillis(1_000_000)) - val lock = write("pubspec.lock") - Files.setLastModifiedTime(lock, FileTime.fromMillis(3_000_000)) - assertTrue(DartPackages.needsPubGet(dir), "the lock file changed since") - } - - @Test - fun pubGetIsNeededWhenAPackageTheConfigNamesIsGone() { - val cache = Files.createDirectories(dir.resolve("cache/meta-1.17.0")) - val pubspec = write("p/pubspec.yaml", "name: p\n") - val config = write( - "p/" + DartPackages.PACKAGE_CONFIG, - """{"configVersion":2,"packages":[ - {"name":"meta","rootUri":"${cache.toUri()}","packageUri":"lib/"}, - {"name":"p","rootUri":"../","packageUri":"lib/"}]}""", - ) - Files.setLastModifiedTime(pubspec, FileTime.fromMillis(1_000_000)) - Files.setLastModifiedTime(config, FileTime.fromMillis(2_000_000)) - val pkg = dir.resolve("p") - assertEquals(listOf("meta" to cache, "p" to pkg), DartPackages.packages(pkg)) - assertFalse(DartPackages.needsPubGet(pkg)) - Files.delete(cache) - assertTrue(DartPackages.needsPubGet(pkg), "the pub cache lost a package the config names") - } - - @Test - fun executablesAreTheTopLevelDartFilesInBin() { - assertEquals(emptyList(), DartPackages.executables(dir)) - write("bin/zeta.dart") - write("bin/alpha.dart") - write("bin/notes.txt") - write("bin/src/helper.dart") - assertEquals(listOf("alpha.dart", "zeta.dart"), DartPackages.executables(dir).map { it.fileName.toString() }) - } - - @Test - fun theRootIsTheNearestPubspecWithinTheProject() { - write("pubspec.yaml", "name: outer\n") - write("packages/inner/pubspec.yaml", "name: inner\n") - val file = write("packages/inner/lib/src/a.dart") - assertEquals(dir.resolve("packages/inner"), DartPackages.packageRootOf(file, dir)) - assertEquals(dir, DartPackages.packageRootOf(write("tool/b.dart"), dir)) - // Never above the project, even when a pubspec is there. - assertNull(DartPackages.packageRootOf(file, dir.resolve("packages/inner/lib"))) - } - - @Test - fun contentRootsAreTheConventionalDirectoriesThatExist() { - // `lib/` and `test/` even before they exist; the rest only when they are there. - assertEquals(mapOf("main" to listOf("lib"), "test" to listOf("test")), DartPackages.contentRoots(dir)) - write("bin/app.dart") - write("tool/build.dart") - write("test/app_test.dart") - assertEquals( - mapOf("main" to listOf("lib", "bin", "tool"), "test" to listOf("test")), - DartPackages.contentRoots(dir), - ) - } -} diff --git a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartPreviewsTest.kt b/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartPreviewsTest.kt deleted file mode 100644 index db91b58024..0000000000 --- a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartPreviewsTest.kt +++ /dev/null @@ -1,78 +0,0 @@ -package dev.codeassist.dart - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import java.nio.file.Files -import java.nio.file.Path - -class DartPreviewsTest { - - @TempDir - lateinit var dir: Path - - private val source = """ - import 'package:flutter/material.dart'; - import 'package:flutter/widget_previews.dart'; - - // @Preview(name: 'commented out') - @Preview(name: 'Top level') - Widget topLevel() => const Text('a'); - - @Preview(size: Size(200, 100)) - @override - WidgetBuilder builderPreview() => (context) => const Text('b'); - - @Preview() - Widget _private() => const Text('c'); - - class Card extends StatelessWidget { - @Preview(name: 'Default card') - const Card({super.key}); - - @Preview(name: 'Named') - const Card.compact({super.key, this.label = 'x'}); - - final String label; - - @Preview(group: 'Statics') - static Widget statically() => const Card(); - - @Preview() - Widget instanceMethod() => const Text('no'); - - @override - Widget build(BuildContext context) => const Text("@Preview() in a string"); - } - """.trimIndent() - - @Test - fun previewsAreTheDeclarationsAPreviewCanBe() { - val found = DartPreviews.scan(source) - assertEquals( - listOf("topLevel()", "builderPreview()", "Card()", "Card.compact()", "Card.statically()"), - found.map { it.call }, - ) - assertEquals(listOf(false, true, false, false, false), found.map { it.builder }) - assertEquals("name: 'Top level'", found[0].arguments) - assertEquals("size: Size(200, 100)", found[1].arguments) - assertEquals(6, found[0].line) - } - - @Test - fun theGalleryImportsEachLibraryAndCallsEachPreview() { - Files.createDirectories(dir.resolve("lib/widgets")) - Files.write(dir.resolve("lib/widgets/card.dart"), source.toByteArray()) - Files.write(dir.resolve("lib/part.dart"), "part of 'main.dart';\n@Preview()\nWidget inAPart() => const Text('');\n".toByteArray()) - val found = DartPreviews.find(dir, "app") - assertEquals(5, found.size, "a part file is not a library the gallery can import") - assertEquals("package:app/widgets/card.dart", found.first().library) - val gallery = DartPreviews.gallery(found) - assertTrue("import 'package:app/widgets/card.dart' as p0;" in gallery, gallery) - assertTrue("_Entry('topLevel', 'widgets/card.dart', 6, const Preview(name: 'Top level'), (context) => p0.topLevel())," in gallery, gallery) - assertTrue("(context) => p0.builderPreview()(context))," in gallery, gallery) - assertTrue("(context) => p0.Card.compact())," in gallery, gallery) - assertTrue("void main() => runApp(const _Gallery());" in gallery) - } -} diff --git a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartTestsTest.kt b/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartTestsTest.kt deleted file mode 100644 index 0db5582419..0000000000 --- a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/DartTestsTest.kt +++ /dev/null @@ -1,119 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.build.TestReport -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import java.nio.file.Files -import java.nio.file.Path - -class DartTestsTest { - - @TempDir - lateinit var dir: Path - - @Test - fun theScannerFindsTestsAndGroupsWithTheirFullNames() { - val text = """ - import 'package:test/test.dart'; - - void main() { - test('adds', () => expect(1 + 1, 2)); - // test('commented out', () {}); - group('strings', () { - test("upper", () { expect('test(not a call)', isNotNull); }); - test(r'raw ${'$'}name', () {}); - group('nested', () { - test('deep', () {}); - }); - }); - test('interpolated ${'$'}x', () {}); - group('dynamic ${'$'}y', () { - test('inside', () {}); - }); - x.test('a method, not a test', () {}); - } - """.trimIndent() - val calls = DartTestScanner.scan(text) - assertEquals( - listOf("adds", "strings", "strings upper", "strings raw \$name", "strings nested", "strings nested deep"), - calls.map { it.fullName }, - ) - assertEquals(listOf(false, true, false, false, true, false), calls.map { it.group }) - assertEquals(text.indexOf("test('adds'"), calls.first().offset) - } - - @Test - fun runnerEventsBecomeTestReportRecords() { - val out = StringBuilder() - val events = DartTestEvents { out.append(it) } - listOf( - """{"type":"codeassist.suite","suite":"test.calc_test"}""", - """{"protocolVersion":"0.1.1","type":"start","time":0}""", - """{"test":{"id":2,"name":"adds","metadata":{"skip":false,"skipReason":null}},"type":"testStart","time":6}""", - """{"testID":2,"result":"success","skipped":false,"hidden":false,"type":"testDone","time":21}""", - """{"test":{"id":4,"name":"strings upper","metadata":{"skip":false,"skipReason":null}},"type":"testStart","time":24}""", - """{"testID":4,"messageType":"print","message":"hello from a test","type":"print","time":26}""", - """{"testID":4,"error":"Expected: 'b'","stackTrace":"calc_test.dart 7:5","isFailure":true,"type":"error","time":40}""", - """{"testID":4,"result":"failure","skipped":false,"hidden":false,"type":"testDone","time":44}""", - """{"test":{"id":6,"name":"strings later","metadata":{"skip":true,"skipReason":"not yet"}},"type":"testStart","time":46}""", - """{"testID":6,"result":"success","skipped":true,"hidden":false,"type":"testDone","time":47}""", - // A second engine (a filtered run) numbers its tests from scratch. - """{"protocolVersion":"0.1.1","type":"start","time":0}""", - """{"test":{"id":2,"name":"again","metadata":{"skip":false,"skipReason":null}},"type":"testStart","time":1}""", - """{"testID":2,"result":"success","skipped":false,"hidden":false,"type":"testDone","time":3}""", - "not an event", - ).forEach(events::line) - - val expected = TestReport.started("test.calc_test", "adds") + - TestReport.passed("test.calc_test", "adds", 15) + - TestReport.started("test.calc_test", "strings upper") + - "hello from a test\n" + - TestReport.failed("test.calc_test", "strings upper", 20, "Expected: 'b'\ncalc_test.dart 7:5") + - TestReport.started("test.calc_test", "strings later") + - TestReport.skipped("test.calc_test", "strings later", "not yet") + - TestReport.started("test.calc_test", "again") + - TestReport.passed("test.calc_test", "again", 2) + - "not an event\n" - assertEquals(expected, out.toString()) - assertEquals(3, events.ran) - assertEquals(1, events.failed) - } - - @Test - fun aSuiteThatCannotLoadFailsAsASuite() { - val out = StringBuilder() - val events = DartTestEvents { out.append(it) } - events.line("""{"type":"codeassist.suite","suite":"test.broken_test"}""") - events.line("""{"type":"codeassist.error","error":"Bad state: no","stackTrace":"main"}""") - assertEquals(TestReport.suiteFailed("test.broken_test", "Bad state: no\nmain"), out.toString()) - assertEquals(1, events.failed) - } - - @Test - fun theRunnerImportsEachSuiteAndEscapesItsNames() { - val source = DartTestRunnerSource.generate(linkedMapOf("test.a_test" to "../../../test/a_test.dart", "test.it's" to "../../../test/it's.dart")) - assertTrue("import '../../../test/a_test.dart' as s0;" in source, source) - assertTrue("import '../../../test/it\\'s.dart' as s1;" in source, source) - assertTrue("'test.a_test': () => s0.main()," in source, source) - assertTrue("a.startsWith('\${entry.key}#')" in source, source) - } - - @Test - fun theFileMarkIsOnMainNotTheLineAbove() { - val text = "import 'package:test/test.dart';\n\nvoid main() {\n}\n" - assertEquals(text.indexOf("void main"), DartTestProvider.mainOffset(text)) - assertEquals(0, DartTestProvider.mainOffset("// no main here\n")) - } - - @Test - fun suitesAreDottedPathsInThePackage() { - val file = dir.resolve("test/models/user_test.dart") - Files.createDirectories(file.parent) - Files.write(file, ByteArray(0)) - Files.write(dir.resolve("test/helpers.dart"), ByteArray(0)) - assertEquals(listOf(file), DartTestProvider.testFiles(dir)) - assertEquals("test.models.user_test", DartTestProvider.suiteOf(dir, file)) - } -} diff --git a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterApkTest.kt b/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterApkTest.kt deleted file mode 100644 index 9bf7965788..0000000000 --- a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterApkTest.kt +++ /dev/null @@ -1,177 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.model.Workspace -import dev.ide.model.template.ProjectScaffold -import dev.ide.model.template.TemplateArgs -import dev.ide.vfs.VirtualFile -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Assertions.assertNull -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths -import java.nio.file.attribute.FileTime - -class FlutterApkTest { - - @TempDir - lateinit var dir: Path - - @Test - fun theFlutterTableRoundTrips() { - assertEquals(FlutterFacet("../.."), FlutterFacetCodec.decode(emptyMap())) - assertEquals(FlutterFacet("../../app"), FlutterFacetCodec.decode(FlutterFacetCodec.encode(FlutterFacet("../../app")))) - // A blank source would resolve to the module itself; the default is what was meant. - assertEquals(FlutterFacet(), FlutterFacetCodec.decode(mapOf("source" to " "))) - } - - @Test - fun theEngineDirectoryNamesItsAbi() { - // An installed app's extracted libraries are under the instruction set's name, an APK's under the ABI's. - assertEquals("arm64-v8a", FlutterApkTask.abiOf(Paths.get("/data/app/x/lib/arm64"))) - assertEquals("arm64-v8a", FlutterApkTask.abiOf(Paths.get("lib/arm64-v8a"))) - assertEquals("armeabi-v7a", FlutterApkTask.abiOf(Paths.get("/data/app/x/lib/arm"))) - assertEquals("x86_64", FlutterApkTask.abiOf(Paths.get("/data/app/x/lib/x86_64"))) - assertNull(FlutterApkTask.abiOf(Paths.get("/data/app/x/lib/mips"))) - assertNull(FlutterApkTask.abiOf(null)) - } - - @Test - fun onlyReleaseVariantsAreRelease() { - assertTrue(FlutterBuildPlugin.isRelease("release")) - assertTrue(FlutterBuildPlugin.isRelease("freeRelease")) - assertFalse(FlutterBuildPlugin.isRelease("debug")) - assertFalse(FlutterBuildPlugin.isRelease("freeDebug")) - } - - @Test - fun anUnchangedFileIsNotCopiedAgain() { - val from = dir.resolve("app.dill").also { Files.write(it, byteArrayOf(1, 2, 3)) } - val to = dir.resolve("out/flutter_assets/kernel_blob.bin") - FlutterApkTask.copyIfChanged(from, to) - assertEquals(Files.getLastModifiedTime(from), Files.getLastModifiedTime(to)) - - // Same size and time: left alone, so the APK's inputs do not change for nothing. - Files.write(to, byteArrayOf(9, 9, 9)) - Files.setLastModifiedTime(to, Files.getLastModifiedTime(from)) - FlutterApkTask.copyIfChanged(from, to) - assertEquals(listOf(9, 9, 9), Files.readAllBytes(to).toList()) - - // A new compile (a new time) is copied. - Files.setLastModifiedTime(from, FileTime.fromMillis(Files.getLastModifiedTime(from).toMillis() + 5_000)) - FlutterApkTask.copyIfChanged(from, to) - assertEquals(listOf(1, 2, 3), Files.readAllBytes(to).toList()) - } - - @Test - fun identicalContentKeepsItsTime() { - val to = dir.resolve("FontManifest.json") - FlutterApkTask.writeIfChanged("[]".byteInputStream(), to) - val old = FileTime.fromMillis(1_000_000) - Files.setLastModifiedTime(to, old) - FlutterApkTask.writeIfChanged("[]".byteInputStream(), to) - assertEquals(old, Files.getLastModifiedTime(to)) - FlutterApkTask.writeIfChanged("[{}]".byteInputStream(), to) - assertEquals("[{}]", String(Files.readAllBytes(to))) - } - - @Test - fun theAndroidSideIsWhatAFlutterActivityAppNeeds() { - val files = LinkedHashMap() - FlutterAndroidFiles.write(RecordingScaffold(files), "android/app", "com.example.counter", "Tom & Jerry's ") - - val main = "android/app/src/main" - val manifest = files.getValue("$main/AndroidManifest.xml") - assertTrue("android:label=\"Tom & Jerry's <App>\"" in manifest, manifest) - assertTrue("android:name=\".MainActivity\"" in manifest) - assertTrue("android.intent.category.LAUNCHER" in manifest) - assertTrue("io.flutter.embedding.android.NormalTheme" in manifest) - assertTrue("android.permission.INTERNET" in manifest) - assertTrue(files.getValue("$main/java/com/example/counter/MainActivity.java").let { - it.startsWith("package com.example.counter;") && "extends FlutterActivity" in it - }) - assertTrue("registerWith(@NonNull FlutterEngine" in files.getValue("$main/java/io/flutter/plugins/GeneratedPluginRegistrant.java")) - // Every resource the manifest and themes name exists. - for (path in listOf( - "res/values/styles.xml", "res/values-night/styles.xml", "res/values/colors.xml", - "res/drawable/launch_background.xml", "res/drawable/ic_launcher_foreground.xml", - "res/mipmap-anydpi-v26/ic_launcher.xml", - )) assertTrue("$main/$path" in files, path) - assertTrue(files.values.none { "\${" in it }, "a template placeholder was left unfilled") - } - - @Test - fun theTemplateDeclaresOneEmbeddingPerBuildType() { - val deps = FlutterAppTemplate().dependencies(TemplateArgs(emptyMap())) - assertTrue(deps.all { it.module == FlutterAppTemplate.ANDROID_MODULE }) - assertEquals( - setOf( - "io.flutter:flutter_embedding_debug:1.0.0-${FlutterSdk.ENGINE}", - "io.flutter:flutter_embedding_release:1.0.0-${FlutterSdk.ENGINE}", - ), - deps.map { it.coordinate }.toSet(), - ) - assertEquals( - mapOf("debug" to FlutterSdk.EMBEDDING_DEBUG, "release" to FlutterSdk.EMBEDDING_RELEASE), - FlutterAppTemplate.EMBEDDINGS.toMap(), - ) - } - - @Test - fun theReleaseKernelIsCompiledAheadOfTimeAgainstTheProductPlatform() { - val command = FlutterApkTask.aotKernelCommand( - Paths.get("/lib/libdartaotruntime.so"), Paths.get("/lib/libfrontend_server.so"), - Paths.get("/sdk/flutter_patched_sdk_product"), Paths.get("/app/.dart_tool/package_config.json"), - Paths.get("/app/build/app.dill"), "package:app/main.dart", - ) - assertEquals("/lib/libdartaotruntime.so", command.first()) - assertEquals("package:app/main.dart", command.last()) - // The trailing slash matters: the compiler appends file names to the sdk root as given. - assertEquals("/sdk/flutter_patched_sdk_product/", command[command.indexOf("--sdk-root") + 1]) - for (flag in listOf("--target=flutter", "--aot", "--tfa", "-Ddart.vm.product=true", "--output-dill=/app/build/app.dill")) { - assertTrue(flag in command, flag) - } - assertFalse("--incremental" in command) - assertFalse("--enable-asserts" in command) - } - - @Test - fun genSnapshotWritesAStrippedElfLibrary() { - val arm64 = FlutterApkTask.genSnapshotCommand(Paths.get("/lib/libgen_snapshot.so"), "arm64-v8a", Paths.get("app.dill"), Paths.get("libapp.so")) - assertEquals( - listOf("/lib/libgen_snapshot.so", "--deterministic", "--snapshot_kind=app-aot-elf", "--elf=libapp.so", "--strip", "app.dill"), - arm64, - ) - val arm = FlutterApkTask.genSnapshotCommand(Paths.get("gs"), "armeabi-v7a", Paths.get("app.dill"), Paths.get("libapp.so")) - assertTrue("--no-use-integer-division" in arm) - assertEquals("app.dill", arm.last()) - } - - @Test - fun theCompilersResultLineCarriesItsErrorCount() { - assertEquals(0, FlutterApkTask.compileErrors("9b6763f8-a07f-47ef-8219-a340a2e2c7c1 /data/x/app.dill 0")) - assertEquals(3, FlutterApkTask.compileErrors("9b6763f8 /data/x/app.dill 3")) - assertNull(FlutterApkTask.compileErrors("lib/main.dart:3:5: Error: Expected ';' after this.")) - assertNull(FlutterApkTask.compileErrors("+file:///data/x/lib/main.dart")) - } - - @Test - fun theEngineRevisionMatchesThePluginsOwnBuild() { - // The plugin's player is built against the embedding of this revision; an app has to get the same one. - val build = String(Files.readAllBytes(Paths.get("build.gradle.kts"))) - assertTrue("\"${FlutterSdk.ENGINE}\"" in build, "build.gradle.kts pins another engine than FlutterSdk.ENGINE") - } - - /** Records [writeText] calls; the model surface is not used by [FlutterAndroidFiles]. */ - private class RecordingScaffold(private val files: MutableMap) : ProjectScaffold { - override val workspace: Workspace get() = error("not used") - override val rootDir: VirtualFile get() = error("not used") - override val languageLevel get() = error("not used") - override fun moduleType(id: String) = error("not used") - override fun writeText(relPath: String, content: String) { files[relPath] = content } - override fun writeBytes(relPath: String, bytes: ByteArray) { files[relPath] = String(bytes) } - } -} diff --git a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterImportTest.kt b/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterImportTest.kt deleted file mode 100644 index 0576cb65ea..0000000000 --- a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterImportTest.kt +++ /dev/null @@ -1,124 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.model.sync.ExternalLibrary -import dev.ide.model.sync.SyncReason -import dev.ide.model.sync.SyncRequest -import dev.ide.platform.ProgressReporter -import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertNull -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import java.nio.file.Files -import java.nio.file.Path - -/** A project `flutter create` made (Flutter 3.47.9's Kotlin app template, rendered) opens with its Android app. */ -class FlutterImportTest { - - @TempDir - lateinit var dir: Path - - private fun resource(name: String): String = - javaClass.classLoader.getResourceAsStream("flutter-create/$name")!!.readBytes().toString(Charsets.UTF_8) - - private val noProgress = object : ProgressReporter { - override fun report(fraction: Double, message: String?) {} - override fun checkCanceled() {} - override val isCanceled = false - } - - private fun write(rel: String, text: String) = - dir.resolve(rel).also { Files.createDirectories(it.parent); Files.write(it, text.toByteArray()) } - - @Test - fun theTemplatesBuildFileReads() { - val build = FlutterPlugins.parseAppBuild(resource("app.build.gradle.kts.txt")) - assertEquals("com.example.real_app", build.namespace) - assertEquals("com.example.real_app", build.applicationId) - // `flutter.minSdkVersion` and the like are the Flutter Gradle plugin's: left for the importer to fill. - assertNull(build.minSdk) - assertNull(build.compileSdk) - assertNull(build.targetSdk) - assertNull(build.versionCode) - assertNull(build.versionName) - assertTrue(build.dependencies.isEmpty()) - } - - @Test - fun aFlutterCreateProjectImportsWithItsAndroidApp() { - write("pubspec.yaml", """ - name: real_app - description: "A new Flutter project." - publish_to: 'none' - version: 1.2.0+7 - environment: - sdk: ^3.9.0 - dependencies: - flutter: - sdk: flutter - flutter: - uses-material-design: true - """.trimIndent()) - write("lib/main.dart", "void main() {}") - write("android/app/build.gradle.kts", resource("app.build.gradle.kts.txt")) - write("android/app/src/main/AndroidManifest.xml", resource("AndroidManifest.xml.txt")) - write("android/app/src/main/kotlin/com/example/real_app/MainActivity.kt", "package com.example.real_app\n") - // No package config: pub cannot run here, so the import goes on without plugins and says why. - - val outcome = runBlocking { PubImporter.resolve(SyncRequest(dir, noProgress, SyncReason.IMPORT)) } - val model = outcome.model!! - - assertEquals(listOf("real_app", "app"), model.modules.map { it.name }) - val app = model.modules.single { it.name == "app" } - assertEquals("android/app", app.dirRelPath) - assertEquals("android-app", app.typeId) - val android = app.facets.single { it.table == "android" }.values - assertEquals("com.example.real_app", android["namespace"]) - assertEquals("com.example.real_app", android["applicationId"]) - assertEquals(36, android["compileSdk"]) - assertEquals(24, android["minSdk"]) - assertEquals(36, android["targetSdk"]) - assertEquals(7, android["versionCode"], "the pubspec's build number, as flutter.versionCode") - assertEquals("1.2.0", android["versionName"]) - // The manifest names `${'$'}{applicationName}`, which only the Flutter Gradle plugin fills in. - assertEquals(listOf("applicationName=android.app.Application"), android["manifestPlaceholders"]) - assertTrue(app.facets.any { it.table == "flutter" }) - val embeddings = app.dependencies.filterIsInstance().associate { it.variant to it.coordinate } - assertEquals(FlutterSdk.EMBEDDING_DEBUG, embeddings["debug"]) - assertEquals(FlutterSdk.EMBEDDING_RELEASE, embeddings["release"]) - assertTrue(model.repositories.any { it.url == FlutterSdk.MAVEN_REPOSITORY }) - assertTrue(Files.isRegularFile(dir.resolve("android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java"))) - } - - @Test - fun theBuildFilesSettingsApplyOnlyWhenItChanges() { - write("pubspec.yaml", "name: real_app\nversion: 1.0.0+1\ndependencies:\n flutter:\n sdk: flutter\n") - write("android/app/build.gradle.kts", resource("app.build.gradle.kts.txt")) - write("android/app/src/main/AndroidManifest.xml", resource("AndroidManifest.xml.txt")) - fun androidFacet() = runBlocking { PubImporter.resolve(SyncRequest(dir, noProgress, SyncReason.IMPORT)) } - .model!!.modules.single { it.name == "app" }.facets.firstOrNull { it.table == "android" } - - assertTrue(androidFacet() != null, "the first sync takes the settings from the build file") - // Nothing changed in the build file: a later sync (say, after pub get) leaves Module Settings edits alone. - assertNull(androidFacet()) - write("android/app/build.gradle.kts", resource("app.build.gradle.kts.txt").replace("com.example.real_app\"", "com.example.renamed\"")) - assertEquals("com.example.renamed", androidFacet()!!.values["applicationId"], "an edited build file wins again") - } - - @Test - fun theVersionComesFromThePubspec() { - assertEquals(7, PubImporter.versionCode("1.2.0+7")) - assertEquals(1, PubImporter.versionCode("1.2.0")) - assertEquals(1, PubImporter.versionCode(null)) - assertEquals("1.2.0", PubImporter.versionName("1.2.0+7")) - assertEquals("1.0.0", PubImporter.versionName(null)) - } - - @Test - fun aMissingNativeBuildSaysWhatToInstall() { - val message = FlutterApkTask.noNativeBuild(listOf("jni")) - assertTrue("jni has C code" in message, message) - assertTrue("NDK (C/C++)" in message) - } -} diff --git a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterPluginsTest.kt b/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterPluginsTest.kt deleted file mode 100644 index 3144fe8128..0000000000 --- a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterPluginsTest.kt +++ /dev/null @@ -1,273 +0,0 @@ -package dev.codeassist.dart - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Assertions.assertNotNull -import org.junit.jupiter.api.Assertions.assertNull -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import java.nio.file.Files -import java.nio.file.Path - -class FlutterPluginsTest { - - @TempDir - lateinit var dir: Path - - private fun write(rel: String, text: String): Path = - dir.resolve(rel).also { Files.createDirectories(it.parent); Files.write(it, text.trimIndent().toByteArray()) } - - /** A package at `pkgs/` with [pubspec], listed in the app's package config. */ - private fun pkg(name: String, pubspec: String) = write("pkgs/$name/pubspec.yaml", pubspec) - - private fun packageConfig(vararg names: String) = write( - "app/.dart_tool/package_config.json", - """{"configVersion":2,"packages":[""" + (names.toList() + "app").joinToString(",") { n -> - val uri = if (n == "app") "../" else "../../pkgs/$n/" - """{"name":"$n","rootUri":"$uri","packageUri":"lib/"}""" - } + "]}", - ) - - @Test - fun discoverFindsTheAndroidPluginsTheAppsDependenciesReach() { - write("app/pubspec.yaml", """ - name: app - dependencies: - flutter: - sdk: flutter - shared_preferences: ^2.0.0 - dev_dependencies: - test_helper_plugin: ^1.0.0 - """) - pkg("shared_preferences", """ - name: shared_preferences - flutter: - plugin: - platforms: - android: - default_package: shared_preferences_android - dependencies: - shared_preferences_android: ^2.0.0 - """) - pkg("shared_preferences_android", """ - name: shared_preferences_android - flutter: - plugin: - implements: shared_preferences - platforms: - android: - package: io.flutter.plugins.sharedpreferences - pluginClass: SharedPreferencesPlugin - dartPluginClass: SharedPreferencesAndroid - dependencies: - jni: ^1.0.0 - """) - pkg("jni", """ - name: jni - flutter: - plugin: - platforms: - android: - ffiPlugin: true - package: com.github.dart_lang.jni - pluginClass: JniPlugin - """) - pkg("test_helper_plugin", """ - name: test_helper_plugin - flutter: - plugin: - platforms: - android: - package: x.y - pluginClass: Helper - """) - for (n in listOf("shared_preferences_android", "jni", "test_helper_plugin")) Files.createDirectories(dir.resolve("pkgs/$n/android")) - packageConfig("shared_preferences", "shared_preferences_android", "jni", "test_helper_plugin") - - val plugins = FlutterPlugins.discover(dir.resolve("app")) - - // The app-facing package registers nothing for Android itself; a dev dependency's plugin is left out. - assertEquals(listOf("jni", "shared_preferences_android"), plugins.map { it.name }) - val prefs = plugins.single { it.name == "shared_preferences_android" } - assertEquals("SharedPreferencesAndroid", prefs.dartPluginClass) - assertEquals("shared_preferences", prefs.implements) - assertEquals(listOf("jni"), prefs.dependsOn, "a plugin's Android library depends on the plugins its package does") - assertTrue(plugins.single { it.name == "jni" }.ffi) - assertTrue(plugins.all { it.hasAndroidCode }) - } - - @Test - fun aDartOnlyImplementationHasNoAndroidLibrary() { - pkg("path_provider_android", """ - name: path_provider_android - flutter: - plugin: - implements: path_provider - platforms: - android: - dartPluginClass: PathProviderAndroid - """) - val plugin = FlutterPlugins.describe( - "path_provider_android", dir.resolve("pkgs/path_provider_android"), - MiniYaml.parse(String(Files.readAllBytes(dir.resolve("pkgs/path_provider_android/pubspec.yaml")))) as Map<*, *>, - ) - assertNotNull(plugin) - assertFalse(plugin!!.hasAndroidCode) - assertEquals("PathProviderAndroid", plugin.dartPluginClass) - } - - @Test - fun aKotlinDslBuildFileReads() { - // shared_preferences_android 2.5.5's android/build.gradle.kts, cut down. - val build = FlutterPlugins.parseAndroidBuild( - """ - plugins { - id("com.android.library") - } - android { - namespace = "io.flutter.plugins.sharedpreferences" - compileSdk = flutter.compileSdkVersion - defaultConfig { - minSdk = 24 - } - dependencies { - implementation("androidx.datastore:datastore:1.2.1") - implementation("androidx.datastore:datastore-preferences:1.2.1") - implementation("androidx.preference:preference:1.2.1") - // implementation("commented:out:1.0") - testImplementation("junit:junit:4.13.2") - implementation(libs.some.catalog.entry) - } - } - """.trimIndent(), - ) - assertEquals("io.flutter.plugins.sharedpreferences", build.namespace) - assertEquals(24, build.minSdk) - assertEquals( - listOf( - "implementation" to "androidx.datastore:datastore:1.2.1", - "implementation" to "androidx.datastore:datastore-preferences:1.2.1", - "implementation" to "androidx.preference:preference:1.2.1", - ), - build.dependencies, - ) - assertEquals(listOf("implementation libs.some.catalog.entry"), build.unreadDependencies) - assertNull(build.cmakePath) - } - - @Test - fun aGroovyBuildFileWithExtraSourcesAndCMakeReads() { - // jni 1.2.1's android/build.gradle, cut down. - val build = FlutterPlugins.parseAndroidBuild( - """ - apply plugin: 'com.android.library' - android { - if (project.android.hasProperty("namespace")) { - namespace = 'com.github.dart_lang.jni' - } - sourceSets { - main { - java { - srcDirs '../java/src/main/java' - } - } - } - compileSdk = 35 - externalNativeBuild { - cmake { - path = "../src/CMakeLists.txt" - } - } - defaultConfig { - minSdkVersion 21 - } - } - """.trimIndent(), - ) - assertEquals("com.github.dart_lang.jni", build.namespace) - assertEquals(21, build.minSdk) - assertEquals(listOf("../java/src/main/java"), build.extraJavaDirs) - assertEquals("../src/CMakeLists.txt", build.cmakePath) - assertTrue(build.dependencies.isEmpty()) - } - - @Test - fun theCMakeLibraryOfAnFfiPluginReads() { - // jni 1.2.1's src/CMakeLists.txt, the parts that matter. - val lib = FlutterPlugins.parseCMake( - """ - if (JNI_AVAILABLE) - add_library(jni SHARED - "dartjni.c" - "third_party/global_jni_env.c" - "include/dart_api_dl.c" - ) - set_target_properties(jni PROPERTIES - PUBLIC_HEADER dartjni.h - OUTPUT_NAME "dartjni" - ) - target_compile_definitions(jni PUBLIC DART_SHARED_LIB) - if (ANDROID) - target_link_libraries(jni log) - else() - target_link_libraries(jni ${'$'}{JNI_LIBRARIES}) - endif() - endif() - """.trimIndent(), - ) - assertNotNull(lib) - assertEquals("dartjni", lib!!.outputName) - assertEquals(listOf("dartjni.c", "third_party/global_jni_env.c", "include/dart_api_dl.c"), lib.sources) - assertEquals(listOf("DART_SHARED_LIB"), lib.definitions) - assertEquals(listOf("log"), lib.linkLibraries) - } - - @Test - fun copyingLaysTheLibraryOutAsOneModule() { - write("pkgs/jni/android/src/main/AndroidManifest.xml", "") - write("pkgs/jni/java/src/main/java/com/github/dart_lang/jni/JniPlugin.java", "class JniPlugin {}") - write("pkgs/jni/src/dartjni.c", "int x;") - write("pkgs/jni/src/dartjni.h", "") - write("pkgs/jni/src/include/dart_api_dl.c", "") - write("pkgs/jni/src/include/dart_api_dl.h", "") - write("pkgs/jni/src/test/ignored.c", "") - val plugin = FlutterPlugin("jni", dir.resolve("pkgs/jni"), ffi = true, pluginClass = "JniPlugin") - val build = PluginAndroidBuild(extraJavaDirs = listOf("../java/src/main/java"), cmakePath = "../src/CMakeLists.txt") - val cmake = CMakeLibrary("jni", "dartjni", listOf("dartjni.c", "include/dart_api_dl.c")) - val dest = dir.resolve("app/.dart_tool/codeassist/android-plugins/jni") - - FlutterPlugins.copyAndroidLibrary(plugin, build, cmake, dest) - - assertTrue(Files.isRegularFile(dest.resolve("src/main/AndroidManifest.xml"))) - assertTrue(Files.isRegularFile(dest.resolve("src/main/java/com/github/dart_lang/jni/JniPlugin.java"))) - assertTrue(Files.isRegularFile(dest.resolve("src/main/cpp/dartjni.c"))) - assertTrue(Files.isRegularFile(dest.resolve("src/main/cpp/include/dart_api_dl.c"))) - assertTrue(Files.isRegularFile(dest.resolve("src/main/cpp/include/dart_api_dl.h")), "headers come along") - assertFalse(Files.exists(dest.resolve("src/main/cpp/test/ignored.c")), "only the library's own sources are built") - } - - @Test - fun theRegistrantsNameEachPluginOnce() { - val prefs = FlutterPlugin( - "shared_preferences_android", dir, androidPackage = "io.flutter.plugins.sharedpreferences", - pluginClass = "SharedPreferencesPlugin", dartPluginClass = "SharedPreferencesAndroid", implements = "shared_preferences", - ) - val other = FlutterPlugin("other_prefs", dir, dartPluginClass = "OtherPrefs", implements = "shared_preferences") - val java = FlutterPlugins.javaRegistrant(listOf(prefs, FlutterPlugin("dart_only", dir, dartPluginClass = "X"))) - assertTrue("new io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin()" in java) - assertFalse("dart_only" in java) - assertTrue(java.startsWith("package io.flutter.plugins;")) - - // One implementation per interface: the app's direct dependency wins. - val dart = FlutterPlugins.dartRegistrant(listOf(prefs, other), directDependencies = setOf("other_prefs"))!! - assertTrue("other_prefs.OtherPrefs.registerWith();" in dart) - assertFalse("SharedPreferencesAndroid" in dart) - assertTrue("import 'package:other_prefs/other_prefs.dart' as other_prefs;" in dart) - assertNull(FlutterPlugins.dartRegistrant(listOf(FlutterPlugin("p", dir, pluginClass = "P")), emptySet())) - - val args = FlutterPlugins.dartRegistrantArgs(dir.resolve("r.dart")) - assertEquals("package:flutter/src/dart_plugin_registrant.dart", args[3]) - assertTrue(args.last().startsWith("-Dflutter.dart_plugin_registrant=file:")) - } -} diff --git a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterRunParticipantTest.kt b/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterRunParticipantTest.kt deleted file mode 100644 index ef526282f6..0000000000 --- a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterRunParticipantTest.kt +++ /dev/null @@ -1,36 +0,0 @@ -package dev.codeassist.dart - -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import java.net.URI - -class FlutterRunParticipantTest { - - @Test - fun theLaunchAsksTheDebugEngineForAKnownPortWithNoAuthCode() { - // FlutterActivity copies these intent extras into the engine's shell arguments; a typo here launches an - // app whose VM service sits on a random port behind an auth code, and the run waits for it forever. - val extras = FlutterRunParticipant.extras(40922) - assertEquals(mapOf("vm-service-port" to 40922, "disable-service-auth-codes" to true), extras) - assertTrue(extras.values.all { it is Int || it is Boolean }, "extras the installer cannot put in a Bundle") - } - - @Test - fun theSessionAttachesToTheServicesHttpRoot() { - // VmService.connect appends `ws` to the root it is given; handing it the WebSocket URI made it knock on - // `/ws/ws` and the run stuck at "Connecting to the app". - val uri = URI(FlutterRunParticipant.serviceUri(40922)) - assertEquals("http", uri.scheme) - assertEquals(40922, uri.port) - assertEquals("/", uri.rawPath) - } - - @Test - fun onlyDebugVariantsHaveAServiceToAttachTo() { - assertTrue(FlutterBuildPlugin.isRelease("release")) - assertTrue(FlutterBuildPlugin.isRelease("freeRelease")) - assertFalse(FlutterBuildPlugin.isRelease("debug")) - } -} diff --git a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterTest.kt b/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterTest.kt deleted file mode 100644 index 6020444269..0000000000 --- a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/FlutterTest.kt +++ /dev/null @@ -1,130 +0,0 @@ -package dev.codeassist.dart - -import org.junit.jupiter.api.Assertions.assertArrayEquals -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertFalse -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import java.io.ByteArrayInputStream -import java.nio.file.Files -import java.nio.file.Path - -class FlutterTest { - - @TempDir - lateinit var dir: Path - - private fun write(rel: String, text: String = "x"): Path = - dir.resolve(rel).also { Files.createDirectories(it.parent); Files.write(it, text.toByteArray()) } - - @Test - fun theAssetManifestIsWhatFlutterWrites() { - // `flutter build bundle` of the stock app (cupertino_icons and nothing else): its AssetManifest.bin. - val key = "packages/cupertino_icons/assets/CupertinoIcons.ttf" - val expected = byteArrayOf(0x0d, 0x01, 0x07, key.length.toByte()) + key.toByteArray() + - byteArrayOf(0x0c, 0x01, 0x0d, 0x01, 0x07, 0x05) + "asset".toByteArray() + - byteArrayOf(0x07, key.length.toByte()) + key.toByteArray() - assertArrayEquals(expected, FlutterAssets.assetManifest(listOf(key))) - // Sizes from 254 on take a marker and two little-endian bytes. - val long = "a".repeat(300) - assertArrayEquals(byteArrayOf(0x07, 254.toByte(), 0x2c, 0x01), StandardMessageCodec.encode(long).copyOf(4)) - } - - @Test - fun aMultiLineDescriptionDoesNotHideTheKeysAfterIt() { - // shared_preferences 2.5.6's pubspec, the top of it. - val yaml = """ - name: shared_preferences - description: Flutter plugin for reading and writing simple key-value pairs. - Wraps NSUserDefaults on iOS and SharedPreferences on Android. - version: 2.5.6 - dependencies: - flutter: - sdk: flutter - shared_preferences_android: ^2.3.4 - """.trimIndent() - val spec = MiniYaml.parse(yaml) as Map<*, *> - assertEquals( - "Flutter plugin for reading and writing simple key-value pairs. Wraps NSUserDefaults on iOS and SharedPreferences on Android.", - spec["description"], - ) - assertEquals("2.5.6", spec["version"]) - assertTrue("shared_preferences_android" in (spec["dependencies"] as Map<*, *>)) - } - - @Test - fun aPubspecFlutterSectionReads() { - val yaml = """ - name: app # the app - dependencies: - flutter: - sdk: flutter - flutter: - uses-material-design: true - assets: - - assets/images/ - - path: assets/data.json - fonts: - - family: Roboto - fonts: - - asset: fonts/Roboto-Regular.ttf - - asset: fonts/Roboto-Bold.ttf - weight: 700 - """.trimIndent() - val flutter = (MiniYaml.parse(yaml) as Map<*, *>)["flutter"] as Map<*, *> - assertEquals("true", flutter["uses-material-design"]) - assertEquals(listOf("assets/images/", mapOf("path" to "assets/data.json")), flutter["assets"]) - val family = (flutter["fonts"] as List<*>).single() as Map<*, *> - assertEquals("Roboto", family["family"]) - assertEquals(listOf(mapOf("asset" to "fonts/Roboto-Regular.ttf"), mapOf("asset" to "fonts/Roboto-Bold.ttf", "weight" to "700")), family["fonts"]) - assertTrue(FlutterSdk.isFlutter(yaml)) - assertFalse(FlutterSdk.isFlutter("name: cli\ndev_dependencies:\n flutter_test:\n sdk: flutter\n")) - } - - @Test - fun theBundleHoldsTheAppsAssetsItsPackagesFontsAndTheBase() { - write("pubspec.yaml", "name: app\nflutter:\n uses-material-design: true\n assets:\n - images/\n") - write("images/logo.png") - write("images/sub/ignored.png") - val icons = dir.resolve("cache/cupertino_icons") - write("cache/cupertino_icons/pubspec.yaml", "name: cupertino_icons\nflutter:\n fonts:\n - family: CupertinoIcons\n fonts:\n - asset: assets/CupertinoIcons.ttf\n") - write("cache/cupertino_icons/assets/CupertinoIcons.ttf") - write(".dart_tool/package_config.json", """{"configVersion":2,"packages":[ - {"name":"cupertino_icons","rootUri":"${icons.toUri()}","packageUri":"lib/"}, - {"name":"app","rootUri":"../","packageUri":"lib/"}]}""") - val base = dir.resolve("base") - write("base/fonts/MaterialIcons-Regular.otf") - write("base/shaders/ink_sparkle.frag") - write("base/NOTICES.Z") - - val bundle = FlutterAssets.build(dir, base) - assertEquals( - setOf("images/logo.png", "packages/cupertino_icons/assets/CupertinoIcons.ttf", "fonts/MaterialIcons-Regular.otf", "shaders/ink_sparkle.frag", "NOTICES.Z"), - bundle.files.keys, - ) - assertEquals( - """[{"family":"MaterialIcons","fonts":[{"asset":"fonts/MaterialIcons-Regular.otf"}]},{"family":"packages/cupertino_icons/CupertinoIcons","fonts":[{"asset":"packages/cupertino_icons/assets/CupertinoIcons.ttf"}]}]""", - String(bundle.generated.getValue("FontManifest.json")), - ) - // The app's assets come before its packages', and the Material font is not an asset-manifest entry. - assertArrayEquals( - FlutterAssets.assetManifest(listOf("images/logo.png", "packages/cupertino_icons/assets/CupertinoIcons.ttf")), - bundle.generated.getValue("AssetManifest.bin"), - ) - } - - @Test - fun webSocketFramesRoundTrip() { - val payload = "{\"jsonrpc\":\"2.0\"}".repeat(10).toByteArray() - val frame = WsFrames.encode(VmService.OP_TEXT, payload, byteArrayOf(1, 2, 3, 4)) - val read = WsFrames.read(ByteArrayInputStream(frame)) - assertTrue(read.fin) - assertEquals(VmService.OP_TEXT, read.opcode) - assertArrayEquals(payload, read.payload) - // A server frame: unmasked, with a 16-bit length. - val big = ByteArray(300) { it.toByte() } - val serverFrame = byteArrayOf(0x82.toByte(), 126, 0x01, 0x2c) + big - assertArrayEquals(big, WsFrames.read(ByteArrayInputStream(serverFrame)).payload) - } -} diff --git a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/PackageWatcherTest.kt b/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/PackageWatcherTest.kt deleted file mode 100644 index 3fa585d256..0000000000 --- a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/PackageWatcherTest.kt +++ /dev/null @@ -1,85 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.platform.ContentHash -import dev.ide.platform.impl.MessageBusImpl -import dev.ide.vfs.FileChanged -import dev.ide.vfs.VfsTopics -import dev.ide.vfs.VirtualFile -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.attribute.FileTime - -class PackageWatcherTest { - - @TempDir - lateinit var pkg: Path - - private fun write(rel: String, text: String = "// $rel"): Path = - pkg.resolve(rel).also { Files.createDirectories(it.parent); Files.write(it, text.toByteArray()) } - - /** Move a file's time on, as a save does, without waiting for the clock. */ - private fun touch(p: Path) = Files.setLastModifiedTime(p, FileTime.fromMillis(Files.getLastModifiedTime(p).toMillis() + 5_000)) - - private fun saved(bus: MessageBusImpl, p: Path) = - bus.syncPublisher(VfsTopics.CHANGES).onEvents(listOf(FileChanged(FakeFile(p.toString()), ContentHash(""), ContentHash("")))) - - @Test - fun aSaveIsReportedAtOnceAndOnlyOnce() { - val main = write("lib/main.dart") - val bus = MessageBusImpl() - PackageWatcher(pkg, bus, walkEveryMs = 60_000).use { w -> - assertEquals(emptyList(), w.changes()) - touch(main) - saved(bus, main) - assertTrue(w.wake.tryReceive().isSuccess, "a save wakes the waiter") - assertEquals(listOf(main), w.changes()) - // The same save again changes nothing on disk, so it is not a change. - saved(bus, main) - assertEquals(emptyList(), w.changes()) - } - } - - @Test - fun filesNothingWatchesAreIgnoredByEventsAndTheWalk() { - val generated = write(".dart_tool/codeassist/preview/main.dart") - val built = write("build/app.dart") - val notes = write("lib/notes.txt") - val lib = write("lib/a.dart") - val bus = MessageBusImpl() - PackageWatcher(pkg, bus, walkEveryMs = 0).use { w -> - w.changes() - for (p in listOf(generated, built, notes)) { touch(p); saved(bus, p) } - assertEquals(emptyList(), w.changes()) - touch(lib) - assertEquals(listOf(lib), w.changes(), "the walk finds an edit no event announced") - } - } - - @Test - fun theWalkFindsNewDeletedAndPubspecChanges() { - val a = write("lib/a.dart") - val pubspec = write("pubspec.yaml", "name: app\n") - PackageWatcher(pkg, bus = null, walkEveryMs = 0).use { w -> - Files.delete(a) - val b = write("lib/src/b.dart") - touch(pubspec) - assertEquals(setOf(a, b, pubspec), w.changes().toSet()) - } - } - - private class FakeFile(override val path: String) : VirtualFile { - override val name: String get() = path.substringAfterLast('/') - override val isDirectory = false - override val exists = true - override val length = 0L - override fun parent(): VirtualFile? = null - override fun children(): List = emptyList() - override fun contentHash() = ContentHash("") - override fun readBytes() = ByteArray(0) - override fun readText(): CharSequence = "" - } -} diff --git a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/PubImporterTest.kt b/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/PubImporterTest.kt deleted file mode 100644 index 7c522a8dc7..0000000000 --- a/samples/dart-plugin/src/test/kotlin/dev/codeassist/dart/PubImporterTest.kt +++ /dev/null @@ -1,71 +0,0 @@ -package dev.codeassist.dart - -import dev.ide.model.DependencyScope -import dev.ide.model.sync.ModelOwnership -import dev.ide.model.sync.SyncReason -import dev.ide.model.sync.SyncRequest -import dev.ide.platform.ProgressReporter -import kotlinx.coroutines.runBlocking -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertNull -import org.junit.jupiter.api.Assertions.assertTrue -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.io.TempDir -import java.nio.file.Files -import java.nio.file.Path - -class PubImporterTest { - - @TempDir - lateinit var dir: Path - - private fun write(rel: String, text: String = "") { - val p = dir.resolve(rel) - Files.createDirectories(p.parent) - Files.write(p, text.toByteArray()) - } - - private val noProgress = object : ProgressReporter { - override fun report(fraction: Double, message: String?) {} - override fun checkCanceled() {} - override val isCanceled = false - } - - @Test - fun aFolderWithAPubspecIsAdoptedAsOneDartPackageModule() { - assertNull(PubImporter.detect(dir), "no pubspec, not a Dart project") - write("pubspec.yaml", "name: weather_cli\nenvironment:\n sdk: ^3.0.0\n") - write("bin/weather.dart", "void main() {}\n") - write("test/weather_test.dart") - - val detection = PubImporter.detect(dir)!! - assertEquals("weather_cli", detection.name) - - val outcome = runBlocking { PubImporter.resolve(SyncRequest(dir, noProgress, SyncReason.IMPORT)) } - val model = outcome.model!! - val module = model.modules.single() - assertEquals("weather_cli", module.name) - assertEquals(".", module.dirRelPath, "the package is the project root (a blank path would mean a directory named after the module)") - assertEquals(DartModuleType.ID, module.typeId) - assertEquals( - mapOf("main" to setOf("lib", "bin"), "test" to setOf("test")), - module.sourceSets.associate { it.name to it.roots.keys }, - ) - assertEquals(DependencyScope.TEST_IMPLEMENTATION, module.sourceSets.first { it.name == "test" }.scope) - // Adopted into a model the IDE owns, synced before a build when pub get changed the package config - // (which decides a Flutter app's plugin modules) or an Android app's build file changed. - assertEquals(ModelOwnership.IDE, PubImporter.ownership) - assertTrue(PubImporter.syncBeforeBuild) - assertTrue(DartPackages.PACKAGE_CONFIG in PubImporter.syncFiles()) - // A plain Dart package has no Android side: no app module, no Flutter repository. - assertEquals(1, outcome.model!!.modules.size) - assertTrue(outcome.model!!.repositories.isEmpty()) - } - - @Test - fun aPubspecWithoutANameFallsBackToTheFolder() { - write("pubspec.yaml", "environment:\n sdk: ^3.0.0\n") - val name = PubImporter.detect(dir)!!.name - assertEquals(DartPackages.packageName(dir.fileName.toString()), name) - } -} diff --git a/samples/dart-plugin/src/test/resources/flutter-create/AndroidManifest.xml.txt b/samples/dart-plugin/src/test/resources/flutter-create/AndroidManifest.xml.txt deleted file mode 100644 index 49d23143fd..0000000000 --- a/samples/dart-plugin/src/test/resources/flutter-create/AndroidManifest.xml.txt +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/dart-plugin/src/test/resources/flutter-create/app.build.gradle.kts.txt b/samples/dart-plugin/src/test/resources/flutter-create/app.build.gradle.kts.txt deleted file mode 100644 index b4afc226ae..0000000000 --- a/samples/dart-plugin/src/test/resources/flutter-create/app.build.gradle.kts.txt +++ /dev/null @@ -1,49 +0,0 @@ -plugins { - id("com.android.application") - // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. - id("dev.flutter.flutter-gradle-plugin") -} - -android { - namespace = "com.example.real_app" - compileSdk = flutter.compileSdkVersion - ndkVersion = flutter.ndkVersion - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - defaultConfig { - // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId = "com.example.real_app" - // You can update the following values to match your application needs. - // For more information, see: https://flutter.dev/to/review-gradle-config. - minSdk = flutter.minSdkVersion - targetSdk = flutter.targetSdkVersion - // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION - // is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions) - // You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true` - // flag during build. - versionCode = flutter.versionCode - versionName = flutter.versionName - } - - buildTypes { - release { - // TODO: Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig = signingConfigs.getByName("debug") - } - } -} - -kotlin { - compilerOptions { - jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 - } -} - -flutter { - source = "../.." -} diff --git a/samples/dotnet-plugin/README.md b/samples/dotnet-plugin/README.md deleted file mode 100644 index dc3d832407..0000000000 --- a/samples/dotnet-plugin/README.md +++ /dev/null @@ -1,117 +0,0 @@ -# The C# plugin - -C# on the device, shipped as its own Android app. It carries a .NET 10 runtime and the Roslyn compiler, -compiles and runs console programs, and gives the editor errors, completion, parameter help and quick fixes -that come from the compiler itself. - -Originally written by aio and contributed to this repository. - -## Building it - -The runtime and compiler are **not in this repository**. Assemble them first: - -``` -tools/dotnet-toolchain/build-dotnet-android.sh # a few minutes; downloads the NDK if none is set -./gradlew :samples:dotnet-plugin:assembleDebug # picks up tools/dotnet-toolchain/build/out/arm64-v8a -``` - -`-Pdotnet.abi=x86_64` builds for the other ABI there is a runtime for (run the toolchain script with -`HOST_ABI=x86_64` first). One APK serves one ABI, because the runtime's native libraries are inside the asset -archive. Point the module somewhere else with `-Pdotnet.toolchain.dir=/path/to/out`. Building with no -toolchain present still produces an APK; it installs and reports that it has no .NET for the device. - -## How it is put together - -``` -CSharpPlugin (registers everything) - ├─ sdk/ DotnetSdk (unpacks the tree, starts programs) CsServer (the one process kept running) - │ CsCompilerHost (compile) CsChecker (diagnostics) CsCompleter (completion, signatures) - │ CsNavigator (declarations, documentation, colouring) - ├─ project/ Csproj* (reads .csproj, follows project references) nuget/ (package restore) CsMains* (entry points) templates/ - ├─ build/ CsBuildPlugin CsCompileTask CsRunProgramTask CsRestoreTask CsRunTaskProvider - │ tests/ (CsTestProvider, CsTestScan, CsTestRunner) - ├─ editor/ CsLanguageBackend CsDiagnosticProvider CsDeclarationProvider quick fixes for usings CsRunGutter - ├─ completion/ CsCompletionContributor CsSemanticCompletion CsSymbols CsprojCompletionContributor - └─ ui/ CsUiPlugin (editor languages, file icons, new-file templates) -``` - -**Two halves.** What is executed is the launcher, `libdotnetlaunch.so`, in the package's native library -directory, the one place Android lets an app run a file from. What is only read (the runtime, Roslyn, the -reference assemblies, OpenSSL) is `assets/dotnet-sdk.zip`, unpacked on first use into the plugin's private -directory in the IDE's internal storage. tools/dotnet-toolchain/README.md explains where each comes from. - -**Several projects in a module.** The module's own project runs from the Run button; every other project -under it that builds a program has a Run row of its own. - -**One resident server.** Starting the compiler costs seconds, nearly all of it the runtime warming up, so -one small C# program (`CsServer`) is compiled once and kept running. It compiles a project, reports -diagnostics, and answers completion and parameter-help requests, taking requests on stdin and answering on -stdout. It is one process rather than one per job because each would load the runtime and Roslyn for itself. -It keeps the project's compilation between requests and replaces only the files that changed, so the editor's -check binds the file being edited and not the whole project. Requests wait for one another: completion asked -during a build is answered after it. The server stops after five idle minutes and starts again on the next -request. If it cannot be built or started, a build falls back to a plain `csc` process and completion to -names read from the reference assemblies. - -**Navigation and colouring come from the same compilation.** Go to Declaration, quick documentation and the -colouring of names are three more requests to the server: where the symbol at the caret is declared, its -signature and doc comment, and what each name in the file resolves to. A symbol from the framework or a -package has no source to go to; its documentation still shows, from the XML beside the reference assembly. -Find Usages lists every place the project declares, reads or writes a symbol, and Rename changes them all; a -symbol the project does not declare is refused. The structure view and code folding come from the file's -syntax tree. - -**Completion reaches types that are not imported.** Past the names already in scope, completion offers the -public types of every reference by name, and accepting one also writes its `using`, where the quick fix -would put it. - -**Formatting is Roslyn's.** Reformat uses the formatter the compiler's own tooling uses, to C#'s conventions: -braces on their own lines, four spaces. Of the editor's style only tabs or spaces is taken. Its assemblies -are loaded when something is first reformatted. A file that does not parse is left as it is. - -**Project references.** A `` reaches the referenced project and everything it references -in turn. A build compiles those first, each into its own `bin/`, and copies their DLLs beside the program. -The editor does not wait for a build: the server compiles a referenced project in memory from its sources -and hands it to the referencing one as a reference, so an edit saved in one project shows in the other at the -next check, and Go to Declaration crosses from one into the other. A file belongs to the nearest project -file above it, and a project's sources leave out any folder that has a project file of its own, so a module -may hold several projects. - -**Tests.** A project that references xUnit, NUnit or MSTest gets run marks beside its test methods and -classes, a "C# tests" row in the Run picker, and results in the Run screen's Tests tab, with re-run and -re-run failed. A run compiles the project as a library and hands the DLL to a small runner of the plugin's -own, which finds the methods those frameworks mark as tests and calls them. The assertions are the -framework's, so a failure reads as it would anywhere. It runs facts, theories and test cases with inline data or data from a member or a class, data rows, async -tests, setup and teardown methods, xUnit class fixtures and its output helper, and skip reasons. It reports -as skipped, saying why, a test class whose constructor asks for anything else, such as a collection fixture. - -**No MSBuild, no NuGet client.** Neither is shipped. `Csproj` reads the subset of a project file the plugin -honours and turns it into compiler arguments; it is the single place that interprets a `.csproj`, used by the -build, the editor check and completion alike. `NuGet` talks to nuget.org's package base address directly, -picks the best target framework folder of each package, and follows dependencies with the highest requested -version winning. - -**Diagnostics come from a compilation, not from `csc` output.** `csc` stops after the syntax stage, so while -any file has a syntax error it reports only those. The checker asks Roslyn for the diagnostics of the -compilation, built from the editor's unsaved buffer and the project's other files on disk. - -## What is not supported - -- `Import` and `Directory.Build.props`, solution files, multi-targeting, analyzers and source generators. -- NuGet beyond nuget.org and managed DLLs: no other feeds, no native assets, no package signature checks. -- Conditions in a `.csproj` other than simple comparisons on `Configuration`, evaluated for Debug. -- A debugger, the `dotnet` command line, and workloads such as MAUI or Blazor. -- The test frameworks' own runners: collection fixtures, test ordering and custom test attributes are not - honoured. -- A terminal for Run. A program's input and output are pipes, so `Console.ReadKey` and cursor movement do not - work. A pseudo-terminal was tried: .NET then echoes every typed line itself, on top of the console's echo. -- 32-bit devices: there is no Android runtime published for them. - -## Older IDE versions - -Two things the plugin uses were added to the plugin API in SPI 3.7.0, and it works without them: - -- A run mark's action id comes from `GutterActions.RUN_TASK_PREFIX`. It is a constant, so its text is compiled - into the plugin and an older IDE honours it just the same. -- The entry point chosen in Module Settings comes from the `RunSettings` service. An older IDE has none, and - there `CsRunConfig` reads the value from the project's `.platform/settings.properties`. diff --git a/samples/dotnet-plugin/build.gradle.kts b/samples/dotnet-plugin/build.gradle.kts deleted file mode 100644 index 5ed6d3a02d..0000000000 --- a/samples/dotnet-plugin/build.gradle.kts +++ /dev/null @@ -1,147 +0,0 @@ -// The C# plugin: .NET on the device, shipped as its own Android app. -// -// It carries a .NET runtime, the Roslyn compiler and a launcher that RUN on Android (tools/dotnet-toolchain). -// Those bytes are NOT in this repository: `tools/dotnet-toolchain/build-dotnet-android.sh` assembles them -// from Microsoft's published packages, and this module packages whatever that build left behind. Building -// the plugin without them produces an APK that installs and reports that it has no .NET for the device. -// Imported rather than fully qualified: the Java plugin's `java` project extension shadows the `java.*` -// package inside a build script, so `java.util.Properties` would parse as `(java extension).util`. -import java.util.Properties - -plugins { - alias(libs.plugins.android.application) - // No Compose compiler plugin: this plugin's UI facet registers editor languages and file templates and - // contributes no @Composable of its own. -} - -/** - * The device ABI this APK is for. Unlike a compiler that only differs in its executables, the runtime's - * native libraries live in the asset archive, so one APK serves one ABI: `-Pdotnet.abi=x86_64` builds the - * other one the runtime is published for. - */ -val dotnetAbi: String = providers.gradleProperty("dotnet.abi").orNull ?: "arm64-v8a" - -/** Where `build-dotnet-android.sh` put its output for [dotnetAbi]. Override with `-Pdotnet.toolchain.dir=…`. */ -val toolchainOut: File = - (providers.gradleProperty("dotnet.toolchain.dir").orNull?.let(::File) - ?: rootProject.file("tools/dotnet-toolchain/build/out")).resolve(dotnetAbi) - -val toolchainLibs: File = File(toolchainOut, "jniLibs") -val toolchainAssets: File = File(toolchainOut, "assets") -val hasToolchain: Boolean = File(toolchainAssets, "dotnet-sdk.zip").isFile - -if (!hasToolchain) { - logger.warn( - "No .NET tree at $toolchainAssets -- the plugin will build without a runtime. " + - "Run tools/dotnet-toolchain/build-dotnet-android.sh first." - ) -} - -android { - namespace = "dev.codeassist.csharp" - compileSdk = 36 - - defaultConfig { - applicationId = "dev.codeassist.csharp" - // The IDE's own floor: this code runs inside the IDE's process. - minSdk = 26 - targetSdk = 36 - versionCode = 2 - versionName = "1.1.0" - if (hasToolchain) ndk { abiFilters += dotnetAbi } - } - - // Signed with the same upload key the IDE is, when one is configured, so the published plugin APK is a - // release build rather than a debuggable one. Resolution order and file are the IDE's (a gitignored - // keystore.properties at the repo root); with no keystore the release variant is simply left unsigned, - // which is what a contributor building this sample gets. - signingConfigs { - val keystoreProps = Properties().apply { - val f = rootProject.file("keystore.properties") - if (f.exists()) f.inputStream().use { load(it) } - } - fun signingValue(key: String, prop: String, env: String): String? = - keystoreProps.getProperty(key) ?: (findProperty(prop) as String?) ?: System.getenv(env) - - val storeFileResolved = signingValue("storeFile", "RELEASE_STORE_FILE", "RELEASE_STORE_FILE") - ?.let { rootProject.file(it) } - if (storeFileResolved != null && storeFileResolved.exists()) { - create("release") { - storeFile = storeFileResolved - storePassword = signingValue("storePassword", "RELEASE_STORE_PASSWORD", "RELEASE_STORE_PASSWORD") - keyAlias = signingValue("keyAlias", "RELEASE_KEY_ALIAS", "RELEASE_KEY_ALIAS") - keyPassword = signingValue("keyPassword", "RELEASE_KEY_PASSWORD", "RELEASE_KEY_PASSWORD") - } - } - } - - buildTypes { - // Never minify a plugin: the IDE loads the entry points by the names in the packaged manifest. - getByName("debug") { isMinifyEnabled = false } - getByName("release") { - isMinifyEnabled = false - signingConfig = signingConfigs.findByName("release") - } - } - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - // The launcher and the tree are static files produced outside this build, so they join the source set - // directly. The tree stays one archive: the plugin reads it back through its classloader, which can open - // a named entry but cannot list a directory. - sourceSets["main"].jniLibs.srcDir(toolchainLibs) - sourceSets["main"].assets.srcDir(toolchainAssets) - - androidResources { - // Already compressed; deflating it again costs build time and first-run time for nothing. - noCompress += "zip" - } - - packaging { - // The launcher has to exist as a FILE to be executed. Left compressed in the APK it is mapped - // straight out of the archive, which serves System.loadLibrary and is useless for exec: there would - // be nothing on disk to hand a child process. - jniLibs.useLegacyPackaging = true - } - - testOptions { - // The code under test logs through android.util.Log, which the unit-test android.jar only stubs. - unitTests.isReturnDefaultValues = true - } -} - -// The tests are JUnit 4; the vintage engine runs them on the JUnit Platform the rest of this build uses. -tasks.withType().configureEach { useJUnitPlatform() } - -dependencies { - // Compiled against, never bundled: the IDE's classloader is the parent of the plugin's, so the SPI, the - // Kotlin stdlib and coroutines all resolve to the IDE's copies. - compileOnly(project(":plugin-api")) - compileOnly(project(":plugin-ui-api")) - compileOnly(project(":platform-core")) - compileOnly(project(":project-model-api")) - compileOnly(project(":model-api")) - compileOnly(project(":language-api")) - compileOnly(project(":analysis-api")) - compileOnly(project(":build-api")) - compileOnly(project(":vfs-api")) - compileOnly(libs.kotlinx.coroutines.core) - - testImplementation(platform(libs.junit.bom)) - testImplementation("junit:junit:4.13.2") - testRuntimeOnly("org.junit.vintage:junit-vintage-engine") - testRuntimeOnly(libs.junit.platform.launcher) - testImplementation(project(":plugin-api")) - testImplementation(project(":plugin-ui-api")) - testImplementation(project(":platform-core")) - testImplementation(project(":project-model-api")) - testImplementation(project(":model-api")) - testImplementation(project(":language-api")) - testImplementation(project(":analysis-api")) - testImplementation(project(":build-api")) - testImplementation(project(":vfs-api")) - testImplementation(libs.kotlinx.coroutines.core) -} diff --git a/samples/dotnet-plugin/src/main/AndroidManifest.xml b/samples/dotnet-plugin/src/main/AndroidManifest.xml deleted file mode 100644 index 83f135c4e2..0000000000 --- a/samples/dotnet-plugin/src/main/AndroidManifest.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/CSharpPlugin.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/CSharpPlugin.kt deleted file mode 100644 index 685aaea5c9..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/CSharpPlugin.kt +++ /dev/null @@ -1,139 +0,0 @@ -package dev.codeassist.csharp - -import dev.codeassist.csharp.build.CsBuildPlugin -import dev.codeassist.csharp.build.tasks.CsRunTaskProvider -import dev.codeassist.csharp.build.tests.CsTestRegistration -import dev.codeassist.csharp.completion.CsSemanticCompletion -import dev.codeassist.csharp.completion.CsSymbols -import dev.codeassist.csharp.completion.csCompletionContribution -import dev.codeassist.csharp.completion.csprojCompletionContribution -import dev.codeassist.csharp.editor.CsContextProvider -import dev.codeassist.csharp.editor.CsLanguageBackend -import dev.codeassist.csharp.editor.CsNavigationRegistration -import dev.codeassist.csharp.editor.CsReferenceRegistration -import dev.codeassist.csharp.editor.CsRunGutter -import dev.codeassist.csharp.editor.CsSignatureHelp -import dev.codeassist.csharp.editor.CsUsingCleanup -import dev.codeassist.csharp.editor.CsprojAnalyzer -import dev.codeassist.csharp.editor.diagnostics.CsDiagnosticProvider -import dev.codeassist.csharp.editor.quickfixes.CsUsingFixProvider -import dev.codeassist.csharp.project.CsModuleType -import dev.codeassist.csharp.project.nuget.CsPackageRestorer -import dev.codeassist.csharp.project.nuget.CsPackageWatcher -import dev.codeassist.csharp.project.templates.CsConsoleTemplate -import dev.codeassist.csharp.project.templates.CsLibraryTemplate -import dev.codeassist.csharp.sdk.CsServer -import dev.codeassist.csharp.sdk.DotnetSdk -import dev.codeassist.csharp.ui.CsFileIconProvider -import dev.codeassist.csharp.ui.CsFileIcons -import dev.ide.analysis.ANALYZER_EP -import dev.ide.analysis.DIAGNOSTIC_PROVIDER_EP -import dev.ide.analysis.QUICK_FIX_PROVIDER_EP -import dev.ide.build.BUILD_PLUGIN_EP -import dev.ide.build.RUN_TASK_PROVIDER_EP -import dev.ide.lang.COMPILATION_CONTEXT_PROVIDER_EP -import dev.ide.lang.FILE_TYPE_EP -import dev.ide.lang.FileTypeMapping -import dev.ide.lang.LANGUAGE_BACKEND_EP -import dev.ide.lang.LanguageId -import dev.ide.lang.completion.COMPLETION_CONTRIBUTOR_EP -import dev.ide.model.FileIconExtensionPoint -import dev.ide.model.ModuleTypeExtensionPoint -import dev.ide.model.template.ProjectTemplateExtensionPoint -import dev.ide.platform.notify.USER_MESSAGES -import dev.ide.plugin.Plugin -import dev.ide.plugin.PluginRegistration -import dev.ide.plugin.editor.EDITOR_DECORATION_EP - -class CSharpPlugin : Plugin { - - /** Keeps the message-bus subscription alive; see [CsPackageWatcher]. */ - private var packageWatcher: CsPackageWatcher? = null - - // Registration - - override fun register(reg: PluginRegistration) { - val log = reg.logger("CsPlugin") - val messages = reg.appServices.getServiceOrNull(USER_MESSAGES) - val sdk = DotnetSdk(reg, messages) - - reg.register(FILE_TYPE_EP, FileTypeMapping(CsFileIcons.SUFFIXES, LanguageId(LANGUAGE))) - - // Project files have no language backend. The analyzer and completion contributor below provide - // diagnostics and completion, similar to the host's support for .aidl files. - reg.register( - FILE_TYPE_EP, - FileTypeMapping(listOf(".csproj", ".props", ".targets"), LanguageId("csproj")), - ) - - reg.register(ANALYZER_EP, CsprojAnalyzer()) - reg.register(ModuleTypeExtensionPoint, CsModuleType) - reg.register(ProjectTemplateExtensionPoint, CsConsoleTemplate()) - reg.register(ProjectTemplateExtensionPoint, CsLibraryTemplate()) - reg.register(FileIconExtensionPoint, CsFileIconProvider) - - // Shared symbol table for completion, editor checks, and quick fixes. - val symbols = CsSymbols(sdk) - val roslynLog = reg.logger("CsRoslyn") - val restorer = CsPackageRestorer(sdk, roslynLog, messages) - - reg.register(RUN_TASK_PROVIDER_EP, CsRunTaskProvider(sdk, log, restorer)) - - // Restore packages when a .csproj file is saved, rather than waiting for the next editor check. - val watcher = CsPackageWatcher(reg.messageBus, restorer) - packageWatcher = watcher - reg.onDispose { - watcher.close() - restorer.close() - } - - // The check records unused usings; the remove-all quick fix reads the same results. - val unusedUsings = CsUsingCleanup.Unused() - reg.register( - DIAGNOSTIC_PROVIDER_EP, - CsDiagnosticProvider(sdk, roslynLog, symbols, restorer, unusedUsings), - ) - reg.register(QUICK_FIX_PROVIDER_EP, CsUsingFixProvider(symbols, unusedUsings)) - - reg.register(EDITOR_DECORATION_EP, CsRunGutter()) - - // Completion and signature help use the same Roslyn-backed semantic completion service. - val semantic = CsSemanticCompletion(sdk) - reg.register(LANGUAGE_BACKEND_EP, CsLanguageBackend(CsSignatureHelp(semantic), semantic)) - - // Go to Declaration needs an extension point an older host does not have. - runCatching { CsNavigationRegistration.register(reg, semantic) } - .onFailure { log.info("this IDE has no go-to-declaration for plugins; C# navigation is off") } - runCatching { CsReferenceRegistration.references(reg, semantic) } - .onFailure { log.info("this IDE has no find usages for plugins; it is off for C#") } - runCatching { CsReferenceRegistration.rename(reg, semantic) } - .onFailure { log.info("this IDE has no rename for plugins; it is off for C#") } - - // Provides the workspace needed to request checks for open files. - reg.register(COMPILATION_CONTEXT_PROVIDER_EP, CsContextProvider()) - - reg.register(BUILD_PLUGIN_EP, CsBuildPlugin(sdk)) - - // Test running needs an extension point an older host does not have. - runCatching { CsTestRegistration.register(reg, sdk) } - .onFailure { log.info("this IDE has no test runners for plugins; C# tests are off") } - reg.register(COMPLETION_CONTRIBUTOR_EP, csCompletionContribution(symbols, semantic)) - reg.register(COMPLETION_CONTRIBUTOR_EP, csprojCompletionContribution()) - - log.info("registered; .NET is prepared on first use") - } - - /** - * Shuts down the resident Roslyn process, which the host does not manage. - * It is a singleton of this plugin's classloader, and [ResidentProgram.shutdown] - * can safely be called more than once. - */ - override fun dispose() { - CsServer.shutdown() - } - - companion object { - /** Language ID shared by the file-type mapping and editor profile. */ - const val LANGUAGE = "csharp" - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/PluginInfoActivity.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/PluginInfoActivity.kt deleted file mode 100644 index 7fd1a0aa48..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/PluginInfoActivity.kt +++ /dev/null @@ -1,50 +0,0 @@ -package dev.codeassist.csharp - -import android.app.Activity -import android.graphics.Color -import android.os.Bundle -import android.util.TypedValue -import android.view.ViewGroup -import android.widget.LinearLayout -import android.widget.ScrollView -import android.widget.TextView - -/** - * This app's own screen, and the activity whose intent filter makes the app discoverable as a - * CodeAssist plugin. The code that matters runs inside the IDE, not here. - */ -class PluginInfoActivity : Activity() { - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - val body = LinearLayout(this).apply { - orientation = LinearLayout.VERTICAL - setBackgroundColor(Color.parseColor("#101014")) - setPadding(dp(24), dp(48), dp(24), dp(24)) - } - body.addView(text(getString(R.string.app_name), 28f)) - body.addView( - text( - "A CodeAssist plugin.\n\n" + - "Install this app, then open CodeAssist and look under " + - "Settings > Plugins > Installed. It loads on the IDE's next launch.\n\n" + - "Entry point: CSharpPlugin", - 15f, - ) - ) - setContentView( - ScrollView(this).apply { - addView(body, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) - } - ) - } - - private fun text(value: String, size: Float) = TextView(this).apply { - this.text = value - setTextColor(Color.parseColor("#F2F2F7")) - setTextSize(TypedValue.COMPLEX_UNIT_SP, size) - setPadding(0, dp(6), 0, dp(6)) - } - - private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/CsBuildPlugin.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/CsBuildPlugin.kt deleted file mode 100644 index 4ee2d3a94f..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/CsBuildPlugin.kt +++ /dev/null @@ -1,59 +0,0 @@ -package dev.codeassist.csharp.build - -import dev.codeassist.csharp.build.tasks.CsCompileTask -import dev.codeassist.csharp.project.CsModuleType -import dev.codeassist.csharp.project.CsProject -import dev.codeassist.csharp.project.csproj.Csproj -import dev.codeassist.csharp.sdk.DotnetSdk -import dev.ide.build.BuildConfiguration -import dev.ide.build.BuildGoal -import dev.ide.build.BuildPlugin -import dev.ide.build.Lifecycle -import dev.ide.build.TaskName -import java.nio.file.Paths - -/** - * Compiles every C# module during the ordinary build, leaving the DLL in the project's `bin/` folder - * for Run to use. Libraries without an entry point are built here as well. - * - * Registers one `compileCs` task per module and wires it to `assemble`. The Run picker uses the same task name and output, so a Build followed by a Run can reuse - * the up-to-date output. - */ -internal class CsBuildPlugin(private val sdk: DotnetSdk) : BuildPlugin { - - override val id = "csharp" - - // Applicability - - override fun appliesTo(config: BuildConfiguration): Boolean = - config.request.goal != BuildGoal.CLEAN && - config.project.modules.any { it.type.id == CsModuleType.ID } - - override fun apply(config: BuildConfiguration) { - val variant = config.request.variant.name - - for (module in config.project.modules) { - if (module.type.id != CsModuleType.ID) continue - - val dir = Paths.get(module.dir.path) - if (CsProject.sources(dir).isEmpty()) continue - - val info = Csproj.load(dir) - val assembly = Csproj.assemblyName(info, module.name) - val dll = Csproj.outputDir(dir, info).resolve("$assembly.dll") - - val taskName = TaskName(":${module.name}:compileCs") - - config.tasks.register(taskName) { - CsCompileTask(taskName, dir, dll, sdk, console = null) - } - - config.tasks.named(Lifecycle.assemble(module.name)).configure { - dependsOn(taskName) - } - config.tasks.named(Lifecycle.assemble(module.name, variant)).configure { - dependsOn(taskName) - } - } - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsCompileTask.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsCompileTask.kt deleted file mode 100644 index 1a69d76cf3..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsCompileTask.kt +++ /dev/null @@ -1,482 +0,0 @@ -package dev.codeassist.csharp.build.tasks - -import android.util.Log -import dev.codeassist.csharp.editor.diagnostics.CsDiagnostic -import dev.codeassist.csharp.editor.diagnostics.CsDiagnosticTags -import dev.codeassist.csharp.editor.diagnostics.CsDiagnostics -import dev.codeassist.csharp.project.CsMains -import dev.codeassist.csharp.project.CsProject -import dev.codeassist.csharp.project.csproj.Csproj -import dev.codeassist.csharp.project.csproj.CsprojGraph -import dev.codeassist.csharp.project.csproj.CsprojExtras -import dev.codeassist.csharp.project.csproj.CsprojInfo -import dev.codeassist.csharp.sdk.CsChecker -import dev.codeassist.csharp.sdk.CsCompilerHost -import dev.codeassist.csharp.sdk.DotnetSdk -import dev.codeassist.csharp.sdk.RUNTIME_CONFIG -import dev.codeassist.csharp.util.TAG -import dev.codeassist.csharp.util.ToolCancellation -import dev.codeassist.csharp.util.killableTool -import dev.ide.build.BuildDiagnostic -import dev.ide.build.BuildSeverity -import dev.ide.build.DiagnosticKind -import dev.ide.build.DiagnosticLocation -import dev.ide.build.DiagnosticSink -import dev.ide.build.RunConsole -import dev.ide.build.Task -import dev.ide.build.TaskContext -import dev.ide.build.TaskInputs -import dev.ide.build.TaskInputsImpl -import dev.ide.build.TaskName -import dev.ide.build.TaskOutputs -import dev.ide.build.TaskOutputsImpl -import dev.ide.build.TaskResult -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.StandardCopyOption - -/** - * Compiles the project's sources to [dll] with Roslyn. - * - * Compiler output is sent to the Run [console] and the build log. This ensures that a Run which stops - * at a compile error does not leave the console showing "(no output)". - * - * Roslyn's output is also parsed into editor diagnostics (see `CsDiagnostics`) and reported as structured - * build diagnostics. This supplies the Problems tab with messages that can be opened at their source locations. - * - * `csc` stops after the syntax stage, so a syntax error in one file can prevent it from reporting errors - * in other files. After a failed compile, [CsChecker] is asked for all diagnostics. The Problems tab and - * console receive those additional diagnostics, while the DLL and exit code remain those from `csc`. - * - * Warnings follow the editor's diagnostic rules: they are not sent to the console, and only warnings in - * [PROBLEM_WARNINGS] are reported to the Problems tab. Errors are sent to both. - */ -internal class CsCompileTask( - override val name: TaskName, - private val dir: Path, - private val dll: Path, - private val sdk: DotnetSdk, - private val console: RunConsole?, - private val mainClass: String? = null, - /** - * False for a project being built because another references it: the projects it needs in turn were - * built before it, and it is left alone when its DLL is newer than everything it is made from. - */ - private val root: Boolean = true, - /** Compile as a library whatever the project's output type: a test run loads the DLL and needs no `Main`. */ - private val asLibrary: Boolean = false, -) : Task { - - /** The folder of the project file, which is [dir] unless the module keeps its project in a subfolder. */ - private val projectDir: Path get() = Csproj.find(dir)?.parent ?: dir - - /** The projects this one references, in build order, or null when it has no project file. */ - private fun referencedProjects(project: CsprojInfo?): CsprojGraph.Result? { - val file = Csproj.find(dir) ?: return null - if (project == null || project.projectReferences.isEmpty()) return null - return CsprojGraph.referenced(file, project) - } - - // Task inputs and outputs - - /** - * Declares the inputs that determine whether the project needs recompilation: source files, the project file, - * referenced DLLs, and the runtime tree used for compilation. - */ - override val inputs: TaskInputs - get() = TaskInputsImpl().apply { - val project = Csproj.load(dir) - val referenced = referencedProjects(project)?.nodes.orEmpty() - filePaths("sources", CsprojGraph.sources(projectDir, project)) - filePaths("project", listOfNotNull(Csproj.find(dir))) - filePaths("references", project?.let { resolveReferences(it) }?.first ?: emptyList()) - // A change in a referenced project is a change to this one's build. - filePaths("referencedSources", referenced.flatMap { CsprojGraph.sources(it.dir, it.info) }) - filePaths("referencedProjects", referenced.map { it.file }) - property("tree", DotnetSdk.VERSION) - property("mainClass", mainClass.orEmpty()) - } - - override val outputs: TaskOutputs - get() = TaskOutputsImpl().apply { - filePath("assembly", dll) - } - - override suspend fun execute(ctx: TaskContext): TaskResult { - val status = sdk.prepare() - if (status is DotnetSdk.Status.Unavailable) return TaskResult.Failed(status.reason) - - val launcher = sdk.launcher ?: return TaskResult.Failed(DotnetSdk.NO_DOTNET) - val report: (String) -> Unit = - console?.let { alsoToConsole(ctx.logger(), it) } ?: { line -> ctx.logger()(line) } - - val project = Csproj.load(dir) - project?.let { Csproj.unsupported(it) }?.let { reason -> - report(reason) - ctx.diagnostics.reportProblem(reason, DiagnosticKind.DEPENDENCY) - return TaskResult.Failed(reason) - } - - val all = CsprojGraph.sources(projectDir, project) - - // `-main:` is incompatible with top-level statements, so exclude those files when running a chosen class. - val leftOut = if (mainClass != null) CsMains.topLevelFiles(dir).filter { it in all } else emptyList() - if (leftOut.isNotEmpty()) { - report("Top-level file(s) left out of this run: ${leftOut.joinToString { it.fileName.toString() }}") - } - - val sources = all - leftOut.toSet() - if (sources.isEmpty()) return TaskResult.Failed("no .cs files in ${dir.fileName}") - - if (project != null && project.packageReferences.isNotEmpty()) { - val problems = restorePackages(project, report) - if (problems.isNotEmpty()) { - problems.forEach { ctx.diagnostics.reportProblem(it, DiagnosticKind.DEPENDENCY) } - return TaskResult.Failed(problems.first()) - } - } - - val graph = referencedProjects(project) - if (graph != null && graph.problems.isNotEmpty()) { - graph.problems.forEach { - report(it) - ctx.diagnostics.reportProblem(it, DiagnosticKind.DEPENDENCY) - } - return TaskResult.Failed(graph.problems.first()) - } - val nodes = graph?.nodes.orEmpty() - - if (!root && isCurrent(all, nodes)) { - ctx.logger()("${dir.fileName} is up to date") - return TaskResult.Success - } - - // Referenced projects first, each after the ones it needs. - if (root) { - for (node in nodes) { - report("Building ${node.assemblyName}") - val built = CsCompileTask( - TaskName(":${node.assemblyName}:compileCs"), node.dir, node.output, sdk, console, root = false, - ).execute(ctx) - if (built !is TaskResult.Success) return built - } - } - - val (own, missing) = project?.let { resolveReferences(it) } - ?: (emptyList() to emptyList()) - - // What a referenced project compiles against reaches this one too, as it does in an SDK build. - val inherited = nodes.flatMap { node -> - Csproj.resolveReferences(node.info, node.dir, sdk.nuget, sdk.frameworkDllNames()).first - } - val projectDlls = nodes.map { it.output } - val referenced = (own + projectDlls + inherited).distinctBy { it.fileName.toString().lowercase() } - - if (missing.isNotEmpty()) { - val reason = "reference not found: ${missing.joinToString()}" - report(reason) - ctx.diagnostics.reportProblem(reason, DiagnosticKind.DEPENDENCY) - return TaskResult.Failed(reason) - } - - var startedAt = 0L - var usedResidentHost = false - var arguments = emptyList() - val compilerLines = ArrayList() - - val exitCode = killableTool { cancellation -> - startedAt = System.nanoTime() - - prepareOutput(project) - val usings = writeGlobalUsings(project) - copyReferences(project, referenced, projectDlls + nodes.flatMap { copiedBy(it) }) - val assemblyInfo = writeAssemblyInfo(project) - arguments = compilerArguments(project, sources, referenced, usings, assemblyInfo).let { built -> - if (!asLibrary) built - else built.filterNot { it.startsWith("-main:") }.map { if (it == "-target:exe") "-target:library" else it } - } - - val onLine: (String) -> Unit = { line -> - Log.d(TAG, "csc> $line") - if (!isWarning(line)) report(line) - compilerLines += line - } - - // Try the resident compiler first. A warm host takes about 0.1 s, compared with about 3.5 s - // for a fresh csc process. If the host cannot be used, fall back to the regular csc process. - val viaHost = - if (CsCompilerHost.ENABLED) CsCompilerHost.compile(sdk, arguments, cancellation, onLine) else null - - if (viaHost != null) { - usedResidentHost = true - viaHost - } else { - runPlainCsc(launcher, arguments, cancellation, onLine) - } - } - - val tookMs = (System.nanoTime() - startedAt) / 1_000_000 - val summary = "csc exited with $exitCode in $tookMs ms" + - if (usedResidentHost) " (resident compiler)" else "" - - Log.d(TAG, summary) - ctx.logger()(summary) - - val failed = exitCode != 0 || !Files.isRegularFile(dll) - reportProblems(ctx, compilerLines, failed, arguments, report) - - if (failed) return TaskResult.Failed("${dir.fileName} did not compile") - return TaskResult.Success - } - - // Diagnostic reporting - - /** - * Sends compiler problems to the Problems tab. - * - * After a failed compile, [CsChecker] supplies syntax and semantic diagnostics together. Diagnostics - * that `csc` did not print are also sent to the console. If the checker cannot be used, or compilation - * succeeds, the Problems tab receives the compiler's own lines. - */ - private suspend fun reportProblems( - ctx: TaskContext, - compilerLines: List, - failed: Boolean, - arguments: List, - report: (String) -> Unit, - ) { - var problems = compilerLines - - if (failed) { - val checked = ArrayList() - val checkerExit = killableTool { cancellation -> - CsChecker.check(sdk, arguments, cancellation) { checked += it } - } - - if (checkerExit != null) { - checked.filterNot { it in compilerLines || isWarning(it) }.forEach(report) - problems = checked - } - } - - problems.forEach { ctx.diagnostics.reportCompilerLine(it) } - } - - /** - * Reports compiler output as a structured diagnostic when it is an error or warning, whether located - * (`path(line,col): error CS0029: ...`) or unlocated (`error CS5001: ...`). - * - * Other lines, such as the compiler banner, are treated as plain text. - */ - private fun DiagnosticSink.reportCompilerLine(line: String) { - val located = CsDiagnostics.parse(line) - if (located != null) { - if (located.severity == CsDiagnostic.Severity.WARNING && located.code !in PROBLEM_WARNINGS) return - - report( - BuildDiagnostic( - severity = located.severity.toBuildSeverity(), - message = located.message, - kind = DiagnosticKind.COMPILER, - source = COMPILER_NAME, - location = DiagnosticLocation(located.path, located.line, located.column), - code = located.code, - detail = line, - ), - ) - return - } - - val unlocated = UNLOCATED.matchEntire(line) ?: return - val (severity, code, message) = unlocated.destructured - if (severity == "warning" && code !in PROBLEM_WARNINGS) return - - report( - BuildDiagnostic( - severity = if (severity == "error") BuildSeverity.ERROR else BuildSeverity.WARNING, - message = message, - kind = DiagnosticKind.COMPILER, - source = COMPILER_NAME, - code = code, - detail = line, - ), - ) - } - - /** Returns true when a compiler output line represents a warning, whether located or unlocated. */ - private fun isWarning(line: String): Boolean = - CsDiagnostics.parse(line)?.severity == CsDiagnostic.Severity.WARNING || - UNLOCATED.matchEntire(line)?.groupValues?.get(1) == "warning" - - /** Reports a problem found before compilation, such as a missing reference. */ - private fun DiagnosticSink.reportProblem(message: String, kind: DiagnosticKind) { - report(BuildDiagnostic(BuildSeverity.ERROR, message, kind, COMPILER_NAME)) - } - - private fun CsDiagnostic.Severity.toBuildSeverity(): BuildSeverity = when (this) { - CsDiagnostic.Severity.ERROR -> BuildSeverity.ERROR - CsDiagnostic.Severity.WARNING -> BuildSeverity.WARNING - } - - /** - * Creates the output folder, removes the previous DLL, and writes the runtimeconfig beside it. - * Only executable projects need a runtimeconfig; libraries are emitted as DLLs alone. - */ - private fun prepareOutput(project: CsprojInfo?) { - Files.createDirectories(dll.parent) - Files.deleteIfExists(dll) - if (project?.isLibrary == true) return - - Files.write( - dll.resolveSibling(dll.fileName.toString().removeSuffix(".dll") + ".runtimeconfig.json"), - RUNTIME_CONFIG.toByteArray(Charsets.UTF_8), - ) - } - - /** Writes the project's requested global usings under `obj/`, or returns null when there are none. */ - private fun writeGlobalUsings(project: CsprojInfo?): Path? { - val text = Csproj.globalUsingsText(project) - val usings = dir.resolve("obj").resolve("codeassist").resolve("GlobalUsings.g.cs") - .takeIf { text.isNotEmpty() } - - usings?.let { - Files.createDirectories(it.parent) - Files.write(it, text.toByteArray(Charsets.UTF_8)) - } - - return usings - } - - /** Writes generated assembly attributes, such as `` and ``, under `obj/`. */ - private fun writeAssemblyInfo(project: CsprojInfo?): Path? { - val text = project?.let(CsprojExtras::assemblyInfoText).orEmpty() - if (text.isEmpty()) return null - - val file = dir.resolve("obj").resolve("codeassist").resolve("AssemblyInfo.g.cs") - Files.createDirectories(file.parent) - Files.write(file, text.toByteArray(Charsets.UTF_8)) - return file - } - - // References and packages - - /** Resolves the project's explicit references and already-restored NuGet package references. */ - private fun resolveReferences(project: CsprojInfo) = - Csproj.resolveReferences(project, dir, sdk.nuget, sdk.frameworkDllNames()) - - /** Returns the DLLs from the project's cached NuGet packages. */ - private fun packageDlls(project: CsprojInfo): List = - sdk.nuget.cached(Csproj.packageRequests(project), sdk.frameworkDllNames()).dlls - - /** - * Restores packages that have not yet been unpacked. - * - * Returns any problems encountered, each of which is also sent to the console. - */ - private suspend fun restorePackages(project: CsprojInfo, report: (String) -> Unit): List { - val requests = Csproj.packageRequests(project) - val exclude = sdk.frameworkDllNames() - if (sdk.nuget.isRestored(requests, exclude)) return emptyList() - - report("Restoring NuGet packages: ${project.packageReferences.joinToString { it.id }}") - - val result = killableTool { cancellation -> - sdk.nuget.restore(requests, exclude) { cancellation.isCancelled } - } - - result.problems.forEach(report) - return result.problems - } - - /** - * Copies references not marked `false` beside the program's DLL, where the runtime - * looks for them. When there is no project file, all references are copied. - */ - private fun copyReferences(project: CsprojInfo?, referenced: List, fromProjects: List) { - val toCopy = project?.let { Csproj.copyLocal(it, dir) + packageDlls(it) + fromProjects } ?: referenced - - for (reference in toCopy.distinctBy { it.fileName.toString().lowercase() }) { - val copy = dll.parent.resolve(reference.fileName.toString()) - if (copy == reference) continue - Files.copy(reference, copy, StandardCopyOption.REPLACE_EXISTING) - } - } - - /** What a referenced project needs beside it at run time: its copy-local references and its packages. */ - private fun copiedBy(node: CsprojGraph.Node): List = - Csproj.copyLocal(node.info, node.dir) + - sdk.nuget.cached(Csproj.packageRequests(node.info), sdk.frameworkDllNames()).dlls - - /** - * Whether [dll] is newer than the sources it is built from, its project file, and the DLLs of the - * projects it references. - */ - private fun isCurrent(sources: List, nodes: List): Boolean { - fun stamp(file: Path): Long? = runCatching { Files.getLastModifiedTime(file).toMillis() }.getOrNull() - val built = stamp(dll) ?: return false - val inputs = sources + listOfNotNull(Csproj.find(dir)) + nodes.map { it.output } - return inputs.all { input -> stamp(input)?.let { it <= built } ?: false } - } - - private fun compilerArguments( - project: CsprojInfo?, - sources: List, - referenced: List, - usings: Path?, - assemblyInfo: Path?, - ): List { - if (project != null) { - return Csproj.arguments( - project, sources, sdk.references() + referenced, dll, usings, mainClass = mainClass, - assemblyInfo = assemblyInfo, resources = CsprojExtras.resources(project, dir), - ) - } - - return buildList { - add("-nologo"); add("-noconfig"); add("-target:exe") - mainClass?.let { add("-main:$it") } - add("-out:$dll") - sdk.references().forEach { add("-r:$it") } - sources.forEach { add(it.toString()) } - } - } - - /** Runs a separate `csc` process when the resident compiler cannot be used. Returns its exit code. */ - private fun runPlainCsc( - launcher: Path, - arguments: List, - cancellation: ToolCancellation, - onLine: (String) -> Unit, - ): Int { - val command = listOf(launcher.toString(), sdk.csc.toString()) + arguments - val referenceCount = command.count { it.startsWith("-r:") } - val shortened = command.filterNot { it.startsWith("-r:") }.joinToString(" ") - - Log.d(TAG, "csc: $shortened (+$referenceCount references)") - - val process = ProcessBuilder(command).directory(dir.toFile()).redirectErrorStream(true) - .apply { environment().putAll(sdk.environment()) }.start() - - cancellation.attach(process) - runCatching { process.outputStream.close() } - process.inputStream.bufferedReader().forEachLine(onLine) - - return process.waitFor() - } - - private companion object { - /** Producer label shown in the Problems tab. */ - const val COMPILER_NAME = "csc" - - /** - * Warnings shown in the Problems tab; all other warnings remain in the editor. - * - * Obsolete-use warnings: CS0612 (no message), CS0618 (with a message), CS0672 (overrides an obsolete - * member), and CS0809 (an obsolete member overrides a non-obsolete one). - */ - val PROBLEM_WARNINGS = CsDiagnosticTags.DEPRECATED - - /** Matches an unlocated compiler message, such as `error CS5001: message` for a missing `Main`. */ - val UNLOCATED = Regex("""^(error|warning) (CS\d{4}): (.*)$""") - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRestoreTask.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRestoreTask.kt deleted file mode 100644 index ee9b3945b9..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRestoreTask.kt +++ /dev/null @@ -1,58 +0,0 @@ -package dev.codeassist.csharp.build.tasks - -import dev.codeassist.csharp.project.csproj.Csproj -import dev.codeassist.csharp.project.nuget.CsPackageRestorer -import dev.ide.build.AlwaysRun -import dev.ide.build.RunConsole -import dev.ide.build.Task -import dev.ide.build.TaskContext -import dev.ide.build.TaskInputs -import dev.ide.build.TaskInputsImpl -import dev.ide.build.TaskName -import dev.ide.build.TaskOutputs -import dev.ide.build.TaskOutputsImpl -import dev.ide.build.TaskResult -import java.nio.file.Path - -/** - * Restores the project's NuGet packages when requested from the Run picker. - * - * Retries even if an earlier attempt failed, such as when the network becomes available again - * after the editor's automatic restore attempts. Reports the result in the task console. - * - * Always runs because the restorer determines whether packages need restoring. - */ -internal class CsRestoreTask( - override val name: TaskName, - private val dir: Path, - private val restorer: CsPackageRestorer, - private val console: RunConsole, -) : Task, AlwaysRun { - - override val inputs: TaskInputs - get() = TaskInputsImpl() - - override val outputs: TaskOutputs - get() = TaskOutputsImpl() - - override suspend fun execute(ctx: TaskContext): TaskResult { - val report = alsoToConsole(ctx.logger(), console) - val project = Csproj.load(dir) - ?: return TaskResult.Failed("no .csproj in ${dir.fileName}") - - if (project.packageReferences.isEmpty()) { - report("The project has no PackageReference.") - return TaskResult.Success - } - - report("Restoring NuGet packages: ${project.packageReferences.joinToString { it.id }}") - - val problems = restorer.restore(project, dir, force = true, notify = false) - problems.forEach(report) - - if (problems.isNotEmpty()) return TaskResult.Failed(problems.first()) - - report("Packages are restored.") - return TaskResult.Success - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRunIds.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRunIds.kt deleted file mode 100644 index f0babb05b1..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRunIds.kt +++ /dev/null @@ -1,57 +0,0 @@ -package dev.codeassist.csharp.build.tasks - -import dev.ide.plugin.editor.GutterActions - -/** - * IDs for this plugin's Run rows. - * - * `csRun:` runs the module's entry point: the class configured in Module Settings > Run, - * or the first `Main` if none is configured. - * - * `csRun::` runs the specified class's `Main` using `-main:`. - * - * Keeps the host's `:[:...]` format, which the Run button uses to determine whether - * a remembered task still belongs to the project. The module therefore follows the kind directly. - */ -internal object CsRunIds { - - const val PREFIX = "csRun:" - - /** - * Prefix for an editor gutter action that starts a Run task. The constant's text is compiled into this - * plugin, so it needs nothing from a host older than the SPI that named it. - */ - const val GUTTER_ACTION_PREFIX = GutterActions.RUN_TASK_PREFIX - - /** Prefix for a module's Restore row in the Run picker: `csRestore:`. */ - const val RESTORE_PREFIX = "csRestore:" - - fun restoreId(module: String): String = RESTORE_PREFIX + module - - /** Returns the module named by a Restore row ID, or null if the ID does not match. */ - fun restoreModule(id: String): String? = - if (id.startsWith(RESTORE_PREFIX)) { - id.removePrefix(RESTORE_PREFIX).ifEmpty { null } - } else { - null - } - - class Parsed(val module: String, val mainClass: String?) - - fun taskId(module: String, mainClass: String? = null): String = - PREFIX + module + (mainClass?.let { ":$it" } ?: "") - - /** Parses a Run task ID, or returns null if it does not belong to this plugin. */ - fun parse(id: String): Parsed? { - if (!id.startsWith(PREFIX)) return null - - val rest = id.removePrefix(PREFIX) - val module = rest.substringBefore(':') - if (module.isEmpty()) return null - - return Parsed(module, rest.substringAfter(':', "").ifEmpty { null }) - } - - /** Returns the simple name: `Namespace.Outer.Program` becomes `Program`. */ - fun simpleName(mainClass: String): String = mainClass.substringAfterLast('.') -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRunProgramTask.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRunProgramTask.kt deleted file mode 100644 index 28f93830b0..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRunProgramTask.kt +++ /dev/null @@ -1,139 +0,0 @@ -package dev.codeassist.csharp.build.tasks - -import dev.codeassist.csharp.sdk.DotnetSdk -import dev.codeassist.csharp.util.LineSplitter -import dev.codeassist.csharp.util.Utf8Chunks -import dev.codeassist.csharp.util.killableTool -import dev.ide.build.AlwaysRun -import dev.ide.build.ProgramIo -import dev.ide.build.RunConsole -import dev.ide.build.Task -import dev.ide.build.TaskContext -import dev.ide.build.TaskInputs -import dev.ide.build.TaskInputsImpl -import dev.ide.build.TaskName -import dev.ide.build.TaskOutputs -import dev.ide.build.TaskOutputsImpl -import dev.ide.build.TaskResult -import java.io.IOException -import java.io.InputStream -import java.io.OutputStream -import java.nio.file.Path - -/** - * Runs [dll] in the Run console, sending program output to the console and forwarding console input to the program. - * - * [title] identifies the program in failure messages. - * - * Always runs because a program has no inputs that can establish whether it is up to date. - */ -internal class CsRunProgramTask( - override val name: TaskName, - private val dir: Path, - private val dll: Path, - private val title: String, - private val sdk: DotnetSdk, - private val console: RunConsole, -) : Task, AlwaysRun { - - override val inputs: TaskInputs - get() = TaskInputsImpl() - - override val outputs: TaskOutputs - get() = TaskOutputsImpl() - - // Execution - - override suspend fun execute(ctx: TaskContext): TaskResult { - val launcher = sdk.launcher ?: return TaskResult.Failed(DotnetSdk.NO_DOTNET) - val io: ProgramIo? = console.io - val lineSplitter = LineSplitter(ctx.logger()) - - // Write directly to the console when available. Otherwise, send output to the build log one line at a time. - // The console lays out lines itself, so its text is passed through as it arrives. - val writeOutput: (String) -> Unit = io?.let { it::stdout } ?: lineSplitter::append - - val exitCode = killableTool { cancellation -> - val process = ProcessBuilder(listOf(launcher.toString(), dll.toString())) - .directory(dir.toFile()) - .redirectErrorStream(true) - .apply { environment().putAll(sdk.environment()) } - .start() - - cancellation.attach(process) - io?.started() - - val stdin = io?.stdin - if (stdin == null) { - runCatching { process.outputStream.close() } - } else { - pumpInput(stdin, process.outputStream) - } - - val decoder = Utf8Chunks() - val buffer = ByteArray(OUTPUT_BUFFER_BYTES) - - try { - while (true) { - val bytesRead = process.inputStream.read(buffer) - if (bytesRead < 0) break - - decoder.decode(buffer, bytesRead) - .takeIf { it.isNotEmpty() } - ?.let(writeOutput) - } - } catch (e: IOException) { - // Stop closes the stream. Treat the resulting read failure as expected cancellation. - if (!cancellation.isCancelled) throw e - } - - decoder.finish() - .takeIf { it.isNotEmpty() } - ?.let(writeOutput) - - process.waitFor() - } - - lineSplitter.flush() - - if (io != null) { - io.exited(exitCode) - } else { - ctx.logger()("Process finished with exit code $exitCode") - } - - return if (exitCode == 0) { - TaskResult.Success - } else { - TaskResult.Failed("$title exited with code $exitCode") - } - } - - // Standard input - - /** Forwards console input to the program's stdin on a separate thread because both streams can block. */ - private fun pumpInput(from: InputStream, to: OutputStream) { - Thread({ - try { - val buffer = ByteArray(INPUT_BUFFER_BYTES) - - while (true) { - val bytesRead = from.read(buffer) - if (bytesRead < 0) break - - to.write(buffer, 0, bytesRead) - to.flush() - } - } catch (_: IOException) { - // The program exited and closed its stdin. - } finally { - runCatching { to.close() } - } - }, "cs-run-stdin").apply { isDaemon = true }.start() - } - - private companion object { - const val OUTPUT_BUFFER_BYTES = 8192 - const val INPUT_BUFFER_BYTES = 4096 - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRunTaskProvider.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRunTaskProvider.kt deleted file mode 100644 index 3ac7fa1d7b..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/CsRunTaskProvider.kt +++ /dev/null @@ -1,206 +0,0 @@ -package dev.codeassist.csharp.build.tasks - -import dev.codeassist.csharp.editor.CsModules -import dev.codeassist.csharp.project.CsMains -import dev.codeassist.csharp.project.CsModuleType -import dev.codeassist.csharp.project.CsProject -import dev.codeassist.csharp.project.CsRunConfig -import dev.codeassist.csharp.project.csproj.Csproj -import dev.codeassist.csharp.project.nuget.CsPackageRestorer -import dev.codeassist.csharp.sdk.DotnetSdk -import dev.ide.build.BuildContext -import dev.ide.build.RunAction -import dev.ide.build.RunConsole -import dev.ide.build.RunTaskProvider -import dev.ide.build.RunTaskSpec -import dev.ide.build.TaskName -import dev.ide.model.Module -import dev.ide.model.Project -import dev.ide.platform.log.Logger -import java.nio.file.Path -import java.nio.file.Paths - -/** - * Provides Run picker entries for C# projects with source files. - * - * Executable projects get a Run entry; libraries get a Build entry. A run compiles the project's `.cs` files - * with Roslyn's `csc.dll` into the output folder (see [Csproj.outputDir]), then launches the DLL with the - * .NET runtime. Both steps use [DotnetSdk.launcher], not `dotnet`. - * - * Uses a [RunTaskProvider] with its own two-task graph. - * [CsBuildPlugin] registers the same compile task for ordinary builds. - */ -internal class CsRunTaskProvider( - private val sdk: DotnetSdk, - private val log: Logger, - private val restorer: CsPackageRestorer, -) : RunTaskProvider { - - // Run picker entries - - override fun tasksFor(module: Module): List { - if (module.type.id != CsModuleType.ID) return emptyList() - - CsModules.remember(module) - - val dir = Paths.get(module.dir.path) - if (CsProject.sources(dir).isEmpty()) return emptyList() - - val project = Csproj.load(dir) - - // Offer a manual restore entry when the project has package references. - val restore = RunTaskSpec( - CsRunIds.restoreId(module.name), - "Restore NuGet packages", - "build", - ).takeIf { project?.packageReferences?.isNotEmpty() == true } - - // A library has no entry point, so its Build entry only compiles the DLL. - if (project?.isLibrary == true) { - return listOfNotNull( - RunTaskSpec(CsRunIds.taskId(module.name), "Build ${module.name}", "run"), - restore, - ) - } - - val rows = mutableListOf( - RunTaskSpec(CsRunIds.taskId(module.name), "Run ${module.name}", "run"), - ) - - // The module entry runs its configured entry point. Add individual entries for projects with multiple - // Main methods or top-level statements alongside Main methods. The host only runs entries listed here, - // and editor gutter actions use these entries to run the corresponding class. - if (CsMains.classRows(dir)) { - for (main in CsMains.classes(dir)) { - rows += RunTaskSpec( - CsRunIds.taskId(module.name, main), - "Run ${CsRunIds.simpleName(main)}", - "run", - ) - } - } - - // A module may hold several projects. The one above is the module's own; each other one that builds a - // program gets a row of its own, named by its project file. - for (other in otherPrograms(dir)) { - rows += RunTaskSpec( - CsRunIds.taskId(module.name, PROJECT_MARK + dir.relativize(other).toString().replace('\\', '/')), - "Run ${other.fileName.toString().removeSuffix(".csproj")}", - "run", - ) - } - - restore?.let { rows += it } - return rows - } - - /** The project files under [dir], other than the module's own, that build a program and not a library. */ - private fun otherPrograms(dir: Path): List { - val own = Csproj.find(dir) - return CsProject.files(dir, PROJECT_DEPTH, skipHidden = true) - .filter { it.fileName.toString().endsWith(".csproj") && it != own } - .filter { file -> runCatching { !Csproj.read(file).isLibrary }.getOrDefault(false) } - .sorted() - } - - override fun actionFor( - spec: RunTaskSpec, - project: Project, - module: Module, - ctx: BuildContext, - ): RunAction? { - val dir = Paths.get(module.dir.path) - - // Manual NuGet restore - CsRunIds.restoreModule(spec.id)?.let { restoreOf -> - if (restoreOf != module.name) return null - - val console = RunConsole(module.name) - val task = CsRestoreTask( - TaskName(":${module.name}:restoreCs"), - dir, - restorer, - console, - ) - - return RunAction("> Restore NuGet packages", LinearGraph(listOf(task))) - .also { it.console = console } - } - - // C# execution or library build - val id = CsRunIds.parse(spec.id) ?: return null - if (id.module != module.name) return null - - // A row for another project of the module: built and run from that project's own folder. - id.mainClass?.takeIf { it.startsWith(PROJECT_MARK) }?.let { marked -> - val file = dir.resolve(marked.removePrefix(PROJECT_MARK)).normalize() - if (!file.startsWith(dir) || !java.nio.file.Files.isRegularFile(file)) return null - val projectDir = file.parent - val info = runCatching { Csproj.read(file) }.getOrNull() ?: return null - val name = file.fileName.toString().removeSuffix(".csproj") - val dll = Csproj.outputDir(projectDir, info).resolve(Csproj.assemblyName(info, name) + ".dll") - val console = RunConsole(name) - val tasks = listOf( - CsCompileTask( - TaskName(":${module.name}:compileCs:$name"), projectDir, dll, sdk, console, - CsMains.compilerMain(projectDir, null), - ), - CsRunProgramTask(TaskName(":${module.name}:runCs:$name"), projectDir, dll, name, sdk, console), - ) - return RunAction("> Run $name", LinearGraph(tasks)).also { it.console = console } - } - - val info = Csproj.load(dir) - val assembly = Csproj.assemblyName(info, module.name) - val dll = Csproj.outputDir(dir, info).resolve("$assembly.dll") - - val console = RunConsole(module.name) - - // A class entry runs that class. The module entry uses the configured entry point or the first Main. - val mainClass = id.mainClass - ?: CsMains.compilerMain(dir, CsRunConfig.entryPoint(module, dir)) - - val compile = CsCompileTask( - TaskName(":${module.name}:compileCs"), - dir, - dll, - sdk, - console, - mainClass, - ) - - if (info?.isLibrary == true) { - return RunAction("> Build ${module.name}", LinearGraph(listOf(compile))) - .also { it.console = console } - } - - val tasks = listOf( - compile, - CsRunProgramTask( - TaskName(":${module.name}:runCs"), - dir, - dll, - module.name, - sdk, - console, - ), - ) - - val header = id.mainClass?.let { - "> Run ${CsRunIds.simpleName(it)}" - } ?: "> Run ${module.name}" - - return RunAction(header, LinearGraph(tasks)).also { it.console = console } - } - - companion object { - /** Prefix shared by this plugin's Run entry IDs. */ - const val RUN_PREFIX = CsRunIds.PREFIX - - /** Marks the part of a Run id that names a project file in the module, where a class name would be. */ - const val PROJECT_MARK = "@" - - /** How far below the module's folder another project is looked for. */ - const val PROJECT_DEPTH = 4 - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/RunSupport.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/RunSupport.kt deleted file mode 100644 index b22f5536a6..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tasks/RunSupport.kt +++ /dev/null @@ -1,25 +0,0 @@ -package dev.codeassist.csharp.build.tasks - -import dev.ide.build.RunConsole -import dev.ide.build.Task -import dev.ide.build.TaskGraph - -/** A line logger that also writes to [console]'s output, when the Run opened one. */ -internal fun alsoToConsole(log: (String) -> Unit, console: RunConsole?): (String) -> Unit = { line -> - log(line) - console?.io?.stdout(line + "\n") -} - -/** Tasks run one after another, each depending on the one before. */ -internal class LinearGraph(override val tasks: List) : TaskGraph { - - override fun dependencies(t: Task): List { - val index = tasks.indexOf(t) - return if (index > 0) listOf(tasks[index - 1]) else emptyList() - } - - override fun topologicalLevels(): List> = - tasks.map { - listOf(it) - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tests/CsTestProvider.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tests/CsTestProvider.kt deleted file mode 100644 index 0e472fe4ad..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tests/CsTestProvider.kt +++ /dev/null @@ -1,176 +0,0 @@ -package dev.codeassist.csharp.build.tests - -import dev.codeassist.csharp.CSharpPlugin -import dev.codeassist.csharp.build.tasks.CsCompileTask -import dev.codeassist.csharp.build.tasks.LinearGraph -import dev.codeassist.csharp.editor.CsModules -import dev.codeassist.csharp.project.CsModuleType -import dev.codeassist.csharp.project.csproj.Csproj -import dev.codeassist.csharp.project.csproj.CsprojGraph -import dev.codeassist.csharp.project.csproj.CsprojInfo -import dev.codeassist.csharp.sdk.DotnetSdk -import dev.codeassist.csharp.util.Utf8Chunks -import dev.codeassist.csharp.util.killableTool -import dev.ide.build.AlwaysRun -import dev.ide.build.BuildContext -import dev.ide.build.RunAction -import dev.ide.build.RunConsole -import dev.ide.build.TEST_PROVIDER_EP -import dev.ide.build.Task -import dev.ide.build.TaskContext -import dev.ide.build.TaskInputs -import dev.ide.build.TaskInputsImpl -import dev.ide.build.TaskName -import dev.ide.build.TaskOutputs -import dev.ide.build.TaskOutputsImpl -import dev.ide.build.TaskResult -import dev.ide.build.TestDeclaration -import dev.ide.build.TestProvider -import dev.ide.build.TestReport -import dev.ide.lang.LanguageId -import dev.ide.model.Module -import dev.ide.model.Project -import dev.ide.plugin.PluginRegistration -import java.io.IOException -import java.nio.file.Path -import java.nio.file.Paths - -/** - * Tests for C# projects that reference xUnit, NUnit or MSTest: run marks beside test methods and classes, a - * row in the Run picker, and results in the Run screen's Tests tab. - * - * A run compiles the project as a library, whatever its output type, and hands the DLL to [CsTestRunner]. - */ -internal class CsTestProvider(private val sdk: DotnetSdk) : TestProvider { - - override val id = ID - override val displayName = "C# tests" - override val languages = setOf(LanguageId(CSharpPlugin.LANGUAGE)) - - override fun appliesTo(module: Module): Boolean { - if (module.type.id != CsModuleType.ID) return false - return usesTestFramework(Csproj.load(Paths.get(module.dir.path))) - } - - override fun tests(module: Module, path: String, text: String): List { - if (!path.endsWith(".cs", ignoreCase = true) || !CsTestScan.mayHoldTests(text)) return emptyList() - val file = runCatching { Paths.get(path) }.getOrNull() ?: return emptyList() - val dir = CsprojGraph.owningDir(file) ?: Paths.get(module.dir.path) - if (!usesTestFramework(Csproj.load(dir))) return emptyList() - - CsModules.remember(module) - val found = CsTestScan.scan(text) - return found.suites.map { TestDeclaration(it.name, it.offset, it.fullName, group = true) } + - found.tests.map { TestDeclaration(it.name, it.offset, "${it.suite}#${it.name}") } - } - - override fun run(module: Module, targets: List, project: Project, ctx: BuildContext): RunAction? { - val dir = Paths.get(module.dir.path) - val info = Csproj.load(dir) ?: return null - val dll = Csproj.outputDir(dir, info).resolve(Csproj.assemblyName(info, module.name) + ".dll") - - val console = RunConsole("C# tests · ${module.name}") - val tasks = listOf( - CsCompileTask(TaskName(":${module.name}:compileCsTests"), dir, dll, sdk, console, asLibrary = true), - CsRunTestsTask(TaskName(":${module.name}:testCs"), dir, dll, targets, sdk, console), - ) - return RunAction("> C# tests ${module.name}", LinearGraph(tasks)).also { it.console = console } - } - - companion object { - const val ID = "csTest" - - /** Package ids that make a project a test project, lowercase. A prefix matches the framework's family. */ - private val FRAMEWORKS = listOf("xunit", "nunit", "mstest") - - fun usesTestFramework(info: CsprojInfo?): Boolean = - info?.packageReferences?.any { reference -> - val id = reference.id.lowercase() - FRAMEWORKS.any { id == it || id.startsWith("$it.") } - } == true - } -} - -/** - * Registers [CsTestProvider]. A class of its own so that a host without the extension point (before - * SPI 3.3.0) fails to link here, where the caller guards it, and not in the plugin's entry point. - */ -internal object CsTestRegistration { - fun register(reg: PluginRegistration, sdk: DotnetSdk) { - reg.register(TEST_PROVIDER_EP, CsTestProvider(sdk)) - } -} - -/** - * Runs the tests in [dll] with [CsTestRunner] and passes what it prints to the Run console, where the - * records it writes become the Tests tab. - */ -internal class CsRunTestsTask( - override val name: TaskName, - private val dir: Path, - private val dll: Path, - private val targets: List, - private val sdk: DotnetSdk, - private val console: RunConsole, -) : Task, AlwaysRun { - - override val inputs: TaskInputs - get() = TaskInputsImpl() - - override val outputs: TaskOutputs - get() = TaskOutputsImpl() - - override suspend fun execute(ctx: TaskContext): TaskResult { - val launcher = sdk.launcher ?: return TaskResult.Failed(DotnetSdk.NO_DOTNET) - val io = console.io - val write: (String) -> Unit = { text -> io?.stdout(text) ?: ctx.logger()(text.trimEnd('\n')) } - - val code = killableTool { cancellation -> - val runner = CsTestRunner.ensure(sdk, cancellation) - if (runner == null) { - // The Tests tab needs a record to say anything; the reason goes with it. - write(TestReport.run(CsTestProvider.ID)) - write(TestReport.suiteFailed(dll.fileName.toString(), "The test runner could not be built.")) - write(TestReport.finished()) - return@killableTool RUNNER_MISSING - } - - val command = listOf(launcher.toString(), runner.toString(), dll.toString(), CsTestProvider.ID) + targets - val process = ProcessBuilder(command) - .directory(dir.toFile()) - .redirectErrorStream(true) - .apply { environment().putAll(sdk.environment()) } - .start() - - cancellation.attach(process) - io?.started() - runCatching { process.outputStream.close() } - - val decoder = Utf8Chunks() - val buffer = ByteArray(8192) - try { - while (true) { - val read = process.inputStream.read(buffer) - if (read < 0) break - decoder.decode(buffer, read).takeIf { it.isNotEmpty() }?.let(write) - } - } catch (e: IOException) { - // Stop closes the stream. Treat the resulting read failure as expected cancellation. - if (!cancellation.isCancelled) throw e - } - decoder.finish().takeIf { it.isNotEmpty() }?.let(write) - process.waitFor() - } - - io?.exited(code) - return when (code) { - 0 -> TaskResult.Success - RUNNER_MISSING -> TaskResult.Failed("the C# test runner could not be built") - else -> TaskResult.Failed("C# tests failed") - } - } - - private companion object { - const val RUNNER_MISSING = 120 - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tests/CsTestRunner.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tests/CsTestRunner.kt deleted file mode 100644 index c874bc70c2..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tests/CsTestRunner.kt +++ /dev/null @@ -1,577 +0,0 @@ -package dev.codeassist.csharp.build.tests - -import android.util.Log -import dev.codeassist.csharp.sdk.CsCompilerHost -import dev.codeassist.csharp.sdk.DotnetSdk -import dev.codeassist.csharp.sdk.ensureRuntimeConfig -import dev.codeassist.csharp.util.TAG -import dev.codeassist.csharp.util.ToolCancellation -import java.nio.file.Files -import java.nio.file.Path - -/** - * The program that runs a project's tests: `TestRunner.dll [targets...]`. - * - * It is not xUnit's, NUnit's or MSTest's own runner. Each of those is a host of its own with discovery, - * fixtures and reporters, and none is in the packages a test project references. This one loads the test - * assembly, finds the methods those frameworks mark as tests by the names of their attributes, and calls - * them, which is what the IDE's own JUnit runner does for the same reason. The assertions are the - * framework's: a failed one throws, and the exception is the failure. - * - * What it runs: xUnit `[Fact]` and `[Theory]` with `[InlineData]`; NUnit `[Test]` and `[TestCase]` with - * `[SetUp]`, `[TearDown]`, `[OneTimeSetUp]` and `[OneTimeTearDown]`; MSTest `[TestMethod]` with `[DataRow]`, - * `[TestInitialize]` and `[TestCleanup]`; async tests; a skip or ignore reason; `IDisposable` and - * `IAsyncLifetime` on the test class; xUnit class fixtures and `ITestOutputHelper`; data from a member or a - * class (`[MemberData]`, `[ClassData]`, `[TestCaseSource]`, `[DynamicData]`). What it reports as skipped, - * saying why: a test class whose constructor asks for anything else, such as a collection fixture. - * - * A suite is the test class's full name. A target is a suite, `suite#Method` for every case of a method, or - * `suite#Method(arguments)` for one case, which is what a re-run from the Tests tab sends back. - */ -internal object CsTestRunner { - - /** Builds the runner when its source changed or its DLL is missing, and returns the DLL. */ - @Synchronized - fun ensure(sdk: DotnetSdk, cancellation: ToolCancellation): Path? { - val dir = sdk.home.resolve("tools") - val source = dir.resolve("TestRunner.cs") - val dll = dir.resolve("TestRunner.dll") - - val current = runCatching { String(Files.readAllBytes(source), Charsets.UTF_8) }.getOrNull() - if (current == RUNNER_SOURCE && Files.isRegularFile(dll)) { - ensureRuntimeConfig(dir.resolve("TestRunner.runtimeconfig.json")) - return dll - } - - Files.createDirectories(dir) - Files.write(source, RUNNER_SOURCE.toByteArray(Charsets.UTF_8)) - ensureRuntimeConfig(dir.resolve("TestRunner.runtimeconfig.json")) - Files.deleteIfExists(dll) - - val arguments = buildList { - add("-nologo") - add("-noconfig") - add("-target:exe") - add("-out:$dll") - sdk.references().forEach { add("-r:$it") } - add(source.toString()) - } - - val code = CsCompilerHost.compile(sdk, arguments, cancellation) { Log.d(TAG, "test runner> $it") } - if (code != 0 || !Files.isRegularFile(dll)) { - Log.d(TAG, "tests: the runner did not build (exit $code)") - return null - } - return dll - } -} - -/** The runner. No `$` anywhere in it: this is a Kotlin raw string. */ -internal const val RUNNER_SOURCE = """using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.Loader; -using System.Text; -using System.Threading.Tasks; - -// xUnit's ITestOutputHelper, made at run time so that no xUnit type is needed to compile this: what a test -// writes to it goes to the console, where the run's output is shown. -public class OutputHelper : DispatchProxy -{ - protected override object Invoke(MethodInfo method, object[] arguments) - { - if (method.Name == "WriteLine" || method.Name == "Write") - { - string text = arguments.Length > 0 ? arguments[0] as string ?? "" : ""; - object[] values = arguments.Length > 1 ? arguments[1] as object[] : null; - if (values != null && values.Length > 0) text = string.Format(text, values); - if (method.Name == "WriteLine") Console.Out.WriteLine(text); else Console.Out.Write(text); - return null; - } - return method.ReturnType == typeof(string) ? "" : null; - } -} - -sealed class Case -{ - public Type Type; - public MethodInfo Method; - public object[] Arguments; - public string Suite; - public string Name; - public string Skip; -} - -static class TestRunner -{ - const string Mark = "\u0001ca-test\u0002"; - - static readonly string[] TestAttributes = { "FactAttribute", "TheoryAttribute", "TestAttribute", "TestCaseAttribute", "TestCaseSourceAttribute", "TestMethodAttribute", "DataTestMethodAttribute" }; - static readonly string[] RowAttributes = { "InlineDataAttribute", "TestCaseAttribute", "DataRowAttribute" }; - static readonly string[] DataAttributes = { "MemberDataAttribute", "ClassDataAttribute", "TestCaseSourceAttribute", "DynamicDataAttribute" }; - - static int Main(string[] args) - { - if (args.Length < 2) return 2; - string path = Path.GetFullPath(args[0]); - string directory = Path.GetDirectoryName(path); - AssemblyLoadContext.Default.Resolving += (context, name) => - { - string candidate = Path.Combine(directory, name.Name + ".dll"); - return File.Exists(candidate) ? context.LoadFromAssemblyPath(candidate) : null; - }; - - Record("RUN", "", "", 0, args[1]); - var targets = args.Skip(2).ToList(); - List cases; - try - { - Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(path); - cases = Discover(assembly).Where(c => Selected(c, targets)).ToList(); - } - catch (Exception e) - { - Record("CLASS_FAILED", Path.GetFileNameWithoutExtension(path), "", 0, Describe(e)); - Record("FINISHED", "", "", 0, ""); - return 1; - } - - foreach (Case c in cases) Record("QUEUED", c.Suite, c.Name, 0, ""); - int failed = 0; - foreach (var group in cases.GroupBy(c => c.Type)) - failed += RunClass(group.Key, group.ToList()); - Record("FINISHED", "", "", 0, cases.Count == 0 ? "no tests" : ""); - return failed > 0 ? 1 : 0; - } - - // ---- discovery - - static IEnumerable Discover(Assembly assembly) - { - Type[] types; - try { types = assembly.GetTypes(); } - catch (ReflectionTypeLoadException e) { types = e.Types.Where(t => t != null).ToArray(); } - - foreach (Type type in types.OrderBy(t => t.FullName, StringComparer.Ordinal)) - { - if (!type.IsClass || (type.IsAbstract && !type.IsSealed) || type.IsGenericTypeDefinition) continue; - string suite = (type.FullName ?? type.Name).Replace('+', '.'); - string classSkip = SkipReason(type.GetCustomAttributesData()); - var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; - foreach (MethodInfo method in type.GetMethods(flags).OrderBy(m => m.MetadataToken)) - { - IList attributes; - try { attributes = method.GetCustomAttributesData(); } - catch (Exception) { continue; } - if (!attributes.Any(a => TestAttributes.Contains(a.AttributeType.Name))) continue; - - string skip = classSkip ?? SkipReason(attributes); - var rows = attributes.Where(a => RowAttributes.Contains(a.AttributeType.Name)) - .Select(a => Values(a.ConstructorArguments)).ToList(); - // Data named by the attribute and held in a member or a class is read here, once, like the rows. - foreach (CustomAttributeData source in attributes.Where(a => DataAttributes.Contains(a.AttributeType.Name))) - { - if (skip != null) break; - try { rows.AddRange(Supplied(type, source)); } - catch (Exception e) { skip = "Its data could not be read: " + Unwrap(e).Message; } - } - if (rows.Count == 0) - { - if (method.GetParameters().Length > 0 && skip == null) skip = "It takes arguments and no data is given for them."; - yield return new Case { Type = type, Method = method, Arguments = new object[0], Suite = suite, Name = method.Name, Skip = skip }; - continue; - } - foreach (object[] values in rows) - { - yield return new Case - { - Type = type, Method = method, Arguments = values, Suite = suite, - Name = method.Name + "(" + string.Join(", ", values.Select(Show)) + ")", Skip = skip, - }; - } - } - } - } - - // The values of a data row. A `params object[]` arrives as one array argument, which is spread out. - static object[] Values(IList arguments) - { - var values = new List(); - foreach (CustomAttributeTypedArgument argument in arguments) - { - var many = argument.Value as System.Collections.IEnumerable; - if (many == null || argument.Value is string) { values.Add(Plain(argument.Value)); continue; } - foreach (object item in many) values.Add(Plain(item)); - } - return values.ToArray(); - } - - // An element of an attribute's array argument arrives wrapped with its type; the value is inside. - static object Plain(object value) - { - return value is CustomAttributeTypedArgument ? ((CustomAttributeTypedArgument)value).Value : value; - } - - // The rows a data attribute points at: a static member of the test class, or of the type it names, or an - // instance of a class that is itself the list. - static List Supplied(Type testClass, CustomAttributeData attribute) - { - Type owner = testClass; - string member = null; - foreach (CustomAttributeTypedArgument argument in attribute.ConstructorArguments) - { - if (argument.Value is Type) owner = (Type)argument.Value; - else if (argument.Value is string && member == null) member = (string)argument.Value; - } - foreach (CustomAttributeNamedArgument named in attribute.NamedArguments) - if (named.TypedValue.Value is Type) owner = (Type)named.TypedValue.Value; - - object data; - if (attribute.AttributeType.Name == "ClassDataAttribute") data = Activator.CreateInstance(owner, true); - else - { - if (member == null) throw new InvalidOperationException("the attribute names no member"); - var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy; - PropertyInfo property = owner.GetProperty(member, flags); - FieldInfo field = owner.GetField(member, flags); - MethodInfo method = owner.GetMethod(member, flags, null, Type.EmptyTypes, null); - if (property != null) data = property.GetValue(null); - else if (field != null) data = field.GetValue(null); - else if (method != null) data = method.Invoke(null, null); - else throw new InvalidOperationException(owner.Name + " has no static member named " + member); - } - - var rows = new List(); - var list = data as System.Collections.IEnumerable; - if (list == null) throw new InvalidOperationException("the data is not a list of rows"); - foreach (object row in list) - { - object[] values = row as object[]; - if (values == null && row != null && !(row is string)) - { - // NUnit's TestCaseData, and xUnit's rows in later versions, keep the values in a property. - PropertyInfo arguments = row.GetType().GetProperty("Arguments") ?? row.GetType().GetProperty("OriginalArguments"); - if (arguments != null) values = arguments.GetValue(row) as object[]; - } - if (values == null) - { - var tuple = row as System.Runtime.CompilerServices.ITuple; - if (tuple != null) - { - values = new object[tuple.Length]; - for (int i = 0; i < tuple.Length; i++) values[i] = tuple[i]; - } - } - rows.Add(values ?? new object[] { row }); - } - return rows; - } - - static string Show(object value) - { - if (value == null) return "null"; - string text = value as string; - if (text != null) return "\"" + text + "\""; - if (value is bool) return (bool)value ? "true" : "false"; - return System.Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture); - } - - static string SkipReason(IList attributes) - { - foreach (CustomAttributeData attribute in attributes) - { - string name = attribute.AttributeType.Name; - if (name == "IgnoreAttribute") - { - object reason = attribute.ConstructorArguments.Count > 0 ? attribute.ConstructorArguments[0].Value : null; - return reason as string ?? "Ignored."; - } - if (!TestAttributes.Contains(name)) continue; - foreach (CustomAttributeNamedArgument named in attribute.NamedArguments) - { - if ((named.MemberName == "Skip" || named.MemberName == "Ignore" || named.MemberName == "IgnoreReason") - && named.TypedValue.Value is string) return (string)named.TypedValue.Value; - } - } - return null; - } - - static bool Selected(Case c, List targets) - { - if (targets.Count == 0) return true; - foreach (string target in targets) - { - if (target == c.Suite || target == c.Suite + "#" + c.Name || target == c.Suite + "#" + c.Method.Name) return true; - } - return false; - } - - // ---- running - - static int RunClass(Type type, List cases) - { - string suite = cases[0].Suite; - // NUnit runs every test of a fixture on one object; the others make a new one for each test. - bool shared = Has(type, "TestFixtureAttribute") || Marked(type, "OneTimeSetUpAttribute").Count > 0 - || cases.Any(c => c.Method.GetCustomAttributesData().Any(a => a.AttributeType.Namespace == "NUnit.Framework")); - object fixture = null; - if (shared && cases.Any(c => c.Skip == null)) - { - try - { - fixture = Create(type); - foreach (MethodInfo m in Marked(type, "OneTimeSetUpAttribute")) Call(m, fixture, null); - } - catch (Exception e) - { - Record("CLASS_FAILED", suite, "", 0, Describe(Unwrap(e))); - foreach (Case c in cases) Record("SKIPPED", c.Suite, c.Name, 0, "The fixture could not be set up."); - return 1; - } - } - - // xUnit's class fixtures: one object per IClassFixture the class names, shared by its tests. - var fixtures = new Dictionary(); - string unsupplied = null; - try - { - foreach (Type contract in type.GetInterfaces()) - { - if (!contract.IsGenericType || contract.Name != "IClassFixture`1") continue; - Type held = contract.GetGenericArguments()[0]; - if (!fixtures.ContainsKey(held)) fixtures[held] = Activator.CreateInstance(held, true); - } - } - catch (Exception e) - { - Record("CLASS_FAILED", suite, "", 0, Describe(Unwrap(e))); - foreach (Case c in cases) Record("SKIPPED", c.Suite, c.Name, 0, "A fixture of its class could not be made."); - return 1; - } - - int failed = 0; - foreach (Case c in cases) - { - if (c.Skip != null) { Record("SKIPPED", c.Suite, c.Name, 0, c.Skip); continue; } - Record("STARTED", c.Suite, c.Name, 0, ""); - IDisposable isolated = Isolate(); - var watch = Stopwatch.StartNew(); - string skipped = null; - Exception failure = null; - object instance = fixture; - try - { - if (instance == null && !c.Method.IsStatic) - { - instance = Construct(type, fixtures, out unsupplied); - if (instance == null) skipped = "Its class needs a " + unsupplied + " in its constructor, which this runner does not supply."; - } - if (skipped == null) - { - if (instance != null) Lifetime(instance, "InitializeAsync"); - foreach (MethodInfo m in Marked(type, "SetUpAttribute", "TestInitializeAttribute")) Call(m, instance, null); - Type expected = Expected(c.Method); - try - { - Call(c.Method, c.Method.IsStatic ? null : instance, ConvertRow(c.Method, c.Arguments)); - if (expected != null) failure = new Exception("Expected " + expected.Name + " to be thrown, and nothing was."); - } - catch (Exception e) - { - Exception thrown = Unwrap(e); - if (expected == null || !expected.IsInstanceOfType(thrown)) throw; - } - } - } - catch (Exception e) - { - Exception thrown = Unwrap(e); - string kind = thrown.GetType().Name; - if (kind == "IgnoreException" || kind == "InconclusiveException" || kind == "SkipException" || kind == "AssertInconclusiveException") - skipped = thrown.Message; - else if (kind != "SuccessException") failure = thrown; - } - finally - { - try - { - if (instance != null) - { - foreach (MethodInfo m in Marked(type, "TearDownAttribute", "TestCleanupAttribute")) Call(m, instance, null); - if (!shared) - { - Lifetime(instance, "DisposeAsync"); - IDisposable disposable = instance as IDisposable; - if (disposable != null) disposable.Dispose(); - } - } - } - catch (Exception e) { if (failure == null) failure = Unwrap(e); } - if (isolated != null) isolated.Dispose(); - } - watch.Stop(); - if (skipped != null) Record("SKIPPED", c.Suite, c.Name, 0, skipped); - else if (failure != null) { failed++; Record("FAILED", c.Suite, c.Name, watch.ElapsedMilliseconds, Describe(failure)); } - else Record("PASSED", c.Suite, c.Name, watch.ElapsedMilliseconds, ""); - } - - foreach (object held in fixtures.Values) - { - try - { - IDisposable disposable = held as IDisposable; - if (disposable != null) disposable.Dispose(); - } - catch (Exception e) { failed++; Record("CLASS_FAILED", suite, "", 0, Describe(Unwrap(e))); } - } - - if (fixture != null) - { - try - { - foreach (MethodInfo m in Marked(type, "OneTimeTearDownAttribute")) Call(m, fixture, null); - IDisposable disposable = fixture as IDisposable; - if (disposable != null) disposable.Dispose(); - } - catch (Exception e) { failed++; Record("CLASS_FAILED", suite, "", 0, Describe(Unwrap(e))); } - } - return failed; - } - - // NUnit keeps the failures of the test in progress in a context of its own, and outside its runner that - // context is never reset: a later test would be handed an earlier one's failure. Its own isolated context, - // one per test, keeps them apart. Null when the tests are not NUnit's. - static IDisposable Isolate() - { - try - { - foreach (Assembly loaded in AppDomain.CurrentDomain.GetAssemblies()) - { - if (loaded.GetName().Name != "nunit.framework") continue; - Type context = loaded.GetType("NUnit.Framework.Internal.TestExecutionContext+IsolatedContext"); - return context == null ? null : Activator.CreateInstance(context) as IDisposable; - } - } - catch (Exception) { } - return null; - } - - // A test object, with what its constructor asks for: nothing, the class's fixtures, or xUnit's output - // helper. Null when it asks for anything else, and `unsupplied` then names the type. - static object Construct(Type type, Dictionary fixtures, out string unsupplied) - { - unsupplied = null; - var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; - ConstructorInfo chosen = type.GetConstructors(flags).OrderByDescending(c => c.GetParameters().Length).FirstOrDefault(); - if (chosen == null || chosen.GetParameters().Length == 0) return Activator.CreateInstance(type, true); - - ParameterInfo[] parameters = chosen.GetParameters(); - var arguments = new object[parameters.Length]; - for (int i = 0; i < parameters.Length; i++) - { - Type wanted = parameters[i].ParameterType; - object held; - if (fixtures.TryGetValue(wanted, out held)) arguments[i] = held; - else if (wanted.IsInterface && wanted.Name == "ITestOutputHelper") arguments[i] = DispatchProxy.Create(wanted, typeof(OutputHelper)); - else { unsupplied = wanted.Name; return null; } - } - return chosen.Invoke(arguments); - } - - static object Create(Type type) - { - return Activator.CreateInstance(type, true); - } - - static bool Has(MemberInfo member, string attribute) - { - return member.GetCustomAttributesData().Any(a => a.AttributeType.Name == attribute); - } - - static List Marked(Type type, params string[] attributes) - { - var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; - return type.GetMethods(flags) - .Where(m => m.GetParameters().Length == 0 && m.GetCustomAttributesData().Any(a => attributes.Contains(a.AttributeType.Name))) - .ToList(); - } - - // MSTest's [ExpectedException(typeof(X))]: the test passes when X is thrown. - static Type Expected(MethodInfo method) - { - foreach (CustomAttributeData attribute in method.GetCustomAttributesData()) - { - if (attribute.AttributeType.Name != "ExpectedExceptionAttribute" || attribute.ConstructorArguments.Count == 0) continue; - return attribute.ConstructorArguments[0].Value as Type; - } - return null; - } - - // Calls a method and, when it returns a task, waits for it. - static void Call(MethodInfo method, object instance, object[] arguments) - { - object result = method.Invoke(method.IsStatic ? null : instance, arguments); - if (result == null) return; - Task task = result as Task; - if (task == null && result.GetType().Name.StartsWith("ValueTask", StringComparison.Ordinal)) - { - MethodInfo asTask = result.GetType().GetMethod("AsTask", Type.EmptyTypes); - if (asTask != null) task = asTask.Invoke(result, null) as Task; - } - if (task != null) task.GetAwaiter().GetResult(); - } - - // xUnit's IAsyncLifetime, found by the method's name so that no xUnit type is needed here. - static void Lifetime(object instance, string method) - { - foreach (Type contract in instance.GetType().GetInterfaces()) - { - if (contract.Name != "IAsyncLifetime" && !(method == "DisposeAsync" && contract.Name == "IAsyncDisposable")) continue; - MethodInfo found = contract.GetMethod(method, Type.EmptyTypes); - if (found != null) { Call(found, instance, null); return; } - } - } - - // A row's values as the method's parameter types: an int literal for a long parameter, a name for an enum. - static object[] ConvertRow(MethodInfo method, object[] values) - { - ParameterInfo[] parameters = method.GetParameters(); - if (parameters.Length != values.Length) - throw new ArgumentException("The test takes " + parameters.Length + " argument(s) and the data row has " + values.Length + "."); - var converted = new object[values.Length]; - for (int i = 0; i < values.Length; i++) - { - object value = values[i]; - Type wanted = Nullable.GetUnderlyingType(parameters[i].ParameterType) ?? parameters[i].ParameterType; - if (value == null || wanted.IsInstanceOfType(value)) converted[i] = value; - else if (wanted.IsEnum) converted[i] = Enum.ToObject(wanted, value); - else converted[i] = System.Convert.ChangeType(value, wanted, System.Globalization.CultureInfo.InvariantCulture); - } - return converted; - } - - static Exception Unwrap(Exception e) - { - while ((e is TargetInvocationException || e is AggregateException) && e.InnerException != null) e = e.InnerException; - return e; - } - - static string Describe(Exception e) - { - string trace = e.StackTrace ?? ""; - // The runner's own frames say nothing about the test. - var kept = trace.Split('\n').Where(line => !line.Contains("TestRunner.") && !line.Contains("System.Reflection.") && !line.Contains("System.RuntimeMethodHandle") && !line.Contains("InvokeStub_")).ToArray(); - string text = e.GetType().Name + ": " + e.Message; - return kept.Length == 0 ? text : text + "\n" + string.Join("\n", kept).TrimEnd(); - } - - static void Record(string what, string suite, string test, long millis, string message) - { - Console.Out.Write(Mark + what + " " + suite.Length + ":" + suite + " " + test.Length + ":" + test + " " + millis + " " + message.Length + ":" + message + "\n"); - Console.Out.Flush(); - } -} -""" diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tests/CsTestScan.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tests/CsTestScan.kt deleted file mode 100644 index d97dc66d96..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/build/tests/CsTestScan.kt +++ /dev/null @@ -1,193 +0,0 @@ -package dev.codeassist.csharp.build.tests - -/** - * Finds the tests a C# file declares, for the gutter: the methods marked `[Fact]`, `[Theory]`, `[Test]`, - * `[TestCase]`, `[TestMethod]` or `[DataTestMethod]`, and the classes that hold them. - * - * Not a parser. Comments and strings are blanked first, so an attribute inside either is not taken for one; - * then namespaces and types are found by keyword and their bodies by matching braces. That is enough to - * name a test the way the runner does, `Namespace.Class` and the method, which is what makes a mark run the - * test it sits beside. - */ -internal object CsTestScan { - - /** A test method: its name, where the name is, and the full name of the class holding it. */ - data class Test(val name: String, val offset: Int, val suite: String) - - /** A class with tests: its simple name, where the name is, and its full name. */ - data class Suite(val name: String, val offset: Int, val fullName: String) - - class Result(val suites: List, val tests: List) - - private val TEST_WORDS = listOf("Fact", "Theory", "TestCase", "TestMethod", "DataTestMethod", "Test") - - private val ATTRIBUTE = Regex( - """\[\s*(?:[\w.]+\s*(?:\([^\[\]]*\))?\s*,\s*)*(?:[\w.]+\.)?(?:Fact|Theory|TestCaseSource|TestCase|TestMethod|DataTestMethod|Test)(?:Attribute)?\s*(?:\([^\[\]]*\))?\s*(?:,[^\[\]]*)?]""", - ) - private val NAMESPACE = Regex("""\bnamespace\s+([\w.]+)\s*([;{])""") - private val TYPE = Regex("""\b(?:class|struct|record(?:\s+(?:class|struct))?)\s+(\w+)""") - - private class Block(val name: String, val nameOffset: Int, val open: Int, val close: Int, val isType: Boolean) - - /** Whether [text] can hold a test at all, checked before the scan proper. */ - fun mayHoldTests(text: String): Boolean = TEST_WORDS.any { "[$it" in text || " $it]" in text || ".$it" in text || "$it(" in text } - - fun scan(text: String): Result { - val code = blank(text) - val blocks = ArrayList() - var fileNamespace = "" - - for (match in NAMESPACE.findAll(code)) { - val name = match.groupValues[1] - if (match.groupValues[2] == ";") { - fileNamespace = name - } else { - val open = match.range.last - blocks += Block(name, match.groups[1]!!.range.first, open, closeOf(code, open), isType = false) - } - } - for (match in TYPE.findAll(code)) { - val open = bodyOf(code, match.range.last + 1) ?: continue - blocks += Block(match.groupValues[1], match.groups[1]!!.range.first, open, closeOf(code, open), isType = true) - } - - fun suiteAt(offset: Int): Pair? { - val around = blocks.filter { it.open < offset && offset < it.close }.sortedBy { it.open } - val owner = around.lastOrNull { it.isType } ?: return null - val names = listOf(fileNamespace).filter { it.isNotEmpty() } + around.map { it.name } - return names.joinToString(".") to owner - } - - val tests = LinkedHashMap() - val suites = LinkedHashMap() - for (match in ATTRIBUTE.findAll(code)) { - val (name, offset) = methodAfter(code, match.range.last + 1) ?: continue - val (suite, owner) = suiteAt(offset) ?: continue - tests.putIfAbsent(offset, Test(name, offset, suite)) - suites.putIfAbsent(suite, Suite(owner.name, owner.nameOffset, suite)) - } - return Result(suites.values.toList(), tests.values.toList()) - } - - /** - * The name of the method declared after [from], and where it is: past any further attributes, the word - * before the first `(`. Null when a `;`, `{` or `}` comes first, which is no method declaration. - */ - private fun methodAfter(code: String, from: Int): Pair? { - var i = from - while (true) { - while (i < code.length && code[i].isWhitespace()) i++ - if (i < code.length && code[i] == '[') { - i = (code.indexOf(']', i).takeIf { it >= 0 } ?: return null) + 1 - } else { - break - } - } - var paren = i - while (paren < code.length && code[paren] != '(') { - if (code[paren] == ';' || code[paren] == '{' || code[paren] == '}') return null - paren++ - } - if (paren >= code.length) return null - - var end = paren - while (end > i && code[end - 1].isWhitespace()) end-- - // A generic method's type parameters sit between the name and the parenthesis. - if (end > i && code[end - 1] == '>') { - var depth = 0 - while (end > i) { - end-- - if (code[end] == '>') depth++ - if (code[end] == '<' && --depth == 0) break - } - while (end > i && code[end - 1].isWhitespace()) end-- - } - var start = end - while (start > i && (code[start - 1].isLetterOrDigit() || code[start - 1] == '_')) start-- - if (start == end) return null - return code.substring(start, end) to start - } - - /** The `{` that opens the body of the type declared before [from], or null when it has none. */ - private fun bodyOf(code: String, from: Int): Int? { - var i = from - var parens = 0 - while (i < code.length) { - when (code[i]) { - '(' -> parens++ - ')' -> parens-- - '{' -> if (parens == 0) return i - ';' -> if (parens == 0) return null - } - i++ - } - return null - } - - /** The `}` matching the `{` at [open], or the end of the text when it is not closed yet. */ - private fun closeOf(code: String, open: Int): Int { - var depth = 0 - for (i in open until code.length) { - when (code[i]) { - '{' -> depth++ - '}' -> if (--depth == 0) return i - } - } - return code.length - } - - /** - * [text] with comments, strings and character literals replaced by spaces, offsets unchanged. Handles - * `//` and block comments, ordinary, verbatim (`@"..."`) and raw (`"""..."""`) strings. - */ - internal fun blank(text: String): String { - val out = CharArray(text.length) { text[it] } - fun wipe(from: Int, until: Int) { - for (k in from until minOf(until, out.size)) if (out[k] != '\n') out[k] = ' ' - } - var i = 0 - while (i < text.length) { - val c = text[i] - val next = text.getOrElse(i + 1) { ' ' } - when { - c == '/' && next == '/' -> { - val end = text.indexOf('\n', i).let { if (it < 0) text.length else it } - wipe(i, end); i = end - } - c == '/' && next == '*' -> { - val end = text.indexOf("*/", i + 2).let { if (it < 0) text.length else it + 2 } - wipe(i, end); i = end - } - c == '"' && text.startsWith("\"\"\"", i) -> { - var quotes = 0 - while (i + quotes < text.length && text[i + quotes] == '"') quotes++ - val fence = "\"".repeat(quotes) - val end = text.indexOf(fence, i + quotes).let { if (it < 0) text.length else it + quotes } - wipe(i, end); i = end - } - c == '"' -> { - val verbatim = i > 0 && (text[i - 1] == '@' || (text[i - 1] == '$' && i > 1 && text[i - 2] == '@')) - var j = i + 1 - while (j < text.length) { - if (verbatim) { - if (text[j] == '"') { if (text.getOrElse(j + 1) { ' ' } == '"') j++ else break } - } else { - if (text[j] == '\\') j++ else if (text[j] == '"' || text[j] == '\n') break - } - j++ - } - val end = minOf(j + 1, text.length) - wipe(i, end); i = end - } - c == '\'' -> { - var j = i + 1 - while (j < text.length && j < i + 8 && text[j] != '\'' && text[j] != '\n') { if (text[j] == '\\') j++; j++ } - val end = if (j < text.length && text[j] == '\'') j + 1 else i + 1 - wipe(i, end); i = end - } - else -> i++ - } - } - return String(out) - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsCompletionContributor.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsCompletionContributor.kt deleted file mode 100644 index 4bcca9dcd3..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsCompletionContributor.kt +++ /dev/null @@ -1,382 +0,0 @@ -package dev.codeassist.csharp.completion - - -import android.util.Log -import dev.codeassist.csharp.CSharpPlugin -import dev.codeassist.csharp.editor.quickfixes.CsUsingFix -import dev.codeassist.csharp.project.CsProject -import dev.codeassist.csharp.project.csproj.Csproj -import dev.codeassist.csharp.project.csproj.CsprojGraph -import dev.codeassist.csharp.project.csproj.CsprojInfo -import dev.codeassist.csharp.util.TAG -import dev.ide.lang.LanguageId -import dev.ide.lang.completion.CaretAction -import dev.ide.lang.completion.CompletionContribution -import dev.ide.lang.completion.CompletionContributor -import dev.ide.lang.completion.CompletionItem -import dev.ide.lang.completion.CompletionItemKind -import dev.ide.lang.completion.CompletionParams -import dev.ide.lang.completion.CompletionResultSet -import dev.ide.lang.completion.TextEdit -import dev.ide.lang.dom.TextRange -import kotlinx.coroutines.CancellationException -import java.nio.file.Path -import java.nio.file.Paths - -/** - * Completes what follows a dot: `Foo.` lists the namespace's types, `Foo.Greeter.` lists the static members of - * that type, and `greeter.` lists the instance members of the type `greeter` was declared with. Only symbols of - * the project's referenced DLLs and of its own sources are known, as [CsSymbols] reports them. - * - * Works on the text before the caret, not on a syntax tree: the backend has none. A chain like `a.b.c.` is - * taken from the characters before the dot, so an expression such as `list[0].` is not completed. - */ -internal class CsCompletionContributor( - private val symbols: CsSymbols, - private val semantic: CsSemanticCompletion, -) : CompletionContributor { - - override val id = "csharp.symbols" - - override suspend fun fillCompletionVariants(params: CompletionParams, result: CompletionResultSet) { - val text = params.document.text - val caret = params.replacementRange.start.coerceIn(0, text.length) - val before = text.subSequence(lineStartBefore(text, caret), caret).toString() - when { - before.endsWith('.') -> { - // Roslyn knows the receiver's real type (a local, a call's result, an inherited member); the symbol - // table is the fallback for when it cannot answer or has nothing to say. - val items = semanticItems(params) - if (!items.isNullOrEmpty()) { - result.stopHere() - addSemantic(params, result, items) - } else { - completeAfterDot(params, result, text, before) - } - } - USING_START.matches(before) -> completeNamespaceNames(params, result) - // An empty prefix would offer every type of the base class library on each keystroke. - params.prefix.isNotEmpty() -> { - semanticItems(params)?.let { addSemantic(params, result, it) } - completeTypeNames(params, result, text) - completeKeywordsAndNames(params, result, text) - } - } - } - - /** Roslyn's candidates, or null when it could not answer. A failure is logged and never reaches the editor. */ - private suspend fun semanticItems(params: CompletionParams): List? = try { - semantic.itemsFor(params) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - Log.d(TAG, "completion: the semantic model could not answer: $e") - null - } - - private fun addSemantic( - params: CompletionParams, - result: CompletionResultSet, - items: List, - ) { - val source by lazy { params.document.text.toString() } - for (item in items) { - if (!params.prefixMatches(item.name)) continue - // A type no using reaches yet: accepting it also writes the using, where the quick fix would. - if (item.importNamespace.isNotEmpty()) { - if (CsUsingFix.imports(source, item.importNamespace)) continue - val using = CsUsingFix.insertion(source, item.importNamespace) - result.addElement( - CompletionItem( - label = item.name, - insertText = item.name, - kind = CompletionItemKind.CLASS, - detail = "using ${item.importNamespace}", - container = item.importNamespace, - sortPriority = UNIMPORTED_PRIORITY, - additionalEdits = listOf(TextEdit(TextRange(using.offset, using.offset), using.text)), - ), - ) - continue - } - val kind = when (item.kind) { - "class", "struct", "delegate" -> CompletionItemKind.CLASS - "interface" -> CompletionItemKind.INTERFACE - "enum" -> CompletionItemKind.ENUM - "method", "extension" -> CompletionItemKind.METHOD - "enummember" -> CompletionItemKind.ENUM_CONSTANT - "property", "field", "constant", "event" -> CompletionItemKind.FIELD - "parameter" -> CompletionItemKind.PARAMETER - "typeparameter" -> CompletionItemKind.TYPE_PARAMETER - "namespace" -> CompletionItemKind.PACKAGE - else -> CompletionItemKind.VARIABLE - } - val overloads = if (item.overloads > 1) " (+${item.overloads - 1} overloads)" else "" - val container = if (item.kind == "extension") "${item.container} (extension)" else item.container - // A method is accepted as `name()`, with the caret between the parentheses when every overload takes - // arguments. - val call = item.isMethod - result.addElement( - CompletionItem( - label = item.name, - insertText = if (call) item.name + "()" else item.name, - kind = kind, - detail = (item.detail + overloads).ifEmpty { null }, - container = container.ifEmpty { null }, - documentation = CsDocText.summary(item.documentation), - caret = if (call && item.takesArguments) { - CaretAction.At(item.name.length + 1) - } else { - CaretAction.AtEnd - }, - ), - ) - } - } - - /** `Foo.`: what can follow a dot after the chain of names before it. */ - private suspend fun completeAfterDot( - params: CompletionParams, - result: CompletionResultSet, - text: CharSequence, - before: String, - ) { - val chain = before.dropLast(1).takeLastWhile { it.isLetterOrDigit() || it == '_' || it == '.' } - if (chain.isEmpty() || chain.startsWith('.') || chain.first().isDigit()) return - // After a dot only members make sense, so the keywords are not offered here, resolved or not. - result.stopHere() - - val table = loadSymbols(params)?.table ?: return - addStaticMembers(params, result, table, chain) - if (!chain.contains('.')) addInstanceMembers(params, result, table, text, chain) - addNamespaceContents(params, result, table, chain) - } - - /** `using Sy`: the first segment of every namespace. Longer paths are completed after their dots. */ - private suspend fun completeNamespaceNames(params: CompletionParams, result: CompletionResultSet) { - val table = loadSymbols(params)?.table ?: return - for (namespace in topLevelNamespaces(table)) addVariant(params, result, namespace, "namespace") - } - - /** - * `Con`: the types of the namespaces the file can see, and the first segment of every namespace, for a - * name written in full such as `System.Console`. The keywords stay, so [CompletionResultSet.stopHere] is not - * called. A text match on the `using` lines: it does not know scope, comments or strings. - */ - private suspend fun completeTypeNames(params: CompletionParams, result: CompletionResultSet, text: CharSequence) { - // The symbol tool failing must not take the keywords and the file's own names with it. - var read: Loaded? = null - try { - read = loadSymbols(params) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - Log.d(TAG, "completion: symbols could not be read: $e") - } - val loaded = read ?: return - val visible = visibleNamespaces(text, loaded.info) - // What the semantic model already offered is not offered twice. - val offered = result.elements.mapTo(HashSet()) { it.label } - for (type in loaded.table.types) { - if (type.namespace in visible && type.name !in offered) addVariant(params, result, type.name, type.kind) - } - for (namespace in topLevelNamespaces(loaded.table)) { - if (namespace !in offered) addVariant(params, result, namespace, "namespace") - } - } - - /** - * The keywords, and the names the file already uses (a local written above, a parameter, a method). The host - * has no keyword or word source for C#: each language backend publishes its own, and [CsLanguageBackend] has none. - * A keyword is a fallback below real symbols (a positive priority); a name that is declared in the file is a - * variable, any other word of the file comes last. Names a symbol already offered are not repeated. - */ - private fun completeKeywordsAndNames(params: CompletionParams, result: CompletionResultSet, text: CharSequence) { - val offered = result.elements.mapTo(HashSet()) { it.label } - for (keyword in CsKeywords.ALL) { - if (keyword in offered || !params.prefixMatches(keyword)) continue - result.addElement( - CompletionItem( - label = keyword, insertText = keyword, kind = CompletionItemKind.KEYWORD, - detail = "keyword", sortPriority = 1, - ), - ) - } - for (word in CsWords.nearby(text.toString(), params.offset, { it !in offered && params.prefixMatches(it) })) { - result.addElement( - CompletionItem( - label = word.name, insertText = word.name, - kind = if (word.declared) CompletionItemKind.VARIABLE else CompletionItemKind.WORD, - detail = if (word.declared) "in this file" else null, - ), - ) - } - } - - /** The symbols of the module the file belongs to, or null when no module is found. */ - private suspend fun loadSymbols(params: CompletionParams): Loaded? { - // The module the host says the file belongs to; the search upwards only when it says none. - val moduleDir = params.module?.let { Paths.get(it.dir.path) } - ?: moduleDirOf(Paths.get(params.document.file.path)) - ?: return null - // Null for a module with no `.csproj`: its own sources are all there is to read, as in the editor's check. - val info = Csproj.load(moduleDir) - val sources = CsprojGraph.sources(moduleDir, info) - return Loaded(info, symbols.tableFor(info, moduleDir, sources)) - } - - private class Loaded(val info: CsprojInfo?, val table: CsSymbolTable) - - /** - * The namespaces whose types can be written without a prefix: the global one (`-`), those the file names in - * `using` and `namespace` lines, and the implicit usings when the project has them. - */ - private fun visibleNamespaces(text: CharSequence, info: CsprojInfo?): Set { - val visible = hashSetOf("-") - NAMESPACE_LINE.findAll(text).forEach { visible += it.groupValues[1] } - IMPLICIT_USING.findAll(Csproj.globalUsingsText(info)).forEach { visible += it.groupValues[1] } - return visible - } - - private fun topLevelNamespaces(table: CsSymbolTable): List = - table.types.map { it.namespace } - .filter { it != "-" } - .map { it.substringBefore('.') } - .distinct() - - /** The offset where the line holding [offset] starts. */ - private fun lineStartBefore(text: CharSequence, offset: Int): Int { - val newline = text.lastIndexOf('\n', (offset - 1).coerceAtLeast(0)) - return if (newline < 0 || offset == 0) 0 else newline + 1 - } - - /** `Foo.Greeter.`: the static members of a type named by [chain], in full or, with no dot, by its short name. */ - private fun addStaticMembers( - params: CompletionParams, - result: CompletionResultSet, - table: CsSymbolTable, - chain: String, - ) { - for (type in table.types) { - val named = type.fullName == chain || (!chain.contains('.') && type.name == chain) - if (!named) continue - for (member in table.members) { - if (member.typeFullName != type.fullName || !member.isStatic) continue - addVariant(params, result, member.name, member.kind, member.paramCount) - } - } - } - - /** `greeter.`: the instance members of the declared types of the variable [variable]. */ - private fun addInstanceMembers( - params: CompletionParams, - result: CompletionResultSet, - table: CsSymbolTable, - text: CharSequence, - variable: String, - ) { - for (typeName in declaredTypesOf(text, variable)) { - for (type in table.types) { - if (type.name != typeName) continue - for (member in table.members) { - if (member.typeFullName != type.fullName || member.isStatic) continue - addVariant(params, result, member.name, member.kind, member.paramCount) - } - } - } - } - - /** `Foo.`: the types of the namespace [chain], and the namespaces directly inside it. */ - private fun addNamespaceContents( - params: CompletionParams, - result: CompletionResultSet, - table: CsSymbolTable, - chain: String, - ) { - for (type in table.types) { - if (type.namespace != chain) continue - addVariant(params, result, type.name, type.kind) - } - val childNamespaces = table.types.map { it.namespace } - .filter { it.startsWith("$chain.") } - .map { it.removePrefix("$chain.").substringBefore('.') } - .distinct() - for (child in childNamespaces) addVariant(params, result, child, "namespace") - } - - /** - * The type names a variable is declared with in this file: `Greeter g =` or `var g = new Greeter(`. - * A text match, not a resolver result: it ignores scope, so two variables with one name in different - * methods both count, and a field or parameter declared in another file is not found. - */ - private fun declaredTypesOf(text: CharSequence, variable: String): List { - val name = Regex.escape(variable) - val declared = Regex("""(?)?\s+$name\s*[=;,)]""") - .findAll(text).map { it.groupValues[1] } - val created = Regex("""\bvar\s+$name\s*=\s*new\s+([A-Z]\w*)""") - .findAll(text).map { it.groupValues[1] } - return (declared + created).distinct().toList() - } - - /** Offers [name] when it matches what is typed; [kind] is the tool's kind word, which picks the icon. */ - private fun addVariant( - params: CompletionParams, - result: CompletionResultSet, - name: String, - kind: String, - paramCount: Int = 0, - ) { - if (!params.prefixMatches(name)) return - val itemKind = when (kind) { - "class" -> CompletionItemKind.CLASS - "interface" -> CompletionItemKind.INTERFACE - "method" -> CompletionItemKind.METHOD - "field" -> CompletionItemKind.FIELD - "property" -> CompletionItemKind.FIELD - "namespace" -> CompletionItemKind.PACKAGE - else -> CompletionItemKind.VARIABLE - } - // A method is accepted as `name()`, with the caret between the parentheses when it takes arguments. - if (kind == "method") { - val caret = if (paramCount > 0) CaretAction.At(name.length + 1) else CaretAction.AtEnd - result.addElement( - CompletionItem(label = name, insertText = "$name()", kind = itemKind, detail = kind, caret = caret), - ) - return - } - result.addElement(CompletionItem(label = name, insertText = name, kind = itemKind, detail = kind)) - } - - /** The folder with the `.csproj`, looked for from the file upwards, for when the host names no module. */ - private fun moduleDirOf(file: Path): Path? { - var dir: Path? = file.parent - var depth = 0 - while (dir != null && depth < 4) { - if (Csproj.find(dir) != null) return dir - dir = dir.parent - depth++ - } - return null - } - - private companion object { - /** After everything already in scope: a type that needs a using is the less likely pick. */ - const val UNIMPORTED_PRIORITY = 50 - - /** A line that has only `using` before the name: `using `, `global using `. */ - val USING_START = Regex("""^\s*(?:global\s+)?using\s+$""") - - /** `using X;`, `namespace X;` and `namespace X {`: the namespace a file names. */ - val NAMESPACE_LINE = Regex("""(?m)^\s*(?:using|namespace)\s+([\w.]+)\s*[;{]?\s*$""") - - /** A plain line of [Csproj.globalUsingsText]; an alias or static one names no namespace to list. */ - val IMPLICIT_USING = Regex("""global using global::([\w.]+);""") - } -} - -/** Registers the contributor for the C# language. */ -internal fun csCompletionContribution(symbols: CsSymbols, semantic: CsSemanticCompletion): CompletionContribution = - CompletionContribution( - contributor = CsCompletionContributor(symbols, semantic), - languages = setOf(LanguageId(CSharpPlugin.LANGUAGE)), - ) diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsCompletionItems.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsCompletionItems.kt deleted file mode 100644 index 3e8b2c539d..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsCompletionItems.kt +++ /dev/null @@ -1,61 +0,0 @@ -package dev.codeassist.csharp.completion - -/** - * Parses the completion output of [dev.codeassist.csharp.sdk.CsCompleter]. - * - * Expected format, one candidate per line, with fields separated by tabs: - * `itemnamekinddetailtakesArguments 0|1containerdeprecated 0|1overloadsdocumentationnamespace to import` - * - * Documentation is optional and escaped (see [CsDocText.unescape]). - * Pure, so it can be tested without a device. - */ -internal object CsCompletionItems { - - /** - * A completion candidate. - * - * [kind] is one of `method`, `extension`, `property`, `field`, `constant`, `enummember`, `event`, `local`, - * `parameter`, `namespace`, `typeparameter`, `class`, `struct`, `interface`, `enum`, or `delegate`. - * - * [detail] is the value's type or a method's return type. - * [container] is the declaring type or namespace. - */ - class Item( - val name: String, - val kind: String, - val detail: String, - val takesArguments: Boolean, - val container: String, - val deprecated: Boolean, - val overloads: Int, - /** The member's summary documentation XML, or empty. See [CsDocText]. */ - val documentation: String = "", - /** The namespace a `using` must name for this type to resolve, or empty when it already does. */ - val importNamespace: String = "", - ) { - val isMethod: Boolean get() = kind == "method" || kind == "extension" - val isType: Boolean get() = kind in TYPE_KINDS - } - - private val TYPE_KINDS = setOf("class", "struct", "interface", "enum", "delegate") - - /** Parses valid completion candidates, skipping malformed or unrelated lines. */ - fun parse(lines: List): List = lines.mapNotNull { line -> - if (!line.startsWith("item\t")) return@mapNotNull null - - val fields = line.split('\t') - if (fields.size < 8 || fields[1].isEmpty()) return@mapNotNull null - - Item( - name = fields[1], - kind = fields[2], - detail = fields[3], - takesArguments = fields[4] == "1", - container = fields[5], - deprecated = fields[6] == "1", - overloads = fields[7].toIntOrNull() ?: 1, - documentation = fields.getOrNull(8)?.let(CsDocText::unescape) ?: "", - importNamespace = fields.getOrNull(9).orEmpty(), - ) - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsDocText.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsDocText.kt deleted file mode 100644 index 443ba105e2..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsDocText.kt +++ /dev/null @@ -1,135 +0,0 @@ -package dev.codeassist.csharp.completion - -/** - * Converts Roslyn's XML documentation (`/// ...`) into plain text for popups. - * - * Roslyn sends only the `summary` and `param` elements of a member's XML, escaped onto one line. - * [unescape] reverses that escaping. - * - * Pure, so it can be tested without a device. - */ -internal object CsDocText { - - /** Maximum popup text length. Longer text is cut at a word and ended with an ellipsis. */ - private const val LIMIT = 600 - - // Markers for characters that cannot occur in documentation XML. - private const val LINE = '\u0000' - private const val OPEN = '\u0001' - private const val CLOSE = '\u0002' - - private val SUMMARY = Regex("(.*?)", RegexOption.DOT_MATCHES_ALL) - private val INHERIT = Regex("]*?cref=\"([^\"]*)\"[^>]*?/?>") - private val LANGWORD = Regex("]*?langword=\"([^\"]*)\"[^>]*?/?>") - private val HREF = Regex("]*?href=\"([^\"]*)\"[^>]*?(?:/>|>(.*?))", RegexOption.DOT_MATCHES_ALL) - private val REF = Regex("<(?:paramref|typeparamref)\\s+[^>]*?name=\"([^\"]*)\"[^>]*?/?>") - private val BREAK = Regex("|") - private val TAG = Regex("<[^>]*>") - private val SPACES = Regex("[ \\t\\r\\n]+") - - /** Returns the member's summary text, or null when no non-empty summary exists. */ - fun summary(xml: String): String? { - val inner = SUMMARY.find(xml)?.groupValues?.get(1) ?: return null - return render(inner).takeIf { it.isNotEmpty() } - } - - /** Returns the documentation for parameter [name], or null when none exists. */ - fun param(xml: String, name: String): String? { - val pattern = Regex( - "(.*?)", - RegexOption.DOT_MATCHES_ALL, - ) - val inner = pattern.find(xml)?.groupValues?.get(1) ?: return null - return render(inner).takeIf { it.isNotEmpty() } - } - - /** Whether the member inherits its documentation from another declaration. */ - fun inherits(xml: String): Boolean = INHERIT.containsMatchIn(xml) - - /** - * Converts an XML fragment to plain text. - * - * References are replaced with their target names (`T:System.String` becomes `String`), - * parameter references with their names, paragraph breaks with newlines, and other tags - * are removed. XML entities are decoded. - */ - fun render(fragment: String): String { - var text = fragment - text = HREF.replace(text) { it.groupValues[2].ifBlank { it.groupValues[1] } } - - // Protect generic angle brackets from the tag removal below. - text = CREF.replace(text) { - shortName(it.groupValues[1]).replace('<', OPEN).replace('>', CLOSE) - } - text = LANGWORD.replace(text) { it.groupValues[1] } - text = REF.replace(text) { it.groupValues[1] } - text = BREAK.replace(text, LINE.toString()) - text = TAG.replace(text, "") - text = decode(text) - - // Source line breaks are spaces; only explicit paragraph breaks create new lines. - val lines = text.split(LINE) - .map { SPACES.replace(it, " ").trim() } - .filter { it.isNotEmpty() } - - return cut(lines.joinToString("\n").replace(OPEN, '<').replace(CLOSE, '>')) - } - - /** - * Extracts a short name from an XML documentation reference. - * - * Examples: - * - `T:System.Collections.Generic.List{T}` becomes `List`. - * - `M:System.Math.Max(System.Int32,System.Int32)` becomes `Max`. - */ - fun shortName(cref: String): String { - var name = cref.substringAfter(':', cref).substringBefore('(') - name = name.substringAfterLast('.') - return name.replace('{', '<').replace('}', '>').replace(Regex("`+\\d+"), "") - } - - /** - * Decodes the line protocol escaping: - * `\\n` becomes a newline, `\\t` a tab, and `\\\\` a backslash. - */ - fun unescape(text: String): String { - if ('\\' !in text) return text - - val out = StringBuilder(text.length) - var i = 0 - - while (i < text.length) { - val c = text[i] - if (c == '\\' && i + 1 < text.length) { - when (val next = text[i + 1]) { - 'n' -> out.append('\n') - 't' -> out.append('\t') - else -> out.append(next) - } - i += 2 - } else { - out.append(c) - i++ - } - } - - return out.toString() - } - - /** Decodes the XML entities used in documentation text. */ - private fun decode(text: String): String = text - .replace("<", "<") - .replace(">", ">") - .replace(""", "\"") - .replace("'", "'") - .replace("&", "&") - - /** Truncates long text at a nearby word boundary. */ - private fun cut(text: String): String { - if (text.length <= LIMIT) return text - - val at = text.lastIndexOf(' ', LIMIT).takeIf { it > LIMIT / 2 } ?: LIMIT - return text.substring(0, at).trimEnd() + "…" - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsKeywords.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsKeywords.kt deleted file mode 100644 index 346d67a8bf..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsKeywords.kt +++ /dev/null @@ -1,17 +0,0 @@ -package dev.codeassist.csharp.completion - -/** C#'s keywords, as the editor colors them and as completion offers them. */ -internal object CsKeywords { - /** C#'s reserved words and the contextual ones that read as keywords in ordinary code. */ - val ALL = setOf( - "abstract", "as", "async", "await", "base", "bool", "break", "byte", "case", "catch", "char", "checked", - "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", - "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "get", "goto", "if", - "implicit", "in", "init", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", - "null", "object", "operator", "out", "override", "params", "partial", "private", "protected", "public", - "readonly", "record", "ref", "required", "return", "sbyte", "sealed", "set", "short", "sizeof", - "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", - "ulong", "unchecked", "unsafe", "ushort", "using", "var", "virtual", "void", "volatile", "when", - "where", "while", "yield", - ) -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsNavigationLines.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsNavigationLines.kt deleted file mode 100644 index a89de50606..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsNavigationLines.kt +++ /dev/null @@ -1,109 +0,0 @@ -package dev.codeassist.csharp.completion - -/** - * Reads what the server prints for the navigation requests (see `CsNavigator`): tab-separated lines, one - * record each. A line of another shape is skipped, so a diagnostic the server printed is not taken for data. - */ -internal object CsNavigationLines { - - /** One source location of a symbol: the file, the offset of its name, and its display text. */ - data class Definition(val path: String, val offset: Int, val label: String) - - /** What a symbol is. [kind] is the server's word for it (`class`, `method`, `localVariable`, ...). */ - data class Hover( - val kind: String, - val name: String, - val container: String, - val signature: String, - /** The doc comment's `summary` and `param` elements as XML, or empty. */ - val documentation: String, - ) - - /** One name to colour. [modifiers] are the server's words (`declaration`, `static`, ...). */ - data class Token(val start: Int, val length: Int, val kind: String, val modifiers: List) - - /** A declaration in the file's outline. [depth] is its nesting, 0 at the top. */ - data class Item(val kind: String, val depth: Int, val nameOffset: Int, val end: Int, val name: String, val detail: String) - - /** A region that can be collapsed. [kind] is the editor's word for it (`classBody`, `imports`, ...). */ - data class Fold(val start: Int, val end: Int, val kind: String, val placeholder: String) - - class Outline(val items: List, val folds: List) - - /** The name at the caret: its text and range, what it is, and whether the project declares it. */ - data class Named(val name: String, val start: Int, val end: Int, val kind: String, val inSource: Boolean) - - /** One place a symbol appears. [access] is `d` for its declaration, `w` where it is assigned, `r` elsewhere. */ - data class Reference(val path: String, val start: Int, val end: Int, val access: Char) - - class References(val symbol: Named, val places: List) - - fun outline(lines: List): Outline { - val items = ArrayList() - val folds = ArrayList() - for (line in lines) { - val parts = line.split('\t') - when (parts[0]) { - "item" -> { - if (parts.size < 6) continue - val depth = parts[2].toIntOrNull() ?: continue - val offset = parts[3].toIntOrNull() ?: continue - val end = parts[4].toIntOrNull() ?: continue - items += Item(parts[1], depth, offset, end, parts[5], parts.getOrElse(6) { "" }) - } - "fold" -> { - if (parts.size < 4) continue - val start = parts[1].toIntOrNull() ?: continue - val end = parts[2].toIntOrNull() ?: continue - if (end > start) folds += Fold(start, end, parts[3], parts.getOrElse(4) { "..." }.ifEmpty { "..." }) - } - } - } - return Outline(items, folds) - } - - fun references(lines: List): References? { - var symbol: Named? = null - val places = ArrayList() - for (line in lines) { - val parts = line.split('\t') - when (parts[0]) { - "sym" -> { - if (parts.size < 6) continue - val start = parts[2].toIntOrNull() ?: continue - val end = parts[3].toIntOrNull() ?: continue - symbol = Named(parts[1], start, end, parts[4], parts[5] == "1") - } - "ref" -> { - if (parts.size < 5) continue - val start = parts[2].toIntOrNull() ?: continue - val end = parts[3].toIntOrNull() ?: continue - places += Reference(parts[1], start, end, parts[4].firstOrNull() ?: 'r') - } - } - } - return symbol?.let { References(it, places) } - } - - fun definitions(lines: List): List = lines.mapNotNull { line -> - val parts = line.split('\t') - if (parts.size < 4 || parts[0] != "def") return@mapNotNull null - val offset = parts[2].toIntOrNull() ?: return@mapNotNull null - Definition(parts[1], offset, parts[3]) - } - - fun hover(lines: List): Hover? = lines.firstNotNullOfOrNull { line -> - val parts = line.split('\t') - if (parts.size < 5 || parts[0] != "hover") return@firstNotNullOfOrNull null - Hover(parts[1], parts[2], parts[3], parts[4], CsDocText.unescape(parts.getOrElse(5) { "" })) - } - - fun tokens(lines: List): List = lines.mapNotNull { line -> - val parts = line.split('\t') - if (parts.size < 4 || parts[0] != "tok") return@mapNotNull null - val start = parts[1].toIntOrNull() ?: return@mapNotNull null - val length = parts[2].toIntOrNull() ?: return@mapNotNull null - if (start < 0 || length <= 0) return@mapNotNull null - Token(start, length, parts[3], parts.getOrElse(4) { "" }.split(',').filter { it.isNotEmpty() }) - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSemanticCompletion.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSemanticCompletion.kt deleted file mode 100644 index 41f7ed5a43..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSemanticCompletion.kt +++ /dev/null @@ -1,272 +0,0 @@ -package dev.codeassist.csharp.completion - - -import android.util.Log -import dev.codeassist.csharp.project.CsProject -import dev.codeassist.csharp.project.csproj.Csproj -import dev.codeassist.csharp.project.csproj.CsprojGraph -import dev.codeassist.csharp.project.csproj.CsprojReferences -import dev.codeassist.csharp.sdk.CsCompleter -import dev.codeassist.csharp.sdk.CsFormatEdits -import dev.codeassist.csharp.sdk.CsFormatter -import dev.codeassist.csharp.sdk.CsNavigator -import dev.codeassist.csharp.sdk.DotnetSdk -import dev.codeassist.csharp.util.TAG -import dev.codeassist.csharp.util.ToolCancellation -import dev.codeassist.csharp.util.killableTool -import dev.ide.lang.completion.CompletionParams -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths - -/** - * Gets completion candidates from Roslyn's semantic model for the editor buffer, including unsaved text, - * using the project's other source files and settings. - */ -internal class CsSemanticCompletion(private val sdk: DotnetSdk) { - - private val projectReferences = CsprojReferences(sdk) - - /** - * Returns candidates at the caret, or null when Roslyn cannot answer. - * The caller then falls back to the symbol table. - */ - suspend fun itemsFor(params: CompletionParams): List? { - val file = runCatching { - Paths.get(params.document.file.path).toAbsolutePath().normalize() - }.getOrNull() ?: return null - - val moduleDir = params.module?.let { Paths.get(it.dir.path) } - val text = params.document.text.toString() - - val lines = ask("complete", file, moduleDir, text) { buffer, arguments, cancellation, onLine -> - CsCompleter.complete( - sdk, - buffer, - params.offset, - params.replacementRange.start, - arguments, - cancellation, - onLine, - ) - } ?: return null - - return CsCompletionItems.parse(lines) - } - - /** - * Returns the overloads of the call at [offset], or null when Roslyn cannot answer - * or the caret is not inside a call. The module is found from [path]. - */ - suspend fun signaturesAt( - path: String, - text: String, - offset: Int, - ): CsSignatureLines.Result? { - val file = runCatching { - Paths.get(path).toAbsolutePath().normalize() - }.getOrNull() ?: return null - - val lines = ask("signature", file, null, text) { buffer, arguments, cancellation, onLine -> - CsCompleter.signatures( - sdk, - buffer, - offset, - arguments, - cancellation, - onLine, - ) - } ?: return null - - return CsSignatureLines.parse(lines) - } - - /** - * Returns where the symbol at [offset] is declared in the project's sources: empty when it has no source - * (a framework or package type), null when Roslyn cannot answer. - */ - suspend fun definitionsAt(path: String, text: String, offset: Int): List? { - val file = runCatching { Paths.get(path).toAbsolutePath().normalize() }.getOrNull() ?: return null - var scratch: String? = null - - val lines = ask("definition", file, null, text) { buffer, arguments, cancellation, onLine -> - scratch = buffer - CsNavigator.definition(sdk, buffer, offset, arguments, cancellation, onLine) - } ?: return null - - // The server saw the buffer as a scratch copy; a declaration in it is one in the file being edited. - return CsNavigationLines.definitions(lines).map { - if (it.path == scratch) it.copy(path = file.toString()) else it - } - } - - /** Returns what the symbol at [offset] is, or null when there is none or Roslyn cannot answer. */ - suspend fun hoverAt(path: String, text: String, offset: Int): CsNavigationLines.Hover? { - val file = runCatching { Paths.get(path).toAbsolutePath().normalize() }.getOrNull() ?: return null - - val lines = ask("hover", file, null, text) { buffer, arguments, cancellation, onLine -> - CsNavigator.hover(sdk, buffer, offset, arguments, cancellation, onLine) - } ?: return null - - return CsNavigationLines.hover(lines) - } - - /** Returns the declarations and collapsible regions of [text], or null when Roslyn cannot answer. */ - suspend fun outlineFor(path: String, text: String): CsNavigationLines.Outline? { - val file = runCatching { Paths.get(path).toAbsolutePath().normalize() }.getOrNull() ?: return null - - val lines = ask("outline", file, null, text) { buffer, arguments, cancellation, onLine -> - CsNavigator.outline(sdk, buffer, arguments, cancellation, onLine) - } ?: return null - - return CsNavigationLines.outline(lines) - } - - /** - * Returns the symbol at [offset] and every place the project declares or uses it, the buffer's own - * places under [path]. Null when there is no name there or Roslyn cannot answer. - */ - suspend fun referencesAt(path: String, text: String, offset: Int): CsNavigationLines.References? { - val file = runCatching { Paths.get(path).toAbsolutePath().normalize() }.getOrNull() ?: return null - var scratch: String? = null - - val lines = ask("references", file, null, text) { buffer, arguments, cancellation, onLine -> - scratch = buffer - CsNavigator.references(sdk, buffer, offset, arguments, cancellation, onLine) - } ?: return null - - val found = CsNavigationLines.references(lines) ?: return null - return CsNavigationLines.References( - found.symbol, - found.places.map { if (it.path == scratch) it.copy(path = file.toString()) else it }, - ) - } - - /** - * Returns the edits that reformat [text], or the part of it from [start] to [end] when both are given. - * Empty when there is nothing to change, or the text does not parse and is best left alone. Null when - * Roslyn cannot answer. - */ - suspend fun formatEdits( - path: String, - text: String, - start: Int, - end: Int, - indentSize: Int, - useTabs: Boolean, - ): List? { - val file = runCatching { Paths.get(path).toAbsolutePath().normalize() }.getOrNull() ?: return null - - val lines = ask("format", file, null, text) { buffer, arguments, cancellation, onLine -> - CsFormatter.format(sdk, buffer, start, end, indentSize, useTabs, arguments, cancellation, onLine) - } ?: return null - - return CsFormatEdits.parse(lines) - } - - /** Returns the names of [text] with what each one is, or null when Roslyn cannot answer. */ - suspend fun tokensFor(path: String, text: String): List? { - val file = runCatching { Paths.get(path).toAbsolutePath().normalize() }.getOrNull() ?: return null - - val lines = ask("tokens", file, null, text) { buffer, arguments, cancellation, onLine -> - CsNavigator.tokens(sdk, buffer, arguments, cancellation, onLine) - } ?: return null - - return CsNavigationLines.tokens(lines) - } - - /** - * Writes [text] as the buffer of [file] beside the project's other sources, - * then runs [run] with the compiler arguments for that source set. - */ - private suspend fun ask( - what: String, - file: Path, - module: Path?, - text: String, - run: (String, List, ToolCancellation, (String) -> Unit) -> Int?, - ): List? { - if (sdk.prepare() !is DotnetSdk.Status.Ready) return null - - // The nearest project file above the buffer decides, in a module that holds several projects. - val moduleDir = CsprojGraph.owningDir(file) ?: module ?: moduleDirOf(file) ?: return null - val work = sdk.home.resolve("complete-work") - .resolve(Integer.toHexString(file.toString().hashCode())) - val buffer = work.resolve(file.fileName.toString()) - - val project = Csproj.load(moduleDir) - val sources = CsprojGraph.sources(moduleDir, project) - val others = sources.filter { - runCatching { it.toAbsolutePath().normalize() }.getOrNull() != file - } - - val usingsText = Csproj.globalUsingsText(project) - val usings = work.resolve("GlobalUsings.g.cs").takeIf { usingsText.isNotEmpty() } - - val referenced = project - ?.let { - Csproj.resolveReferences( - it, - moduleDir, - sdk.nuget, - sdk.frameworkDllNames(), - ).first - } - ?: emptyList() - - // Referenced projects are compiled by the server from their sources, alongside this one. - val projects = projectReferences.forEditor(Csproj.find(moduleDir), project) - - val arguments = if (project != null) { - Csproj.arguments( - project, - listOf(buffer) + others, - sdk.references() + referenced + projects.libraries, - work.resolve("complete.dll"), - usings, - forceLibrary = true, - ) + projects.arguments - } else { - buildList { - add("-nologo") - add("-noconfig") - add("-target:library") - add("-out:" + work.resolve("complete.dll")) - sdk.references().forEach { add("-r:$it") } - add(buffer.toString()) - others.forEach { add(it.toString()) } - } - } - - val lines = ArrayList() - val startedAt = System.nanoTime() - - val exit = killableTool { cancellation -> - Files.createDirectories(work) - Files.write(buffer, text.toByteArray(Charsets.UTF_8)) - usings?.let { - Files.write(it, usingsText.toByteArray(Charsets.UTF_8)) - } - run(buffer.toString(), arguments, cancellation) { lines += it } - } - - val elapsedMs = (System.nanoTime() - startedAt) / 1_000_000 - Log.d(TAG, "$what: exit=$exit, ${lines.size} line(s) in $elapsedMs ms") - - return if (exit == null) null else lines - } - - /** Finds the folder containing the `.csproj` by walking up from the file. */ - private fun moduleDirOf(file: Path): Path? { - var dir: Path? = file.parent - var depth = 0 - - while (dir != null && depth < 8) { - if (Csproj.find(dir) != null) return dir - dir = dir.parent - depth++ - } - - return null - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSignatureLines.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSignatureLines.kt deleted file mode 100644 index 26acdeb1c3..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSignatureLines.kt +++ /dev/null @@ -1,73 +0,0 @@ -package dev.codeassist.csharp.completion - -/** - * Parses the output of [CsCompleter] for a signature request. - * - * Expected format: - * - `sighelpactive signatureactive parameter` - * - One `siglabelstart,end;start,end...` line per overload, where each pair is a parameter's character - * range inside the label. - * - Optional member documentation XML (escaped; see [CsDocText.unescape]). - * - Optional parameter names separated by `;`. - * - * Pure, so it can be tested without a device. - */ -internal object CsSignatureLines { - - /** A parsed overload with its display label, parameter ranges, documentation, and parameter names. */ - class Signature( - val label: String, - val parameters: List, - val documentation: String = "", - val names: List = emptyList(), - ) - - /** Parsed overloads and the currently active signature and parameter. */ - class Result( - val signatures: List, - val activeSignature: Int, - val activeParameter: Int, - ) - - /** - * Parses [lines], returning null when there is no call under the caret or the output is malformed. - */ - fun parse(lines: List): Result? { - val header = lines.firstOrNull { it.startsWith("sighelp\t") }?.split('\t') ?: return null - if (header.size < 3) return null - val activeSignature = header[1].toIntOrNull() ?: return null - val activeParameter = header[2].toIntOrNull() ?: return null - - val signatures = lines.filter { it.startsWith("sig\t") }.mapNotNull { line -> - val fields = line.split('\t') - val label = fields.getOrNull(1)?.takeIf { it.isNotEmpty() } ?: return@mapNotNull null - val ranges = fields.getOrElse(2) { "" }.split(';').mapNotNull { range(it, label.length) } - val documentation = fields.getOrNull(3)?.let(CsDocText::unescape) ?: "" - val names = fields.getOrElse(4) { "" }.split(';').filter { it.isNotEmpty() } - - Signature(label, ranges, documentation, names) - } - - if (signatures.isEmpty()) return null - - return Result( - signatures, - activeSignature.coerceIn(0, signatures.size - 1), - activeParameter.coerceAtLeast(0), - ) - } - - /** - * Parses a parameter's `[start, end)` range. - * Invalid or out-of-bounds ranges are dropped rather than clamped to avoid misleading highlights. - */ - private fun range(pair: String, length: Int): IntRange? { - val parts = pair.split(',') - if (parts.size != 2) return null - - val start = parts[0].toIntOrNull() ?: return null - val end = parts[1].toIntOrNull() ?: return null - - return if (start in 0..end && end <= length) start until end else null - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSymbolTable.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSymbolTable.kt deleted file mode 100644 index d93113132c..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSymbolTable.kt +++ /dev/null @@ -1,64 +0,0 @@ -package dev.codeassist.csharp.completion - - -internal class CsSymbolTable(lines: List) { - - /** A public type. [namespace] is `-` when the type has no namespace. */ - class Type( - val namespace: String, - val name: String, - val kind: String, - val isStatic: Boolean, - ) { - val fullName: String - get() = if (namespace == "-") name else "$namespace.$name" - } - - /** A public member of [typeFullName]. [paramCount] is 0 for non-method members. */ - class Member( - val typeFullName: String, - val kind: String, - val name: String, - val isStatic: Boolean, - val paramCount: Int = 0, - ) - - val types = ArrayList() - val members = ArrayList() - - // Parse each line directly to avoid intermediate lists. - init { - for (line in lines) { - val fields = line.split('\t') - - when (fields[0]) { - "type" -> if (fields.size >= 5) { - types.add( - Type( - namespace = fields[1], - name = fields[2], - kind = fields[3], - isStatic = fields[4] == "1", - ), - ) - } - - "member" -> if (fields.size >= 6) { - val typeFullName = - if (fields[1] == "-") fields[2] else "${fields[1]}.${fields[2]}" - val paramCount = fields.getOrNull(6)?.toIntOrNull() ?: 0 - - members.add( - Member( - typeFullName = typeFullName, - kind = fields[3], - name = fields[4], - isStatic = fields[5] == "1", - paramCount = paramCount, - ), - ) - } - } - } - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSymbols.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSymbols.kt deleted file mode 100644 index 57d6f1c8c4..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsSymbols.kt +++ /dev/null @@ -1,316 +0,0 @@ -package dev.codeassist.csharp.completion - - -import android.util.Log -import dev.codeassist.csharp.project.csproj.Csproj -import dev.codeassist.csharp.project.csproj.CsprojInfo -import dev.codeassist.csharp.sdk.CsCompilerHost -import dev.codeassist.csharp.sdk.DotnetSdk -import dev.codeassist.csharp.sdk.ensureRuntimeConfig -import dev.codeassist.csharp.util.TAG -import dev.codeassist.csharp.util.ToolCancellation -import dev.codeassist.csharp.util.killableTool -import java.nio.file.Files -import java.nio.file.Path - -/** - * Reads public types and members from referenced DLLs using a small C# tool. - * - * The tool uses System.Reflection.Metadata and runs through the same launcher as the program. - * It is built once with the resident compiler into /tools/ and its output is cached - * until a DLL changes. - * - * Output is one tab-separated symbol per line. A namespace of "-" means no namespace: - * typensnameclass|interfacestatic 0|1 - * membernstypemethod|field|propertynamestatic 0|1[parameter count] - * - * The parameter count appears only on method lines and is used by completion to place the caret. - */ -internal class CsSymbols(private val sdk: DotnetSdk) { - - private var cacheKey: String? = null - private var cached: List = emptyList() - - /** Last built table for each module directory, available to synchronous quick fixes. */ - private val tables = java.util.concurrent.ConcurrentHashMap() - - private var projectKey: String? = null - private var projectDll: Path? = null - private var projectOwner: Path? = null - - // Symbol lookup - - /** Returns the symbol lines for [dlls], cached by DLL paths and modification times. */ - suspend fun linesFor(dlls: List): List { - if (dlls.isEmpty()) return emptyList() - - val key = stampOf(dlls) - return killableTool { cancellation -> runTool(key, dlls, cancellation) } - } - - /** - * Builds the symbol table from project sources, referenced DLLs, and the SDK reference assemblies. - * - * [info] is null for modules without a .csproj. Such modules use their own sources and the - * base class library, without additional project references. - */ - suspend fun tableFor( - info: CsprojInfo?, - dir: Path, - sources: List, - ): CsSymbolTable { - val references = info?.let { - Csproj.resolveReferences(it, dir, sdk.nuget, sdk.frameworkDllNames()).first - } ?: emptyList() - - val bcl = sdk.references() - val project = projectLibrary(info, dir, sources, references + bcl) - val table = CsSymbolTable(linesFor(bcl + references + listOfNotNull(project))) - - tables[dir.toAbsolutePath().normalize()] = table - return table - } - - /** Returns the last table built for [dir], without running the symbol tool. */ - fun cachedTable(dir: Path): CsSymbolTable? = - tables[dir.toAbsolutePath().normalize()] - - // Project assembly - - /** - * Compiles the project's sources into a library the symbol tool can inspect. - * - * Recompiles when a source file's modification time changes. If compilation fails, - * the last successfully compiled library is retained. Sources are read from disk, - * not from the editor's unsaved buffer. - */ - suspend fun projectLibrary( - info: CsprojInfo?, - dir: Path, - sources: List, - references: List, - ): Path? { - if (sources.isEmpty()) return null - - val key = stampOf(sources) - return killableTool { cancellation -> - compileProject(key, info, dir, sources, references, cancellation) - } - } - - @Synchronized - private fun compileProject( - key: String, - info: CsprojInfo?, - dir: Path, - sources: List, - references: List, - cancellation: ToolCancellation, - ): Path? { - if (key == projectKey && projectOwner == dir) return projectDll - - val work = sdk.home.resolve("symbols") - Files.createDirectories(work) - - val out = work.resolve("project-" + Integer.toHexString(dir.toString().hashCode()) + ".dll") - val usingsText = Csproj.globalUsingsText(info) - val usings = work.resolve("GlobalUsings.g.cs").takeIf { usingsText.isNotEmpty() } - - usings?.let { - Files.write(it, usingsText.toByteArray(Charsets.UTF_8)) - } - - val arguments = if (info != null) { - Csproj.arguments(info, sources, references, out, usings, forceLibrary = true) - } else { - // Use the same plain library arguments as the editor's check without a project file. - buildList { - add("-nologo") - add("-noconfig") - add("-target:library") - add("-out:$out") - references.forEach { add("-r:$it") } - sources.forEach { add(it.toString()) } - } - } - - val exitCode = CsCompilerHost.compile(sdk, arguments, cancellation) { - Log.d(TAG, "project types> $it") - } - Log.d(TAG, "project types: compile exit $exitCode") - - if (exitCode == 0 && Files.isRegularFile(out)) { - projectKey = key - projectDll = out - projectOwner = dir - } - - return projectDll?.takeIf { projectOwner == dir } - } - - // Symbol tool - - /** Builds a cache key from each file path and its last modification time. */ - private fun stampOf(paths: List): String = - paths.joinToString("|") { path -> - "$path@" + runCatching { - Files.getLastModifiedTime(path).toMillis() - }.getOrDefault(0L) - } - - /** Runs the symbol tool when [key] differs from the last successful run. */ - @Synchronized - private fun runTool( - key: String, - dlls: List, - cancellation: ToolCancellation, - ): List { - if (key == cacheKey) return cached - - val launcher = sdk.launcher ?: return emptyList() - val tool = ensureTool(cancellation) ?: return emptyList() - - val process = ProcessBuilder( - listOf(launcher.toString(), tool.toString()) + dlls.map { it.toString() } - ) - .redirectErrorStream(true) - .apply { environment().putAll(sdk.environment()) } - .start() - - cancellation.attach(process) - runCatching { process.outputStream.close() } - - val output = process.inputStream.bufferedReader().readLines() - val exitCode = process.waitFor() - - Log.d(TAG, "symbols: tool exit $exitCode, ${output.size} lines for ${dlls.size} dll(s)") - - if (exitCode != 0) return emptyList() - - cacheKey = key - cached = output.filter { - it.startsWith("type\t") || it.startsWith("member\t") - } - - return cached - } - - /** Builds the symbol tool when its source changes or its DLL is missing. */ - private fun ensureTool(cancellation: ToolCancellation): Path? { - val dir = sdk.home.resolve("tools") - val source = dir.resolve("SymbolDump.cs") - val dll = dir.resolve("SymbolDump.dll") - - val current = runCatching { - String(Files.readAllBytes(source), Charsets.UTF_8) - }.getOrNull() - - if (current == TOOL_SOURCE && Files.isRegularFile(dll)) { - ensureRuntimeConfig(dir.resolve("SymbolDump.runtimeconfig.json")) - return dll - } - - Files.createDirectories(dir) - Files.write(source, TOOL_SOURCE.toByteArray(Charsets.UTF_8)) - ensureRuntimeConfig(dir.resolve("SymbolDump.runtimeconfig.json")) - Files.deleteIfExists(dll) - - val arguments = buildList { - add("-nologo") - add("-noconfig") - add("-target:exe") - add("-out:$dll") - sdk.references().forEach { add("-r:$it") } - add(source.toString()) - } - - val code = CsCompilerHost.compile(sdk, arguments, cancellation) { - Log.d(TAG, "symbols tool> $it") - } - - if (code != 0 || !Files.isRegularFile(dll)) { - Log.d(TAG, "symbols: the tool did not build (exit $code)") - return null - } - - return dll - } - - private companion object { - - /** No string interpolation is used in this embedded C# source. */ - val TOOL_SOURCE = """using System; - using System.IO; - using System.Reflection; - using System.Reflection.Metadata; - using System.Reflection.Metadata.Ecma335; - using System.Reflection.PortableExecutable; - - static class SymbolDump - { - static int Main(string[] args) - { - foreach (string path in args) - { - using (var stream = File.OpenRead(path)) - using (var pe = new PEReader(stream)) - { - MetadataReader reader = pe.GetMetadataReader(); - foreach (TypeDefinitionHandle handle in reader.TypeDefinitions) - { - TypeDefinition type = reader.GetTypeDefinition(handle); - if ((type.Attributes & TypeAttributes.VisibilityMask) != TypeAttributes.Public) continue; - string rawName = reader.GetString(type.Name); - if (rawName == "") continue; - - string ns = reader.GetString(type.Namespace); - if (ns.Length == 0) ns = "-"; - string name = rawName.Split('`')[0]; - string kind = (type.Attributes & TypeAttributes.Interface) != 0 ? "interface" : "class"; - bool isStatic = (type.Attributes & TypeAttributes.Abstract) != 0 && (type.Attributes & TypeAttributes.Sealed) != 0; - Console.WriteLine("type\t" + ns + "\t" + name + "\t" + kind + "\t" + (isStatic ? "1" : "0")); - - foreach (MethodDefinitionHandle mh in type.GetMethods()) - { - MethodDefinition m = reader.GetMethodDefinition(mh); - if ((m.Attributes & MethodAttributes.Public) == 0) continue; - if ((m.Attributes & MethodAttributes.SpecialName) != 0) continue; - string mname = reader.GetString(m.Name); - bool mstatic = (m.Attributes & MethodAttributes.Static) != 0; - int pcount = 0; - foreach (ParameterHandle ph in m.GetParameters()) - { - if (reader.GetParameter(ph).SequenceNumber > 0) pcount++; - } - Console.WriteLine("member\t" + ns + "\t" + name + "\tmethod\t" + mname + "\t" + (mstatic ? "1" : "0") + "\t" + pcount); - } - - foreach (FieldDefinitionHandle fh in type.GetFields()) - { - FieldDefinition f = reader.GetFieldDefinition(fh); - if ((f.Attributes & FieldAttributes.Public) == 0) continue; - string fname = reader.GetString(f.Name); - bool fstatic = (f.Attributes & FieldAttributes.Static) != 0; - Console.WriteLine("member\t" + ns + "\t" + name + "\tfield\t" + fname + "\t" + (fstatic ? "1" : "0")); - } - - foreach (PropertyDefinitionHandle ph in type.GetProperties()) - { - PropertyDefinition p = reader.GetPropertyDefinition(ph); - PropertyAccessors accessors = p.GetAccessors(); - if (accessors.Getter.IsNil) continue; - MethodDefinition getter = reader.GetMethodDefinition(accessors.Getter); - if ((getter.Attributes & MethodAttributes.Public) == 0) continue; - bool pstatic = (getter.Attributes & MethodAttributes.Static) != 0; - string pname = reader.GetString(p.Name); - Console.WriteLine("member\t" + ns + "\t" + name + "\tproperty\t" + pname + "\t" + (pstatic ? "1" : "0")); - } - } - } - } - return 0; - } - } - """ - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsWords.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsWords.kt deleted file mode 100644 index 2006aab695..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsWords.kt +++ /dev/null @@ -1,65 +0,0 @@ -package dev.codeassist.csharp.completion - -import dev.codeassist.csharp.project.CsMainScan - -/** - * Finds names already used in a file for completion. - * - * This is text-based and does not understand scope, so a name from another method can also be offered. - * Comments, strings, and preprocessor lines are masked by [CsMainScan.mask]. - */ -internal object CsWords { - - /** A word found in the file, marked when it looks like a declaration. */ - class Word(val name: String, val declared: Boolean) - - private val wordPattern = Regex("""[A-Za-z_]\w*""") - - /** - * Matches a type followed by a variable name and a declaration-like token. - * Covers locals, fields, parameters, and foreach variables. - * - * This is heuristic: expressions such as `return x;` can also match. - */ - private val declarationPattern = Regex( - """(?)?(?:\[[,\s]*]\??)*\??\s+([A-Za-z_]\w*)\s*(?=[=;,)]|\bin\b)""" - ) - - /** - * Returns up to [limit] distinct accepted words, nearest to [caret] first. - * Excludes keywords, member names after dots, and the word containing the caret. - */ - fun nearby( - text: String, - caret: Int, - accept: (String) -> Boolean, - limit: Int = 30, - ): List { - val clean = CsMainScan.mask(text) - val declared = declarationPattern.findAll(clean) - .map { it.groupValues[1] } - .toSet() - - val distance = HashMap() - - for (match in wordPattern.findAll(clean)) { - val start = match.range.first - val end = match.range.last + 1 - - if (caret in start..end) continue - if (start > 0 && (clean[start - 1] == '.' || clean[start - 1].isDigit())) continue - - val word = match.value - if (word in CsKeywords.ALL || !accept(word)) continue - - val away = if (caret < start) start - caret else caret - end - distance.merge(word, away, ::minOf) - } - - return distance.entries - .sortedBy { it.value } - .take(limit) - .map { Word(it.key, it.key in declared) } - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsprojCompletionContributor.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsprojCompletionContributor.kt deleted file mode 100644 index a27301407e..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/completion/CsprojCompletionContributor.kt +++ /dev/null @@ -1,58 +0,0 @@ -package dev.codeassist.csharp.completion - -import dev.codeassist.csharp.project.csproj.CsprojCompleter -import dev.ide.lang.LanguageId -import dev.ide.lang.completion.CaretAction -import dev.ide.lang.completion.CompletionContribution -import dev.ide.lang.completion.CompletionContributor -import dev.ide.lang.completion.CompletionItem -import dev.ide.lang.completion.CompletionItemKind -import dev.ide.lang.completion.CompletionParams -import dev.ide.lang.completion.CompletionResultSet - -/** - * Provides completion in .csproj, .props, and .targets files using [CsprojCompleter]. - * - * Device behavior still needs verification: whether the host invokes contributors without a language - * backend, and what [CompletionParams.replacementRange] covers around `<`, `"` and `.`. - */ -internal class CsprojCompletionContributor : CompletionContributor { - - override val id = "csharp.csproj" - - override suspend fun fillCompletionVariants( - params: CompletionParams, - result: CompletionResultSet, - ) { - val text = params.document.text.toString() - val caret = params.replacementRange.end.coerceIn(0, text.length) - - // Use only project-file suggestions; buffer words are not useful in XML. - result.stopHere() - - for (suggestion in CsprojCompleter.suggest(text, caret)) { - val kind = when (suggestion.kind) { - CsprojCompleter.Kind.TAG -> CompletionItemKind.CLASS - CsprojCompleter.Kind.ATTRIBUTE -> CompletionItemKind.FIELD - CsprojCompleter.Kind.VALUE -> CompletionItemKind.VARIABLE - } - - result.addElement( - CompletionItem( - label = suggestion.label, - insertText = suggestion.insert, - kind = kind, - detail = suggestion.detail, - caret = suggestion.caret?.let { CaretAction.At(it) } ?: CaretAction.AtEnd, - ), - ) - } - } -} - -/** Registers the contributor for the csproj language. */ -internal fun csprojCompletionContribution(): CompletionContribution = - CompletionContribution( - contributor = CsprojCompletionContributor(), - languages = setOf(LanguageId("csproj")), - ) diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsDeclarationProvider.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsDeclarationProvider.kt deleted file mode 100644 index 357c6133a5..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsDeclarationProvider.kt +++ /dev/null @@ -1,39 +0,0 @@ -package dev.codeassist.csharp.editor - -import dev.codeassist.csharp.CSharpPlugin -import dev.codeassist.csharp.completion.CsSemanticCompletion -import dev.ide.analysis.AnalysisTarget -import dev.ide.analysis.DECLARATION_PROVIDER_EP -import dev.ide.analysis.DeclarationProvider -import dev.ide.analysis.NavigationTarget -import dev.ide.lang.LanguageId -import dev.ide.plugin.PluginRegistration - -/** - * Go to Declaration for C#: Roslyn resolves the name at the caret and says where the project declares it. - * A symbol from the framework or a package has no source here and gives no target. - */ -internal class CsDeclarationProvider( - private val semantic: CsSemanticCompletion, -) : DeclarationProvider { - - override val id = "csharp.declaration" - override val languages = setOf(LanguageId(CSharpPlugin.LANGUAGE)) - - override suspend fun declarations(target: AnalysisTarget, offset: Int): List { - CsModules.remember(target.module) - val found = semantic.definitionsAt(target.file.path, target.parsed.text().toString(), offset) - ?: return emptyList() - return found.map { NavigationTarget(it.path, it.offset, it.label) } - } -} - -/** - * Registers [CsDeclarationProvider]. A class of its own so that a host without the extension point - * (before SPI 3.1.0) fails to link here, where the caller guards it, and not in the plugin's entry point. - */ -internal object CsNavigationRegistration { - fun register(reg: PluginRegistration, semantic: CsSemanticCompletion) { - reg.register(DECLARATION_PROVIDER_EP, CsDeclarationProvider(semantic)) - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsFileNames.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsFileNames.kt deleted file mode 100644 index 41e6d3237d..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsFileNames.kt +++ /dev/null @@ -1,91 +0,0 @@ -package dev.codeassist.csharp.editor - -import dev.codeassist.csharp.project.CsMainScan - -/** - * Checks the convention of naming a C# file after its single public type. - * - * C# does not require this convention, so a mismatch is only a hint. - */ -internal object CsFileNames { - - /** A public type declaration and the location of its name in the source. */ - class Mismatch( - val name: String, - val start: Int, - val end: Int, - ) - - private val typeDeclaration = Regex( - """^\s*(?:\[[^\]]*]\s*)*((?:(?:public|internal|static|sealed|abstract|partial|readonly|ref|unsafe|file|""" + - """protected|private|new)\s+)*)""" + - """(?:class|struct|interface|enum|record(?:\s+(?:class|struct))?|delegate\s+\S+)\s+([A-Za-z_]\w*)""", - ) - - /** - * Returns the public type whose name does not match [fileName], or null. - * - * Only files containing exactly one public type are considered. Files with top-level - * statements are ignored. Partial types may use names such as `Person.Part.cs`. - */ - fun mismatch(text: String, fileName: String): Mismatch? { - if (!fileName.endsWith(".cs", ignoreCase = true)) return null - if (CsMainScan.topLevel(text) != null) return null - - val stem = fileName.dropLast(3) - val onlyType = publicTypes(text).singleOrNull() ?: return null - - if (stem == onlyType.name || stem.startsWith("${onlyType.name}.")) { - return null - } - - return onlyType - } - - /** Finds public type declarations at namespace scope, in source order. */ - internal fun publicTypes(text: String): List { - val masked = CsMainScan.mask(text) - val found = ArrayList() - val namespaceScopes = ArrayList() - var headerStart = 0 - - for (i in masked.indices) { - val char = masked[i] - if (char != '{' && char != '}' && char != ';') continue - - if (char == '}') { - if (namespaceScopes.isNotEmpty()) { - namespaceScopes.removeAt(namespaceScopes.lastIndex) - } - } else { - val header = masked.substring(headerStart, i) - - if (namespaceScopes.all { it }) { - findPublicType(header, headerStart)?.let(found::add) - } - - if (char == '{') { - namespaceScopes.add(Regex("""\bnamespace\b""").containsMatchIn(header)) - } - } - - headerStart = i + 1 - } - - return found - } - - private fun findPublicType(header: String, headerStart: Int): Mismatch? { - val match = typeDeclaration.find(header) ?: return null - if (!Regex("""\bpublic\b""").containsMatchIn(match.groupValues[1])) return null - - val name = match.groups[2] ?: return null - val start = headerStart + name.range.first - - return Mismatch( - name = name.value, - start = start, - end = start + name.value.length, - ) - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsLanguageBackend.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsLanguageBackend.kt deleted file mode 100644 index a61de1a280..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsLanguageBackend.kt +++ /dev/null @@ -1,319 +0,0 @@ -package dev.codeassist.csharp.editor - - -import dev.codeassist.csharp.CSharpPlugin -import dev.codeassist.csharp.completion.CsDocText -import dev.codeassist.csharp.completion.CsNavigationLines -import dev.codeassist.csharp.completion.CsSemanticCompletion -import dev.codeassist.csharp.editor.CsSourceAnalyzer.TextFile -import dev.ide.lang.AnalysisResult -import dev.ide.lang.BackendCapability -import dev.ide.lang.CompilationContext -import dev.ide.lang.LanguageBackend -import dev.ide.lang.LanguageId -import dev.ide.lang.SourceAnalyzer -import dev.ide.lang.dom.Diagnostic -import dev.ide.lang.dom.DomNode -import dev.ide.lang.dom.NodeKind -import dev.ide.lang.dom.ParsedFile -import dev.ide.lang.dom.TextRange -import dev.ide.lang.folding.FoldKind -import dev.ide.lang.folding.FoldRegion -import dev.ide.lang.folding.FoldingService -import dev.ide.lang.formatting.FormatStyle -import dev.ide.lang.formatting.FormattingService -import dev.ide.lang.highlight.HighlightKind -import dev.ide.lang.highlight.HighlightModifier -import dev.ide.lang.highlight.SemanticHighlightService -import dev.ide.lang.highlight.SemanticToken -import dev.ide.lang.hints.InlayHintService -import dev.ide.lang.imports.ImportOrganizerService -import dev.ide.lang.incremental.DocumentEdit -import dev.ide.lang.incremental.DocumentSnapshot -import dev.ide.lang.incremental.IncrementalParser -import dev.ide.lang.incremental.ReparseResult -import dev.ide.lang.resolve.DocFormat -import dev.ide.lang.resolve.QuickDocInfo -import dev.ide.lang.resolve.ResolveResult -import dev.ide.lang.resolve.Scope -import dev.ide.lang.resolve.StructureItem -import dev.ide.lang.resolve.Symbol -import dev.ide.lang.resolve.SymbolFilter -import dev.ide.lang.resolve.SymbolKind -import dev.ide.lang.resolve.TypeRef -import dev.ide.lang.signature.SignatureHelpService -import dev.ide.vfs.VirtualFile -import java.util.concurrent.ConcurrentHashMap -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.runBlocking - -/** - * Minimal C# backend that lets the host create parsed files and analysis targets. - * - * It represents each source file as one node containing the entire buffer. It does not parse - * syntax or resolve symbols itself: parameter help, the colouring of names and quick documentation are - * answered by Roslyn through [CsSemanticCompletion]. - * Without a backend the host builds no parsed tree for a `.cs` file, so the file gets no analysis - * target and the diagnostic provider is never asked about it. - */ -class CsLanguageBackend internal constructor( - private val signatureHelp: SignatureHelpService? = null, - private val semantic: CsSemanticCompletion? = null, -) : LanguageBackend { - - override val id = "csharp" - override val languages = setOf(LanguageId(CSharpPlugin.LANGUAGE)) - override val capabilities = setOf( - BackendCapability.ERROR_RECOVERY, - BackendCapability.SIGNATURE_HELP, - BackendCapability.SEMANTIC_HIGHLIGHT, - BackendCapability.CODE_FOLDING, - BackendCapability.FORMAT, - ) - - override fun createAnalyzer(ctx: CompilationContext): SourceAnalyzer = - CsSourceAnalyzer(signatureHelp, semantic) -} - -internal class CsSourceAnalyzer( - override val signatureHelp: SignatureHelpService? = null, - private val semantic: CsSemanticCompletion? = null, -) : SourceAnalyzer { - - /** The last buffer handed to [incrementalParser] per file: the host refreshes it before asking for tokens. */ - private val buffers = ConcurrentHashMap() - - // Parsing - - override val incrementalParser: IncrementalParser = object : IncrementalParser { - - override fun parseFull(snapshot: DocumentSnapshot): ParsedFile { - buffers[snapshot.file.path] = snapshot.text - return TextFile(snapshot.file, snapshot.version, snapshot.text) - } - - override fun reparse( - previous: ParsedFile, - newSnapshot: DocumentSnapshot, - edits: List, - ): ReparseResult { - val tree = parseFull(newSnapshot) - return ReparseResult(tree, tree.range, reusedSubtrees = 0) - } - } - - override suspend fun parsedFile(file: VirtualFile): ParsedFile { - return TextFile(file, 0, "") - } - - // Optional editor services - - override val inlayHints: InlayHintService? = null - /** - * Colours each name by what Roslyn resolves it to: a type, a method, a parameter, a local. No answer - * (the server is not up, the file is in no project) leaves the editor's keyword colouring as it is. - */ - override val semanticHighlighter: SemanticHighlightService? = semantic?.let { service -> - object : SemanticHighlightService { - override suspend fun highlight(file: VirtualFile): List { - val text = buffers[file.path]?.toString() ?: return emptyList() - val tokens = try { - service.tokensFor(file.path, text) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - null - } ?: return emptyList() - - return tokens.mapNotNull { token -> - if (token.start + token.length > text.length) return@mapNotNull null - SemanticToken( - TextRange(token.start, token.start + token.length), - HighlightKind(token.kind), - token.modifiers.mapNotNullTo(HashSet()) { MODIFIERS[it] }, - ) - } - } - } - } - - /** The signature and summary of the symbol at [offset], from Roslyn. */ - override fun quickDoc(file: VirtualFile, text: CharSequence, offset: Int): QuickDocInfo? { - val service = semantic ?: return null - val hover = runCatching { - runBlocking { service.hoverAt(file.path, text.toString(), offset) } - }.getOrNull() ?: return null - - return QuickDocInfo( - signature = hover.signature, - name = hover.name, - kind = KINDS[hover.kind] ?: SymbolKind.FIELD, - container = hover.container.ifEmpty { null }, - doc = CsDocText.summary(hover.documentation), - docFormat = DocFormat.PLAIN, - ) - } - /** The last outline asked for, by file: folding and the structure view ask for the same text in turn. */ - private val outlines = ConcurrentHashMap>() - - private suspend fun outlineOf(path: String, text: String): CsNavigationLines.Outline? { - val key = text.hashCode() - outlines[path]?.let { if (it.first == key) return it.second } - val outline = semantic?.outlineFor(path, text) ?: return null - outlines[path] = key to outline - return outline - } - - override val folding: FoldingService? = semantic?.let { - object : FoldingService { - override suspend fun folds(file: VirtualFile): List { - val text = buffers[file.path]?.toString() ?: return emptyList() - val outline = try { - outlineOf(file.path, text) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - null - } ?: return emptyList() - - return outline.folds.mapNotNull { fold -> - if (fold.end > text.length) return@mapNotNull null - FoldRegion( - TextRange(fold.start, fold.end), - fold.placeholder, - FoldKind(fold.kind), - collapsedByDefault = false, - ) - } - } - } - } - - /** The file's declarations, for the structure view and the sticky headers. */ - override fun fileStructure(file: VirtualFile, text: CharSequence): List { - val outline = runCatching { - runBlocking { outlineOf(file.path, text.toString()) } - }.getOrNull() ?: return emptyList() - - return outline.items.map { item -> - StructureItem( - name = item.name, - detail = item.detail.ifEmpty { null }, - kind = KINDS[item.kind] ?: SymbolKind.FIELD, - nameOffset = item.nameOffset, - endOffset = item.end, - depth = item.depth, - ) - } - } - /** - * Reformats with Roslyn's formatter, to C#'s own conventions: braces on their own lines, four spaces. - * Of the editor's style only tabs or spaces is taken, since its other settings are Java's and Kotlin's. - */ - override val formatting: FormattingService? = semantic?.let { service -> - object : FormattingService { - override suspend fun format(file: VirtualFile, text: CharSequence, style: FormatStyle): List = - edits(file, text, -1, -1, style) - - override suspend fun formatRange( - file: VirtualFile, - text: CharSequence, - range: TextRange, - style: FormatStyle, - ): List = edits(file, text, range.start, range.end, style) - - private suspend fun edits(file: VirtualFile, text: CharSequence, start: Int, end: Int, style: FormatStyle): List { - val source = text.toString() - val found = try { - service.formatEdits(file.path, source, start, end, CS_INDENT, style.useTabs) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - null - } ?: return emptyList() - - return found - .filter { it.offset + it.length <= source.length } - .map { DocumentEdit(it.offset, it.length, it.text) } - } - } - } - override val importOrganizer: ImportOrganizerService? = null - - // Analysis and resolution - - override suspend fun analyze(file: VirtualFile): AnalysisResult = - AnalysisResult(file, emptyList()) - - override fun resolve(node: DomNode): ResolveResult = - ResolveResult.Unresolved - - override fun scopeAt(file: VirtualFile, offset: Int): Scope = - EmptyScope - - override fun expectedTypeAt(file: VirtualFile, offset: Int): TypeRef? = null - - // Parsed file - - /** Represents the entire source buffer as a single node. */ - private class TextFile( - override val file: VirtualFile, - override val documentVersion: Long, - private val text: CharSequence, - ) : ParsedFile { - - override val kind = NodeKind("csharp.file") - override val range = TextRange(0, text.length) - override val parent: DomNode? = null - override val children: List = emptyList() - override val diagnostics: List = emptyList() - - override fun text(): CharSequence = text - - override fun nodeAt(offset: Int): DomNode = this - - override fun nodesIn(range: TextRange): Sequence = - sequenceOf(this) - } - - private companion object { - /** C#'s conventional indentation. */ - const val CS_INDENT = 4 - - val MODIFIERS = mapOf( - "declaration" to HighlightModifier.DECLARATION, - "static" to HighlightModifier.STATIC, - "abstract" to HighlightModifier.ABSTRACT, - "deprecated" to HighlightModifier.DEPRECATED, - "readonly" to HighlightModifier.READONLY, - "extension" to HighlightModifier.EXTENSION, - ) - - /** The server's word for a symbol, as the kind quick documentation is headed with. */ - val KINDS = mapOf( - "namespace" to SymbolKind.PACKAGE, - "class" to SymbolKind.CLASS, - "interface" to SymbolKind.INTERFACE, - "enum" to SymbolKind.ENUM, - "typeParameter" to SymbolKind.TYPE_PARAMETER, - "method" to SymbolKind.METHOD, - "function" to SymbolKind.METHOD, - "constructor" to SymbolKind.CONSTRUCTOR, - "property" to SymbolKind.FIELD, - "field" to SymbolKind.FIELD, - "constant" to SymbolKind.FIELD, - "enumConstant" to SymbolKind.ENUM_CONSTANT, - "parameter" to SymbolKind.PARAMETER, - "localVariable" to SymbolKind.LOCAL_VARIABLE, - ) - } - - private object EmptyScope : Scope { - override val enclosing: Scope? = null - - override fun symbols(filter: SymbolFilter): List = emptyList() - - override fun resolve(name: String): ResolveResult = - ResolveResult.Unresolved - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsModules.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsModules.kt deleted file mode 100644 index 2b4569a2f6..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsModules.kt +++ /dev/null @@ -1,27 +0,0 @@ -package dev.codeassist.csharp.editor - -import dev.ide.model.Module - -/** - * The modules this plugin has been handed, by folder, so a file path can be traced to its module. - * The editor's decoration pass gets only a path, and a run mark needs the module's name (the Run row's id carries it). - * Modules are remembered when the diagnostics or the Run picker see them. - */ -internal object CsModules { - private val byDir = LinkedHashMap() - - @Synchronized - fun remember(module: Module) { - byDir[module.dir.path.trimEnd('/')] = module - } - - /** The module owning path: the longest remembered folder that contains it. */ - @Synchronized - fun forPath(path: String): Module? = - byDir.entries.filter { - path.startsWith(it.key + "/") - - }.maxByOrNull { - it.key.length - }?.value -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsReferenceProviders.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsReferenceProviders.kt deleted file mode 100644 index 5172676873..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsReferenceProviders.kt +++ /dev/null @@ -1,155 +0,0 @@ -package dev.codeassist.csharp.editor - -import dev.codeassist.csharp.CSharpPlugin -import dev.codeassist.csharp.completion.CsNavigationLines -import dev.codeassist.csharp.completion.CsSemanticCompletion -import dev.ide.analysis.AnalysisTarget -import dev.ide.analysis.REFERENCE_PROVIDER_EP -import dev.ide.analysis.RENAME_PROVIDER_EP -import dev.ide.analysis.ReferenceProvider -import dev.ide.analysis.RenameProvider -import dev.ide.analysis.RenameResult -import dev.ide.analysis.RenameTarget -import dev.ide.analysis.SymbolReference -import dev.ide.analysis.WorkspaceEdit -import dev.ide.lang.LanguageId -import dev.ide.lang.dom.TextRange -import dev.ide.lang.highlight.UsageAccess -import dev.ide.lang.highlight.UsageHighlight -import dev.ide.lang.incremental.DocumentEdit -import dev.ide.platform.ContentHash -import dev.ide.plugin.PluginRegistration -import dev.ide.vfs.VirtualFile -import java.nio.file.Files -import java.nio.file.Paths - -/** - * Find Usages for C#, and the highlighting of a name's other uses in the file: Roslyn resolves the name at - * the caret and every place in the project that resolves to the same symbol is a usage. - */ -internal class CsReferenceProvider( - private val semantic: CsSemanticCompletion, -) : ReferenceProvider { - - override val id = "csharp.references" - override val languages = setOf(LanguageId(CSharpPlugin.LANGUAGE)) - - override suspend fun references( - target: AnalysisTarget, - offset: Int, - includeDeclaration: Boolean, - ): List { - val found = find(target, offset) ?: return emptyList() - return found.places - .filter { includeDeclaration || it.access != DECLARED } - .map { SymbolReference(it.path, TextRange(it.start, it.end), it.access == DECLARED) } - } - - override suspend fun highlights(target: AnalysisTarget, offset: Int): List? { - val found = find(target, offset) ?: return null - val here = runCatching { Paths.get(target.file.path).toAbsolutePath().normalize().toString() } - .getOrDefault(target.file.path) - return found.places.filter { it.path == here }.map { - val access = when (it.access) { - DECLARED -> UsageAccess.DECLARATION - WRITTEN -> UsageAccess.WRITE - else -> UsageAccess.READ - } - UsageHighlight(TextRange(it.start, it.end), access) - } - } - - private suspend fun find(target: AnalysisTarget, offset: Int): CsNavigationLines.References? { - CsModules.remember(target.module) - return semantic.referencesAt(target.file.path, target.parsed.text().toString(), offset) - } - - private companion object { - const val DECLARED = 'd' - const val WRITTEN = 'w' - } -} - -/** - * Rename for C#: every place Find Usages reports takes the new name. A symbol the project does not declare - * (a framework or package type) is refused, since its declaration cannot be changed. - */ -internal class CsRenameProvider( - private val semantic: CsSemanticCompletion, -) : RenameProvider { - - override val id = "csharp.rename" - override val languages = setOf(LanguageId(CSharpPlugin.LANGUAGE)) - - override suspend fun prepare(target: AnalysisTarget, offset: Int): RenameTarget? { - val found = semantic.referencesAt(target.file.path, target.parsed.text().toString(), offset) ?: return null - if (!found.symbol.inSource) return null - return RenameTarget(found.symbol.name, TextRange(found.symbol.start, found.symbol.end), found.symbol.kind) - } - - override suspend fun rename(target: AnalysisTarget, offset: Int, newName: String): RenameResult { - val name = newName.trim() - if (!IDENTIFIER.matches(name)) return RenameResult.rejected("\"$newName\" is not a valid C# name.") - if (name in KEYWORDS) return RenameResult.rejected("\"$name\" is a C# keyword. Write @$name to use it as a name.") - - val found = semantic.referencesAt(target.file.path, target.parsed.text().toString(), offset) - ?: return RenameResult.rejected("There is nothing to rename here.") - if (!found.symbol.inSource) { - return RenameResult.rejected("${found.symbol.name} is not declared in this project, so it cannot be renamed.") - } - if (found.places.isEmpty()) return RenameResult.rejected("No use of ${found.symbol.name} was found.") - - val edits = found.places - .groupBy { it.path } - .mapKeys { (path, _) -> CsFile(path) as VirtualFile } - .mapValues { (_, places) -> - // Last first, so that each edit's offsets are still those of the text as it was read. - places.distinctBy { it.start }.sortedByDescending { it.start } - .map { DocumentEdit(it.start, it.end - it.start, name) } - } - return RenameResult.of(WorkspaceEdit(edits)) - } - - private companion object { - val IDENTIFIER = Regex("""@?[\p{L}_][\p{L}\p{Nd}_]*""") - val KEYWORDS = setOf( - "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", - "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", - "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", - "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", - "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", - "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", - "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", - "while", - ) - } -} - -/** A file on disk that a [WorkspaceEdit] edits. The host reads only its [path]. */ -internal class CsFile(override val path: String) : VirtualFile { - override val name: String get() = path.substringAfterLast('/') - override val isDirectory: Boolean get() = false - override val exists: Boolean get() = true - override val length: Long get() = runCatching { Files.size(Paths.get(path)) }.getOrDefault(0L) - override fun parent(): VirtualFile? = null - override fun children(): List = emptyList() - override fun contentHash(): ContentHash = ContentHash.of(readBytes()) - override fun readBytes(): ByteArray = runCatching { Files.readAllBytes(Paths.get(path)) }.getOrDefault(ByteArray(0)) - override fun readText(): CharSequence = String(readBytes()) - override fun equals(other: Any?): Boolean = other is CsFile && other.path == path - override fun hashCode(): Int = path.hashCode() -} - -/** - * Registers Find Usages and Rename. Each in a call of its own: a host that has one extension point and not - * the other keeps the one it has. - */ -internal object CsReferenceRegistration { - fun references(reg: PluginRegistration, semantic: CsSemanticCompletion) { - reg.register(REFERENCE_PROVIDER_EP, CsReferenceProvider(semantic)) - } - - fun rename(reg: PluginRegistration, semantic: CsSemanticCompletion) { - reg.register(RENAME_PROVIDER_EP, CsRenameProvider(semantic)) - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsRunGutter.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsRunGutter.kt deleted file mode 100644 index 606d6e364f..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsRunGutter.kt +++ /dev/null @@ -1,102 +0,0 @@ -package dev.codeassist.csharp.editor - - -import dev.codeassist.csharp.build.tasks.CsRunIds -import dev.codeassist.csharp.project.CsMainScan -import dev.codeassist.csharp.project.CsMains -import dev.codeassist.csharp.project.CsRunConfig -import dev.codeassist.csharp.project.csproj.Csproj -import dev.ide.plugin.editor.DecorationTint -import dev.ide.plugin.editor.EditorDecorationContext -import dev.ide.plugin.editor.EditorDecorationProvider -import dev.ide.plugin.editor.EditorDecorations -import dev.ide.plugin.editor.GutterMark -import java.nio.file.Paths - -/** - * Adds Run gutter marks for C# entry points. - * - * Top-level statements get one mark on the first statement, which runs the module's default task. - * Otherwise, every `Main` gets a mark. The configured entry point uses the module's task; other - * classes use their own tasks when the project has multiple class run configurations. - * - * The action ID is the plugin API's run action (`GutterActions.RUN_TASK_PREFIX`) followed by a Run task ID, - * which the editor starts as a run. - * - * The module is resolved through [CsModules], which is populated when diagnostics or the Run - * picker first encounters it. Marks may therefore appear after the editor's first check. - * A `Main` added but not yet saved may refer to a task that does not exist yet. - */ -internal class CsRunGutter : EditorDecorationProvider { - - override val id = "csharp.run.gutter" - - override fun appliesTo(ctx: EditorDecorationContext): Boolean = - ctx.path.endsWith(".cs", ignoreCase = true) - - override suspend fun decorate(ctx: EditorDecorationContext): EditorDecorations { - val module = CsModules.forPath(ctx.path) ?: return EditorDecorations.EMPTY - val dir = Paths.get(module.dir.path) - - if (Csproj.load(dir)?.isLibrary == true) { - return EditorDecorations.EMPTY - } - - val topLevel = CsMainScan.topLevel(ctx.text) - if (topLevel != null) { - return topLevelDecoration(ctx, module, topLevel) - } - - return mainDecorations(ctx, module, dir) - } - - private fun topLevelDecoration( - ctx: EditorDecorationContext, - module: dev.ide.model.Module, - firstStatement: Int, - ): EditorDecorations { - return EditorDecorations( - gutter = listOf( - GutterMark( - line = CsMainScan.lineOf(ctx.text, firstStatement), - iconId = "run", - tint = DecorationTint.Success, - tooltip = "Run ${module.name}", - actionId = CsRunIds.GUTTER_ACTION_PREFIX + CsRunIds.taskId(module.name), - order = 100, - ), - ), - ) - } - - private fun mainDecorations( - ctx: EditorDecorationContext, - module: dev.ide.model.Module, - dir: java.nio.file.Path, - ): EditorDecorations { - val hits = CsMainScan.hits(ctx.text) - if (hits.isEmpty()) return EditorDecorations.EMPTY - - val entry = CsMains.entry(dir, CsRunConfig.entryPoint(module, dir)) - val hasClassRows = CsMains.classRows(dir) - - return EditorDecorations( - gutter = hits.map { hit -> - val task = if (hasClassRows && hit.className != entry) { - CsRunIds.taskId(module.name, hit.className) - } else { - CsRunIds.taskId(module.name) - } - - GutterMark( - line = CsMainScan.lineOf(ctx.text, hit.offset), - iconId = "run", - tint = DecorationTint.Success, - tooltip = "Run ${CsRunIds.simpleName(hit.className)}", - actionId = CsRunIds.GUTTER_ACTION_PREFIX + task, - order = 100, - ) - }, - ) - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsSignatureHelp.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsSignatureHelp.kt deleted file mode 100644 index 62307a8db8..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsSignatureHelp.kt +++ /dev/null @@ -1,61 +0,0 @@ -package dev.codeassist.csharp.editor - - -import android.util.Log -import dev.codeassist.csharp.completion.CsDocText -import dev.codeassist.csharp.completion.CsSemanticCompletion -import dev.codeassist.csharp.util.TAG -import dev.ide.lang.signature.ParameterInfo -import dev.ide.lang.signature.SignatureHelp -import dev.ide.lang.signature.SignatureHelpRequest -import dev.ide.lang.signature.SignatureHelpService -import dev.ide.lang.signature.SignatureInfo -import kotlinx.coroutines.CancellationException - -/** - * Provides parameter information for C# calls. - * - * Roslyn finds the call at the caret and its overloads through - * [CsSemanticCompletion.signaturesAt]. This class converts the result into the - * editor's signature-help model. - */ -internal class CsSignatureHelp( - private val semantic: CsSemanticCompletion, -) : SignatureHelpService { - - override suspend fun signatureHelp(request: SignatureHelpRequest): SignatureHelp? { - val result = try { - semantic.signaturesAt( - request.document.file.path, - request.document.text.toString(), - request.offset, - ) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - Log.d(TAG, "signature help: could not answer: $e") - return null - } ?: return null - - return SignatureHelp( - signatures = result.signatures.map { signature -> - SignatureInfo( - label = signature.label, - parameters = signature.parameters.mapIndexed { index, range -> - ParameterInfo( - label = signature.label.substring(range.first, range.last + 1), - labelStart = range.first, - labelEnd = range.last + 1, - documentation = signature.names.getOrNull(index)?.let { name -> - CsDocText.param(signature.documentation, name) - }, - ) - }, - documentation = CsDocText.summary(signature.documentation), - ) - }, - activeSignature = result.activeSignature, - activeParameter = result.activeParameter, - ) - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsUsingCleanup.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsUsingCleanup.kt deleted file mode 100644 index 3b515e1392..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsUsingCleanup.kt +++ /dev/null @@ -1,210 +0,0 @@ -package dev.codeassist.csharp.editor - - -import java.util.concurrent.ConcurrentHashMap - -/** - * Removes unnecessary using directives and sorts the remaining ones. - * - * This is pure text processing and does not depend on the IDE or plugin API. - * - * CS8019 reports only "Unnecessary using directive" and a source position, - * without identifying the namespace. Therefore, unused directives are matched - * by their own trimmed text, such as `using System.Linq;`. - */ -internal object CsUsingCleanup { - - enum class Kind { - PLAIN, - STATIC, - ALIAS, - } - - /** A using directive at the beginning of a file. */ - class Directive( - val text: String, - val start: Int, - val end: Int, - val global: Boolean, - val kind: Kind, - val name: String, - ) - - /** A source edit replacing [length] characters at [offset] with [text]. */ - class Edit( - val offset: Int, - val length: Int, - val text: String, - ) - - /** The using directives found at the beginning of a file. */ - class Head( - val directives: List, - val onlyDirectives: Boolean, - ) - /** - * Matches using directives. - * - * Groups: - * 1. global modifier - * 2. static import type - * 3. alias name - * 4. namespace name - */ - private val DIRECTIVE = Regex( - """(global\s+)?using\s+(?:static\s+([\w.]+)|([A-Za-z_]\w*)\s*=\s*[^;]+|([A-Za-z_][\w.]*))\s*;.*""" - ) - - /** - * Finds using directives at the beginning of [source]. - * - * Only column-zero directives are recognized. [Head.onlyDirectives] - * indicates whether the section contains anything besides directives - * and blank lines. - * - * Comments and preprocessor directives prevent the entire section - * from being reorganized. - */ - fun head(source: String): Head { - val found = ArrayList() - var onlyDirectives = true - var inBlockComment = false - var start = 0 - - while (start < source.length) { - val newlineAt = source.indexOf('\n', start) - val end = if (newlineAt < 0) source.length else newlineAt + 1 - val text = source.substring(start, end).trim() - - when { - inBlockComment -> { - onlyDirectives = false - if ("*/" in text) inBlockComment = false - } - - text.isEmpty() -> Unit - - text.startsWith("//") || text.startsWith("#") -> { - onlyDirectives = false - } - - text.startsWith("/*") -> { - onlyDirectives = false - if ("*/" !in text) inBlockComment = true - } - - else -> { - // using var and using (...) are statements, not directives. - val match = ( - if (source[start].isWhitespace()) null - else DIRECTIVE.matchEntire(text) - ) ?: return Head(found, onlyDirectives) - - val kind = when { - match.groups[2] != null -> Kind.STATIC - match.groups[3] != null -> Kind.ALIAS - else -> Kind.PLAIN - } - - val name = ( - match.groups[2] - ?: match.groups[3] - ?: match.groups[4] - )!!.value - - found += Directive( - text = text.substringBefore(';') + ";", - start = start, - end = end, - global = match.groups[1] != null, - kind = kind, - name = name, - ) - } - } - - start = end - } - - return Head(found, onlyDirectives) - } - - /** Returns the directive on the line containing [offset], or null. */ - fun directiveAt(source: String, offset: Int): String? = - head(source).directives - .firstOrNull { offset in it.start until maxOf(it.end, it.start + 1) } - ?.text - - /** Removes the first directive matching [text]. */ - fun remove(source: String, text: String): List = - head(source).directives - .firstOrNull { it.text == text } - ?.let { - listOf(Edit(it.start, it.end - it.start, "")) - } - .orEmpty() - - /** - * Removes unused directives and sorts the remaining ones. - * - * Ordering: - * 1. Global directives before regular directives. - * 2. Plain, static and alias directives. - * 3. System namespaces before other namespaces. - * 4. Alphabetical order within each group. - * - * Duplicate directives are kept only once. - * - * If the section contains only directives and blank lines, the entire - * section is replaced with the organized result. Otherwise, only unused - * directives are removed, preserving comments and preprocessor directives. - */ - fun organize(source: String, unused: Set): List { - val head = head(source) - - if (head.directives.isEmpty()) return emptyList() - - if (!head.onlyDirectives) { - return head.directives - .filter { it.text in unused } - .map { Edit(it.start, it.end - it.start, "") } - } - - val newline = if (source.contains("\r\n")) "\r\n" else "\n" - - val kept = head.directives - .filter { it.text !in unused } - .distinctBy { it.text } - .sortedWith( - compareBy( - { if (it.global) 0 else 1 }, - { it.kind.ordinal }, - { systemFirst(it.name) }, - { it.name }, - ), - ) - - val start = head.directives.first().start - val end = head.directives.last().end - val block = kept.joinToString("") { it.text + newline } - - if (source.substring(start, end) == block) return emptyList() - - return listOf(Edit(start, end - start, block)) - } - - private fun systemFirst(name: String): Int = - if (name == "System" || name.startsWith("System.")) 0 else 1 - - /** Stores unused directives by file path for later quick fixes. */ - class Unused { - private val byFile = ConcurrentHashMap>() - - fun put(path: String, texts: Set) { - byFile[path] = texts - } - - fun of(path: String): Set = - byFile[path].orEmpty() - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsWorkspace.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsWorkspace.kt deleted file mode 100644 index 792072f2c6..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsWorkspace.kt +++ /dev/null @@ -1,117 +0,0 @@ -package dev.codeassist.csharp.editor - - -import android.util.Log -import dev.codeassist.csharp.CSharpPlugin -import dev.codeassist.csharp.util.TAG -import dev.ide.analysis.REANALYSIS -import dev.ide.analysis.Reanalysis -import dev.ide.build.RUN_SETTINGS -import dev.ide.lang.CompilationContext -import dev.ide.lang.CompilationContextProvider -import dev.ide.lang.LanguageId -import dev.ide.model.Module -import dev.ide.model.Workspace - -/** - * Provides workspace-level reanalysis for the C# plugin. - * - * Reanalysis is useful after a NuGet restore finishes. The source files - * have not changed, but previously unresolved package types may now exist. - * - * Reanalysis is workspace-scoped, and the plugin does not receive a - * workspace during registration. Instead, [CsContextProvider] obtains - * it through contextFor() and passes it here. - * - * The provider is called while the editor prepares the analysis context - * for a C# module, before checking its files. - * - * Until a workspace service is available, the plugin retains its previous - * behavior and waits for a restore to finish before checking again. - */ -internal object CsWorkspace { - - @Volatile - private var reanalysis: Reanalysis? = null - - /** - * Reads the entry point chosen on a module's Run card, once a workspace has been seen on a host that - * offers it (SPI 3.7.0). Null until then, and always on an older host. - */ - @Volatile - var entryPoints: ((Module) -> String?)? = null - private set - - /** Whether a workspace has been found and reanalysis is available. */ - val available: Boolean - get() = reanalysis != null - - /** - * Finds and remembers the workspace's reanalysis service. - * - * Hosts older than SPI 3.5.0 may not provide this service. In that case, - * the plugin continues without workspace-level reanalysis. - */ - fun remember(workspace: Workspace) { - if (entryPoints == null) { - entryPoints = runCatching { CsRunSettings.entryPointsOf(workspace) }.getOrNull() - } - - if (reanalysis != null) return - - reanalysis = runCatching { - workspace.service(REANALYSIS) - }.getOrNull() - - Log.d( - TAG, - "workspace: reanalysis ${if (available) "available" else "not available"}", - ) - } - - /** Requests another analysis pass for all open files. */ - fun reanalyzeOpenFiles() { - val service = reanalysis ?: return - - Log.d(TAG, "workspace: asking for the open files to be checked again") - - runCatching { - service.reanalyzeOpenFiles() - } - } -} - -/** - * Registers workspace and module information during compilation context creation. - * - * The host retains responsibility for providing the actual compilation context. - */ -internal class CsContextProvider : CompilationContextProvider { - - override val languages = setOf( - LanguageId(CSharpPlugin.LANGUAGE), - ) - - override fun contextFor( - workspace: Workspace, - module: Module, - language: LanguageId, - variant: Set?, - ): CompilationContext? { - CsWorkspace.remember(workspace) - CsModules.remember(module) - - return null - } -} - -/** - * The one place that names `RunSettings`. A host older than SPI 3.7.0 has no such class, so the failure to - * link stays inside the call that [CsWorkspace.remember] guards. - */ -private object CsRunSettings { - fun entryPointsOf(workspace: Workspace): (Module) -> String? { - val settings = workspace.service(RUN_SETTINGS) - return { module -> settings.entryPoint(module) } - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsprojAnalyzer.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsprojAnalyzer.kt deleted file mode 100644 index 6fdd17b35f..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/CsprojAnalyzer.kt +++ /dev/null @@ -1,84 +0,0 @@ -package dev.codeassist.csharp.editor - - -import dev.codeassist.csharp.project.CsMains -import dev.codeassist.csharp.project.csproj.CsprojCheck -import dev.ide.analysis.AnalysisTarget -import dev.ide.analysis.AnalyzerId -import dev.ide.analysis.AnalyzerTier -import dev.ide.analysis.DiagnosticSink -import dev.ide.analysis.FileAnalyzer -import dev.ide.lang.LanguageId -import dev.ide.lang.dom.NodeKind -import dev.ide.lang.dom.Severity -import dev.ide.lang.dom.TextRange -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths - -/** - * Reports problems in `.csproj`, `.props` and `.targets` files while they are being edited. - * - * Uses the SEMANTIC tier because some checks read project files from disk, such as checking - * whether referenced files exist and finding C# entry points. - */ -internal class CsprojAnalyzer : FileAnalyzer { - - override val id = AnalyzerId("csproj") - override val displayName = "C# project file problems" - override val languages = setOf(LanguageId("csproj")) - override val defaultSeverity = Severity.WARNING - override val tier = AnalyzerTier.SEMANTIC - override val interestedIn: Set? = null - - override fun analyze(target: AnalysisTarget, sink: DiagnosticSink) { - val file = Paths.get(target.file.path) - val text = target.parsed.text().toString() - val dir = file.parent - val isProjectFile = file.fileName.toString().endsWith(".csproj", ignoreCase = true) - - val env = CsprojCheck.Env( - exists = { path -> exists(dir, path) }, - mainClasses = if (isProjectFile && dir != null) { - CsMains.classes(dir) - } else { - emptyList() - }, - hasTopLevelStatements = isProjectFile && - dir != null && - CsMains.hasTopLevelStatements(dir), - ) - - target.checkCanceled() - - CsprojCheck.check(text, env).forEach { finding -> - reportFinding(text, finding, sink) - } - } - - private fun reportFinding( - text: String, - finding: CsprojCheck.Finding, - sink: DiagnosticSink, - ) { - val start = finding.start.coerceIn(0, text.length) - val end = finding.end.coerceIn(start, text.length) - val rangeEnd = if (end == start) minOf(start + 1, text.length) else end - - sink.report( - TextRange(start, rangeEnd), - if (finding.level == CsprojCheck.Level.ERROR) Severity.ERROR else Severity.WARNING, - finding.message, - finding.code, - ) - } - - /** Resolves a path relative to the project directory, accepting either path separator. */ - private fun exists(dir: Path?, path: String): Boolean = try { - val normalized = path.replace('\\', '/') - val resolved = if (dir == null) Paths.get(normalized) else dir.resolve(normalized) - Files.exists(resolved) - } catch (e: Exception) { - true // Don't report paths that could not be checked. - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnosticProvider.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnosticProvider.kt deleted file mode 100644 index 90b2717d94..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnosticProvider.kt +++ /dev/null @@ -1,458 +0,0 @@ -package dev.codeassist.csharp.editor.diagnostics - - -import android.util.Log -import dev.codeassist.csharp.CSharpPlugin -import dev.codeassist.csharp.completion.CsSymbols -import dev.codeassist.csharp.editor.CsFileNames -import dev.codeassist.csharp.editor.CsModules -import dev.codeassist.csharp.editor.CsUsingCleanup -import dev.codeassist.csharp.editor.CsWorkspace -import dev.codeassist.csharp.editor.quickfixes.CsUsingFix -import dev.codeassist.csharp.project.CsProject -import dev.codeassist.csharp.project.csproj.Csproj -import dev.codeassist.csharp.project.csproj.CsprojGraph -import dev.codeassist.csharp.project.csproj.CsprojReferences -import dev.codeassist.csharp.project.csproj.CsprojInfo -import dev.codeassist.csharp.project.nuget.CsPackageRestorer -import dev.codeassist.csharp.sdk.CsChecker -import dev.codeassist.csharp.sdk.CsCompilerHost -import dev.codeassist.csharp.sdk.CsCompleter -import dev.codeassist.csharp.sdk.DotnetSdk -import dev.codeassist.csharp.util.RestoreNotice -import dev.codeassist.csharp.util.TAG -import dev.codeassist.csharp.util.killableTool -import dev.ide.analysis.AnalysisTarget -import dev.ide.analysis.AnalyzerId -import dev.ide.analysis.Diagnostic -import dev.ide.analysis.DiagnosticProvider -import dev.ide.analysis.DiagnosticSource -import dev.ide.analysis.DiagnosticTag -import dev.ide.lang.LanguageId -import dev.ide.lang.dom.Severity -import dev.ide.lang.dom.TextRange -import dev.ide.platform.log.Logger -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths -import java.util.concurrent.atomic.AtomicBoolean - -/** - * Reports C# compiler diagnostics for the current editor buffer. - * - * Uses the same Roslyn compiler as Run. The current buffer is compiled from its unsaved text, - * while the module's other source files are read from disk. Compilation uses library output - * so a missing Main does not produce CS5001. - * - * Only diagnostics belonging to the current buffer are reported. - */ -internal class CsDiagnosticProvider( - private val sdk: DotnetSdk, - private val log: Logger, - private val symbols: CsSymbols, - private val restorer: CsPackageRestorer, - private val unused: CsUsingCleanup.Unused, -) : DiagnosticProvider { - - private val projectReferences = CsprojReferences(sdk) - - override val id = "csharp.roslyn" - override val languages = setOf(LanguageId(CSharpPlugin.LANGUAGE)) - - /** One cached result, keyed by the buffer path and its current project state. */ - private var cachedKey: Pair? = null - private var cached: List = emptyList() - - /** Starts the completer once, after the first diagnostic check. */ - private val completerWarmed = AtomicBoolean(false) - - override suspend fun diagnose(target: AnalysisTarget): List { - Log.d(TAG, "diagnose: called for ${target.file.path}") - - if (sdk.prepare() !is DotnetSdk.Status.Ready) { - Log.d(TAG, "diagnose: .NET not ready, skipping") - return emptyList() - } - - val file = runCatching { - Paths.get(target.file.path).toAbsolutePath().normalize() - }.getOrNull() ?: return emptyList() - - val text = target.parsed.text().toString() - - CsModules.remember(target.module) - - // The project the file belongs to: in a module holding several, the nearest project file above it. - val moduleDir = CsprojGraph.owningDir(file) ?: Paths.get(target.module.dir.path) - val key = file.toString() to - (text.hashCode() * 31 + packagesStamp(moduleDir)) * 31 + - restorer.failuresFor(moduleDir).hashCode() - - synchronized(this) { - if (cachedKey == key) { - Log.d(TAG, "diagnose: cached") - return cached - } - } - - // Keep each buffer's compiler copy separate, even when files share a name. - val work = sdk.home.resolve("editor") - .resolve(Integer.toHexString(file.toString().hashCode())) - val buffer = work.resolve(file.fileName.toString()) - val bufferPath = buffer.toAbsolutePath().normalize() - - // Use the same project settings as Run. - val project = Csproj.load(moduleDir) - val sources = CsprojGraph.sources(moduleDir, project) - - val others = sources.filter { - runCatching { it.toAbsolutePath().normalize() }.getOrNull() != file - } - - val usingsText = Csproj.globalUsingsText(project) - val usings = work.resolve("GlobalUsings.g.cs") - .takeIf { usingsText.isNotEmpty() } - - if (project != null && project.packageReferences.isNotEmpty()) { - if (CsWorkspace.available && restorer.pending(project, moduleDir)) { - // The restore requests another check when it finishes. Until then, keep the last result. - restorer.restoreInBackground(project, moduleDir) - Log.d(TAG, "diagnose: packages are being restored, ${file.fileName} is checked again after") - return synchronized(this) { - if (cachedKey?.first == file.toString()) cached else emptyList() - } - } - - restorer.restore(project, moduleDir) - } - - val referenced = project - ?.let { - Csproj.resolveReferences(it, moduleDir, sdk.nuget, sdk.frameworkDllNames()).first - } - ?: emptyList() - - // Projects this one references are compiled by the server from their sources; `csc` knows nothing - // of that, so the fallbacks below go without them. - val projects = projectReferences.forEditor(Csproj.find(moduleDir), project) - val arguments = checkArguments(project, buffer, others, work, usings, referenced + projects.libraries) - - val lines = ArrayList() - val startedAt = System.nanoTime() - var viaChecker = false - - val exitCode = killableTool { cancellation -> - Files.createDirectories(work) - Files.write(buffer, text.toByteArray(Charsets.UTF_8)) - usings?.let { - Files.write(it, usingsText.toByteArray(Charsets.UTF_8)) - } - - // Prefer the checker, which reports syntax and semantic errors together. - // Fall back to the compiler host when the checker cannot be used. - val checked = CsChecker.checkFile( - sdk, buffer.toString(), arguments + projects.arguments, cancellation, - ) { lines += it } - - if (checked != null) { - viaChecker = true - checked - } else if (cancellation.isCancelled) { - null - } else { - lines.clear() - CsCompilerHost.compile(sdk, arguments, cancellation) { lines += it } - } - } - - target.checkCanceled() - warmCompleter() - - val tookMs = (System.nanoTime() - startedAt) / 1_000_000 - Log.d(TAG, "diagnose: host exit=$exitCode, ${lines.size} output lines in $tookMs ms") - - if (exitCode == null) { - log.warn("the resident compiler could not check ${file.fileName}") - return emptyList() - } - - var diagnostics = diagnosticsFor(bufferPath, lines, text) - - // The compiler may hide semantic errors while another source file has syntax errors. - if (!viaChecker && exitCode != 0 && diagnostics.isEmpty()) { - diagnostics = checkWithoutBrokenFiles(target, bufferPath, lines, text, others) { remaining -> - checkArguments(project, buffer, remaining, work, usings, referenced) - } ?: diagnostics - } - - diagnostics = diagnostics + - unusedUsings(bufferPath, lines, text, file, diagnostics) + - fileNameHint(text, file) - - diagnostics = diagnostics + restoreWarning(moduleDir, text) - - Log.d(TAG, "diagnose: ${diagnostics.size} diagnostics for ${file.fileName}") - - // Build the symbol table when a missing-using quick fix needs it. - if (diagnostics.any { it.code in CsUsingFix.CODES } && - symbols.cachedTable(moduleDir) == null - ) { - runCatching { - symbols.tableFor(project, moduleDir, sources) - } - target.checkCanceled() - } - - if (exitCode != 0 && diagnostics.isEmpty()) { - Log.d(TAG, "diagnose: no located error for exit $exitCode; first line: ${lines.firstOrNull()}") - } - - synchronized(this) { - cachedKey = key - cached = diagnostics - } - - return diagnostics - } - - /** - * Starts completion in the background after the first check, avoiding a build competing - * with the initial diagnostic check. - */ - private fun warmCompleter() { - if (!completerWarmed.compareAndSet(false, true)) return - - Thread( - { runCatching { CsCompleter.warm(sdk) } }, - "cs-complete-warm", - ).apply { - isDaemon = true - start() - } - } - - /** Hints when the single public type does not match the file name. */ - private fun fileNameHint(text: String, file: Path): List { - val mismatch = CsFileNames.mismatch(text, file.fileName.toString()) - ?: return emptyList() - - return listOf( - Diagnostic( - range = TextRange(mismatch.start, mismatch.end), - severity = Severity.INFO, - message = "Type '${mismatch.name}' does not match the file name '${file.fileName}'", - source = DiagnosticSource.Analyzer(AnalyzerId("csharp.file-name")), - code = "CSFILENAME", - ), - ) - } - - /** - * Converts hidden CS8019 diagnostics into unused-using hints. - * - * Hints are omitted while the buffer has errors because unresolved names can make a - * required using directive appear unused. - */ - private fun unusedUsings( - bufferPath: Path, - lines: List, - text: String, - file: Path, - found: List, - ): List { - unused.put(file.toString(), emptySet()) - if (found.any { it.severity == Severity.ERROR }) return emptyList() - - val offsets = CsLineOffsets(text) - val texts = HashSet() - - val out = lines - .mapNotNull { CsDiagnostics.parseUnusedUsing(it) } - .filter { - runCatching { Paths.get(it.path).toAbsolutePath().normalize() }.getOrNull() == bufferPath - } - .mapNotNull { hidden -> - val start = offsets.offsetOf(hidden.line, hidden.column) - val lineText = CsUsingCleanup.directiveAt(text, start) - ?: return@mapNotNull null - - texts += lineText - - val end = text.indexOf('\n', start).let { - if (it < 0) text.length else it - } - - Diagnostic( - range = TextRange( - start, - text.substring(start, end).trimEnd().length + start, - ), - severity = Severity.HINT, - message = hidden.message, - source = DiagnosticSource.Compiler, - code = hidden.code, - tags = setOf(DiagnosticTag.UNUSED), - ) - } - - unused.put(file.toString(), texts) - return out - } - - /** Shows the last package restore failure on the first line of the buffer. */ - private fun restoreWarning(moduleDir: Path, text: String): List { - val problems = restorer.failuresFor(moduleDir) - if (problems.isEmpty() || text.isEmpty()) return emptyList() - - val lineEnd = text.indexOf('\n') - .let { if (it < 0) text.length else it } - .coerceAtLeast(1) - - return listOf( - Diagnostic( - range = TextRange(0, lineEnd.coerceAtMost(text.length)), - severity = Severity.WARNING, - message = RestoreNotice.fileWarning(problems), - source = DiagnosticSource.Compiler, - code = "NUGET_RESTORE", - ), - ) - } - - /** - * Includes project settings and the number of unpacked package DLLs in the cache key. - * A saved project change can affect every source file without changing its buffer text. - */ - private fun packagesStamp(moduleDir: Path): Int { - val project = Csproj.load(moduleDir) ?: return 0 - - val unpacked = if (project.packageReferences.isEmpty()) { - 0 - } else { - sdk.nuget.cached( - Csproj.packageRequests(project), - sdk.frameworkDllNames(), - ).dlls.size - } - - return project.hashCode() * 31 + unpacked - } - - /** Builds compiler arguments for the buffer and the other module sources, using library output. */ - private fun checkArguments( - project: CsprojInfo?, - buffer: Path, - others: List, - work: Path, - usings: Path?, - referenced: List, - ): List { - val output = work.resolve("check.dll") - - if (project != null) { - return Csproj.arguments( - project, - listOf(buffer) + others, - sdk.references() + referenced, - output, - usings, - forceLibrary = true, - ) - } - - return buildList { - add("-nologo") - add("-noconfig") - add("-target:library") - add("-out:$output") - sdk.references().forEach { add("-r:$it") } - add(buffer.toString()) - others.forEach { add(it.toString()) } - } - } - - /** Converts compiler output belonging to the current buffer into editor diagnostics. */ - private fun diagnosticsFor( - bufferPath: Path, - lines: List, - text: String, - ): List { - val offsets = CsLineOffsets(text) - - return lines - .mapNotNull { CsDiagnostics.parse(it) } - // Match the compiler's buffer copy, not the original file path. - .filter { - runCatching { Paths.get(it.path).toAbsolutePath().normalize() }.getOrNull() == bufferPath - } - // Top-level statements are valid programs, even though this check compiles as a library. - .filter { it.code != "CS8805" } - .map { diagnostic -> - Diagnostic( - range = offsets.tokenAt(diagnostic.line, diagnostic.column), - severity = when (diagnostic.severity) { - CsDiagnostic.Severity.ERROR -> Severity.ERROR - CsDiagnostic.Severity.WARNING -> Severity.WARNING - }, - message = diagnostic.message, - source = DiagnosticSource.Compiler, - code = diagnostic.code, - tags = CsDiagnosticTags.of(diagnostic.code), - ) - } - } - - /** - * Rechecks the buffer without other files that produced syntax errors. - * - * Types declared in excluded files are missing from this check, so diagnostics referring - * to those types are filtered out. - */ - private suspend fun checkWithoutBrokenFiles( - target: AnalysisTarget, - bufferPath: Path, - firstLines: List, - text: String, - others: List, - argumentsFor: (List) -> List, - ): List? { - val broken = firstLines - .mapNotNull { CsDiagnostics.parse(it) } - .filter { it.severity == CsDiagnostic.Severity.ERROR } - .mapNotNull { - runCatching { Paths.get(it.path).toAbsolutePath().normalize() }.getOrNull() - } - .filter { it != bufferPath } - .toSet() - - if (broken.isEmpty()) return null - - val remaining = others.filter { - runCatching { it.toAbsolutePath().normalize() }.getOrNull() !in broken - } - - val lines = ArrayList() - val exitCode = killableTool { cancellation -> - CsCompilerHost.compile(sdk, argumentsFor(remaining), cancellation) { lines += it } - } - - target.checkCanceled() - if (exitCode == null) return null - - val leftOutTypes = broken.flatMap { declaredTypeNames(readText(it)) }.toSet() - - val kept = lines.filterNot { line -> - CsDiagnostics.parse(line)?.let { - mentionsType(it.message, leftOutTypes) - } == true - } - - Log.d(TAG, "diagnose: rechecked without ${broken.size} broken file(s), ${lines.size - kept.size} dropped") - return diagnosticsFor(bufferPath, kept, text) - } - - private fun readText(path: Path): String = - runCatching { - String(Files.readAllBytes(path), Charsets.UTF_8) - }.getOrDefault("") -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnosticTags.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnosticTags.kt deleted file mode 100644 index f2cf59456c..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnosticTags.kt +++ /dev/null @@ -1,32 +0,0 @@ -package dev.codeassist.csharp.editor.diagnostics - - -import dev.ide.analysis.DiagnosticTag - -/** - * Maps C# compiler warning codes to editor diagnostic tags. - */ -internal object CsDiagnosticTags { - - /** Obsolete member usage. */ - val DEPRECATED = setOf( - "CS0612", // Obsolete, no message - "CS0618", // Obsolete, with a message - "CS0672", // Overrides an obsolete member - "CS0809", // Obsolete member overrides a non-obsolete member - ) - - /** Declarations that are unused or assigned but never read. */ - val UNUSED = setOf( - "CS0168", // Unused local variable - "CS0219", // Local variable assigned but never read - "CS0169", // Unused field - "CS0414", // Field assigned but never read - ) - - fun of(code: String?): Set = when (code) { - in DEPRECATED -> setOf(DiagnosticTag.DEPRECATED) - in UNUSED -> setOf(DiagnosticTag.UNUSED) - else -> emptySet() - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnostics.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnostics.kt deleted file mode 100644 index 702914771f..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsDiagnostics.kt +++ /dev/null @@ -1,74 +0,0 @@ -package dev.codeassist.csharp.editor.diagnostics - - -/** One diagnostic parsed from Roslyn compiler output. */ -internal data class CsDiagnostic( - val path: String, - val line: Int, - val column: Int, - val severity: Severity, - val code: String, - val message: String, -) { - enum class Severity { - ERROR, - WARNING, - } -} - -internal object CsDiagnostics { - - private val diagnosticLine = Regex( - """^(.+)\((\d+),(\d+)\): (error|warning) (CS\d{4}): (.*)$""", - ) - - private val unusedUsingLine = Regex( - """^(.+)\((\d+),(\d+)\): hidden CS8019: .*$""", - ) - - const val UNUSED_USING_CODE = "CS8019" - - /** - * Parses a compiler error or warning. - * - * Lines without a source position, such as `error CS2007: Unrecognized option`, - * do not match. - */ - fun parse(line: String): CsDiagnostic? { - val match = diagnosticLine.matchEntire(line) ?: return null - val (path, lineNumber, columnNumber, severity, code, message) = match.destructured - - return CsDiagnostic( - path = path, - line = lineNumber.toInt(), - column = columnNumber.toInt(), - severity = if (severity == "error") { - CsDiagnostic.Severity.ERROR - } else { - CsDiagnostic.Severity.WARNING - }, - code = code, - message = message, - ) - } - - /** - * Parses Roslyn's `hidden CS8019` output for unnecessary using directives. - * - * This format is handled separately because [parse] only accepts errors and warnings. - * Its exact output format still needs device verification. - */ - fun parseUnusedUsing(line: String): CsDiagnostic? { - val match = unusedUsingLine.matchEntire(line) ?: return null - val (path, lineNumber, columnNumber) = match.destructured - - return CsDiagnostic( - path = path, - line = lineNumber.toInt(), - column = columnNumber.toInt(), - severity = CsDiagnostic.Severity.WARNING, - code = UNUSED_USING_CODE, - message = "Unnecessary using directive", - ) - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsLineOffsets.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsLineOffsets.kt deleted file mode 100644 index c21a7b20bb..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsLineOffsets.kt +++ /dev/null @@ -1,50 +0,0 @@ -package dev.codeassist.csharp.editor.diagnostics - - -import dev.ide.lang.dom.TextRange - -/** - * Converts Roslyn's 1-based line and column positions into buffer offsets. - * - * Line starts are indexed once so multiple diagnostics can be mapped without rescanning the text. - */ -internal class CsLineOffsets(private val text: CharSequence) { - - /** Buffer offset of the first character on each line. */ - private val lineStarts = buildList { - add(0) - text.forEachIndexed { index, char -> - if (char == '\n') add(index + 1) - } - }.toIntArray() - - /** Returns the offset at [line]:[column], clamped to the corresponding line. */ - fun offsetOf(line: Int, column: Int): Int { - val lineIndex = (line - 1).coerceIn(0, lineStarts.lastIndex) - val start = lineStarts[lineIndex] - val end = if (lineIndex < lineStarts.lastIndex) { - lineStarts[lineIndex + 1] - 1 - } else { - text.length - } - - return (start + (column - 1).coerceAtLeast(0)) - .coerceIn(start, maxOf(start, end)) - } - - /** - * Returns the identifier at [line]:[column], or a one-character range if no identifier - * is found, so the diagnostic remains visible. - */ - fun tokenAt(line: Int, column: Int): TextRange { - val start = offsetOf(line, column) - var end = start - - while (end < text.length && (text[end].isLetterOrDigit() || text[end] == '_')) { - end++ - } - - val tokenEnd = if (end > start) end else (start + 1).coerceAtMost(text.length) - return TextRange(start, tokenEnd) - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsMaskedErrors.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsMaskedErrors.kt deleted file mode 100644 index e948e6711f..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/diagnostics/CsMaskedErrors.kt +++ /dev/null @@ -1,37 +0,0 @@ -package dev.codeassist.csharp.editor.diagnostics - -/** - * Helpers for filtering false missing-type errors from the fallback semantic check. - * - * The compiler may report only syntax errors while any source file has syntax errors. - * The fallback check excludes those broken files, but this can make types declared in - * them appear missing. [mentionsType] filters out errors referring to those types. - */ -private val typeDeclaration = Regex( - """\b(?:class|struct|interface|enum|record)\s+([A-Za-z_]\w*)""", -) - -private val quotedName = Regex("""'([^']+)'""") - -/** Finds type names declared in [source]. This is a text-based check, not a C# parser. */ -internal fun declaredTypeNames(source: String): Set = - typeDeclaration.findAll(source) - .map { it.groupValues[1] } - .toSet() - -/** - * Checks whether [message] refers to a type in [typeNames]. - * - * Handles qualified and generic names, such as `'MyApp.Greeter'` and `'Box'`. - */ -internal fun mentionsType(message: String, typeNames: Set): Boolean { - if (typeNames.isEmpty()) return false - - return quotedName.findAll(message).any { match -> - val name = match.groupValues[1] - .substringBefore('<') - .substringAfterLast('.') - - name in typeNames - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/quickfixes/CsUsingFix.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/quickfixes/CsUsingFix.kt deleted file mode 100644 index d3863d9538..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/quickfixes/CsUsingFix.kt +++ /dev/null @@ -1,223 +0,0 @@ -package dev.codeassist.csharp.editor.quickfixes - -import dev.codeassist.csharp.completion.CsSymbolTable - -/** - * Finds namespaces that can resolve missing names and calculates where their using directives should go. - * This is pure text processing and can be tested without an IDE. - * - * Handles CS0246, CS0103, and CS1061 when its message indicates a missing extension method. - */ -internal object CsUsingFix { - - val CODES = setOf("CS0246", "CS0103", "CS1061") - - private const val LINQ = "System.Linq" - private const val MAX_STATIC = 5 - - private val EXTENSION_RECEIVER = Regex("""first argument of type '([^']+)'""") - private val EXTENSION_MESSAGE = - Regex("""does not contain a definition for '(\w+)' and no accessible extension""") - - private val SEQUENCE_LIKE = Regex( - """^(?:string|[\w.]*\b(?:IEnumerable|IQueryable|IList|ICollection|List|HashSet|ISet|SortedSet|Queue|Stack|""" + - """LinkedList|Dictionary|IDictionary|IReadOnly\w+|ReadOnly\w+|Array|Span|ReadOnlySpan)\b.*|.*\[])$""" - ) - - private val QUOTED = Regex("""'([^']+)'""") - private val IDENTIFIER = Regex("""[A-Za-z_]\w*""") - private val PLAIN_USING = Regex("""using\s+([A-Za-z_][\w.]*)\s*;.*""") - private val OTHER_USING = Regex("""(?:global\s+)?using\s+(?!var\b|\()[^;]*;.*""") - private val STATIC_USING = Regex("""(?m)^using\s+static\s+([\w.]+)\s*;""") - - private val STATIC_KINDS = setOf("method", "field", "property") - - /** A line to add: [text] goes in at [offset], replacing nothing. */ - class Insertion(val offset: Int, val text: String) - - /** - * The name a CS0246 / CS0103 message is about: its first quoted part, without generic arguments. - * Returns null when it is not a plain identifier. - */ - fun missingName(message: String): String? { - val quoted = QUOTED.find(message)?.groupValues?.get(1) ?: return null - val name = quoted.substringBefore('<') - return name.takeIf { IDENTIFIER.matches(it) } - } - - /** - * The type a CS1061 message says the method was called on, or null when it names none. - */ - fun extensionReceiver(message: String): String? = - EXTENSION_RECEIVER.find(message)?.groupValues?.get(1) - - /** - * The method a CS1061 message wants as an extension method, or null for other CS1061 messages. - */ - fun extensionName(message: String): String? = - EXTENSION_MESSAGE.find(message)?.groupValues?.get(1) - - /** - * Finds namespaces declaring a static method called [name], excluding namespaces already imported. - * - * The symbol table does not expose the extension attribute or parameter types, so these candidates - * are not guaranteed to contain extension methods for [receiver]. For sequence-like receivers, - * LINQ is preferred when it is among the candidates. - */ - fun extensionCandidates( - name: String, - table: CsSymbolTable, - source: String, - receiver: String? = null, - ): List { - val imported = scan(source).usings.mapNotNull { it.name }.toSet() - val staticTypes = table.types - .filter { it.isStatic && it.namespace != "-" } - .associateBy { it.fullName } - - val found = table.members - .filter { it.kind == "method" && it.isStatic && it.paramCount >= 1 && it.name == name } - .mapNotNull { staticTypes[it.typeFullName]?.namespace } - .filter { it !in imported } - .distinct() - .sortedBy { orderKey(it) } - - val sequence = receiver != null && SEQUENCE_LIKE.matches(receiver) - return if (sequence && LINQ in found) listOf(LINQ) else found - } - - /** - * Finds namespaces containing public types called [name], excluding namespaces already imported. - * Types without a namespace are not offered. - */ - fun candidates(name: String, table: CsSymbolTable, source: String): List { - val imported = scan(source).usings.mapNotNull { it.name }.toSet() - return table.types - .filter { it.name == name && it.namespace != "-" && it.namespace !in imported } - .map { it.namespace } - .distinct() - .sortedBy { orderKey(it) } - } - - /** - * Finds static classes containing a static member called [name], for a `using static` fix. - * Nested and generic types are excluded. At most [MAX_STATIC] candidates are returned. - */ - fun staticCandidates(name: String, table: CsSymbolTable, source: String): List { - if (table.types.any { it.name == name && it.namespace != "-" }) return emptyList() - - val imported = STATIC_USING.findAll(source).map { it.groupValues[1] }.toSet() - val staticTypes = table.types - .filter { it.isStatic && it.namespace != "-" && '+' !in it.fullName && '`' !in it.fullName } - .associateBy { it.fullName } - - return table.members - .filter { it.isStatic && it.name == name && it.kind in STATIC_KINDS } - .mapNotNull { staticTypes[it.typeFullName]?.fullName } - .filter { it !in imported } - .distinct() - .sortedBy { orderKey(it) } - .take(MAX_STATIC) - } - - /** The text of a `using static` line for [type]. */ - fun staticLine(type: String): String = "using static $type;" - - /** Places a `using static` line after the last using directive. */ - fun staticInsertion(source: String, type: String): Insertion { - val newline = if (source.contains("\r\n")) "\r\n" else "\n" - val line = staticLine(type) - val scanned = scan(source) - - scanned.usings.lastOrNull()?.let { last -> - return if (last.end < source.length) { - Insertion(last.end, line + newline) - } else { - Insertion(source.length, newline + line) - } - } - - val first = scanned.firstDeclaration ?: return Insertion(source.length, line + newline) - return Insertion(first, line + newline + newline) - } - - /** True when [source] already has a plain `using [namespace];` at the head of the file. */ - fun imports(source: String, namespace: String): Boolean = - scan(source).usings.any { it.name == namespace } - - /** Finds where a `using [namespace];` line should be inserted. */ - fun insertion(source: String, namespace: String): Insertion { - val newline = if (source.contains("\r\n")) "\r\n" else "\n" - val line = "using $namespace;" - val scanned = scan(source) - - val plain = scanned.usings.filter { it.name != null } - val key = orderKey(namespace) - - // Insert before the first plain using that sorts after this namespace. - plain.firstOrNull { orderKey(it.name!!) > key }?.let { - return Insertion(it.start, line + newline) - } - - // Otherwise, insert after the last using directive. - scanned.usings.lastOrNull()?.let { last -> - return if (last.end < source.length) { - Insertion(last.end, line + newline) - } else { - Insertion(source.length, newline + line) - } - } - - // No usings: insert before the first declaration. - val first = scanned.firstDeclaration ?: return Insertion(source.length, line + newline) - return Insertion(first, line + newline + newline) - } - - /** `System` names first, then the rest; each ordered by ordinal comparison. */ - private fun orderKey(name: String): String = - (if (name == "System" || name.startsWith("System.")) "0" else "1") + name - - private class Using(val name: String?, val start: Int, val end: Int) - - private class Scanned(val usings: List, val firstDeclaration: Int?) - - /** - * Finds top-level using directives at the head of [source] and the first declaration. - * The end offset includes the line's newline, or is the source length on the last line. - */ - private fun scan(source: String): Scanned { - val usings = ArrayList() - var inBlockComment = false - var start = 0 - - while (start < source.length) { - val newlineAt = source.indexOf('\n', start) - val end = if (newlineAt < 0) source.length else newlineAt + 1 - val text = source.substring(start, end).trim() - - when { - inBlockComment -> if ("*/" in text) inBlockComment = false - text.isEmpty() || text.startsWith("//") || text.startsWith("#") -> Unit - text.startsWith("/*") -> if ("*/" !in text) inBlockComment = true - else -> { - val atColumnZero = !source[start].isWhitespace() - val plain = PLAIN_USING.matchEntire(text) - - when { - atColumnZero && plain != null -> - usings += Using(plain.groupValues[1], start, end) - - atColumnZero && OTHER_USING.matchEntire(text) != null -> - usings += Using(null, start, end) - - else -> return Scanned(usings, start) - } - } - } - - start = end - } - - return Scanned(usings, null) - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/quickfixes/CsUsingFixProvider.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/quickfixes/CsUsingFixProvider.kt deleted file mode 100644 index 41e726cbff..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/editor/quickfixes/CsUsingFixProvider.kt +++ /dev/null @@ -1,148 +0,0 @@ -package dev.codeassist.csharp.editor.quickfixes - - -import dev.codeassist.csharp.CSharpPlugin -import dev.codeassist.csharp.completion.CsSymbols -import dev.codeassist.csharp.editor.CsUsingCleanup -import dev.codeassist.csharp.editor.diagnostics.CsDiagnostics -import dev.ide.analysis.AnalysisTarget -import dev.ide.analysis.CodeActionKind -import dev.ide.analysis.Diagnostic -import dev.ide.analysis.FixContext -import dev.ide.analysis.QuickFix -import dev.ide.analysis.QuickFixProvider -import dev.ide.analysis.WorkspaceEdit -import dev.ide.lang.LanguageId -import dev.ide.lang.incremental.DocumentEdit -import java.nio.file.Paths - -/** - * Adds using directives for unresolved types, names, and extension methods. - * Also provides fixes for unnecessary using directives. - * - * Fixes are attached to compiler diagnostics by their Roslyn diagnostic codes. - * The symbol table is read synchronously from [CsSymbols], so fixes are offered - * only when a cached table is available. - */ -internal class CsUsingFixProvider( - private val symbols: CsSymbols, - private val unused: CsUsingCleanup.Unused, -) : QuickFixProvider { - - override val forCodes = CsUsingFix.CODES + CsDiagnostics.UNUSED_USING_CODE - - override val languages = setOf(LanguageId(CSharpPlugin.LANGUAGE)) - - override fun fixes(diagnostic: Diagnostic, target: AnalysisTarget): List { - if (diagnostic.code == CsDiagnostics.UNUSED_USING_CODE) { - return removeFixes(diagnostic, target) - } - - val extension = diagnostic.code == "CS1061" - val name = if (extension) { - CsUsingFix.extensionName(diagnostic.message) - } else { - CsUsingFix.missingName(diagnostic.message) - } ?: return emptyList() - - val moduleDir = runCatching { - Paths.get(target.module.dir.path) - }.getOrNull() ?: return emptyList() - - val table = symbols.cachedTable(moduleDir) ?: return emptyList() - val source = target.parsed.text().toString() - - val namespaces = if (extension) { - CsUsingFix.extensionCandidates( - name, - table, - source, - CsUsingFix.extensionReceiver(diagnostic.message), - ) - } else { - CsUsingFix.candidates(name, table, source) - } - - if (namespaces.isNotEmpty() || extension) { - return namespaces.map { AddUsing(it) } - } - - return CsUsingFix.staticCandidates(name, table, source).map { AddUsingStatic(it) } - } - - private fun removeFixes(diagnostic: Diagnostic, target: AnalysisTarget): List { - val source = target.parsed.text().toString() - val line = CsUsingCleanup.directiveAt(source, diagnostic.range.start) ?: return emptyList() - - return listOf( - RemoveUsing(line), - OrganizeUsings(target.file.path, unused), - ) - } - - private class RemoveUsing(private val line: String) : QuickFix { - override val title = "Remove unnecessary using" - override val kind = CodeActionKind.QUICK_FIX - - override suspend fun computeEdits(ctx: FixContext): WorkspaceEdit { - val source = ctx.target.parsed.text().toString() - return edits(ctx, CsUsingCleanup.remove(source, line)) - } - } - - private class OrganizeUsings( - private val path: String, - private val unused: CsUsingCleanup.Unused, - ) : QuickFix { - override val title = "Remove unnecessary usings and sort" - override val kind = CodeActionKind.QUICK_FIX - - override suspend fun computeEdits(ctx: FixContext): WorkspaceEdit { - val source = ctx.target.parsed.text().toString() - return edits(ctx, CsUsingCleanup.organize(source, unused.of(path))) - } - } - - private class AddUsingStatic(private val type: String) : QuickFix { - override val title = "Add using static $type;" - override val kind = CodeActionKind.QUICK_FIX - - override suspend fun computeEdits(ctx: FixContext): WorkspaceEdit { - val source = ctx.target.parsed.text().toString() - if (source.lines().any { it.trim() == CsUsingFix.staticLine(type) }) { - return WorkspaceEdit.EMPTY - } - - val insertion = CsUsingFix.staticInsertion(source, type) - return WorkspaceEdit.of( - ctx.target.file, - DocumentEdit(insertion.offset, 0, insertion.text), - ) - } - } - - private class AddUsing(private val namespace: String) : QuickFix { - override val title = "Add using $namespace;" - override val kind = CodeActionKind.QUICK_FIX - - override suspend fun computeEdits(ctx: FixContext): WorkspaceEdit { - // Read the live buffer because it may have changed since the fix menu was built. - val source = ctx.target.parsed.text().toString() - if (CsUsingFix.imports(source, namespace)) return WorkspaceEdit.EMPTY - - val insertion = CsUsingFix.insertion(source, namespace) - return WorkspaceEdit.of( - ctx.target.file, - DocumentEdit(insertion.offset, 0, insertion.text), - ) - } - } -} - -/** Creates one atomic workspace edit for the fix's file. */ -private fun edits(ctx: FixContext, changes: List): WorkspaceEdit { - if (changes.isEmpty()) return WorkspaceEdit.EMPTY - - val edits = changes.map { DocumentEdit(it.offset, it.length, it.text) } - return WorkspaceEdit.of(ctx.target.file, *edits.toTypedArray()) -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsMainScan.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsMainScan.kt deleted file mode 100644 index d2083772c6..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsMainScan.kt +++ /dev/null @@ -1,288 +0,0 @@ -package dev.codeassist.csharp.project - - -/** - * Finds compiler-accepted `static Main` entry points and top-level statements in C# source text. - * - * Recognizes `void`, `int`, `Task`, and `Task` return types, with optional `string[] args`, - * any accessibility, and optional `async`. Entry points must be direct members of a non-generic - * class, struct, record, or interface. - * - * Other signatures and generic `Main` methods are ignored. - * - * Pure text processing without a parser, so it can run on every editor pass and be tested without an IDE. - */ -internal object CsMainScan { - - /** An entry point's compiler class name (`Namespace.Outer.Inner`) and the offset where `Main` starts. */ - class Hit(val className: String, val offset: Int) - - private enum class Kind { NAMESPACE, TYPE, BLOCK } - - private class Scope(val kind: Kind, val name: String?, val generic: Boolean) - - private val TOKEN = Regex( - """\bnamespace\s+([\w.]+)\s*;""" + - """|\bnamespace\s+([\w.]+)""" + - """|\b(?:record\s+(?:class|struct)|class|struct|record|interface)\s+(\w+)(\s*<)?""" + - """|\bMain\s*\(\s*(?:string\s*\[\s*\]\s*\w+\s*)?\)""" + - """|[{};]""" - ) - - private val STATIC = Regex("""\bstatic\b""") - private val TASKS = """(?:System\s*\.\s*Threading\s*\.\s*Tasks\s*\.\s*)?""" - private val RETURN = Regex("""(?:\bvoid|\bint|$TASKS\bTask(?:\s*<\s*int\s*>)?)\s*$""") - - /** Keywords that may follow `class` without declaring a type, such as `where T : class`. */ - private val NOT_TYPE_NAMES = setOf("new", "where", "notnull", "unmanaged") - - /** Returns all recognized entry points in the source. */ - fun hits(text: String): List = scan(text).first - - /** - * Returns the offset of the first top-level statement, or null if none exists. - * - * Declarations and `using`/`extern` lines are excluded. Statements inside file-scoped namespaces - * are not checked because C# does not allow them there. - */ - fun topLevel(text: String): Int? = scan(text).second - - /** Declaration prefixes that distinguish top-level declarations from executable statements. */ - private val DECLARATION = Regex( - """^(?:\[[^\]]*]\s*)*""" + - """(?:(?:public|internal|private|protected|static|sealed|abstract|partial|unsafe|readonly|ref|file|new|""" + - """global)\s+)*""" + - """(?:enum|delegate|class|struct|interface|record|namespace|extern\s+alias|""" + - """using\s+(?!var\b|\()|using\s*$)""" - ) - - private fun scan(text: String): Pair, Int?> { - val clean = mask(text) - val out = ArrayList() - var topLevel: Int? = null - - // A top-level statement ends at `;` or opens the `{` following its header. - fun checkStatement(to: Int, from: Int) { - if (topLevel != null) return - - val header = clean.substring(from, to) - val trimmed = header.trim() - if (trimmed.isEmpty() || DECLARATION.containsMatchIn(trimmed)) return - - topLevel = from + header.indexOfFirst { !it.isWhitespace() } - } - - val stack = ArrayList() - var fileNamespace: String? = null - var pending: Scope? = null - var headerStart = 0 - - for (match in TOKEN.findAll(clean)) { - val after = match.range.last + 1 - - when { - match.groups[1] != null -> { - fileNamespace = match.groupValues[1] - pending = null - headerStart = after - } - - match.groups[2] != null -> { - pending = Scope(Kind.NAMESPACE, match.groupValues[2], false) - } - - match.groups[3] != null -> { - val name = match.groupValues[3] - if (name !in NOT_TYPE_NAMES) { - pending = Scope(Kind.TYPE, name, match.groups[4] != null) - } - } - - match.value == "{" -> { - if (pending == null && stack.isEmpty() && fileNamespace == null) { - checkStatement(match.range.first, headerStart) - } - - stack += pending ?: Scope(Kind.BLOCK, null, false) - pending = null - headerStart = after - } - - match.value == "}" -> { - if (stack.isNotEmpty()) stack.removeAt(stack.lastIndex) - pending = null - headerStart = after - } - - match.value == ";" -> { - if (stack.isEmpty() && fileNamespace == null) { - checkStatement(match.range.first, headerStart) - } - - pending = null - headerStart = after - } - - else -> { - val owner = stack.lastOrNull() ?: continue - if (owner.kind != Kind.TYPE || owner.generic) continue - - val header = clean.substring(headerStart, match.range.first) - if (!STATIC.containsMatchIn(header) || !RETURN.containsMatchIn(header.trimEnd())) continue - - val names = listOfNotNull(fileNamespace) + stack.mapNotNull { it.name } - out += Hit(names.joinToString("."), match.range.first) - } - } - } - - return out to topLevel - } - - /** Returns the zero-based line number containing [offset]. */ - fun lineOf(text: String, offset: Int): Int { - var line = 0 - for (i in 0 until offset.coerceAtMost(text.length)) { - if (text[i] == '\n') line++ - } - return line - } - - /** - * Masks comments, string and character literals, and preprocessor directive lines with spaces. - * - * Newlines are preserved, keeping offsets aligned with the original source. - */ - internal fun mask(text: String): String { - val out = text.toCharArray() - - fun blank(from: Int, to: Int) { - for (k in from until to.coerceAtMost(out.size)) { - if (out[k] != '\n' && out[k] != '\r') out[k] = ' ' - } - } - - var i = 0 - var lineStart = true - - while (i < text.length) { - val c = text[i] - - if (c == '\n') { - lineStart = true - i++ - continue - } - - if (lineStart && c.isWhitespace()) { - i++ - continue - } - - if (lineStart && c == '#') { - val end = text.indexOf('\n', i).let { if (it < 0) text.length else it } - blank(i, end) - i = end - continue - } - - lineStart = false - - when { - text.startsWith("//", i) -> { - val end = text.indexOf('\n', i).let { if (it < 0) text.length else it } - blank(i, end) - i = end - } - - text.startsWith("/*", i) -> { - val end = text.indexOf("*/", i + 2).let { if (it < 0) text.length else it + 2 } - blank(i, end) - i = end - } - - c == '"' || ((c == '$' || c == '@') && startsString(text, i)) -> { - i = maskString(text, i, ::blank) - } - - c == '\'' -> { - i = maskChar(text, i, ::blank) - } - - else -> i++ - } - } - - return String(out) - } - - /** Whether the `$` or `@` prefixes at [i] lead to a string literal. */ - private fun startsString(text: String, i: Int): Boolean { - var j = i - while (j < text.length && (text[j] == '$' || text[j] == '@')) j++ - return j < text.length && text[j] == '"' - } - - private fun maskString(text: String, start: Int, blank: (Int, Int) -> Unit): Int { - var i = start - var verbatim = false - - while (text[i] == '$' || text[i] == '@') { - if (text[i] == '@') verbatim = true - i++ - } - - var quotes = 0 - while (i + quotes < text.length && text[i + quotes] == '"') quotes++ - - val end: Int - - if (quotes >= 3) { - // Raw strings close with a run of at least as many quotes as the opening delimiter. - val close = "\"".repeat(quotes) - end = text.indexOf(close, i + quotes).let { if (it < 0) text.length else it + quotes } - } else { - var j = i + 1 - - while (j < text.length) { - val ch = text[j] - - if (verbatim) { - if (ch != '"') { - j++ - } else if (j + 1 < text.length && text[j + 1] == '"') { - j += 2 - } else { - j++ - break - } - } else { - if (ch == '\\') { - j += 2 - } else if (ch == '"') { - j++ - break - } else if (ch == '\n') { - break - } else { - j++ - } - } - } - - end = j.coerceAtMost(text.length) - } - - blank(start, end) - return end - } - - private val CHAR_LITERAL = Regex("""'(?:\\.[^'\n]{0,8}|[^'\\\n])'""") - - /** Masks a character literal; an unmatched apostrophe is left unchanged. */ - private fun maskChar(text: String, start: Int, blank: (Int, Int) -> Unit): Int { - val literal = CHAR_LITERAL.matchAt(text, start) ?: return start + 1 - blank(start, literal.range.last + 1) - return literal.range.last + 1 - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsMains.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsMains.kt deleted file mode 100644 index 950e9e0878..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsMains.kt +++ /dev/null @@ -1,114 +0,0 @@ -package dev.codeassist.csharp.project - -import dev.codeassist.csharp.project.csproj.Csproj -import dev.codeassist.csharp.project.csproj.CsprojGraph -import java.nio.file.Files -import java.nio.file.Path -import java.util.concurrent.ConcurrentHashMap - -/** - * Finds project entry points using [CsMainScan]. - * - * Results are cached per `.cs` file using its modified time and size, so the Run picker and editor run marks - * don't need to rescan unchanged files. - */ -internal object CsMains { - - private class Cached( - val modified: Long, - val size: Long, - val classes: List, - val topLevel: Boolean, - ) - - private val cache = ConcurrentHashMap() - - private fun sourcesOf(dir: Path): List { - val project = Csproj.load(dir) - return CsprojGraph.sources(dir, project) - } - - /** - * Whether any source file contains top-level statements. - * - * These become the program's entry point. The compiler ignores other `Main` methods (CS7022) and rejects - */ - fun hasTopLevelStatements(dir: Path): Boolean = topLevelFiles(dir).isNotEmpty() - - /** Returns source files containing top-level statements. See [compilerMain]. */ - fun topLevelFiles(dir: Path): List = sourcesOf(dir).filter { scanned(it)?.topLevel == true } - - /** - * Returns each class containing an entry point, once, in file order. - * - * Files with top-level statements are excluded because their `Main` methods are ignored. - */ - fun classes(dir: Path): List = - sourcesOf(dir) - .mapNotNull { scanned(it) } - .filter { !it.topLevel } - .flatMap { it.classes } - .distinct() - - /** - * Whether the Run picker and editor marks need a separate row for each class. - * - * This is needed when there are multiple entry-point classes, or one class alongside top-level statements. - */ - fun classRows(dir: Path): Boolean { - val count = classes(dir).size - return count >= 2 || (count == 1 && hasTopLevelStatements(dir)) - } - - /** - * Returns the class whose `Main` the module's own row runs. - * - * Priority: [override] (Module Settings > Run), ``, then the first discovered class. - * Returns null when no entry point is available. - * - * With top-level statements, the module runs those unless [override] is set. `` is ignored. - */ - fun entry(dir: Path, override: String?): String? { - if (hasTopLevelStatements(dir)) return override - return override ?: Csproj.load(dir)?.startupObject ?: classes(dir).firstOrNull() - } - - /** - * Returns the value for the compiler's `-main:` argument, or null when the compiler can choose automatically. - * - * An explicit [override] or `` takes priority. Otherwise, the first class is selected only when - * multiple entry-point classes exist. - * - * With top-level statements, only [override] applies. The caller excludes those files from compilation because - * `-main:` cannot be used alongside top-level statements. - */ - fun compilerMain(dir: Path, override: String?): String? { - if (hasTopLevelStatements(dir)) return override - return override - ?: Csproj.load(dir)?.startupObject - ?: classes(dir).takeIf { it.size >= 2 }?.first() - } - - private fun scanned(file: Path): Cached? { - val modified = runCatching { Files.getLastModifiedTime(file).toMillis() }.getOrNull() ?: return null - val size = runCatching { Files.size(file) }.getOrNull() ?: return null - - cache[file]?.let { - if (it.modified == modified && it.size == size) return it - } - - val text = runCatching { - String(Files.readAllBytes(file), Charsets.UTF_8) - }.getOrDefault("") - - val found = Cached( - modified = modified, - size = size, - classes = runCatching { CsMainScan.hits(text).map { it.className } }.getOrDefault(emptyList()), - topLevel = runCatching { CsMainScan.topLevel(text) != null }.getOrDefault(false), - ) - - cache[file] = found - return found - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsNewFiles.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsNewFiles.kt deleted file mode 100644 index 77d07022bc..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsNewFiles.kt +++ /dev/null @@ -1,171 +0,0 @@ -package dev.codeassist.csharp.project - -import dev.codeassist.csharp.ui.CsFileIcons -import dev.ide.plugin.ui.NewFileContent -import dev.ide.plugin.ui.NewFileKind -import dev.ide.plugin.ui.NewFileTemplate -import dev.ide.plugin.ui.UiRegistration -import java.io.File - -object CsNewFiles { - - private val IDENTIFIER = Regex("[A-Za-z_][A-Za-z0-9_]*") - - fun getName(input: String): String { - val name = input.trim().removeSuffix(".cs") - - require(name.isNotEmpty()) { - "Enter a class name" - } - - require(IDENTIFIER.matches(name)) { - "A class name must start with a letter or _, and contain only letters, digits and _" - } - - return name - } - - fun csClass(name: String): String = """ - public class $name - { - - } - """.trimIndent() - - fun csInterface(name: String): String = - """ - public interface $name - { - - } - """.trimIndent() - - fun csStruct(name: String): String = - """ - public struct $name - { - - } - """.trimIndent() - - fun csRecord(name: String): String = - """ - public record $name - { - - } - """.trimIndent() - - fun csEnum(name: String): String = - """ - public enum $name - { - - } - """.trimIndent() - - private val CS_DIRS = setOf("src", "bin") - - fun isCsharpDirectory(dir: String): Boolean { - val directory = File(dir) - - if (directory.name in CS_DIRS) return true - - var current: File? = directory - - while (current != null) { - if (current.listFiles()?.any { - it.isFile && it.extension.equals("csproj", ignoreCase = true) - } == true) { - return true - } - current = current.parentFile - } - - return directory.listFiles()?.any { - it.isFile && it.extension.equals("cs", ignoreCase = true) - } == true - } -} - -internal object CsNewFileTemplates { - - fun register(uiRegister: UiRegistration) { - uiRegister.newFileTemplate( - NewFileTemplate( - id = "dev.codeassist.csharp.class", - title = "New C# file", - nameLabel = "Name", - iconId = CsFileIcons.CSHARP, - appliesTo = CsNewFiles::isCsharpDirectory, - kinds = listOf( - NewFileKind( - id = "class", - label = "Class", - files = { _, name -> - val n = CsNewFiles.getName(name) - listOf( - NewFileContent( - "$n.cs", - CsNewFiles.csClass(n) - ), - ) - }, - ), - NewFileKind( - id = "interface", - label = "Interface", - files = { _, name -> - val n = CsNewFiles.getName(name) - listOf( - NewFileContent( - "$n.cs", - CsNewFiles.csInterface(n) - ), - ) - }, - ), - NewFileKind( - id = "struct", - label = "Struct", - files = { _, name -> - val n = CsNewFiles.getName(name) - listOf( - NewFileContent( - "$n.cs", - CsNewFiles.csStruct(n) - ), - ) - }, - ), - NewFileKind( - id = "record", - label = "Record", - files = { _, name -> - val n = CsNewFiles.getName(name) - listOf( - NewFileContent( - "$n.cs", - CsNewFiles.csRecord(n) - ), - ) - }, - ), - NewFileKind( - id = "enum", - label = "Enum", - files = { _, name -> - val n = CsNewFiles.getName(name) - listOf( - NewFileContent( - "$n.cs", - CsNewFiles.csEnum(n) - ), - ) - }, - ) - ) - ) - ) - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsProject.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsProject.kt deleted file mode 100644 index 1cbbda3b17..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsProject.kt +++ /dev/null @@ -1,140 +0,0 @@ -package dev.codeassist.csharp.project - -import dev.ide.model.BuildSystemId -import dev.ide.model.ContentRole -import dev.ide.model.DependencyScope -import dev.ide.model.FacetTemplate -import dev.ide.model.ModuleType -import dev.ide.model.PlatformKind -import dev.ide.model.SourceSetTemplate -import java.nio.file.FileVisitResult -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.SimpleFileVisitor -import java.nio.file.attribute.BasicFileAttributes - -/** - * Represents a C# project as a module. - * - * The project directory is also its source root, using a custom role owned by this plugin. - */ -object CsModuleType : ModuleType { - - /** Module type ID used by the host for Run, Build, and editor module matching. */ - const val ID = "csharp-project" - - override val id = ID - override val displayName = "C# project" - override val platform: PlatformKind - get() = DOTNET_PLATFORM - - override fun defaultSourceSets(): List = listOf( - SourceSetTemplate( - "main", - DependencyScope.IMPLEMENTATION, - mapOf( - "" to setOf(CS_SOURCE, ContentRole.SOURCE), - - // Build output inside the source root: dimmed in the tree and skipped by host - // sweeps such as indexing, search, and project-wide analysis. - "bin" to setOf(ContentRole.EXCLUDED), - "obj" to setOf(ContentRole.EXCLUDED), - ), - ), - ) - - override fun defaultFacets(): List = emptyList() - - override fun supportedBuildSystems(): Set = - setOf(BuildSystemId.NATIVE) - - /** C# source directory role. This is not a Java source root. */ - val CS_SOURCE = ContentRole("csharp-source") - - /** C# uses .NET reference assemblies, never `android.jar` or a JDK. */ - val DOTNET_PLATFORM = PlatformKind("DOTNET") -} - -/** Reads project files and metadata from disk. No .NET processes are started here. */ -object CsProject { - - /** Directories containing build output or tooling, not user source files. */ - private val SKIPPED = setOf("obj", "bin") - - /** Returns all project `.cs` files, sorted by path, as one compilation unit. */ - fun sources(dir: Path): List = - files(dir, Int.MAX_VALUE, skipHidden = true) - .filter { isSource(dir, it) } - .sortedBy { it.toString() } - - /** - * Returns regular files under [dir] up to [maxDepth]. - * - * Skips `bin/` and `obj/`, and optionally hidden directories. Since the project directory - * is also the source root, filtering these directories after walking them could mean - * traversing thousands of generated files. - */ - internal fun files(dir: Path, maxDepth: Int, skipHidden: Boolean): List { - if (!Files.isDirectory(dir)) return emptyList() - - val found = ArrayList() - val visitor = object : SimpleFileVisitor() { - - override fun preVisitDirectory( - folder: Path, - attrs: BasicFileAttributes, - ): FileVisitResult { - if (folder == dir) return FileVisitResult.CONTINUE - - val name = folder.fileName.toString() - return if (name in SKIPPED || (skipHidden && name.startsWith("."))) { - FileVisitResult.SKIP_SUBTREE - } else { - FileVisitResult.CONTINUE - } - } - - override fun visitFile( - file: Path, - attrs: BasicFileAttributes, - ): FileVisitResult { - if (attrs.isRegularFile) found.add(file) - return FileVisitResult.CONTINUE - } - - override fun visitFileFailed( - file: Path, - exc: java.io.IOException, - ): FileVisitResult = FileVisitResult.CONTINUE - } - - Files.walkFileTree(dir, emptySet(), maxDepth, visitor) - return found - } - - /** - * Converts a free-form project name into a valid assembly name. - * - * Keeps only letters, digits, and underscores, and prefixes names that start with a digit. - * For example, `My App` becomes `MyApp`. - */ - fun assemblyName(raw: String): String { - val name = raw.filter { it.isLetterOrDigit() || it == '_' }.ifEmpty { "App" } - return if (name.first().isDigit()) "App$name" else name - } - - /** - * Checks whether [path] is a visible `.cs` file outside the directories in [SKIPPED]. - */ - private fun isSource(dir: Path, path: Path): Boolean { - val fileName = path.fileName.toString() - if (!Files.isRegularFile(path) || !fileName.endsWith(".cs") || fileName.startsWith(".")) { - return false - } - - return dir.relativize(path).none { part -> - val folder = part.toString() - folder.startsWith(".") || folder in SKIPPED - } - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsRunConfig.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsRunConfig.kt deleted file mode 100644 index 62311f21ea..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/CsRunConfig.kt +++ /dev/null @@ -1,52 +0,0 @@ -package dev.codeassist.csharp.project - -import dev.codeassist.csharp.editor.CsWorkspace -import dev.ide.model.Module -import java.nio.file.Files -import java.nio.file.Path -import java.util.Properties - -/** - * The entry point the user chose for a module on its Run card in Module Settings. - * - * Asked of the host through `RunSettings` (SPI 3.7.0) once a workspace has been seen. A host older than that - * has no such service, and there the value is read from where the IDE stores it: - * `/.platform/settings.properties`, under `module.mainClass.`. That file is the IDE's own, - * so if an old host kept it elsewhere the override is not found and Run starts the first `Main`. - */ -internal object CsRunConfig { - - /** Returns the configured entry point for [module], or null when none is set. */ - fun entryPoint(module: Module, moduleDir: Path): String? { - val settings = CsWorkspace.entryPoints ?: return mainClassOverride(module.id.value, moduleDir) - return runCatching { settings(module) }.getOrNull()?.trim()?.takeIf { it.isNotEmpty() } - } - - /** Maximum number of parent directories searched for `.platform`. */ - private const val LEVELS = 6 - - /** Reads the entry point for [moduleId] from the IDE's settings file, or null when none is set. */ - fun mainClassOverride(moduleId: String, moduleDir: Path): String? { - var dir: Path? = moduleDir.toAbsolutePath().normalize() - - repeat(LEVELS) { - val current = dir ?: return null - val file = current.resolve(".platform/settings.properties") - - if (Files.isRegularFile(file)) { - return runCatching { - Properties().apply { - Files.newBufferedReader(file).use { load(it) } - } - .getProperty("module.mainClass.$moduleId") - ?.trim() - ?.takeIf { it.isNotEmpty() } - }.getOrNull() - } - - dir = current.parent - } - - return null - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojCheck.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojCheck.kt deleted file mode 100644 index f0902513e6..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojCheck.kt +++ /dev/null @@ -1,339 +0,0 @@ -package dev.codeassist.csharp.project.csproj - -import dev.codeassist.csharp.project.csproj.CsprojText.Element -import java.io.StringReader -import javax.xml.parsers.DocumentBuilderFactory -import org.xml.sax.InputSource -import org.xml.sax.SAXParseException - -/** - * Checks a project file for issues relevant to the editor: - * invalid or unsupported values, missing referenced files, and settings this plugin does not honour. - * - * Checks are performed against [CsprojText], so every finding has a source range. - * Only definite problems are reported. Unknown properties and elements are left alone, - * and values containing MSBuild expressions (`$(...)`) are not validated. - */ -internal object CsprojCheck { - - enum class Level { ERROR, WARNING } - - class Finding( - val start: Int, - val end: Int, - val level: Level, - val message: String, - val code: String, - ) - - /** Project context used to check referenced paths and entry points. */ - class Env( - /** Checks a path as written in the project, relative to its folder. */ - val exists: (String) -> Boolean, - /** Classes containing a `Main` method in the project sources. */ - val mainClasses: List, - val hasTopLevelStatements: Boolean, - ) - - private val FRAMEWORK = - Regex("""net\d+(\.\d+)?(-[\w.]+)?|netcoreapp\d+\.\d+|netstandard\d+\.\d+|net4\d+""") - - private val LANG_VERSION = Regex("""\d+(\.\d+)?""") - private val LANG_WORDS = setOf("latest", "latestmajor", "preview", "default") - - fun check(text: String, env: Env): List { - wellFormed(text)?.let { return listOf(it) } - - val elements = CsprojText.elements(text) - val out = ArrayList() - - for (el in elements) { - when (el.parent) { - "PropertyGroup" -> property(el, out, env) - "ItemGroup" -> item(el, elements, out, env) - } - } - - duplicatePackages(elements, out) - return out - } - - /** - * Returns the XML parser's error as a finding on the affected line, - * or null when the document is well formed. - */ - fun wellFormed(text: String): Finding? { - val factory = DocumentBuilderFactory.newInstance() - runCatching { - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) - } - - return try { - val builder = factory.newDocumentBuilder() - builder.setErrorHandler(null) - builder.parse(InputSource(StringReader(text))) - null - } catch (e: SAXParseException) { - val start = offsetOfLine(text, e.lineNumber) - val lineEnd = text.indexOf('\n', start).let { - if (it < 0) text.length else it - } - - Finding( - start, - lineEnd.coerceAtLeast(start + 1).coerceAtMost(maxOf(text.length, start + 1)), - Level.ERROR, - "Not well-formed XML: ${e.message?.substringAfter(": ")?.trim().orEmpty()}", - "csproj.xml", - ) - } catch (e: Exception) { - null - } - } - - private fun property(el: CsprojText.Element, out: MutableList, env: Env) { - val value = value(el) - if (value.isEmpty() || "$(" in value) return - - val (start, end) = valueRange(el) - - fun bad(message: String) { - out += Finding(start, end, Level.ERROR, message, "csproj.value") - } - - if (el.name == "StartupObject") { - return startupObject(value, start, end, out, env) - } - - val property = CsprojSchema.property(el.name) ?: return - - when (property.kind) { - CsprojSchema.Kind.ENUM, CsprojSchema.Kind.BOOLEAN -> - if (property.values.none { it.equals(value, ignoreCase = true) }) { - bad("${property.name} is ${property.values.joinToString(", ")}, not '$value'") - } - - CsprojSchema.Kind.INTEGER -> - if (value.toIntOrNull() !in 0..9) { - bad("${property.name} is a number from 0 to 9, not '$value'") - } - - CsprojSchema.Kind.LANG_VERSION -> - if (value.lowercase() !in LANG_WORDS && !LANG_VERSION.matches(value)) { - bad("LangVersion is latest, preview, default or a number such as 12, not '$value'") - } - - CsprojSchema.Kind.FRAMEWORK -> - if (!FRAMEWORK.matches(value)) { - out += Finding( - start, - end, - Level.WARNING, - "Unrecognised target framework '$value'", - "csproj.value", - ) - } - - CsprojSchema.Kind.TEXT -> Unit - } - } - - private fun startupObject( - value: String, - start: Int, - end: Int, - out: MutableList, - env: Env, - ) { - when { - env.hasTopLevelStatements -> out += Finding( - start, - end, - Level.WARNING, - "StartupObject is ignored: a file has top-level statements, which are the entry point", - "csproj.startup", - ) - - env.mainClasses.isNotEmpty() && value !in env.mainClasses -> out += Finding( - start, - end, - Level.WARNING, - "No static Main in '$value' (found: ${env.mainClasses.joinToString()})", - "csproj.startup", - ) - } - } - - private fun item( - el: CsprojText.Element, - all: List, - out: MutableList, - env: Env, - ) { - val include = el.attr("Include") - - fun warn(start: Int, end: Int, message: String, code: String) { - out += Finding(start, end, Level.WARNING, message, code) - } - - when (el.name) { - "PackageReference" -> { - if (include == null && el.attr("Update") == null) { - out += Finding( - el.nameStart, - el.nameEnd, - Level.ERROR, - "PackageReference needs an Include", - "csproj.item", - ) - } else if (include != null && include.value.isBlank()) { - out += Finding( - include.valueStart, - include.valueEnd + 1, - Level.ERROR, - "Empty package id", - "csproj.item", - ) - } else if ( - include != null && - el.attr("Version") == null && - child(el, all, "Version") == null - ) { - warn( - el.nameStart, - el.nameEnd, - "No Version: the restore is asked for the package with none", - "csproj.item", - ) - } - } - - "ProjectReference" -> if ( - include != null && - include.value.isNotBlank() && - "$(" !in include.value && - !env.exists(include.value.replace('\\', '/')) - ) { - warn( - include.valueStart, - include.valueEnd, - "Project not found: ${include.value}", - "csproj.item", - ) - } - - "Reference" -> { - val hint = el.attr("HintPath")?.let { - it.value to (it.valueStart to it.valueEnd) - } ?: child(el, all, "HintPath")?.let { - it.text.trim() to (it.textStart to it.textEnd) - } - - if ( - hint != null && - hint.first.isNotEmpty() && - "$(" !in hint.first && - !env.exists(hint.first) - ) { - warn( - hint.second.first, - hint.second.second, - "HintPath not found: ${hint.first}", - "csproj.item", - ) - } - } - - "Compile" -> include?.let { - val path = it.value - val literal = path.none { c -> c in "*?" } && - "$(" !in path && - ';' !in path && - path.isNotBlank() - - if (literal && !env.exists(path)) { - warn(it.valueStart, it.valueEnd, "File not found: $path", "csproj.item") - } - } - - "Using" -> if (include == null && el.attr("Remove") == null) { - warn( - el.nameStart, - el.nameEnd, - "Using needs an Include or a Remove", - "csproj.item", - ) - } - } - } - - /** - * Finds an element named [name] inside [parent], such as `` - * inside ``. - */ - private fun child( - parent: CsprojText.Element, - all: List, - name: String, - ): CsprojText.Element? { - val end = parent.textEnd - if (parent.selfClosing) return null - - // The scan does not record closing tags. Find the matching child before the next sibling. - val index = all.indexOf(parent) - - for (i in index + 1 until all.size) { - val candidate = all[i] - - if (candidate.parent != parent.name) { - if (candidate.start > end && candidate.parent == parent.parent) return null - continue - } - - if (candidate.name == name && candidate.start >= parent.textStart) return candidate - if (candidate.name == parent.name) return null - } - - return null - } - - private fun duplicatePackages(elements: List, out: MutableList) { - val seen = HashSet() - - for (el in elements) { - if (el.name != "PackageReference" || el.parent != "ItemGroup") continue - - val include = el.attr("Include") ?: continue - if (include.value.isBlank() || "$(" in include.value) continue - - if (!seen.add(include.value.lowercase())) { - out += Finding( - include.valueStart, - include.valueEnd, - Level.WARNING, - "${include.value} is referenced more than once", - "csproj.item", - ) - } - } - } - - private fun value(element: CsprojText.Element) = element.text.trim() - - private fun valueRange(element: CsprojText.Element): Pair { - val lead = element.text.length - element.text.trimStart().length - return (element.textStart + lead) to (element.textStart + lead + value(element).length) - } - - private fun offsetOfLine(text: String, line: Int): Int { - var offset = 0 - - repeat((line - 1).coerceAtLeast(0)) { - val next = text.indexOf('\n', offset) - if (next < 0) return text.length - offset = next + 1 - } - - return offset - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojCompleter.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojCompleter.kt deleted file mode 100644 index 0a556dc059..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojCompleter.kt +++ /dev/null @@ -1,116 +0,0 @@ -package dev.codeassist.csharp.project.csproj - - /** - * Provides completion suggestions for project files: - * child tag names, item attributes, and valid property or attribute values. - * - * All completion logic operates on [CsprojText.positionAt] and [CsprojSchema]. - * The editor's completion contributor is responsible only for converting suggestions - * into completion items. - */ -internal object CsprojCompleter { - - enum class Kind { TAG, ATTRIBUTE, VALUE } - - /** - * [label] is displayed to the user. - * [insert] replaces the typed text. - * [caret] specifies the caret position inside [insert], or null to place it at the end. - */ - class Suggestion( - val label: String, - val insert: String, - val detail: String, - val kind: Kind, - val caret: Int? = null, - ) - - fun suggest(text: String, caret: Int): List = - when (val position = CsprojText.positionAt(text, caret)) { - null -> emptyList() - is CsprojText.Position.TagName -> tags(position) - is CsprojText.Position.ClosingName -> - position.open?.let { - listOf(Suggestion(it, it, "close <$it>", Kind.TAG)) - }.orEmpty() - is CsprojText.Position.AttributeName -> attributes(text, caret, position) - is CsprojText.Position.AttributeValue -> attributeValues(position) - is CsprojText.Position.Value -> values(position) - } - - private fun tags(position: CsprojText.Position.TagName): List = - when (position.parent) { - null -> listOf( - Suggestion("Project", "Project Sdk=\"Microsoft.NET.Sdk\"", "the root element", Kind.TAG), - ) - - "Project" -> CsprojSchema.GROUPS.map { - Suggestion(it, it, " child", Kind.TAG) - } - - "PropertyGroup" -> CsprojSchema.PROPERTIES.map { - Suggestion(it.name, "${it.name}>", it.doc, Kind.TAG, it.name.length + 1) - } - - "ItemGroup" -> CsprojSchema.ITEMS.map { - val head = "${it.name} Include=\"" - Suggestion(it.name, "$head\" />", it.doc, Kind.TAG, head.length) - } - - else -> emptyList() - }.filter { it.label.startsWith(position.typed, ignoreCase = true) } - - private fun attributes( - text: String, - caret: Int, - position: CsprojText.Position.AttributeName, - ): List { - val item = CsprojSchema.item(position.element) ?: return emptyList() - - // Exclude attributes already present in the current start tag. - val tagStart = text.lastIndexOf('<', (caret - 1).coerceAtLeast(0)) - val written = if (tagStart >= 0) { - text.substring(tagStart, caret.coerceIn(0, text.length)) - } else { - "" - } - - return item.attributes - .filter { !Regex("""\s${it}\s*=""").containsMatchIn(written) } - .filter { it.startsWith(position.typed, ignoreCase = true) } - .map { - Suggestion(it, "$it=\"\"", "${item.name} attribute", Kind.ATTRIBUTE, it.length + 2) - } - } - - private fun attributeValues(position: CsprojText.Position.AttributeValue): List { - val words = when (position.element to position.attribute) { - "Reference" to "Private", "Using" to "Static" -> listOf("true", "false") - else -> emptyList() - } - - return words - .filter { it.startsWith(position.typed, ignoreCase = true) } - .map { Suggestion(it, it, "${position.attribute} value", Kind.VALUE) } - } - - private fun values(position: CsprojText.Position.Value): List { - if (position.parent != "PropertyGroup") return emptyList() - - val property = CsprojSchema.property(position.element) ?: return emptyList() - - val words = when (property.kind) { - CsprojSchema.Kind.FRAMEWORK -> - listOf("net10.0", "net9.0", "net8.0", "net7.0", "net6.0", "netstandard2.1") - - CsprojSchema.Kind.LANG_VERSION -> - listOf("latest", "preview", "default", "13", "12", "11", "10") - - else -> property.values - } - - return words - .filter { it.startsWith(position.typed, ignoreCase = true) } - .map { Suggestion(it, it, property.name, Kind.VALUE) } - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojCondition.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojCondition.kt deleted file mode 100644 index 6f71a667aa..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojCondition.kt +++ /dev/null @@ -1,49 +0,0 @@ -package dev.codeassist.csharp.project.csproj -/** - * Evaluates the `Condition="..."` expressions used by hand-written or template-generated project files. - * - * Supports comparisons such as `'$(Configuration)' == 'Debug'` and - * `'$(TargetFramework)' != 'net10.0'`, joined by `and` and `or`. - * String comparisons are case-insensitive, as in MSBuild. - * - * Only these forms are evaluated. - * Unsupported expressions, such as `Exists(...)`, `HasTrailingSlash(...)`, - * `$(A) > 3`, or expressions with parentheses, are treated as true, preserving - * the previous behavior. `and` has higher precedence than `or`. - * `Not` is not supported. Properties missing from [vars] expand to empty strings, - * as in MSBuild. - */ -internal object CsprojCondition { - - private val OR = Regex("""\s+or\s+""", RegexOption.IGNORE_CASE) - private val AND = Regex("""\s+and\s+""", RegexOption.IGNORE_CASE) - - private val COMPARISON = Regex( - """^\s*(?:'([^']*)'|"([^"]*)"|(\S+?))\s*(==|!=)\s*(?:'([^']*)'|"([^"]*)"|(\S+?))\s*$""", - ) - - private val PROPERTY = Regex("""\$\((\w+)\)""") - - /** Returns whether [condition] holds. Missing, blank, and unsupported conditions evaluate to true. */ - fun holds(condition: String?, vars: Map): Boolean { - if (condition.isNullOrBlank()) return true - - return OR.split(condition).any { alternative -> - AND.split(alternative).all { clause -> clause(clause, vars) } - } - } - - private fun clause(text: String, vars: Map): Boolean { - val match = COMPARISON.matchEntire(text) ?: return true - val g = match.groupValues - - val left = expand(g[1].ifEmpty { g[2] }.ifEmpty { g[3] }, vars) - val right = expand(g[5].ifEmpty { g[6] }.ifEmpty { g[7] }, vars) - - val equal = left.equals(right, ignoreCase = true) - return if (g[4] == "==") equal else !equal - } - - private fun expand(text: String, vars: Map): String = - PROPERTY.replace(text) { vars[it.groupValues[1]].orEmpty() } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojExtras.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojExtras.kt deleted file mode 100644 index da850002cd..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojExtras.kt +++ /dev/null @@ -1,148 +0,0 @@ -package dev.codeassist.csharp.project.csproj - -import dev.codeassist.csharp.project.CsProject -import java.nio.file.Path - -/** - * Assembly information configured by project properties such as `` and ``. - * - * The SDK converts these properties into `[assembly: ...]` attributes in a generated file. - * [CsprojExtras.assemblyInfoText] generates the equivalent content. - * - * [generate] corresponds to ``: when false, the project provides its own attributes. - */ -internal data class CsprojAssemblyInfo( - val generate: Boolean = true, - val version: String? = null, - val assemblyVersion: String? = null, - val fileVersion: String? = null, - val informationalVersion: String? = null, - val company: String? = null, - val product: String? = null, - val description: String? = null, - val copyright: String? = null, - val title: String? = null, -) { - val isEmpty: Boolean - get() = listOf( - version, - assemblyVersion, - fileVersion, - informationalVersion, - company, - product, - description, - copyright, - title, - ).all { it.isNullOrBlank() } -} - -/** - * Handles build settings beyond compilation, including debug symbols, platform targets, - * embedded resources, and assembly attributes. - */ -internal object CsprojExtras { - - private val DEBUG_TYPES = setOf("full", "portable", "embedded", "pdbonly") - - private val PLATFORMS = mapOf( - "anycpu" to "anycpu", - "anycpu32bitpreferred" to "anycpu32bitpreferred", - "x86" to "x86", - "x64" to "x64", - "arm" to "arm", - "arm64" to "arm64", - ) - - // Compiler flags - - /** Returns the debug flag, or null for `none`, an unknown value, or no setting. */ - fun debugFlag(info: CsprojInfo): String? = - info.debugType?.takeIf { it in DEBUG_TYPES }?.let { "-debug:$it" } - - /** Returns the platform flag, or null for an unknown value or no setting. */ - fun platformFlag(info: CsprojInfo): String? = - info.platformTarget?.lowercase()?.let { PLATFORMS[it] }?.let { "-platform:$it" } - - // Documentation - - /** Returns the XML documentation filename beside [dll], such as `App.xml` for `App.dll`. */ - fun documentationName(dll: Path): String = - dll.fileName.toString().removeSuffix(".dll") + ".xml" - - // Embedded resources - - /** - * Returns the project files to embed as path and resource-name pairs. - * - * Resource names use the root namespace followed by the project-relative path, with - * `/` replaced by `.` and spaces replaced by `_`. Files under `bin` and `obj` are skipped. - */ - fun resources(info: CsprojInfo, dir: Path): List> { - if (info.embeddedResources.isEmpty()) return emptyList() - val patterns = info.embeddedResources.map(::globToRegex) - val namespace = (info.rootNamespace ?: info.assemblyName ?: info.projectName).orEmpty() - val files = try { - CsProject.files(dir, Int.MAX_VALUE, skipHidden = false).sorted() - } catch (e: Exception) { - emptyList() - } - return files.mapNotNull { path -> - val relative = dir.relativize(path).toString().replace('\\', '/') - if (patterns.none { it.matches(relative) }) return@mapNotNull null - path to resourceName(namespace, relative) - } - } - - fun resourceName(namespace: String, relative: String): String { - val tail = relative.replace(' ', '_').replace('/', '.') - return if (namespace.isEmpty()) tail else "$namespace.$tail" - } - - // Assembly information - - /** - * Generates the C# file containing the project's assembly attributes. - * - * Returns an empty string when no attributes are configured or generation is disabled. - * `` supplies the default assembly and file versions as numeric versions - * (`1.2.3-beta` becomes `1.2.3.0`) and the informational version as written. - * Each version can also be configured independently. - */ - fun assemblyInfoText(info: CsprojInfo): String { - val a = info.assemblyInfo - if (!a.generate || a.isEmpty) return "" - val numeric = a.version?.let(::numericVersion) - val lines = buildList { - (a.assemblyVersion ?: numeric)?.let { add("AssemblyVersion" to it) } - (a.fileVersion ?: numeric)?.let { add("AssemblyFileVersion" to it) } - (a.informationalVersion ?: a.version)?.let { add("AssemblyInformationalVersion" to it) } - a.company?.let { add("AssemblyCompany" to it) } - a.product?.let { add("AssemblyProduct" to it) } - a.description?.let { add("AssemblyDescription" to it) } - a.copyright?.let { add("AssemblyCopyright" to it) } - a.title?.let { add("AssemblyTitle" to it) } - }.filter { it.second.isNotBlank() } - if (lines.isEmpty()) return "" - return buildString { - append("// from the project file by the C# plugin.\n") - for ((attribute, value) in lines) { - append("[assembly: System.Reflection.").append(attribute).append("Attribute(\"") - append(escape(value)).append("\")]\n") - } - } - } - - /** Converts a version to four numeric components, or returns null if it is not numeric. */ - fun numericVersion(version: String): String? { - val core = version.trim().substringBefore('-').substringBefore('+') - val parts = core.split('.') - if (parts.isEmpty() || parts.size > 4 || parts.any { it.isEmpty() || !it.all(Char::isDigit) }) return null - return (parts + List(4 - parts.size) { "0" }).joinToString(".") - } - - // Private helpers - - private fun escape(value: String): String = value.replace("\\", "\\\\").replace("\"", "\\\"") - .replace("\r", "").replace("\n", " ") -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojGraph.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojGraph.kt deleted file mode 100644 index 04fc160fa7..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojGraph.kt +++ /dev/null @@ -1,108 +0,0 @@ -package dev.codeassist.csharp.project.csproj - -import dev.codeassist.csharp.project.CsProject -import java.nio.file.Files -import java.nio.file.Path - -/** - * The projects a project references, directly and through others. - * - * A `` reaches everything the referenced project references in turn, as it does in an - * SDK-style build, so the answer is the whole closure. It is ordered with dependencies first: each project - * comes after the ones it needs, which is the order to build them in. - */ -internal object CsprojGraph { - - /** A referenced project: its file, what the file says, and the name of the assembly it builds. */ - class Node(val file: Path, val info: CsprojInfo) { - val dir: Path get() = file.parent - val assemblyName: String get() = Csproj.assemblyName(info, file.fileName.toString().removeSuffix(".csproj")) - - /** Where a build puts this project's DLL. */ - val output: Path get() = Csproj.outputDir(dir, info).resolve("$assemblyName.dll") - } - - /** [nodes] in build order, and what could not be followed: a missing or unreadable file, a cycle. */ - class Result(val nodes: List, val problems: List) - - /** - * The closure of the references of the project at [projectFile], which says [info]. [read] parses a - * project file and gives null for one it cannot read. - */ - fun referenced( - projectFile: Path, - info: CsprojInfo, - read: (Path) -> CsprojInfo? = { runCatching { Csproj.read(it) }.getOrNull() }, - ): Result { - val root = projectFile.toAbsolutePath().normalize() - val done = LinkedHashMap() - val problems = LinkedHashSet() - val open = ArrayList() - - fun visit(file: Path, declared: CsprojInfo) { - open.add(file) - for (include in declared.projectReferences) { - val target = resolve(file, include) - if (target == null || !Files.isRegularFile(target)) { - problems.add("referenced project not found: $include (from ${file.fileName})") - continue - } - if (target in open) { - val cycle = (open.subList(open.indexOf(target), open.size) + target).joinToString(" -> ") { it.fileName.toString() } - problems.add("project references form a cycle: $cycle") - continue - } - if (target in done) continue - val read = read(target) - if (read == null) { - problems.add("referenced project could not be read: $include (from ${file.fileName})") - continue - } - visit(target, read) - done[target] = Node(target, read) - } - open.removeAt(open.size - 1) - } - - visit(root, info) - done.remove(root) - return Result(done.values.toList(), problems.toList()) - } - - /** The file an `Include` names: relative to the referencing project's folder, with either slash. */ - private fun resolve(from: Path, include: String): Path? = runCatching { - from.parent.resolve(include.trim().replace('\\', '/')).toAbsolutePath().normalize() - }.getOrNull() - - /** - * The `.cs` files of the project in [projectDir]: every one under it that [info]'s Compile items keep, - * except those under a folder with a project file of its own. A solution laid out with one project inside - * another's folder would otherwise compile the inner project's files twice. - */ - fun sources(projectDir: Path, info: CsprojInfo?): List { - val files = CsProject.files(projectDir, Int.MAX_VALUE, skipHidden = true) - val inner = files.filter { it.fileName.toString().endsWith(".csproj") } - .map { it.parent } - .filter { it != projectDir } - .distinct() - val candidates = CsProject.sources(projectDir).filter { file -> inner.none { file.startsWith(it) } } - return info?.let { Csproj.sources(it, projectDir, candidates) } ?: candidates - } - - /** - * The folder of the project [file] belongs to: the nearest folder above it that holds a `.csproj` - * directly, or null when there is none within [levels] folders. - */ - fun owningDir(file: Path, levels: Int = 8): Path? { - var dir: Path? = file.toAbsolutePath().normalize().parent - repeat(levels) { - val current = dir ?: return null - val has = runCatching { - Files.list(current).use { entries -> entries.anyMatch { it.fileName.toString().endsWith(".csproj") } } - }.getOrDefault(false) - if (has) return current - dir = current.parent - } - return null - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojProject.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojProject.kt deleted file mode 100644 index b2bad3f45d..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojProject.kt +++ /dev/null @@ -1,528 +0,0 @@ -package dev.codeassist.csharp.project.csproj - -import android.util.Log -import dev.codeassist.csharp.project.CsProject -import dev.codeassist.csharp.project.nuget.NuGet -import dev.codeassist.csharp.util.TAG -import java.nio.file.Files -import java.nio.file.Path -import javax.xml.parsers.DocumentBuilderFactory -import org.w3c.dom.Element - -/** - * A `` containing the package [id] and its [version] as written. - * - * The version may be a range or a floating version, or null when none is specified. - */ -internal data class CsprojPackage(val id: String, val version: String?) - -/** - * The SDK-style `.csproj` settings that affect how this plugin compiles a project. - * - * The file is read as plain XML, not evaluated by MSBuild. Only properties and items - * that this compiler can honor are retained; unsupported settings are not inferred. - * - * Conditional properties (`Condition="..."`) are currently read as if unconditional. - * When a property is set more than once, its last value wins, as in MSBuild. - */ -internal data class CsprojInfo( - val assemblyName: String?, - val outputType: String, - val langVersion: String?, - val nullable: Boolean, - val implicitUsings: Boolean, - val defines: List, - val includes: List, - val removes: List, - val projectReferences: List, - val packageReferences: List, - val targetFramework: String?, - val references: List, - val outDir: String? = null, - val appendTargetFramework: Boolean = true, - val projectName: String? = null, - /** ``: the class whose `Main` is the entry point; Module Settings > Run takes precedence. */ - val startupObject: String? = null, - /** `` as written; [nullable] is true only when the value is `enable`. */ - val nullableMode: String? = null, - val allowUnsafe: Boolean = false, - val treatWarningsAsErrors: Boolean = false, - val warningsAsErrors: List = emptyList(), - val warningsNotAsErrors: List = emptyList(), - val noWarn: List = emptyList(), - val warningLevel: Int? = null, - val checkedArithmetic: Boolean = false, - val optimize: Boolean = false, - /** `` items: namespaces or, with [CsprojUsing.static], types imported in every file. */ - val usings: List = emptyList(), - /** ``: implicit usings removed by the project. */ - val removedUsings: List = emptyList(), - /** ``: false means only explicit `Compile Include` files are compiled. */ - val enableDefaultCompileItems: Boolean = true, - /** `` as written (`full`, `portable`, `embedded`, `pdbonly`, `none`); null uses the compiler default. */ - val debugType: String? = null, - /** `` as written (`AnyCPU`, `x64`, and so on); null uses the compiler default. */ - val platformTarget: String? = null, - /** ``: whether to write the XML documentation file beside the DLL. */ - val generateDocumentation: Boolean = false, - /** `` patterns, relative to the project folder, using `/` separators. */ - val embeddedResources: List = emptyList(), - val rootNamespace: String? = null, - val assemblyInfo: CsprojAssemblyInfo = CsprojAssemblyInfo(), -) { - /** A library has no entry point: it is built but never started. */ - val isLibrary: Boolean - get() = outputType.equals("Library", ignoreCase = true) -} - -/** A `` item. */ -internal data class CsprojUsing( - val name: String, - val alias: String? = null, - val static: Boolean = false, -) - -/** - * A `` with its name, optional `HintPath`, and copy-local setting. - * - * `false` disables copying the DLL beside the output. - */ -internal data class CsprojReference( - val name: String, - val hintPath: String?, - val copyLocal: Boolean = true, -) - -/** Reads a project file and converts its supported settings into compiler arguments. */ -internal object Csproj { - - /** Maximum depth below the module folder when searching for a `.csproj`. */ - private const val MAX_PROJECT_DEPTH = 3 - - private val cache = java.util.concurrent.ConcurrentHashMap() - - private class Cached( - val stamp: Pair, - val info: CsprojInfo, - ) - - private val IMPLICIT_USINGS = listOf( - "System", - "System.Collections.Generic", - "System.IO", - "System.Linq", - "System.Net.Http", - "System.Threading", - "System.Threading.Tasks", - ) - - private val NULLABLE_MODES = setOf("enable", "disable", "warnings", "annotations") - - /** - * Finds the `.csproj` in [dir]. - * - * Checks [dir] itself first, then searches up to three folders below it, - * excluding `bin` and `obj`. Returns null when no project file exists. - */ - fun find(dir: Path): Path? { - if (!Files.isDirectory(dir)) return null - val direct = Files.list(dir).use { entries -> - entries.filter { it.fileName.toString().endsWith(".csproj") }.sorted().findFirst().orElse(null) - } - if (direct != null) return direct - return CsProject.files(dir, MAX_PROJECT_DEPTH, skipHidden = false) - .filter { it.fileName.toString().endsWith(".csproj") }.minOrNull() - } - - /** - * Loads the project in [dir], or returns null when none exists or it cannot be read. - * - * Parsed data is cached while the file's modification time and size remain unchanged. - * Only actual reads are logged. - */ - fun load(dir: Path): CsprojInfo? { - val file = find(dir) ?: return null - val stamp = try { - Files.getLastModifiedTime(file).toMillis() to Files.size(file) - } catch (e: Exception) { - null - } - if (stamp != null) { - cache[file]?.let { if (it.stamp == stamp) return it.info } - } - return try { - read(file).also { info -> - logSummary(file, info) - if (info.targetFramework != null && info.targetFramework != "net10.0") { - Log.d(TAG, "csproj: targets ${info.targetFramework}; this compiler has net10.0 references only") - } - if (stamp != null) cache[file] = Cached(stamp, info) - } - } catch (e: Exception) { - Log.d(TAG, "csproj: could not read ${file.fileName}: $e") - cache.remove(file) - null - } - } - - /** Parses [file]. Throws when it is not well-formed XML. */ - fun read(file: Path): CsprojInfo { - val factory = DocumentBuilderFactory.newInstance() - factory.isNamespaceAware = false - val root = factory.newDocumentBuilder().parse(file.toFile()).documentElement - - // Conditions are evaluated for a Debug build of the project's own target framework. - val vars = HashMap().apply { - put("Configuration", "Debug") - put("Platform", "AnyCPU") - lastValue(root, "TargetFramework") { true }?.let { put("TargetFramework", it) } - } - - /** Returns true when [element] and all its ancestors have conditions that hold. */ - fun active(element: Element): Boolean { - var node: org.w3c.dom.Node? = element - while (node is Element) { - if (!CsprojCondition.holds(node.getAttribute("Condition"), vars)) return false - node = node.parentNode - } - return true - } - - /** Returns the last non-empty value of [name], allowing later settings to override earlier ones. */ - fun property(name: String): String? = lastValue(root, name, ::active) - - fun flag(name: String): Boolean = property(name).equals("true", ignoreCase = true) - - /** Returns the separated values of [name], excluding unresolved `$(Name)` references. */ - fun list(name: String): List = property(name)?.split(';', ',')?.map { it.trim() } - ?.filter { it.isNotEmpty() && !it.contains("$(") } ?: emptyList() - - /** Returns the `;`-separated values of [attribute] on active elements named [tag]. */ - fun items(tag: String, attribute: String): List { - val nodes = root.getElementsByTagName(tag) - return (0 until nodes.length).map { nodes.item(it) as Element }.filter(::active).flatMap { element -> - element.getAttribute(attribute) - .replace('\\', '/').split(';').map { it.trim() }.filter { it.isNotEmpty() } - } - } - - val usingNodes = root.getElementsByTagName("Using") - val usings = (0 until usingNodes.length).map { usingNodes.item(it) as Element }.filter(::active) - .flatMap { element -> - element.getAttribute("Include").split(';').map { it.trim() }.filter { it.isNotEmpty() }.map { - CsprojUsing( - it, - element.getAttribute("Alias").trim().ifEmpty { null }, - element.getAttribute("Static").equals("true", ignoreCase = true), - ) - } - } - - return CsprojInfo( - assemblyName = property("AssemblyName"), - // The SDK defaults to a library when OutputType is not specified. - outputType = property("OutputType") ?: "Library", - langVersion = property("LangVersion"), - nullable = property("Nullable").equals("enable", ignoreCase = true), - implicitUsings = property("ImplicitUsings").equals("enable", ignoreCase = true), - defines = list("DefineConstants"), - includes = items("Compile", "Include"), - removes = items("Compile", "Remove"), - projectReferences = items("ProjectReference", "Include"), - packageReferences = readPackages(root, ::active), - targetFramework = property("TargetFramework"), - references = readReferences(root, ::active), - outDir = property("OutDir"), - appendTargetFramework = !property("AppendTargetFrameworkToOutputPath").equals("false", ignoreCase = true), - projectName = file.fileName.toString().removeSuffix(".csproj"), - startupObject = property("StartupObject"), - nullableMode = property("Nullable")?.lowercase(), - allowUnsafe = flag("AllowUnsafeBlocks"), - treatWarningsAsErrors = flag("TreatWarningsAsErrors"), - warningsAsErrors = list("WarningsAsErrors"), - warningsNotAsErrors = list("WarningsNotAsErrors"), - noWarn = list("NoWarn"), - warningLevel = property("WarningLevel")?.toIntOrNull(), - checkedArithmetic = flag("CheckForOverflowUnderflow"), - optimize = flag("Optimize"), - usings = usings.filter { it.name.isNotEmpty() }, - removedUsings = items("Using", "Remove"), - enableDefaultCompileItems = !property("EnableDefaultCompileItems").equals("false", ignoreCase = true), - debugType = property("DebugType")?.lowercase(), - platformTarget = property("PlatformTarget"), - generateDocumentation = flag("GenerateDocumentationFile"), - embeddedResources = items("EmbeddedResource", "Include"), - rootNamespace = property("RootNamespace"), - assemblyInfo = CsprojAssemblyInfo( - generate = !property("GenerateAssemblyInfo").equals("false", ignoreCase = true), - version = property("Version"), - assemblyVersion = property("AssemblyVersion"), - fileVersion = property("FileVersion"), - informationalVersion = property("InformationalVersion"), - company = property("Company") ?: property("Authors"), - product = property("Product"), - description = property("Description"), - copyright = property("Copyright"), - title = property("AssemblyTitle"), - ), - ) - } - - /** Returns the last non-empty text of elements named [name] under [root] that [accept] allows. */ - private fun lastValue(root: Element, name: String, accept: (Element) -> Boolean): String? { - val nodes = root.getElementsByTagName(name) - var found: String? = null - for (i in 0 until nodes.length) { - val element = nodes.item(i) as Element - if (!accept(element)) continue - val text = element.textContent?.trim().orEmpty() - if (text.isNotEmpty()) found = text - } - return found - } - - // Source files and output paths - - /** - * Returns the `.cs` files the project compiles. - * - * Applies the project's Compile items to [candidates], which are all `.cs` files - * under [dir] outside `bin` and `obj`. With no Include items, every candidate is compiled. - */ - fun sources(info: CsprojInfo, dir: Path, candidates: List): List { - // When default items are disabled, only explicitly included files are compiled. - if (!info.enableDefaultCompileItems && info.includes.isEmpty()) return emptyList() - val includes = info.includes.map(::globToRegex) - val removes = info.removes.map(::globToRegex) - return candidates.filter { path -> - val relative = dir.relativize(path).toString().replace('\\', '/') - (includes.isEmpty() || includes.any { it.matches(relative) }) && removes.none { it.matches(relative) } - } - } - - /** - * Returns the project's output folder. - * - * `OutDir` takes precedence. Otherwise, the default is `bin/Debug//`, - * without the framework folder when `AppendTargetFrameworkToOutputPath` is false. - * The output remains inside the project folder. - */ - fun outputDir(dir: Path, info: CsprojInfo?): Path { - val projectDir = projectFolder(dir) - info?.outDir?.let { return projectDir.resolve(it.replace('\\', '/')).normalize() } - val debug = projectDir.resolve("bin").resolve("Debug") - return if (info?.appendTargetFramework == false) debug else debug.resolve(info?.targetFramework ?: "net10.0") - } - - /** Returns the assembly name from `AssemblyName`, the project filename, or the module name, in that order. */ - fun assemblyName(info: CsprojInfo?, moduleName: String): String = - CsProject.assemblyName(info?.assemblyName ?: info?.projectName ?: moduleName) - - /** Returns the folder containing the `.csproj`, or [dir] when there is no project file. */ - private fun projectFolder(dir: Path): Path = find(dir)?.parent ?: dir - - // References and packages - - /** - * Resolves project references to DLL files and returns the names of references that could not be found. - * - * A reference is searched for at its `HintPath`, then as `.dll` in the project folder and `lib/`. - */ - fun resolveReferences( - info: CsprojInfo, - dir: Path, - nuget: NuGet? = null, - frameworkDlls: Set = emptySet(), - ): Pair, List> { - val projectDir = projectFolder(dir) - val found = ArrayList() - val missing = ArrayList() - for (reference in info.references) { - val hit = locate(reference, dir, projectDir) - if (hit != null) found.add(hit) else missing.add(reference.name) - } - // Packages must already be unpacked; restoring them is NuGet's responsibility. - if (nuget != null && info.packageReferences.isNotEmpty()) { - found.addAll(nuget.cached(packageRequests(info), frameworkDlls).dlls) - } - return found to missing - } - - /** Returns referenced DLLs that should be copied beside the output. */ - fun copyLocal(info: CsprojInfo, dir: Path): List { - val projectDir = projectFolder(dir) - return info.references.filter { it.copyLocal }.mapNotNull { locate(it, dir, projectDir) } - } - - /** Returns the project's packages in the format expected by NuGet restore. */ - fun packageRequests(info: CsprojInfo): List = - info.packageReferences.map { NuGet.Request(it.id, it.version) } - - /** Returns the folder of a `.csproj` at [path], or null when [path] is not a project-file path. */ - fun dirOfProjectFile(path: String): java.nio.file.Path? { - if (!path.endsWith(".csproj", ignoreCase = true)) return null - return runCatching { java.nio.file.Paths.get(path).toAbsolutePath().normalize().parent }.getOrNull() - } - - private fun readPackages(root: Element, active: (Element) -> Boolean): List { - val nodes = root.getElementsByTagName("PackageReference") - return (0 until nodes.length).map { nodes.item(it) as Element }.filter(active).map { element -> - val version = attributeOrChild(element, "Version").ifEmpty { attributeOrChild(element, "VersionOverride") } - CsprojPackage(element.getAttribute("Include").trim(), version.ifEmpty { null }) - }.filter { it.id.isNotEmpty() } - } - - private fun readReferences(root: Element, active: (Element) -> Boolean): List { - val nodes = root.getElementsByTagName("Reference") - return (0 until nodes.length).map { nodes.item(it) as Element }.filter(active).map { element -> - val name = element.getAttribute("Include") - .replace('\\', '/').substringBefore(',').trim().removeSuffix(".dll") - val hint = attributeOrChild(element, "HintPath").replace('\\', '/').takeIf { it.isNotEmpty() } - val copyLocal = !attributeOrChild(element, "Private").equals("false", ignoreCase = true) - CsprojReference(name, hint, copyLocal) - }.filter { it.name.isNotEmpty() } - } - - /** Reads an attribute value or, when absent, the text of a child element with the same name. */ - private fun attributeOrChild(element: Element, name: String): String = - element.getAttribute(name).ifEmpty { - (element.getElementsByTagName(name).item(0) as? Element)?.textContent.orEmpty() - }.trim() - - /** The DLL a [reference] points to, or null when none of its candidate paths exists. */ - private fun locate(reference: CsprojReference, dir: Path, projectDir: Path): Path? { - val candidates = buildList { - reference.hintPath?.let { add(projectDir.resolve(it)) } - reference.hintPath?.let { add(dir.resolve(it)) } - add(dir.resolve(reference.name + ".dll")) - add(dir.resolve("lib").resolve(reference.name + ".dll")) - } - return candidates.firstOrNull { Files.isRegularFile(it) }?.normalize() - } - - // Compiler settings - - /** Returns the global usings source file, or an empty string when there are no usings. */ - fun globalUsingsText(info: CsprojInfo?): String { - if (info == null) return "" - val removed = info.removedUsings.toSet() - val implicit = if (info.implicitUsings) IMPLICIT_USINGS.filter { it !in removed } else emptyList() - return buildString { - for (name in implicit) append("global using global::$name;\n") - for (using in info.usings) { - append("global using ") - if (using.static) append("static ") - if (using.alias != null) append(using.alias).append(" = ") - append("global::").append(using.name).append(";\n") - } - } - } - - /** Returns the reason this compiler cannot build the project, or null when it can. */ - @Suppress("UNUSED_PARAMETER") - fun unsupported(info: CsprojInfo): String? = null - - /** Removes the `CS` prefix from a warning code, leaving other values unchanged. */ - private fun number(code: String): String = - code.trim().let { if (it.startsWith("CS", ignoreCase = true)) it.drop(2) else it } - - /** - * Returns the symbols the SDK defines without explicit project settings. - * - * Includes `DEBUG`, `TRACE`, `NET`, `NETCOREAPP`, and the target framework's - * symbols such as `NET10_0` and `NET10_0_OR_GREATER`. - * - * The older `NETx_y_OR_GREATER` symbols are not added. - */ - fun implicitDefines(info: CsprojInfo): List = buildList { - add("DEBUG"); add("TRACE") - val version = Regex("""^net(\d+)\.(\d+)$""").matchEntire(info.targetFramework ?: "net10.0") ?: return@buildList - val (major, minor) = version.destructured - add("NET"); add("NETCOREAPP") - add("NET${major}_$minor"); add("NET${major}_${minor}_OR_GREATER") - } - - /** - * Returns the compiler arguments for the project. - * - * [forceLibrary] compiles without an entry point, which is useful when checking - * individual files that do not need to contain `Main`. - */ - fun arguments( - info: CsprojInfo, - sources: List, - references: List, - out: Path, - globalUsings: Path?, - forceLibrary: Boolean = false, - mainClass: String? = null, - assemblyInfo: Path? = null, - resources: List> = emptyList(), - ): List = buildList { - add("-nologo"); add("-noconfig") - add(if (forceLibrary || info.isLibrary) "-target:library" else "-target:exe") - info.langVersion?.let { add("-langversion:$it") } - (info.nullableMode ?: if (info.nullable) "enable" else null) - ?.takeIf { it in NULLABLE_MODES }?.let { add("-nullable:$it") } - // Select the entry point when the project has more than one Main method. - if (mainClass != null && !forceLibrary && !info.isLibrary) add("-main:$mainClass") - val defines = (implicitDefines(info) + info.defines).distinct() - if (defines.isNotEmpty()) add("-define:" + defines.joinToString(";")) - if (info.allowUnsafe) add("-unsafe") - if (info.checkedArithmetic) add("-checked") - if (info.optimize) add("-optimize+") - info.warningLevel?.let { add("-warn:$it") } - if (info.treatWarningsAsErrors) add("-warnaserror") - if (info.warningsAsErrors.isNotEmpty()) { - add("-warnaserror:" + info.warningsAsErrors.joinToString(",") { number(it) }) - } - if (info.warningsNotAsErrors.isNotEmpty()) { - add("-warnaserror-:" + info.warningsNotAsErrors.joinToString(",") { number(it) }) - } - if (info.noWarn.isNotEmpty()) add("-nowarn:" + info.noWarn.joinToString(",") { number(it) }) - // Only a build writes output beyond the DLL; editor checks compile into a scratch folder. - if (!forceLibrary) { - CsprojExtras.debugFlag(info)?.let { add(it) } - CsprojExtras.platformFlag(info)?.let { add(it) } - if (info.generateDocumentation) add("-doc:" + out.resolveSibling(CsprojExtras.documentationName(out))) - resources.forEach { (file, name) -> add("-resource:$file,$name") } - } - add("-out:$out") - references.forEach { add("-r:$it") } - sources.forEach { add(it.toString()) } - globalUsings?.let { add(it.toString()) } - assemblyInfo?.let { add(it.toString()) } - } - - private fun logSummary(file: Path, info: CsprojInfo) { - Log.d( - TAG, - "csproj: ${file.fileName}: ${info.outputType}, ${info.includes.size} include, " + - "${info.removes.size} remove, ${info.projectReferences.size} project ref, " + - "${info.packageReferences.size} package ref, target ${info.targetFramework}, " + - "AssemblyName=${info.assemblyName}, OutDir=${info.outDir}, in $file, " + - "references ${info.references.joinToString { "${it.name}(copy=${it.copyLocal})" }}", - ) - } -} - -/** - * Converts a project-file glob into a regex matching `/`-separated paths relative to the project. - * - * `**` can cross directory boundaries; `*` and `?` cannot. - */ -internal fun globToRegex(glob: String): Regex { - val normalized = glob.replace('\\', '/').removePrefix("./") - val pattern = StringBuilder() - var i = 0 - while (i < normalized.length) { - when { - normalized.startsWith("**/", i) -> { pattern.append("(?:.*/)?"); i += 3 } - normalized.startsWith("**", i) -> { pattern.append(".*"); i += 2 } - normalized[i] == '*' -> { pattern.append("[^/]*"); i++ } - normalized[i] == '?' -> { pattern.append("[^/]"); i++ } - else -> { pattern.append(Regex.escape(normalized[i].toString())); i++ } - } - } - return Regex(pattern.toString()) -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojReferences.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojReferences.kt deleted file mode 100644 index f4d6f8c933..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojReferences.kt +++ /dev/null @@ -1,88 +0,0 @@ -package dev.codeassist.csharp.project.csproj - -import android.util.Log -import dev.codeassist.csharp.sdk.DotnetSdk -import dev.codeassist.csharp.util.TAG -import java.nio.file.Files -import java.nio.file.Path - -/** - * What a project gets from the projects it references, for the editor's requests to the server. - * - * The server takes a referenced project as `-projectref:`, a file holding that project's own - * compiler arguments, and compiles it in memory from its sources on disk. So the editor sees a referenced - * project as it is now, whether or not it has been built. This writes those files. - */ -internal class CsprojReferences(private val sdk: DotnetSdk) { - - /** - * [arguments] to add to the referencing project's own, [libraries] it also compiles against (the DLLs - * and packages the referenced projects use reach it too), and what could not be followed. - */ - class Editor(val arguments: List, val libraries: List, val problems: List) { - companion object { - val NONE = Editor(emptyList(), emptyList(), emptyList()) - } - } - - fun forEditor(projectFile: Path?, info: CsprojInfo?): Editor { - if (projectFile == null || info == null) return Editor.NONE - val key = "-projectkey:$projectFile" - if (info.projectReferences.isEmpty()) return Editor(listOf(key), emptyList(), emptyList()) - - val graph = CsprojGraph.referenced(projectFile, info) - val frameworkDlls = sdk.frameworkDllNames() - val responseFiles = LinkedHashMap() - val libraries = LinkedHashMap() - - for (node in graph.nodes) { - val own = Csproj.resolveReferences(node.info, node.dir, sdk.nuget, frameworkDlls).first - own.forEach { libraries.putIfAbsent(it.fileName.toString().lowercase(), it) } - // Dependencies come first, so every project this one needs already has its file. - val needed = CsprojGraph.referenced(node.file, node.info).nodes.mapNotNull { responseFiles[it.file] } - responseFiles[node.file] = write(node, own, needed) - } - - return Editor( - listOf(key) + responseFiles.values.map { "-projectref:$it" }, - libraries.values.toList(), - graph.problems, - ) - } - - /** Writes [node]'s arguments where the server reads them, and returns the file. */ - private fun write(node: CsprojGraph.Node, own: List, needed: List): Path { - val work = sdk.home.resolve("projects").resolve(Integer.toHexString(node.file.toString().hashCode())) - Files.createDirectories(work) - - val usingsText = Csproj.globalUsingsText(node.info) - val usings = work.resolve("GlobalUsings.g.cs").takeIf { usingsText.isNotEmpty() } - usings?.let { writeIfChanged(it, usingsText) } - - val arguments = Csproj.arguments( - node.info, - CsprojGraph.sources(node.dir, node.info), - sdk.references() + own, - work.resolve("${node.assemblyName}.dll"), - usings, - forceLibrary = true, - ) + needed.map { "-projectref:$it" } - - return work.resolve("project.rsp").also { writeIfChanged(it, arguments.joinToString("\n")) } - } - - private fun writeIfChanged(file: Path, text: String) { - val bytes = text.toByteArray(Charsets.UTF_8) - val same = runCatching { Files.readAllBytes(file).contentEquals(bytes) }.getOrDefault(false) - if (!same) { - runCatching { Files.write(file, bytes) } - .onFailure { Log.d(TAG, "references: could not write $file: $it") } - } - } - - companion object { - /** Whether [argument] is one only the server understands, which `csc` itself would reject. */ - fun isServerOnly(argument: String): Boolean = - argument.startsWith("-projectref:") || argument.startsWith("-projectkey:") - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojSchema.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojSchema.kt deleted file mode 100644 index 6fe86d15e3..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojSchema.kt +++ /dev/null @@ -1,102 +0,0 @@ -package dev.codeassist.csharp.project.csproj - -/** - * Describes the project properties and items supported by this plugin. - * - * Used by completion and [CsprojCheck] to provide allowed values and validation rules. - * This is not the complete MSBuild vocabulary. Properties not listed here are simply - * not offered by completion or checked by this plugin. - */ -internal object CsprojSchema { - - /** Describes a property, its allowed values, validation kind, and completion documentation. */ - class Property( - val name: String, - val doc: String, - val values: List = emptyList(), - val kind: Kind = Kind.TEXT, - ) - - enum class Kind { TEXT, BOOLEAN, ENUM, INTEGER, LANG_VERSION, FRAMEWORK } - - /** Creates a boolean property that accepts `true` or `false`. */ - private fun bool(name: String, doc: String) = - Property(name, doc, listOf("true", "false"), Kind.BOOLEAN) - - // Properties - - val PROPERTIES: List = listOf( - Property("OutputType", "Exe runs, Library is built only", listOf("Exe", "Library", "WinExe"), Kind.ENUM), - Property("TargetFramework", "The framework the project builds for, such as net10.0", kind = Kind.FRAMEWORK), - Property("AssemblyName", "The name of the built assembly"), - Property("RootNamespace", "The namespace new files get"), - Property("LangVersion", "The C# language version: latest, preview, 12, 13 ...", kind = Kind.LANG_VERSION), - Property("Nullable", "Nullable reference types", listOf("enable", "disable", "warnings", "annotations"), Kind.ENUM), - Property("ImplicitUsings", "The usings every file gets", listOf("enable", "disable", "true", "false"), Kind.ENUM), - Property("StartupObject", "The class whose Main starts the program (Module Settings > Run wins)"), - bool("AllowUnsafeBlocks", "Allow unsafe code"), - bool("Optimize", "Compile with optimizations"), - bool("TreatWarningsAsErrors", "Every warning is an error"), - bool("CheckForOverflowUnderflow", "Integer arithmetic overflow throws"), - bool("EnableDefaultCompileItems", "false: only the Compile items are compiled"), - bool("GenerateDocumentationFile", "Write the XML documentation file"), - bool("Deterministic", "The same input gives the same output"), - bool("AppendTargetFrameworkToOutputPath", "Put the framework name in the output folder"), - bool("InvariantGlobalization", "Do not use culture data"), - Property("WarningsAsErrors", "Warnings that are errors, separated by `;`"), - Property("WarningsNotAsErrors", "Warnings that stay warnings, separated by `;`"), - Property("NoWarn", "Warnings to hide, separated by `;`"), - Property("WarningLevel", "How many warnings: 0 to 9", kind = Kind.INTEGER), - Property("DefineConstants", "Symbols for #if, separated by `;`"), - Property("OutDir", "The output folder"), - Property( - "DebugType", - "Debug symbols: portable, embedded, full, pdbonly or none", - listOf("portable", "embedded", "full", "pdbonly", "none"), - Kind.ENUM, - ), - Property( - "PlatformTarget", - "The CPU the DLL is for", - listOf("AnyCPU", "x86", "x64", "arm", "arm64", "anycpu32bitpreferred"), - Kind.ENUM, - ), - bool("GenerateAssemblyInfo", "false: the project writes its own assembly attributes"), - Property("Version", "The package and assembly version"), - Property("AssemblyVersion", "The assembly version, four numbers"), - Property("FileVersion", "The file version, four numbers"), - Property("InformationalVersion", "The version shown to people, any text"), - Property("Authors", "The authors (the company, when none is set)"), - Property("Product", "The product in the assembly information"), - Property("Copyright", "The copyright in the assembly information"), - Property("AssemblyTitle", "The title in the assembly information"), - Property("Company", "The company in the assembly information"), - Property("Description", "The description in the assembly information"), - ) - - /** Describes an item, its supported attributes, and its completion documentation. */ - class Item( - val name: String, - val doc: String, - val attributes: List, - ) - - val ITEMS: List = listOf( - Item("PackageReference", "A NuGet package", listOf("Include", "Version")), - Item("ProjectReference", "Another project, built first and compiled against", listOf("Include")), - Item("Reference", "A DLL", listOf("Include", "HintPath", "Private")), - Item("Compile", "A source file or a pattern of them", listOf("Include", "Remove", "Exclude")), - Item("Using", "A using every file gets", listOf("Include", "Remove", "Alias", "Static")), - Item("EmbeddedResource", "A file embedded in the assembly", listOf("Include", "Remove")), - Item("None", "A file shown in the project and not built", listOf("Include", "Remove")), - ) - - /** Elements that hold properties or items, plus other elements allowed directly under Project. */ - val GROUPS = listOf("PropertyGroup", "ItemGroup", "Import", "Target", "Choose") - - // Lookups - - fun property(name: String): Property? = PROPERTIES.firstOrNull { it.name == name } - - fun item(name: String): Item? = ITEMS.firstOrNull { it.name == name } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojText.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojText.kt deleted file mode 100644 index 30ba3090be..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/csproj/CsprojText.kt +++ /dev/null @@ -1,237 +0,0 @@ -package dev.codeassist.csharp.project.csproj - -import dev.codeassist.csharp.project.csproj.CsprojText.Element - -/** - * Extracts elements and their source positions from project file text. - * - * Diagnostics use the recorded ranges, while completion uses the element containing the caret. - * This works directly on text without an XML parser, so it can handle partially typed files. - * Comments, CDATA sections, and processing instructions are masked first, and unfinished tags - * are skipped. - */ -internal object CsprojText { - - /** An attribute with its name, value, and the range of its unquoted value. */ - class Attr( - val name: String, - val value: String, - val valueStart: Int, - val valueEnd: Int, - ) - - /** - * An element and its source positions. - * - * [start] is the position of `<`, and [nameStart]..[nameEnd] is the tag name. - * [parent] is the name of the containing element. - * - * [text] contains the content after the start tag up to the next `<`, with its range - * recorded by [textStart]..[textEnd]. For example, this is the value in - * `Exe`. Self-closing elements have empty text. - */ - class Element( - val name: String, - val parent: String?, - val start: Int, - val nameStart: Int, - val nameEnd: Int, - val attrs: List, - val selfClosing: Boolean, - val textStart: Int, - val textEnd: Int, - val text: String, - ) { - fun attr(name: String): Attr? = attrs.firstOrNull { it.name == name } - } - - private val TAG = Regex( - """<(/?)([A-Za-z_][\w.\-:]*)((?:\s+[\w:.\-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(/?)>""", - ) - - private val ATTRIBUTE = Regex("""([\w:.\-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')""") - - private val BLANKED = Regex( - """||<\?.*?\?>""", - RegexOption.DOT_MATCHES_ALL, - ) - - /** Returns [text] with comments, CDATA sections, and processing instructions replaced by spaces. */ - fun mask(text: String): String { - val out = StringBuilder(text) - - for (match in BLANKED.findAll(text)) { - for (i in match.range) { - if (out[i] != '\n' && out[i] != '\r') out.setCharAt(i, ' ') - } - } - - return out.toString() - } - - fun elements(text: String): List { - val clean = mask(text) - val out = ArrayList() - val stack = ArrayList() - - for (match in TAG.findAll(clean)) { - val closing = match.groupValues[1] == "/" - val name = match.groupValues[2] - - if (closing) { - val at = stack.lastIndexOf(name) - if (at >= 0) { - while (stack.size > at) stack.removeAt(stack.lastIndex) - } - continue - } - - val selfClosing = match.groupValues[4] == "/" - val attrsGroup = match.groups[3]!! - - val attrs = ATTRIBUTE.findAll(attrsGroup.value).map { a -> - val inDouble = a.groups[2] != null - val group = a.groups[if (inDouble) 2 else 3]!! - val base = attrsGroup.range.first - - Attr( - a.groupValues[1], - group.value, - base + group.range.first, - base + group.range.last + 1, - ) - }.toList() - - val nameStart = match.range.first + 1 - val textStart = match.range.last + 1 - val next = clean.indexOf('<', textStart).let { - if (it < 0) clean.length else it - } - val textEnd = if (selfClosing) textStart else next - - out += Element( - name, - stack.lastOrNull(), - match.range.first, - nameStart, - nameStart + name.length, - attrs, - selfClosing, - textStart, - textEnd, - text.substring(textStart, textEnd), - ) - - if (!selfClosing) stack += name - } - - return out - } - - // Open elements - - /** Returns the names of elements open at [caret], from outermost to innermost. */ - fun openAt(text: String, caret: Int): List { - val clean = mask(text.substring(0, caret.coerceIn(0, text.length))) - val stack = ArrayList() - - for (match in TAG.findAll(clean)) { - val name = match.groupValues[2] - - if (match.groupValues[1] == "/") { - val at = stack.lastIndexOf(name) - if (at >= 0) { - while (stack.size > at) stack.removeAt(stack.lastIndex) - } - } else if (match.groupValues[4] != "/") { - stack += name - } - } - - return stack - } - - // Completion position - - /** Describes what kind of text the caret is currently positioned in. */ - sealed class Position { - - /** A tag name after `<`, inside [parent], or at the root when null. */ - class TagName(val typed: String, val parent: String?) : Position() - - /** A closing tag name after ` raw.lastIndexOf("-->")) return null - if (raw.lastIndexOf(" raw.lastIndexOf("]]>")) return null - - val before = mask(raw) - val lt = before.lastIndexOf('<') - val gt = before.lastIndexOf('>') - - if (lt > gt) { - val inside = before.substring(lt + 1) - - // Declarations and processing instructions are not completion positions. - if (inside.startsWith("!") || inside.startsWith("?")) return null - - val open = openAt(text, lt) - - if (inside.startsWith("/")) { - return Position.ClosingName(inside.drop(1), open.lastOrNull()) - } - - if (inside.all { it.isLetterOrDigit() || it in "_.-:" }) { - return Position.TagName(inside, open.lastOrNull()) - } - - val element = inside.takeWhile { !it.isWhitespace() } - val rest = inside.substring(element.length) - val quote = rest.count { it == '"' } % 2 == 1 - - if (quote) { - val upToQuote = rest.substring(0, rest.lastIndexOf('"')) - val attribute = Regex("""([\w:.\-]+)\s*=\s*$""") - .find(upToQuote)?.groupValues?.get(1) ?: return null - - return Position.AttributeValue( - element, - attribute, - rest.substring(rest.lastIndexOf('"') + 1), - ) - } - - return Position.AttributeName( - element, - rest.takeLastWhile { it.isLetterOrDigit() || it in "_.-:" }, - ) - } - - val open = openAt(text, at) - val element = open.lastOrNull() ?: return null - val typed = before.substring(gt + 1) - - if ('<' in typed) return null - - return Position.Value( - element, - open.getOrNull(open.size - 2), - typed.trim(), - ) - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/CsPackageRestorer.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/CsPackageRestorer.kt deleted file mode 100644 index 34f9d7207f..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/CsPackageRestorer.kt +++ /dev/null @@ -1,175 +0,0 @@ -package dev.codeassist.csharp.project.nuget - -import android.util.Log -import dev.codeassist.csharp.editor.CsWorkspace -import dev.codeassist.csharp.project.csproj.Csproj -import dev.codeassist.csharp.project.csproj.CsprojInfo -import dev.codeassist.csharp.sdk.DotnetSdk -import dev.codeassist.csharp.util.RestoreNotice -import dev.codeassist.csharp.util.TAG -import dev.codeassist.csharp.util.killableTool -import dev.ide.platform.log.Logger -import dev.ide.platform.notify.UserMessages -import dev.ide.platform.notify.info -import dev.ide.platform.notify.warn -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.launch -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import java.nio.file.Path -import java.util.concurrent.ConcurrentHashMap - -/** - * Restores a project's NuGet packages for the editor. - * - * Shared by diagnostics, [CsPackageWatcher], and the Run picker's Restore row. The mutex prevents - * concurrent restores from unpacking the same packages, while the last-attempt check avoids - * repeating failed attempts. - * - * After a restore runs, the editor is asked to reanalyze its open files through [CsWorkspace]. - * This allows errors caused by missing package types to disappear without waiting for another edit. - * - * Failed restores are remembered per project folder through [failuresFor] and reported once - * through a notification. - */ -internal class CsPackageRestorer( - private val sdk: DotnetSdk, - private val log: Logger, - private val messages: UserMessages? = null, -) { - - /** Prevents concurrent restores from writing to the same package cache. */ - private val mutex = Mutex() - - /** Identifies the most recent restore attempt by project folder and requested packages. */ - private var lastAttempt: String? = null - - /** Problems from the last restore of each project folder. Removed after a successful restore. */ - private val failures = ConcurrentHashMap>() - - /** Scope for background restore operations. */ - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - - /** Project folders with a background restore queued or running. */ - private val queued = ConcurrentHashMap.newKeySet() - - // Lifecycle - - fun close() = scope.cancel() - - /** Problems from the last restore of [moduleDir], or an empty list if there are none. */ - fun failuresFor(moduleDir: Path): List = failures[key(moduleDir)].orEmpty() - - /** - * Returns whether [restore] would fetch packages now. - * - * Packages must be missing, and the current set of package requests must not have been tried - * already. Failed attempts are not repeated automatically. - */ - fun pending(project: CsprojInfo, moduleDir: Path): Boolean { - val requests = Csproj.packageRequests(project) - if (requests.isEmpty()) return false - if (sdk.nuget.isRestored(requests, sdk.frameworkDllNames())) return false - - val attempt = key(moduleDir) + requests.joinToString { "${it.id}@${it.version}" } - return synchronized(this) { lastAttempt != attempt } - } - - /** - * Starts [restore] in the background so the caller does not need to wait for downloads. - * - * Only one background restore is queued or running per project folder. The editor is asked - * to reanalyze its open files when the restore finishes. - */ - fun restoreInBackground(project: CsprojInfo, moduleDir: Path) { - val dirKey = key(moduleDir) - if (!queued.add(dirKey)) return - - scope.launch { - try { - restore(project, moduleDir) - } finally { - queued.remove(dirKey) - } - } - } - /** - * Restores [project]'s packages if they are not already unpacked. - * - * Each set of package requests is attempted only once. Failed attempts, such as offline - * restores or invalid package IDs, are not repeated on every keystroke. A changed package - * set or an IDE restart allows another attempt. - * - * [force] bypasses the previous-attempt check, allowing the Run picker's Restore action - * to retry. The build also restores packages before compilation through - * [CsCompileTask]. - * - * Returns the problems from the restore performed by this call, or an empty list if the - * packages were already present or a previous attempt was not repeated. - * - * [notify] controls whether restore failures are shown as notifications. The Run picker's - * Restore row reports failures in its own console instead. - */ - suspend fun restore( - project: CsprojInfo, - moduleDir: Path, - force: Boolean = false, - notify: Boolean = true, - ): List { - val requests = Csproj.packageRequests(project) - if (requests.isEmpty()) return emptyList() - - val exclude = sdk.frameworkDllNames() - val packages = requests.joinToString { "${it.id}@${it.version}" } - val attempt = key(moduleDir) + packages - - mutex.withLock { - // Check inside the lock so callers waiting for another restore can see its result. - if (sdk.nuget.isRestored(requests, exclude)) { - failures.remove(key(moduleDir)) - return emptyList() - } - - if (!force && synchronized(this) { lastAttempt == attempt }) return emptyList() - - Log.d(TAG, "restore: ${requests.size} package(s) for $moduleDir") - - val result = killableTool { cancellation -> - sdk.nuget.restore(requests, exclude) { cancellation.isCancelled } - } - - result.problems.forEach { log.warn(it) } - synchronized(this) { lastAttempt = attempt } - - Log.d( - TAG, - "restore: done, ${result.dlls.size} dll(s), ${result.problems.size} problem(s)", - ) - - val name = moduleDir.fileName?.toString() ?: moduleDir.toString() - - if (result.problems.isEmpty()) { - val hadFailed = failures.remove(key(moduleDir)) != null - if (hadFailed && notify) { - messages?.info("NuGet packages restored for $name") - } - } else { - failures[key(moduleDir)] = result.problems - if (notify) { - messages?.warn(RestoreNotice.failure(name, result.problems)) - } - } - - // Recheck open files because the editor analyzed them before the packages arrived. - CsWorkspace.reanalyzeOpenFiles() - - return result.problems - } - } - - private fun key(moduleDir: Path) = - moduleDir.toAbsolutePath().normalize().toString() -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/CsPackageWatcher.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/CsPackageWatcher.kt deleted file mode 100644 index c00cc16f72..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/CsPackageWatcher.kt +++ /dev/null @@ -1,91 +0,0 @@ -package dev.codeassist.csharp.project.nuget - -import android.util.Log -import dev.codeassist.csharp.editor.CsWorkspace -import dev.codeassist.csharp.project.csproj.Csproj -import dev.codeassist.csharp.util.TAG -import dev.ide.platform.MessageBus -import dev.ide.vfs.FileMoved -import dev.ide.vfs.VfsEvent -import dev.ide.vfs.VfsListener -import dev.ide.vfs.VfsTopics -import java.nio.file.Path -import java.util.concurrent.ConcurrentHashMap -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch - -/** - * Restores a project's packages when its `.csproj` file is saved, keeping the package cache - * warm before the editor next requests diagnostics. - * - * The IDE publishes editor saves through [VfsTopics.CHANGES]. - * - * Saving a file does not by itself make the host rerun editor - * diagnostics. Squiggles still wait for another trigger, such as an edit, tab switch, or build. - * This watcher avoids the package-restoration delay when that check eventually runs. - * - * When the host provides a workspace through [CsWorkspace], open files are also requested - * for reanalysis after every save. - */ -internal class CsPackageWatcher( - bus: MessageBus, - private val restorer: CsPackageRestorer, -) : AutoCloseable { - - private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - - /** One pending restore per project directory. A newer save replaces the previous job. */ - private val pending = ConcurrentHashMap() - - private val connection = bus.connect().also { - it.subscribe(VfsTopics.CHANGES, VfsListener { events -> onEvents(events) }) - } - - // Lifecycle - - override fun close() { - connection.dispose() - scope.cancel() - } - - // Event handling - - private fun onEvents(events: List) { - // Keep the publisher thread (the editor's save path) free of restoration work. - // Only identify affected projects and schedule work in the coroutine scope. - for (event in events) { - val path = if (event is FileMoved) event.to else event.file.path - val dir = Csproj.dirOfProjectFile(path) ?: continue - - pending.remove(dir)?.cancel() - pending[dir] = scope.launch { - // Coalesce bursts of saves, such as autosave, rename, and write operations. - delay(DEBOUNCE_MS) - - val project = Csproj.load(dir) - if (project != null) { - Log.d(TAG, "watcher: ${project.packageReferences.size} package ref(s) in $dir") - restorer.restore(project, dir) - } - - // A saved project can change the meaning of every open file through its - // usings, defines, nullable settings, and references. Reanalyze even if - // the project could no longer be loaded. - // - // The restorer only requests reanalysis after a restore that actually ran. - CsWorkspace.reanalyzeOpenFiles() - } - } - } - - companion object { - - /** Delay used to combine closely spaced project-file saves into one restore. */ - const val DEBOUNCE_MS = 500L - } -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/NuGet.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/NuGet.kt deleted file mode 100644 index 015e0e5f8a..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/NuGet.kt +++ /dev/null @@ -1,458 +0,0 @@ -package dev.codeassist.csharp.project.nuget - -import android.util.Log -import dev.codeassist.csharp.util.TAG -import org.w3c.dom.Element -import java.io.ByteArrayInputStream -import java.net.HttpURLConnection -import java.net.URI -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.StandardCopyOption -import java.util.zip.ZipFile -import javax.xml.parsers.DocumentBuilderFactory - -/** - * Restores NuGet packages for a project. - * - * Packages are downloaded from nuget.org, unpacked under [root], and exposed to the compiler - * as DLLs. - * - * Uses the NuGet Package Base Address resource: - * https://learn.microsoft.com/nuget/api/package-base-address-resource - * - * The base URL comes from the service index. A package is located at - * `{base}/{id}/{version}/{id}.{version}.nupkg`, and its available versions at - * `{base}/{id}/index.json`. Package IDs and versions are lowercase, with versions normalized. - * - * Restores the DLLs from the best compatible target framework of each package, along with - * its dependencies. When multiple versions of a package are requested, the highest requested - * version wins. - * - * Not supported: native libraries, analyzers, source generators, `PrivateAssets`, signature - * verification, and package sources other than nuget.org. - * - * Packages whose DLLs are already provided by the SDK are skipped. For example, restoring - * `System.Memory` separately could introduce duplicate types. - * - * Package layout under [root]: - * - `//dll/` contains the selected framework's DLLs and XML documentation. - * - `//package.nuspec` contains package metadata. - * - `//.ok` marks a completed extraction. - * - * The `.ok` marker is written last, so an interrupted download or extraction is retried. - * - * No `.deps.json` is written for a program: a package's DLLs are placed beside it, as ordinary - * `` assemblies are. - */ -internal class NuGet( - private val root: Path, - private val fetch: Fetch = HttpFetch, -) { - - /** Fetches bytes from a URL, or returns null when unavailable. */ - fun interface Fetch { - fun get(url: String): ByteArray? - } - - /** A package ID and the version specification from the project file. */ - class Request(val id: String, val version: String?) - - /** DLLs available for compilation and any packages that could not be restored. */ - class Result(val dlls: List, val problems: List) - - private var baseUrl: String? = null - - /** Downloads missing packages, then returns the same result as [cached]. */ - @Synchronized - fun restore( - requests: List, - exclude: Set, - isCancelled: () -> Boolean = { false }, - ): Result = walk(requests, exclude, online = true, isCancelled) - - /** Returns DLLs from packages already unpacked. Missing packages are silently skipped. */ - @Synchronized - fun cached(requests: List, exclude: Set): Result = - walk(requests, exclude, false) { false } - - /** Returns true when every requested package and its dependencies are already unpacked. */ - @Synchronized - fun isRestored(requests: List, exclude: Set): Boolean { - val chosen = LinkedHashMap() - - return walkGraph(requests, exclude, online = false, { false }, chosen, ArrayList()) && - requests.all { it.id.lowercase() in chosen || skipped(it.id.lowercase(), exclude) } - } - - // Package graph traversal - - /** - * Resolves the requested packages and collects their DLLs. - * - * @param online whether missing packages may be downloaded - * @param isCancelled checked between packages - */ - private fun walk( - requests: List, - exclude: Set, - online: Boolean, - isCancelled: () -> Boolean, - ): Result { - val chosen = LinkedHashMap() - val problems = ArrayList() - - walkGraph(requests, exclude, online, isCancelled, chosen, problems) - - val dlls = chosen.flatMap { (key, version) -> - val dir = packageDir(key, version).resolve(DLLS) - if (!Files.isDirectory(dir)) { - emptyList() - } else { - Files.list(dir).use { stream -> - // Not Stream.toList(): it is a Java 16 method, absent before Android 14. - stream.iterator().asSequence().filter { - it.fileName.toString().lowercase().endsWith(".dll") - }.toList() - } - } - } - .filter { it.fileName.toString().lowercase() !in exclude } - .sortedBy { it.fileName.toString() } - - return Result(dlls, problems) - } - - /** - * Traverses requested packages and their dependencies, filling [chosen] with the versions - * to use. - * - * Returns false if traversal stopped because [isCancelled] returned true. - */ - private fun walkGraph( - requests: List, - exclude: Set, - online: Boolean, - isCancelled: () -> Boolean, - chosen: MutableMap, - problems: MutableList, - ): Boolean { - val queue = ArrayDeque(requests.map { it.id to it.version }) - - while (queue.isNotEmpty()) { - if (isCancelled()) return false - - val (id, spec) = queue.removeFirst() - val key = id.lowercase() - - // The id becomes a directory name and part of a URL. It comes from a project file or from a - // downloaded package's own dependency list, so one that is not a package id is refused here. - if (!PACKAGE_ID.matches(key)) { - if (online) problems += "NuGet package $id: not a valid package id" - continue - } - - if (skipped(key, exclude)) continue - - val version = pick(key, spec, online)?.takeIf { VERSION_TEXT.matches(it.normalized) } - if (version == null) { - if (online) { - problems += "NuGet package $id${spec?.let { " $it" }.orEmpty()}: no version found" - } - continue - } - - val known = chosen[key] - if (known != null && known >= version) continue - - val dir = packageDir(key, version) - if (!Files.isRegularFile(dir.resolve(DONE))) { - if (!online) continue - - val error = download(key, version, dir) - if (error != null) { - problems += "NuGet package $id ${version.normalized}: $error" - continue - } - } - - chosen[key] = version - - val nuspec = dir.resolve(NUSPEC) - if (Files.isRegularFile(nuspec)) { - queue.addAll( - dependenciesOf(String(Files.readAllBytes(nuspec), Charsets.UTF_8)) - ) - } - } - - return true - } - - // Version selection and cache lookup - - /** Returns the version to use: the lowest allowed version, or the newest stable floating match. */ - private fun pick(key: String, spec: String?, online: Boolean): NuGetVersion? { - val text = spec?.trim().orEmpty() - - if (text.isNotEmpty() && !NuGetVersion.isFloating(text)) { - return NuGetVersion.lowerBound(text) - } - - val prefix = if (text.isEmpty()) "" else NuGetVersion.floatingPrefix(text) - val known = (if (online) remoteVersions(key) else null) ?: cachedVersions(key) - - return known.mapNotNull { NuGetVersion.parse(it) } - .filter { !it.isPrerelease && it.normalized.startsWith(prefix) } - .maxOrNull() - } - - /** Returns versions listed by nuget.org, or null if the request or response cannot be read. */ - private fun remoteVersions(key: String): List? { - val json = fetch.get("${base()}$key/index.json")?.toString(Charsets.UTF_8) - ?: return null - - val list = VERSIONS.find(json)?.groupValues?.get(1) ?: return null - return QUOTED.findAll(list).map { it.groupValues[1] }.toList() - } - - /** Returns versions with a completed extraction in the local cache. */ - private fun cachedVersions(key: String): List { - val dir = root.resolve(key) - if (!Files.isDirectory(dir)) return emptyList() - - return Files.list(dir).use { stream -> - stream.iterator().asSequence() - .filter { Files.isRegularFile(it.resolve(DONE)) } - .map { it.fileName.toString() } - .toList() - } - } - - /** Returns the package directory for [key] and [version]. */ - private fun packageDir(key: String, version: NuGetVersion): Path = - root.resolve(key).resolve(version.normalized) - - /** Whether a package is already provided by the framework or explicitly excluded. */ - private fun skipped(key: String, exclude: Set): Boolean = - key in FRAMEWORK_PACKAGES || "$key.dll" in exclude - - // Download and extraction - - /** Resolves the package base address from the service index, caching it after the first lookup. */ - private fun base(): String { - baseUrl?.let { return it } - - val index = fetch.get(SERVICE_INDEX)?.toString(Charsets.UTF_8) - val found = index?.let { BASE_ADDRESS.find(it)?.groupValues?.get(1) } ?: FALLBACK_BASE - - return (if (found.endsWith("/")) found else "$found/") - .also { baseUrl = it } - } - - /** Downloads and unpacks a package. Returns an error message, or null on success. */ - private fun download(key: String, version: NuGetVersion, dir: Path): String? { - val name = version.normalized - Log.d(TAG, "nuget: downloading $key $name") - - val bytes = fetch.get("${base()}$key/$name/$key.$name.nupkg") - ?: return "could not be downloaded (offline, or there is no such package)" - - return try { - unpack(bytes, dir) - } catch (e: Exception) { - Log.d(TAG, "nuget: unpacking $key $name failed: $e") - "could not be unpacked: ${e.message}" - } - } - - /** Copies a package entry to the destination, replacing any existing file. */ - private fun copy(from: java.io.InputStream, to: Path) { - Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING) - } - - /** - * Extracts the DLLs and XML documentation from the best compatible framework folder, - * along with the `.nuspec` file. - * - * Returns an error message, or null on success. - */ - private fun unpack(bytes: ByteArray, dir: Path): String? { - Files.createDirectories(dir) - - val nupkg = dir.resolve("package.nupkg") - Files.write(nupkg, bytes) - - try { - ZipFile(nupkg.toFile()).use { zip -> - val names = zip.entries().asSequence() - .filter { !it.isDirectory } - .map { it.name } - .toList() - - val libraries = names.map { it.split('/') } - .filter { - it.size == 3 && - it[0].equals("lib", ignoreCase = true) && - it[2].lowercase().endsWith(".dll") - } - - val frameworks = libraries.map { it[1] }.distinct() - val best = NuGetFrameworks.best(frameworks) - - if (frameworks.isNotEmpty() && best == null) { - return "has no library for net10.0 (it has: ${frameworks.joinToString()})" - } - - val dllDir = dir.resolve(DLLS) - Files.createDirectories(dllDir) - - for (parts in libraries.filter { it[1] == best }) { - val entry = zip.getEntry(parts.joinToString("/")) ?: continue - - zip.getInputStream(entry).use { - copy(it, dllDir.resolve(parts[2])) - } - - // XML documentation beside each DLL, used by the completion popup. - val docName = parts.toMutableList().also { - it[2] = it[2].dropLast(4) + ".xml" - } - - zip.getEntry(docName.joinToString("/"))?.let { doc -> - zip.getInputStream(doc).use { - copy(it, dllDir.resolve(docName[2])) - } - } - } - - names.firstOrNull { '/' !in it && it.endsWith(".nuspec") }?.let { spec -> - zip.getInputStream(zip.getEntry(spec)).use { - copy(it, dir.resolve(NUSPEC)) - } - } - } - } finally { - Files.deleteIfExists(nupkg) - } - - Files.write(dir.resolve(DONE), ByteArray(0)) - return null - } - - companion object { - - // Cache layout - - private const val DLLS = "dll" - private const val NUSPEC = "package.nuspec" - private const val DONE = ".ok" - - // NuGet service endpoints - - private const val SERVICE_INDEX = "https://api.nuget.org/v3/index.json" - private const val FALLBACK_BASE = "https://api.nuget.org/v3-flatcontainer/" - - // Package metadata - - /** Packages supplied by the .NET framework and therefore not downloaded or referenced separately. */ - private val FRAMEWORK_PACKAGES = setOf( - "netstandard.library", - "microsoft.netcore.app", - "microsoft.netcore.platforms", - ) - - private val BASE_ADDRESS = - Regex("""\"@id\"\s*:\s*\"([^\"]+)\"\s*,\s*\"@type\"\s*:\s*\"PackageBaseAddress/3\.0\.0""") - - /** A package id as nuget.org accepts one: word characters joined by single `.`, `-` or `_`. */ - private val PACKAGE_ID = Regex("""[a-z0-9_]+(?:[._-][a-z0-9_]+)*""") - - /** A normalized version as it appears in a path: digits, dots and a prerelease label. */ - private val VERSION_TEXT = Regex("""[0-9]+(?:\.[0-9]+)*(?:-[0-9a-z.-]+)?""") - - private val VERSIONS = Regex("""\"versions\"\s*:\s*\[([^\]]*)\]""") - private val QUOTED = Regex("""\"([^\"]+)\"""") - - // Nuspec dependency parsing - - /** - * Returns the dependencies declared by a `.nuspec` file. - * - * Uses the best matching target-framework group, or the group without a target framework. - * Each result contains the dependency ID and its version range, or null when unspecified. - */ - fun dependenciesOf(nuspec: String): List> { - val factory = DocumentBuilderFactory.newInstance() - runCatching { - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) - } - - val doc = factory.newDocumentBuilder() - .parse(ByteArrayInputStream(nuspec.toByteArray(Charsets.UTF_8))) - - val container = doc.getElementsByTagName("dependencies").item(0) as? Element - ?: return emptyList() - - fun children(parent: Element, name: String): List { - val nodes = parent.childNodes - return (0 until nodes.length) - .mapNotNull { nodes.item(it) as? Element } - .filter { it.nodeName == name } - } - - fun dependenciesIn(parent: Element) = children(parent, "dependency") - .map { - it.getAttribute("id") to it.getAttribute("version").ifEmpty { null } - } - .filter { it.first.isNotEmpty() } - - val groups = children(container, "group") - if (groups.isEmpty()) return dependenciesIn(container) - - val targeted = groups.filter { - it.getAttribute("targetFramework").isNotEmpty() - } - - val best = NuGetFrameworks.best( - targeted.map { it.getAttribute("targetFramework") } - ) - - val group = targeted.firstOrNull { - it.getAttribute("targetFramework") == best - } ?: groups.firstOrNull { - it.getAttribute("targetFramework").isEmpty() - } ?: return emptyList() - - return dependenciesIn(group) - } - } -} - -/** Fetches package data from nuget.org over HTTPS. */ -private object HttpFetch : NuGet.Fetch { - - /** Returns response bytes for HTTP 200, or null for other responses and connection failures. */ - override fun get(url: String): ByteArray? = try { - val connection = URI(url).toURL().openConnection() as HttpURLConnection - - connection.connectTimeout = 15_000 - connection.readTimeout = 60_000 - connection.instanceFollowRedirects = true - connection.setRequestProperty("User-Agent", "CodeAssist-CSharp") - - try { - if (connection.responseCode == 200) { - connection.inputStream.use { it.readBytes() } - } else { - Log.d(TAG, "nuget: GET $url answered ${connection.responseCode}") - null - } - } finally { - connection.disconnect() - } - } catch (e: Exception) { - Log.d(TAG, "nuget: GET $url failed: $e") - null - } -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/NuGetVersion.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/NuGetVersion.kt deleted file mode 100644 index 4fa54f3db4..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/nuget/NuGetVersion.kt +++ /dev/null @@ -1,181 +0,0 @@ -package dev.codeassist.csharp.project.nuget - -/** - * Represents a NuGet version with up to four numeric components and an optional prerelease label. - * - * Comparison follows NuGet ordering: numeric components first, then release versions above their - * prereleases, followed by prerelease identifiers compared part by part. - */ -internal class NuGetVersion private constructor( - private val numbers: List, - private val prerelease: String, -) : Comparable { - - /** Flat-container URL form: at least three components, with a trailing zero fourth component omitted. */ - val normalized: String - get() { - val parts = numbers.toMutableList() - while (parts.size < 3) parts.add(0) - if (parts.size == 4 && parts[3] == 0) parts.removeAt(3) - - return parts.joinToString(".") + - if (prerelease.isEmpty()) "" else "-${prerelease.lowercase()}" - } - - val isPrerelease: Boolean - get() = prerelease.isNotEmpty() - - override fun compareTo(other: NuGetVersion): Int { - // Compare up to four numeric components, treating missing components as zero. - for (i in 0 until 4) { - val c = numbers.getOrElse(i) { 0 } - .compareTo(other.numbers.getOrElse(i) { 0 }) - if (c != 0) return c - } - - // A release sorts above any prerelease of the same numeric version. - if (prerelease.isEmpty() || other.prerelease.isEmpty()) { - return when { - prerelease.isEmpty() && other.prerelease.isEmpty() -> 0 - prerelease.isEmpty() -> 1 - else -> -1 - } - } - - // Compare prerelease identifiers individually. - val mine = prerelease.split('.') - val theirs = other.prerelease.split('.') - - for (i in 0 until minOf(mine.size, theirs.size)) { - val a = mine[i] - val b = theirs[i] - val an = a.toIntOrNull() - val bn = b.toIntOrNull() - - val c = when { - an != null && bn != null -> an.compareTo(bn) - an != null -> -1 - bn != null -> 1 - else -> a.compareTo(b, ignoreCase = true) - } - if (c != 0) return c - } - - return mine.size.compareTo(theirs.size) - } - - override fun equals(other: Any?): Boolean = - other is NuGetVersion && compareTo(other) == 0 - - override fun hashCode(): Int = normalized.hashCode() - - override fun toString(): String = normalized - - companion object { - - /** Returns null if [text] is not a valid version. Build metadata (`+...`) is ignored. */ - fun parse(text: String): NuGetVersion? { - val withoutMeta = text.trim().substringBefore('+') - val core = withoutMeta.substringBefore('-') - val pre = if ('-' in withoutMeta) withoutMeta.substringAfter('-') else "" - - val numbers = core.split('.').map { it.toIntOrNull() ?: return null } - if (numbers.isEmpty() || numbers.size > 4) return null - - return NuGetVersion(numbers, pre) - } - - /** Returns true for floating versions (`*`, `1.*`), which select the newest matching version. */ - fun isFloating(range: String): Boolean = '*' in range - - /** Returns the prefix before `*`: `1.` for `1.*`, or an empty string for `*`. */ - fun floatingPrefix(range: String): String = - range.trim().substringBefore('*').trimStart('[', '(') - - /** - * Returns the lowest version allowed by [range], which is the version NuGet picks. - * - * For example, `1.2`, `[1.2,)`, and `[1.2, 2.0)` all have a lower bound of `1.2`. - * Returns null if there is no lower bound or the range is floating. - */ - fun lowerBound(range: String): NuGetVersion? { - val text = range.trim() - if (text.isEmpty() || isFloating(text)) return null - - val bare = if (text.startsWith("[") || text.startsWith("(")) { - text.trim('[', ']', '(', ')') - } else { - text - } - - val first = bare.substringBefore(',').trim() - return if (first.isEmpty()) null else parse(first) - } - } -} - -/** - * Selects a package target framework supported by this compiler. - * - * The project targets `net10.0` (see `Csproj`), so the newest compatible `net` framework - * is preferred, followed by .NET Standard frameworks. - * - * `netstandard.dll` is included in the reference pack and runtime, which is what lets a - * .NET Standard library load. Platform-specific frameworks (such as `net8.0-android`) and .NET Framework - * targets are not supported. - */ -internal object NuGetFrameworks { - - /** - * Normalizes a framework moniker as used in `lib/` directories and `.nuspec` files. - * - * For example, `.NETStandard2.0` becomes `netstandard2.0`. - */ - fun normalize(moniker: String): String { - val lower = moniker.trim().lowercase() - - return when { - lower.startsWith(".netstandard") -> - "netstandard" + lower.removePrefix(".netstandard") - - lower.startsWith(".netcoreapp") -> - "netcoreapp" + lower.removePrefix(".netcoreapp") - - lower.startsWith(".netframework") -> - "net" + lower.removePrefix(".netframework").replace(".", "") - - else -> lower - } - } - - /** Returns the best usable entry from [available], preserving its original spelling. */ - fun best(available: Collection): String? { - val byShortName = available.associateBy { normalize(it) } - return ORDER.firstNotNullOfOrNull { byShortName[it] } - } - - /** Framework preference order for the project's `net10.0` target. */ - private val ORDER = listOf( - "net10.0", - "net9.0", - "net8.0", - "net7.0", - "net6.0", - "net5.0", - "netcoreapp3.1", - "netcoreapp3.0", - "netcoreapp2.2", - "netcoreapp2.1", - "netcoreapp2.0", - "netstandard2.1", - "netstandard2.0", - // Every .NET Standard 1.x library runs on .NET too, and older packages ship nothing newer. - "netstandard1.6", - "netstandard1.5", - "netstandard1.4", - "netstandard1.3", - "netstandard1.2", - "netstandard1.1", - "netstandard1.0", - ) -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/templates/CsConsoleTemplate.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/templates/CsConsoleTemplate.kt deleted file mode 100644 index afb6e2c667..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/templates/CsConsoleTemplate.kt +++ /dev/null @@ -1,68 +0,0 @@ -package dev.codeassist.csharp.project.templates - -import dev.codeassist.csharp.ui.CsFileIcons -import dev.ide.model.template.ProjectScaffold -import dev.ide.model.template.ProjectTemplate -import dev.ide.model.template.TemplateArgs -import dev.ide.model.template.TemplateCategory -import dev.ide.model.template.TemplateId -import dev.ide.model.template.TemplateParameter - -/** - * Creates a C# console project following the `dotnet new console` layout: - * `.csproj` and `Program.cs` directly in the project folder. - * - * No dependencies are required, so the first Run works offline. - * - * The sample program asks for input and waits for an answer. This demonstrates console input and output - * immediately, including whether the prompt appears before the program waits for input. - */ -class CsConsoleTemplate : ProjectTemplate { - - override val id = TemplateId("csharp-console") - override val displayName = "C# Console App" - override val description = "A C# command-line program, compiled and run on the device with Run." - override val category = TemplateCategory.OTHER - override val iconId = CsFileIcons.CSHARP - - override fun parameters(): List = emptyList() - - override fun generate(scaffold: ProjectScaffold, args: TemplateArgs) { - val module = CsTemplateSupport.create(scaffold, args) - - scaffold.writeText("$module.csproj", CsTemplateSupport.csproj("Exe")) - scaffold.writeText("Program.cs", program()) - scaffold.writeText(".gitignore", CsTemplateSupport.GITIGNORE) - scaffold.writeText("README.md", readme(module)) - } - - // Avoid `$"..."`: dollar signs in Kotlin raw strings are treated as template syntax. - private fun program() = """ - class Program - { - static void Main(string[] args) - { - Console.Write("What is your name? "); - string name = (Console.ReadLine() ?? "").Trim(); - if (name.Length == 0) - { - Console.WriteLine("No name given."); - Environment.ExitCode = 1; - return; - } - Console.WriteLine("Hello, " + name + "! This program ran on your device."); - } - } - """.trimIndent() + "\n" - - private fun readme(module: String) = """ - # $module - - A C# program compiled by Roslyn and run by .NET inside the C# plugin. - - - `$module.csproj` contains the project settings. All `.cs` files alongside it are compiled together. - - Press Run to execute the program. Output appears in the Run console, and text entered there is passed - to the program as standard input. - - Roslyn compilation errors appear in the console. - """.trimIndent() + "\n" -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/templates/CsLibraryTemplate.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/templates/CsLibraryTemplate.kt deleted file mode 100644 index d93e36e63d..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/templates/CsLibraryTemplate.kt +++ /dev/null @@ -1,53 +0,0 @@ -package dev.codeassist.csharp.project.templates - -import dev.codeassist.csharp.ui.CsFileIcons -import dev.ide.model.template.ProjectScaffold -import dev.ide.model.template.ProjectTemplate -import dev.ide.model.template.TemplateArgs -import dev.ide.model.template.TemplateCategory -import dev.ide.model.template.TemplateId -import dev.ide.model.template.TemplateParameter - -/** - * Creates a C# class library following the `dotnet new classlib` layout: - * `.csproj` and a single class file directly in the project folder. - * - * The library has no entry point, so Run builds it instead of executing a program. - */ -class CsLibraryTemplate : ProjectTemplate { - - override val id = TemplateId("csharp-library") - override val displayName = "C# Class Library" - override val description = "A C# class library, compiled to a DLL on the device with Build." - override val category = TemplateCategory.OTHER - override val iconId = CsFileIcons.CSHARP - - override fun parameters(): List = emptyList() - - override fun generate(scaffold: ProjectScaffold, args: TemplateArgs) { - val module = CsTemplateSupport.create(scaffold, args) - - scaffold.writeText("$module.csproj", CsTemplateSupport.csproj("Library")) - scaffold.writeText("Class1.cs", classFile(module)) - scaffold.writeText(".gitignore", CsTemplateSupport.GITIGNORE) - scaffold.writeText("README.md", readme(module)) - } - - private fun classFile(module: String) = """ - namespace $module; - - public class Class1 - { - public static string Greet(string name) => "Hello, " + name + "!"; - } - """.trimIndent() + "\n" - - private fun readme(module: String) = """ - # $module - - A C# class library compiled by Roslyn into `$module.dll` inside the C# plugin. - - - `$module.csproj` contains the project settings. All `.cs` files alongside it are compiled together. - - Run builds the library; there is no executable entry point. - """.trimIndent() + "\n" -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/templates/CsTemplateSupport.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/templates/CsTemplateSupport.kt deleted file mode 100644 index 729b720f8d..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/project/templates/CsTemplateSupport.kt +++ /dev/null @@ -1,65 +0,0 @@ -package dev.codeassist.csharp.project.templates - -import dev.codeassist.csharp.project.CsModuleType -import dev.codeassist.csharp.project.CsProject -import dev.ide.model.BuildSystemId -import dev.ide.model.ContentRole -import dev.ide.model.template.ProjectScaffold -import dev.ide.model.template.TemplateArgs - -/** - * Shared support for C# templates: creates the project module and generates its project file. - */ -internal object CsTemplateSupport { - - const val GITIGNORE = "obj/\nbin/\n" - - /** - * Creates a project and its module. - * - * The module directory is the project folder itself, and that folder is its only source root, - * matching the structure of a cloned C# repository. The `bin/` and `obj/` directories are - * excluded as derived-output roots. - * - * Returns the module (and assembly) name. - */ - fun create(scaffold: ProjectScaffold, args: TemplateArgs): String { - val module = CsProject.assemblyName(args.name) - - scaffold.workspace.beginModification().apply { - addProject(args.name, BuildSystemId.NATIVE, scaffold.rootDir) - commit() - } - - scaffold.workspace.projects.first { it.name == args.name }.beginModification().apply { - addModule(module, scaffold.moduleType(CsModuleType.ID)).apply { - dirRelPath = "" - languageLevel = scaffold.languageLevel - - addContentRoot("main", "", setOf(CsModuleType.CS_SOURCE, ContentRole.SOURCE)) - - // Exclude build output inside the source root. The host dims these directories - // and keeps its sweeps out of them (3.46.0). - addContentRoot("main", "bin", setOf(ContentRole.EXCLUDED)) - addContentRoot("main", "obj", setOf(ContentRole.EXCLUDED)) - } - commit() - } - - return module - } - - /** Generates a `.csproj` file with the specified output type (`Exe` or `Library`). */ - fun csproj(outputType: String): String = """ - - - - $outputType - net10.0 - enable - enable - - - - """.trimIndent() + "\n" -} \ No newline at end of file diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsChecker.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsChecker.kt deleted file mode 100644 index 3ac79e4432..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsChecker.kt +++ /dev/null @@ -1,133 +0,0 @@ -package dev.codeassist.csharp.sdk - -import android.util.Log -import dev.codeassist.csharp.util.TAG -import dev.codeassist.csharp.util.ToolCancellation - -/** - * Reports every diagnostic of a compilation at once, syntax and semantic together, as an IDE does. - * - * Why not `csc`: it stops after the syntax stage, - * so while any file has a syntax error it prints only those and nothing else. - * The server ([CHECKER_SOURCE]) asks Roslyn for the diagnostics itself - * (`CSharpCompilation.GetDiagnostics`), which carries on past syntax errors. - * - * It takes the same arguments `csc` would, and prints - * them in `csc`'s format (`path(line,col): error CS0029: ...`), so `CsDiagnostics` reads either. - * It does not emit an assembly: it is for the editor's check and for a failed build's problem list, never for producing a DLL. - */ -internal object CsChecker { - - /** What the program answers when it could not do its work at all (an exception, not a compile error). */ - private const val FAILED = 255 - - /** - * Check with arguments, as compile does. Returns 0 when there are no errors, 1 when there are, - * and null when the program could not be used or failed inside (then onLine may already have been given its message). - */ - fun check( - sdk: DotnetSdk, - arguments: List, - cancellation: ToolCancellation, - onLine: (String) -> Unit, - ): Int? { - return ask(sdk, listOf("@@check") + arguments, cancellation, onLine) - } - - /** - * Check one file of the project: the buffer being edited, at [bufferPath] among the sources in [arguments]. - * The reply is that file's diagnostics, syntax and semantic, and the syntax errors of the other files. - * It costs a fraction of [check] on a large project, because only the one file's code is bound, against a - * compilation the server kept from the request before. Same return contract as [check]. - */ - fun checkFile( - sdk: DotnetSdk, - bufferPath: String, - arguments: List, - cancellation: ToolCancellation, - onLine: (String) -> Unit, - ): Int? = ask(sdk, listOf("@@checkfile", bufferPath) + arguments, cancellation, onLine) - - private fun ask( - sdk: DotnetSdk, - request: List, - cancellation: ToolCancellation, - onLine: (String) -> Unit, - ): Int? { - val exitCode = CsServer.compile(sdk, request, cancellation, onLine) ?: return null - if (exitCode == FAILED) { - Log.d(TAG, "check: the program failed inside; see the lines above") - return null - } - return exitCode - } -} - -/** - * The diagnostics half of [SERVER_SOURCE]. No `$` anywhere in it: this is a Kotlin raw string. - */ -internal const val CHECKER_SOURCE = """ -static class Checker -{ - // Every diagnostic of the project, as `csc` would print them had it not stopped at the syntax stage. - public static int Run(string[] arguments, TextWriter output) - { - Snapshot snapshot = Project.Open(arguments, null); - int errors = Report(snapshot.Problems, output); - if (snapshot.Compilation == null) return 1; - CSharpCompilation compilation = snapshot.Compilation; - - var all = compilation.GetDiagnostics(CancellationToken.None).ToList(); - // The compilation's own list may leave out the hidden "unnecessary using" (CS8019); a file's semantic model - // carries it. Only the first file is asked, the buffer being edited, and only when it has no errors: the - // semantic model binds the file a second time. - if (snapshot.First != null && !all.Any(d => d.Severity == DiagnosticSeverity.Error) && !all.Any(d => d.Id == "CS8019")) - all.AddRange(compilation.GetSemanticModel(snapshot.First).GetDiagnostics(null, CancellationToken.None) - .Where(d => d.Id == "CS8019")); - return errors + Print(all, output) > 0 ? 1 : 0; - } - - // The diagnostics of one file, with the syntax errors of the others. Binding stops at the file's own code, and - // the other files' declarations it needs, so the cost follows the file and not the project. - public static int RunFile(string bufferPath, string[] arguments, TextWriter output) - { - Snapshot snapshot = Project.Open(arguments, Path.GetFullPath(bufferPath)); - int errors = Report(snapshot.Problems, output); - if (snapshot.Compilation == null) return 1; - if (snapshot.Buffer == null) return Run(arguments, output); - - var all = snapshot.Compilation.GetSemanticModel(snapshot.Buffer).GetDiagnostics(null, CancellationToken.None).ToList(); - foreach (SyntaxTree tree in snapshot.Compilation.SyntaxTrees) - if (tree != snapshot.Buffer) all.AddRange(tree.GetDiagnostics(CancellationToken.None)); - return errors + Print(all, output) > 0 ? 1 : 0; - } - - static int Report(List problems, TextWriter output) - { - int errors = 0; - foreach (string problem in problems) - { - output.WriteLine(problem); - if (problem.Contains("error ")) errors++; - } - return errors; - } - - // Prints errors, warnings and the hidden unnecessary-using note in `csc`'s format. Returns the number of errors. - static int Print(List all, TextWriter output) - { - int errors = 0; - var found = all - .Where(d => !d.IsSuppressed && (d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning - || (d.Severity == DiagnosticSeverity.Hidden && d.Id == "CS8019"))) - .OrderBy(d => d.Location.SourceTree == null ? "" : d.Location.SourceTree.FilePath, StringComparer.Ordinal) - .ThenBy(d => d.Location.SourceSpan.Start); - foreach (var d in found) - { - output.WriteLine(d.ToString()); - if (d.Severity == DiagnosticSeverity.Error) errors++; - } - return errors; - } -} -""" diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsCompilerHost.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsCompilerHost.kt deleted file mode 100644 index a8aae23246..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsCompilerHost.kt +++ /dev/null @@ -1,22 +0,0 @@ -package dev.codeassist.csharp.sdk - -import dev.codeassist.csharp.util.ToolCancellation - -/** - * The resident compiler: `csc` kept loaded in the server ([CsServer]), so a compile pays for compiling and - * not for starting the runtime and Roslyn again. Takes the arguments `csc` would and gives back its output - * and exit code. - */ -internal object CsCompilerHost { - - /** Switch for the resident compiler; false sends every compile to a plain `csc`. */ - const val ENABLED = true - - /** Compiles with [arguments]. Returns `csc`'s exit code, or null if the server could not be used. */ - fun compile( - sdk: DotnetSdk, - arguments: List, - cancellation: ToolCancellation, - onLine: (String) -> Unit, - ): Int? = CsServer.compile(sdk, listOf("@@compile") + arguments, cancellation, onLine) -} diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsCompleter.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsCompleter.kt deleted file mode 100644 index ac13e27633..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsCompleter.kt +++ /dev/null @@ -1,562 +0,0 @@ -package dev.codeassist.csharp.sdk - -import android.util.Log -import dev.codeassist.csharp.util.TAG -import dev.codeassist.csharp.util.ToolCancellation - -/** - * Completion from Roslyn's semantic model, answered by the resident server ([CsServer]). - * - * Why Roslyn and not the symbol table: the table is only the public surface of DLLs, so it cannot know a local - * variable, an internal class of the project, an inherited member, what a method returns, or an extension method. - * The semantic model answers all of these with `LookupSymbols`, the call an IDE's completion is built on. - * - * The request is a response file like the compiler's: its first lines are the mode (`@@complete` or `@@signature`), - * the caret offset, the offset where the typed word starts (unused by `@@signature`), and the buffer's path; the - * rest are the compiler's arguments. The reply to `@@complete` is one `item` line per candidate (see - * [CsCompletionItems.parse]); to `@@signature` a `sighelp` line and one `sig` line per overload (see - * [CsSignatureLines.parse]); then `@@CS-DONE@@ `. - */ -internal object CsCompleter { - - private const val FAILED = 255 - - /** Starts the server ahead of the first request; see [ResidentProgram.warm]. */ - fun warm(sdk: DotnetSdk) = CsServer.warm(sdk) - - /** - * The candidates at caret in the buffer at bufferPath, whose word starts at wordStart, - * given the compiler arguments of the project with that buffer among the sources. Null when the program could not be - * used; the lines it printed otherwise go to onLine. - */ - fun complete( - sdk: DotnetSdk, - bufferPath: String, - caret: Int, - wordStart: Int, - arguments: List, - cancellation: ToolCancellation, - onLine: (String) -> Unit, - ): Int? { - return ask(sdk, "@@complete", bufferPath, caret, wordStart, arguments, cancellation, onLine) - } - - /** - * The signatures of the call whose argument list holds caret in the buffer at bufferPath. - * Same contract as complete: null when the program could not be used, else its exit code, with the lines going to [onLine] - * (none when the caret is in no call). - */ - fun signatures( - sdk: DotnetSdk, - bufferPath: String, - caret: Int, - arguments: List, - cancellation: ToolCancellation, - onLine: (String) -> Unit, - ): Int? = ask(sdk, "@@signature", bufferPath, caret, caret, arguments, cancellation, onLine) - - private fun ask( - sdk: DotnetSdk, - mode: String, - bufferPath: String, - caret: Int, - wordStart: Int, - arguments: List, - cancellation: ToolCancellation, - onLine: (String) -> Unit, - ): Int? { - val request = listOf(mode, caret.toString(), wordStart.toString(), bufferPath) + arguments - val exitCode = CsServer.compile(sdk, request, cancellation, onLine) ?: return null - if (exitCode == FAILED) { - Log.d(TAG, "$mode: the program failed inside; see the lines above") - return null - } - return exitCode - } -} - -/** - * The completion half of [SERVER_SOURCE]. No `$` anywhere in it: this is a Kotlin raw string; and no triple - * quote. The compilation it asks comes from the server's `Project`, which keeps it between requests. - */ -internal const val COMPLETER_SOURCE = """ -static class Completer -{ - const int Limit = 400; - - public static int Run(string[] arguments, TextWriter output) - { - if (arguments.Length < 4 || (arguments[0] != "@@complete" && arguments[0] != "@@signature")) return 255; - bool signature = arguments[0] == "@@signature"; - int caret = int.Parse(arguments[1]); - int wordStart = int.Parse(arguments[2]); - string bufferPath = Path.GetFullPath(arguments[3]); - string[] rest = arguments.Skip(4).ToArray(); - - Snapshot snapshot = Project.Open(rest, bufferPath); - SyntaxTree buffer = snapshot.Buffer; - if (buffer == null) return 0; - CSharpCompilation compilation = snapshot.Compilation; - SemanticModel model = compilation.GetSemanticModel(buffer, false); - string source = buffer.GetText(CancellationToken.None).ToString(); - caret = Math.Max(0, Math.Min(caret, source.Length)); - wordStart = Math.Max(0, Math.Min(wordStart, caret)); - if (signature) return Signature(model, buffer, source, caret, output); - string prefix = source.Substring(wordStart, caret - wordStart); - - IEnumerable symbols = Candidates(model, buffer, source, wordStart, caret); - if (symbols == null) return 0; - - var groups = new Dictionary>(); - var order = new List(); - foreach (ISymbol symbol in symbols) - { - if (!Wanted(symbol)) continue; - string name = symbol.Name; - if (name.Length == 0 || !Matches(name, prefix)) continue; - string key = Category(symbol) + "\t" + name; - List list; - if (!groups.TryGetValue(key, out list)) { list = new List(); groups[key] = list; order.Add(key); } - list.Add(symbol); - } - - int count = 0; - foreach (string key in order) - { - if (count++ >= Limit) break; - List list = groups[key]; - ISymbol first = list[0]; - string kind = Category(first); - string detail = Detail(model, wordStart, first); - bool takesArguments = false; - if (first is IMethodSymbol) - takesArguments = list.All(s => s is IMethodSymbol && ((IMethodSymbol)s).Parameters.Length > 0); - string container = Container(first); - bool deprecated = first.GetAttributes().Any( - a => a.AttributeClass != null && a.AttributeClass.Name == "ObsoleteAttribute"); - output.WriteLine("item\t" + Clean(first.Name) + "\t" + kind + "\t" + Clean(detail) - + "\t" + (takesArguments ? "1" : "0") + "\t" + Clean(container) + "\t" + (deprecated ? "1" : "0") - + "\t" + (list.Count > 1 ? list.Count.ToString() : "1") - + "\t" + Documentation(first, false)); - } - - // Types by name that no using reaches yet, each with the namespace to import. Only where a type name can - // stand (not after a dot), and only once two letters say which. - int before = wordStart - 1; - while (before >= 0 && char.IsWhiteSpace(source[before])) before--; - bool afterDot = before >= 0 && source[before] == '.'; - if (!afterDot && prefix.Length >= 2) - { - var offered = new HashSet(order.Select(k => k.Substring(k.IndexOf('\t') + 1)), StringComparer.Ordinal); - int added = 0; - foreach (Importable type in Importables(compilation) - .Where(t => t.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && !offered.Contains(t.Name)) - .OrderBy(t => t.Name.Length).ThenBy(t => t.Name, StringComparer.Ordinal).ThenBy(t => t.Namespace, StringComparer.Ordinal)) - { - if (added++ >= 40) break; - output.WriteLine("item\t" + Clean(type.Name) + "\t" + type.Kind + "\t\t0\t" + Clean(type.Namespace) + "\t0\t1\t\t" + Clean(type.Namespace)); - } - } - return 0; - } - - sealed class Importable - { - public string Name; - public string Namespace; - public string Kind; - } - - // The public types of the references, kept by name for as long as the references are the same ones: walking - // every namespace of the class library on each request would cost more than the request. - static long importablesKey; - static List importables; - - static List Importables(CSharpCompilation compilation) - { - long key = 17; - foreach (MetadataReference reference in compilation.References) - key = key * 31 + System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(reference); - if (importables == null || key != importablesKey) - { - var found = new List(); - foreach (MetadataReference reference in compilation.References) - { - IAssemblySymbol assembly = compilation.GetAssemblyOrModuleSymbol(reference) as IAssemblySymbol; - if (assembly != null) Collect(assembly.GlobalNamespace, found, false); - } - importables = found; - importablesKey = key; - } - // The project's own types change as it is edited, so they are read each time; there are few of them. - var all = new List(importables); - Collect(compilation.Assembly.GlobalNamespace, all, true); - return all; - } - - static void Collect(INamespaceSymbol space, List found, bool own) - { - foreach (INamedTypeSymbol type in space.GetTypeMembers()) - { - if (space.IsGlobalNamespace || type.Name.Length == 0 || type.Name[0] == '<') continue; - bool visible = type.DeclaredAccessibility == Accessibility.Public || (own && type.DeclaredAccessibility == Accessibility.Internal); - if (!visible) continue; - found.Add(new Importable { Name = type.Name, Namespace = space.ToDisplayString(), Kind = Category(type) }); - } - foreach (INamespaceSymbol inner in space.GetNamespaceMembers()) Collect(inner, found, own); - } - - // The documentation of a DLL, read from the .xml file beside it. Roslyn's own XmlDocumentationProvider is in the - // Workspaces assembly, which is not shipped, so this is the small part of it that is needed: member id to the - // member's element. The file is read on the first question and each element cut out only when asked for. - internal sealed class XmlDocs : DocumentationProvider - { - static readonly Regex Member = new Regex("]*>.*?", RegexOptions.Singleline); - readonly string path; - string text; - Dictionary> members; - - public XmlDocs(string path) { this.path = path; } - - protected override string GetDocumentationForSymbol( - string documentationMemberID, System.Globalization.CultureInfo preferredCulture, - CancellationToken cancellationToken = default(CancellationToken)) - { - lock (this) - { - if (members == null) - { - members = new Dictionary>(); - try - { - text = File.ReadAllText(path); - foreach (Match m in Member.Matches(text)) - members[m.Groups[1].Value] = new KeyValuePair(m.Index, m.Length); - } - catch (Exception) { text = ""; } - } - KeyValuePair at; - return members.TryGetValue(documentationMemberID, out at) ? text.Substring(at.Key, at.Value) : ""; - } - } - - public override bool Equals(object obj) { XmlDocs other = obj as XmlDocs; return other != null && other.path == path; } - public override int GetHashCode() { return path.GetHashCode(); } - } - - static readonly Regex SummaryElement = new Regex(".*?", RegexOptions.Singleline); - static readonly Regex ParamElement = new Regex(".*?", RegexOptions.Singleline); - - // The summary of the symbol's XML documentation, and with [withParams] its param elements, escaped onto one line - // (a backslash, a tab and a newline become \\, \t and \n). Empty when it has none. Only those elements are sent: - // remarks and examples can be long and the popup does not show them. - internal static string Documentation(ISymbol symbol, bool withParams) - { - try - { - ISymbol source = symbol.OriginalDefinition; - IMethodSymbol method = source as IMethodSymbol; - if (method != null && method.ReducedFrom != null) source = method.ReducedFrom.OriginalDefinition; - string xml = source.GetDocumentationCommentXml(null, false, CancellationToken.None); - if (string.IsNullOrEmpty(xml)) return ""; - var slim = new StringBuilder(); - Match summary = SummaryElement.Match(xml); - if (summary.Success) slim.Append(summary.Value); - if (withParams) - foreach (Match p in ParamElement.Matches(xml)) slim.Append(p.Value); - if (xml.Contains(""); - return slim.ToString().Replace("\\", "\\\\").Replace("\t", "\\t").Replace("\r", "").Replace("\n", "\\n"); - } - catch (Exception) { return ""; } - } - - const int SignatureLimit = 30; - - // The overloads of the call whose argument list holds the caret. Prints nothing when the caret is in no call. - // sighelp active signature active parameter - // sig label start,end;start,end (the range of each parameter inside the label) - static int Signature(SemanticModel model, SyntaxTree tree, string source, int caret, TextWriter output) - { - SyntaxNode root = tree.GetRoot(CancellationToken.None); - SyntaxToken token = root.FindToken(Math.Max(0, caret - 1)); - ArgumentListSyntax list = null; - for (SyntaxNode node = token.Parent; node != null; node = node.Parent) - { - ArgumentListSyntax candidate = node as ArgumentListSyntax; - if (candidate == null) continue; - if (candidate.OpenParenToken.Span.End > caret) continue; - if (!candidate.CloseParenToken.IsMissing && caret > candidate.CloseParenToken.SpanStart) continue; - list = candidate; - break; - } - if (list == null) return 0; - - // The argument the caret is in: the commas before it. - int active = list.Arguments.GetSeparators().Count(c => c.Span.End <= caret); - - SyntaxNode owner = list.Parent; - var methods = new List(); - SymbolInfo info = default(SymbolInfo); - InvocationExpressionSyntax invocation = owner as InvocationExpressionSyntax; - BaseObjectCreationExpressionSyntax creation = owner as BaseObjectCreationExpressionSyntax; - ConstructorInitializerSyntax initializer = owner as ConstructorInitializerSyntax; - if (invocation != null) - { - info = model.GetSymbolInfo(invocation, CancellationToken.None); - foreach (ISymbol s in model.GetMemberGroup(invocation.Expression, CancellationToken.None)) - { - IMethodSymbol m = s as IMethodSymbol; - if (m != null) methods.Add(m); - } - if (methods.Count == 0) - { - IMethodSymbol one = info.Symbol as IMethodSymbol; - if (one != null) methods.Add(one); - foreach (ISymbol s in info.CandidateSymbols) - { - IMethodSymbol m = s as IMethodSymbol; - if (m != null) methods.Add(m); - } - } - } - else if (creation != null || initializer != null) - { - INamedTypeSymbol type = null; - if (creation != null) - { - info = model.GetSymbolInfo(creation, CancellationToken.None); - type = model.GetTypeInfo(creation, CancellationToken.None).Type as INamedTypeSymbol; - } - else - { - info = model.GetSymbolInfo(initializer, CancellationToken.None); - ConstructorDeclarationSyntax declaration = initializer.Parent as ConstructorDeclarationSyntax; - IMethodSymbol declared = declaration == null - ? null : model.GetDeclaredSymbol(declaration, CancellationToken.None) as IMethodSymbol; - if (declared != null) - type = initializer.ThisOrBaseKeyword.IsKind(SyntaxKind.ThisKeyword) - ? declared.ContainingType : declared.ContainingType.BaseType; - } - if (type == null || type.TypeKind == TypeKind.Error) return 0; - foreach (IMethodSymbol m in type.InstanceConstructors) - if (model.IsAccessible(caret, m)) methods.Add(m); - } - else return 0; - - if (methods.Count == 0) return 0; - methods = methods.OrderBy(m => m.Parameters.Length).ThenBy(m => m.ToDisplayString()) - .Take(SignatureLimit).ToList(); - - ISymbol chosen = info.Symbol; - int activeSignature = -1; - if (chosen != null) - for (int i = 0; i < methods.Count && activeSignature < 0; i++) - if (SymbolEqualityComparer.Default.Equals(methods[i], chosen) - || SymbolEqualityComparer.Default.Equals(methods[i].OriginalDefinition, chosen.OriginalDefinition)) - activeSignature = i; - // An unfinished call has no single binding: the first overload that has room for the argument. - if (activeSignature < 0) - for (int i = 0; i < methods.Count && activeSignature < 0; i++) - if (methods[i].Parameters.Length > active - || (methods[i].Parameters.Length > 0 - && methods[i].Parameters[methods[i].Parameters.Length - 1].IsParams)) - activeSignature = i; - if (activeSignature < 0) activeSignature = 0; - - output.WriteLine("sighelp\t" + activeSignature + "\t" + active); - foreach (IMethodSymbol method in methods) - { - var label = new StringBuilder(); - label.Append(method.MethodKind == MethodKind.Constructor ? method.ContainingType.Name : method.Name); - if (method.TypeParameters.Length > 0) - label.Append('<').Append(string.Join(", ", method.TypeParameters.Select(t => t.Name))).Append('>'); - label.Append('('); - var ranges = new List(); - for (int i = 0; i < method.Parameters.Length; i++) - { - if (i > 0) label.Append(", "); - int start = label.Length; - label.Append(ParameterText(model, caret, method.Parameters[i])); - ranges.Add(start + "," + label.Length); - } - label.Append(')'); - output.WriteLine("sig\t" + Clean(label.ToString()) + "\t" + string.Join(";", ranges) - + "\t" + Documentation(method, true) + "\t" + string.Join(";", method.Parameters.Select(p => p.Name))); - } - return 0; - } - - static string ParameterText(SemanticModel model, int position, IParameterSymbol parameter) - { - var text = new StringBuilder(); - if (parameter.IsParams) text.Append("params "); - if (parameter.RefKind == RefKind.Out) text.Append("out "); - else if (parameter.RefKind == RefKind.Ref) text.Append("ref "); - else if (parameter.RefKind == RefKind.In) text.Append("in "); - string type; - try { type = parameter.Type.ToMinimalDisplayString(model, position); } - catch (Exception) { type = parameter.Type.Name; } - text.Append(type).Append(' ').Append(parameter.Name); - if (parameter.HasExplicitDefaultValue) - { - object value = parameter.ExplicitDefaultValue; - string shown = value == null ? "default" - : value is string ? "\"" + value + "\"" - : value is bool ? ((bool)value ? "true" : "false") - : Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture); - text.Append(" = ").Append(shown); - } - return text.ToString(); - } - - // The symbols that may be written at the caret, or null when the caret is somewhere nothing is offered. - static IEnumerable Candidates( - SemanticModel model, SyntaxTree tree, string source, int wordStart, int caret) - { - SyntaxNode root = tree.GetRoot(CancellationToken.None); - int dot = wordStart - 1; - while (dot >= 0 && char.IsWhiteSpace(source[dot])) dot--; - bool afterDot = dot >= 0 && source[dot] == '.'; - int position = caret; - - if (afterDot) - { - SyntaxToken token = root.FindToken(dot); - ExpressionSyntax receiver = ReceiverOf(token); - if (receiver == null) return null; - - SymbolInfo info = model.GetSymbolInfo(receiver, CancellationToken.None); - ISymbol symbol = info.Symbol; - if (symbol is INamespaceSymbol) - return model.LookupNamespacesAndTypes(position, (INamespaceSymbol)symbol, null); - if (symbol is ITypeSymbol && !(symbol is ITypeParameterSymbol)) - { - // A type's own name: its static members and nested types. (`Color Color` where a property has the - // type's name is read as the type; that case is not handled.) - return model.LookupStaticMembers(position, (ITypeSymbol)symbol, null); - } - ITypeSymbol type = model.GetTypeInfo(receiver, CancellationToken.None).Type; - if (type == null || type.TypeKind == TypeKind.Error) return null; - // A nullable value type completes as the type inside it, as the language reads `x.` on an int?. - INamedTypeSymbol named = type as INamedTypeSymbol; - if (named != null && named.IsValueType - && named.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) - type = named.TypeArguments[0]; - return model.LookupSymbols(position, type, null, true) - .Where(s => !s.IsStatic || s.Kind == SymbolKind.NamedType); - } - - // After `new` only types make sense. - SyntaxToken before = root.FindToken(Math.Max(0, wordStart - 1)); - if (before.Span.End <= wordStart && before.IsKind(SyntaxKind.NewKeyword)) - return model.LookupNamespacesAndTypes(position, null, null); - - return model.LookupSymbols(position, null, null, false); - } - - static ExpressionSyntax ReceiverOf(SyntaxToken dot) - { - SyntaxNode parent = dot.Parent; - MemberAccessExpressionSyntax access = parent as MemberAccessExpressionSyntax; - if (access != null) return access.Expression; - QualifiedNameSyntax qualified = parent as QualifiedNameSyntax; - if (qualified != null) return qualified.Left; - // `x?.` : the dot is the `.` of a member binding, whose receiver is the expression of the conditional access. - MemberBindingExpressionSyntax binding = parent as MemberBindingExpressionSyntax; - if (binding != null) - { - ConditionalAccessExpressionSyntax conditional = binding.Ancestors() - .OfType().FirstOrDefault(); - if (conditional != null) return conditional.Expression; - } - return null; - } - - // What a name may be, without what the language hides: constructors, accessors, operators, compiler names. - static bool Wanted(ISymbol symbol) - { - if (symbol.IsImplicitlyDeclared) return false; - if (symbol.Name.IndexOfAny(new char[] { '<', '>', '.', (char)36 }) >= 0) return false; - IMethodSymbol method = symbol as IMethodSymbol; - if (method != null) - return method.MethodKind == MethodKind.Ordinary || method.MethodKind == MethodKind.ReducedExtension - || method.MethodKind == MethodKind.LocalFunction; - return symbol.Kind != SymbolKind.Label; - } - - // A subsequence match, case-insensitive: lenient on purpose, the editor applies its own matching after. - static bool Matches(string name, string prefix) - { - if (prefix.Length == 0) return true; - int at = 0; - foreach (char c in prefix) - { - at = name.IndexOf(c.ToString(), at, StringComparison.OrdinalIgnoreCase); - if (at < 0) return false; - at++; - } - return true; - } - - static string Category(ISymbol symbol) - { - switch (symbol.Kind) - { - case SymbolKind.Method: - IMethodSymbol method = (IMethodSymbol)symbol; - if (method.MethodKind == MethodKind.ReducedExtension) return "extension"; - return method.MethodKind == MethodKind.LocalFunction ? "local" : "method"; - case SymbolKind.Property: return "property"; - case SymbolKind.Field: - IFieldSymbol field = (IFieldSymbol)symbol; - if (field.ContainingType != null && field.ContainingType.TypeKind == TypeKind.Enum) return "enummember"; - return field.IsConst ? "constant" : "field"; - case SymbolKind.Event: return "event"; - case SymbolKind.Local: return "local"; - case SymbolKind.Parameter: return "parameter"; - case SymbolKind.Namespace: return "namespace"; - case SymbolKind.TypeParameter: return "typeparameter"; - case SymbolKind.NamedType: - switch (((INamedTypeSymbol)symbol).TypeKind) - { - case TypeKind.Interface: return "interface"; - case TypeKind.Enum: return "enum"; - case TypeKind.Struct: return "struct"; - case TypeKind.Delegate: return "delegate"; - default: return "class"; - } - default: return "other"; - } - } - - // The type of a value, or the return type of a method, as it would be written at the caret. - static string Detail(SemanticModel model, int position, ISymbol symbol) - { - ITypeSymbol type = null; - IMethodSymbol method = symbol as IMethodSymbol; - if (method != null) type = method.ReturnType; - else if (symbol is IPropertySymbol) type = ((IPropertySymbol)symbol).Type; - else if (symbol is IFieldSymbol) type = ((IFieldSymbol)symbol).Type; - else if (symbol is ILocalSymbol) type = ((ILocalSymbol)symbol).Type; - else if (symbol is IParameterSymbol) type = ((IParameterSymbol)symbol).Type; - else if (symbol is IEventSymbol) type = ((IEventSymbol)symbol).Type; - if (type == null) return ""; - try { return type.ToMinimalDisplayString(model, position); } - catch (Exception) { return type.Name; } - } - - // The declaring type, or the namespace for a type; empty for a local or a parameter. - internal static string Container(ISymbol symbol) - { - if (symbol is ILocalSymbol || symbol is IParameterSymbol) return ""; - if (symbol.ContainingType != null) return symbol.ContainingType.Name; - INamespaceSymbol ns = symbol.ContainingNamespace; - return ns != null && !ns.IsGlobalNamespace ? ns.ToDisplayString() : ""; - } - - internal static string Clean(string text) - { - return text == null ? "" : text.Replace('\t', ' ').Replace('\r', ' ').Replace('\n', ' '); - } -} -""" diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsFormatter.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsFormatter.kt deleted file mode 100644 index ec086ae208..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsFormatter.kt +++ /dev/null @@ -1,124 +0,0 @@ -package dev.codeassist.csharp.sdk - -import android.util.Log -import dev.codeassist.csharp.util.TAG -import dev.codeassist.csharp.util.ToolCancellation - -/** - * Reformatting, by Roslyn's own formatter in the resident server ([CsServer]). - * - * The request is `@@format`, the start and end of the range to format (both `-1` for the whole file), the - * buffer's path, then the compiler's arguments. The reply is one `edit ` line per - * change, offsets being those of the buffer as sent and the text escaped (see [CsFormatEdits]). - * - * The formatter's assemblies are loaded when the first request arrives and not before: they are several - * megabytes that a session which never reformats does not pay for. - */ -internal object CsFormatter { - - private const val FAILED = 255 - - fun format( - sdk: DotnetSdk, - bufferPath: String, - start: Int, - end: Int, - indentSize: Int, - useTabs: Boolean, - arguments: List, - cancellation: ToolCancellation, - onLine: (String) -> Unit, - ): Int? { - val request = listOf("@@format", start.toString(), end.toString(), indentSize.toString(), if (useTabs) "1" else "0", bufferPath) + - arguments - val exitCode = CsServer.compile(sdk, request, cancellation, onLine) ?: return null - if (exitCode == FAILED) { - Log.d(TAG, "@@format: the program failed inside; see the lines above") - return null - } - return exitCode - } -} - -/** Reads the `edit` lines of a `@@format` reply. Pure, so it can be tested without a device. */ -internal object CsFormatEdits { - - data class Edit(val offset: Int, val length: Int, val text: String) - - fun parse(lines: List): List = lines.mapNotNull { line -> - val parts = line.split('\t') - if (parts.size < 4 || parts[0] != "edit") return@mapNotNull null - val offset = parts[1].toIntOrNull() ?: return@mapNotNull null - val length = parts[2].toIntOrNull() ?: return@mapNotNull null - if (offset < 0 || length < 0) return@mapNotNull null - Edit(offset, length, unescape(parts[3])) - } - - /** Reverses the server's escaping: `\n`, `\r`, `\t` and `\\`. */ - fun unescape(text: String): String { - if ('\\' !in text) return text - val out = StringBuilder(text.length) - var i = 0 - while (i < text.length) { - val c = text[i] - if (c == '\\' && i + 1 < text.length) { - when (val next = text[i + 1]) { - 'n' -> out.append('\n') - 'r' -> out.append('\r') - 't' -> out.append('\t') - else -> out.append(next) - } - i += 2 - } else { - out.append(c) - i++ - } - } - return out.toString() - } -} - -/** The formatting half of [SERVER_SOURCE]. No `$` anywhere in it: this is a Kotlin raw string. */ -internal const val FORMATTER_SOURCE = """ -static class Reformatter -{ - static Microsoft.CodeAnalysis.AdhocWorkspace workspace; - - public static int Run(string[] arguments, TextWriter output) - { - if (arguments.Length < 5) return 255; - int start = int.Parse(arguments[0]); - int end = int.Parse(arguments[1]); - int indent = Math.Max(1, int.Parse(arguments[2])); - bool tabs = arguments[3] == "1"; - Snapshot snapshot = Project.Open(arguments.Skip(5).ToArray(), Path.GetFullPath(arguments[4])); - if (snapshot.Buffer == null) return 0; - - SyntaxNode root = snapshot.Buffer.GetRoot(CancellationToken.None); - // Text that does not parse is left as it is: the formatter would move what it guessed at. - if (root.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) return 3; - - if (workspace == null) workspace = new Microsoft.CodeAnalysis.AdhocWorkspace(); - var options = workspace.Options - .WithChangedOption(Microsoft.CodeAnalysis.Formatting.FormattingOptions.IndentationSize, LanguageNames.CSharp, indent) - .WithChangedOption(Microsoft.CodeAnalysis.Formatting.FormattingOptions.TabSize, LanguageNames.CSharp, indent) - .WithChangedOption(Microsoft.CodeAnalysis.Formatting.FormattingOptions.UseTabs, LanguageNames.CSharp, tabs); - - IList changes; - if (start >= 0 && end > start) - { - int length = root.FullSpan.End; - var span = Microsoft.CodeAnalysis.Text.TextSpan.FromBounds(Math.Min(start, length), Math.Min(end, length)); - changes = Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(root, span, workspace, options, CancellationToken.None); - } - else changes = Microsoft.CodeAnalysis.Formatting.Formatter.GetFormattedTextChanges(root, workspace, options, CancellationToken.None); - - foreach (var change in changes.OrderBy(c => c.Span.Start)) - { - string text = (change.NewText ?? "").Replace("\\", "\\\\").Replace("\t", "\\t").Replace("\r", "\\r").Replace("\n", "\\n"); - output.WriteLine("edit\t" + change.Span.Start + "\t" + change.Span.Length + "\t" + text); - } - return 0; - } -} -""" diff --git a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsNavigator.kt b/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsNavigator.kt deleted file mode 100644 index 56eb89027e..0000000000 --- a/samples/dotnet-plugin/src/main/kotlin/dev/codeassist/csharp/sdk/CsNavigator.kt +++ /dev/null @@ -1,443 +0,0 @@ -package dev.codeassist.csharp.sdk - -import android.util.Log -import dev.codeassist.csharp.util.TAG -import dev.codeassist.csharp.util.ToolCancellation - -/** - * What the editor asks about a symbol in the buffer, answered by the resident server ([CsServer]) from the - * same compilation the check and completion use: where it is declared, what it is, and how each name in the - * file should be coloured. - * - * Requests follow [CsCompleter]'s shape: the mode, the caret (not for `@@tokens`), the buffer's path, then the - * compiler's arguments. The replies are tab-separated lines: - * - * - `@@definition`: `def