diff --git a/azure-pipelines-official.yml b/azure-pipelines-official.yml index a092a98853064..21394b8308535 100644 --- a/azure-pipelines-official.yml +++ b/azure-pipelines-official.yml @@ -11,6 +11,12 @@ resources: # IbcSourceBranchName: 'default' # IbcDropId: 'default' +variables: + - name: _DotNetArtifactsCategory + value: .NETCore + - name: _DotNetValidationArtifactsCategory + value: .NETCoreValidation + stages: - stage: build displayName: Build and Test @@ -81,6 +87,8 @@ stages: /p:PublishToSymbolServer=true /p:DotNetSymbolServerTokenMsdl=$(microsoft-symbol-server-pat) /p:DotNetSymbolServerTokenSymWeb=$(symweb-symbol-server-pat) + /p:DotNetArtifactsCategory=$(_DotNetArtifactsCategory) + /p:DotnetPublishUsingPipelines=true displayName: Build condition: succeeded() @@ -228,6 +236,7 @@ stages: # Publish to Build Asset Registry - template: /eng/common/templates/job/publish-build-assets.yml parameters: + publishUsingPipelines: true dependsOn: - OfficialBuild queue: diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index bceba6fdaa264..b891c1a7c1706 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -3,9 +3,9 @@ - + https://github.com/dotnet/arcade - 10b2260aeed5f07582bf8d8dcd4221a447b171c5 + f5ccfdcbd828383d39cf583086ef42d72ca5b320 diff --git a/eng/Versions.props b/eng/Versions.props index 4ace5a7a4f8f1..5f485ca10e2ea 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -25,12 +25,13 @@ - 2.9.3 + 2.9.4 2.8.2 1.0.0-beta1-63310-01 3.3.0-beta2-19376-02 - 16.1.101 + 16.3.98 5.0.0-alpha1.19409.1 + 16.3.27-develop-gdd55e997 + @@ -163,6 +164,7 @@ + diff --git a/eng/targets/GenerateServiceHubConfigurationFiles.targets b/eng/targets/GenerateServiceHubConfigurationFiles.targets index 05e804ec7f949..e508b70ccad1d 100644 --- a/eng/targets/GenerateServiceHubConfigurationFiles.targets +++ b/eng/targets/GenerateServiceHubConfigurationFiles.targets @@ -10,6 +10,8 @@ + + diff --git a/global.json b/global.json index 3b924c2406282..367dbeded2009 100644 --- a/global.json +++ b/global.json @@ -7,6 +7,6 @@ "xcopy-msbuild": "16.0.0-alpha" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "1.0.0-beta.19419.12" + "Microsoft.DotNet.Arcade.Sdk": "1.0.0-beta.19459.10" } } diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf index 5cca43132380f..54274543a66db 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.xlf @@ -37,6 +37,11 @@ Ve výrazu as se nepovoluje použití typu odkazu s možnou hodnotou null {0}?; místo toho použijte základní typ {0}. + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + Atribut {0} není platný pro přístupové objekty události. Je platný jenom pro deklarace {1}. + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. Automaticky implementovanou vlastnost {0} nelze označit modifikátorem readonly, protože má přístupový objekt set. @@ -47,11 +52,6 @@ Automaticky implementovaný přístupový objekt set {0} nelze označit modifikátorem readonly. - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - Atribut {0} není platný pro přístupové objekty události. Je platný jenom pro deklarace {1}. - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' Asynchronní příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje vhodnou veřejnou definici instance pro {1}. @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Neplatná možnost {0} pro /nullable; musí mít hodnotu disable, enable, safeonly, warnings nebo safeonlywarnings. + Neplatná možnost {0} pro /nullable. Je třeba použít disable, enable, warnings nebo annotations. @@ -124,7 +124,7 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + Duplicitní operátor potlačení hodnoty null (!) @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + Očekávala se možnost warnings nebo annotations nebo konec direktivy. @@ -640,7 +640,7 @@ zástupného znaku. -reference:<alias>=<soubor> Odkazuje na metadata ze zadaného souboru sestavení pomocí daného aliasu. (Krátký formát: -r) --reference:<seznam souborů> Odkazuje na metadata ze zadaných souborů +-reference:<seznam souborů> Odkazuje na metadata ze zadaných souborů sestavení (Krátký formát: -r) -addmodule:<seznam souborů> Připojí zadané moduly k tomuto sestavení. -link:<seznam souborů> Vloží metadata ze zadaných souborů @@ -687,7 +687,7 @@ specifickou diagnostiku. -errorlog:<soubor> Určuje soubor pro protokolování veškeré diagnostiky kompilátoru a analyzátoru. --reportanalyzer Hlásí další informace analyzátoru, např.\r +-reportanalyzer Hlásí další informace analyzátoru, např. dobu spuštění. - JAZYK - @@ -696,13 +696,15 @@ -define:<seznam symbolů> Definuje symboly podmíněné kompilace. (Krátký formát: -d) -langversion:? Zobrazuje povolené hodnoty pro verzi jazyka. --langversion:<řetězec> Určuje verzi jazyka:r - default (poslední hlavní verze) nebo +-langversion:<řetězec> Určuje verzi jazyka, například: latest (poslední verze včetně podverzí), - nebo konkrétní verze jako 6 nebo 7.1. + default (stejné jako latest), + latestmajor (poslední verze bez podverzí), + preview (poslední verze včetně funkcí v nepodporované verzi preview) + nebo konkrétní verze, například 6 nebo 7.1. -nullable[+|-] Určuje pro kontext s hodnotou null možnosti enable|disable. --nullable:{enable|disable|warnings} - Určuje pro kontext s hodnotou null možnosti enable|disable|warnings. +-nullable:{enable|disable|warnings|annotations} + Určuje pro kontext s hodnotou null možnosti enable|disable|warnings|annotations. - ZABEZPEČENÍ - -delaysign[+|-] Vytvoří zpožděný podpis sestavení s využitím @@ -746,7 +748,7 @@ -nosdkpath Zakazuje hledání cesty k výchozí sadě SDK pro sestavení standardních knihoven. -nostdlib[+|-] Neodkazuje na standardní knihovnu (mscorlib.dll). -subsystemversion:<string> Určuje verzi subsystému tohoto sestavení. --lib:<seznam souborů> Určuje další adresáře, ve kterých se mají +-lib:<seznam souborů> Určuje další adresáře, ve kterých se mají hledat reference. -errorreport:<řetězec> Určuje způsob zpracování interních chyb kompilátoru: prompt, send, queue nebo none. Výchozí možnost je @@ -761,7 +763,7 @@ default interface implementation - default interface implementation + implementace výchozího rozhraní @@ -886,7 +888,7 @@ <switch expression> - <switch expression> + <výraz přepínače> @@ -1411,12 +1413,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + Poznámka u typů odkazů s možnou hodnotou null by se měla v kódu používat jenom v kontextu poznámek #nullable. The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + Poznámka u typů odkazů s možnou hodnotou null by se měla v kódu používat jenom v kontextu poznámek #nullable. @@ -1581,7 +1583,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + Typ odkazu s možnou hodnotou null v typu parametru {0} z {1} neodpovídá implicitně implementovanému členu {2}. @@ -1631,7 +1633,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + Typ odkazu s možnou hodnotou null v návratovém typu {0} neodpovídá implicitně implementovanému členu {1}. @@ -1661,7 +1663,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + Typ odkazu s možnou hodnotou null v typu {0} neodpovídá implicitně implementovanému členu {1}. @@ -1671,12 +1673,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + Typ odkazu s možnou hodnotou null v typu neodpovídá přepsanému členu. Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + Typ odkazu s možnou hodnotou null v typu neodpovídá přepsanému členu. @@ -1801,12 +1803,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - Pole {0} {1}, které neumožňuje hodnotu null, není inicializované. + Není inicializované pole {0} ({1}) bez možnosti zadání hodnoty null. Zvažte možnost deklarovat {0} jako pole typu s možnou hodnotou null. Non-nullable field is uninitialized. Consider declaring as nullable. - Pole, které neumožňuje hodnotu null, není inicializované. + Není inicializované pole bez možnosti zadání hodnoty null. Zvažte možnost deklarovat ho jako typ s možnou hodnotou null. @@ -5829,12 +5831,12 @@ Blok catch() po bloku catch (System.Exception e) může zachytit výjimky, kter Expected 'disable' or 'restore' - Byla očekávána hodnota disable, restore, enable nebo safeonly. + Očekávala se hodnota disable nebo restore. Expected 'disable' or 'restore' after #pragma warning - Po #pragma warning byla očekávána hodnota disable, restore, enable nebo safeonly. + Po varování #pragma se očekávala hodnota disable nebo restore. diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf index 56f63e642197b..8f11a663082fa 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.de.xlf @@ -37,6 +37,11 @@ Es ist unzulässig, den Nullable-Verweistyp "{0}?" in einem as-Ausdruck zu verwenden. Verwenden Sie stattdessen den zugrunde liegenden Typ "{0}". + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + Das Attribut "{0}" ist für Ereignisaccessoren nicht gültig. Es gilt nur für {1}-Deklarationen. + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. Die automatisch implementierte Eigenschaft "{0}" kann nicht als "readonly" markiert werden, weil sie einen set-Accessor aufweist. @@ -47,11 +52,6 @@ Der automatisch implementierte set-Accessor "{0}" kann nicht als "readonly" markiert werden. - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - Das Attribut "{0}" ist für Ereignisaccessoren nicht gültig. Es gilt nur für {1}-Deklarationen. - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' Eine asynchrone foreach-Anweisung kann nicht für Variablen vom Typ "{0}" verwendet werden, weil "{0}" keine geeignete öffentliche Instanzdefinition für "{1}" enthält. @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + Ungültige Option "{0}" für "/nullable". Zulässig sind nur "disable", "enable", "warnings" oder "annotations". @@ -124,7 +124,7 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + Operator zum Unterdrücken von doppelten NULL-Werten ("!") @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + Erwartet wurde "warnings", "annotations" oder das Ende der Anweisung. @@ -612,156 +612,158 @@ -modulename:<string> Specify the name of the source module - Visual C#-Compileroptionen + Visual C#-Compileroptionen - – AUSGABEDATEIEN – + – AUSGABEDATEIEN – -out:<Datei> Gibt den Namen der Ausgabedatei an (Standardeinstellung: Basisname der - Datei mit der Hauptklasse oder der ersten Datei) --target:exe Erstellt eine ausführbare Konsolendatei (Standardeinstellung) (Kurzform: - -t:exe) --target:winexe Erstellt eine ausführbare Windows-Datei (Kurzform: - -t:winexe) --target:library Erstellt eine Bibliothek (Kurzform: -t:library) + Datei mit der Hauptklasse oder der ersten Datei). +-target:exe Erstellt eine ausführbare Konsolendatei (Standardeinstellung) + (Kurzform: -t:exe). +-target:winexe Erstellt eine ausführbare Windows-Datei + (Kurzform: -t:winexe). +-target:library Erstellt eine Bibliothek (Kurzform: -t:library). -target:module Erstellt ein Modul, das einer anderen Assembly - hinzugefügt werden kann (Kurzform: -t:module) --target:appcontainerexe Erstellt eine ausführbare App-Containerdatei (Kurzform: - -t:appcontainerexe) --target:winmdobj Erstellt eine temporäre Windows-Runtime-Zwischendatei, die - von WinMDExp verwendet wird (Kurzform: -t:winmdobj) --doc:<Datei> Die zu generierende XML-Dokumentationsdatei --refout:<Datei> Die zu generierende Verweisassemblyausgabe + hinzugefügt werden kann (Kurzform: -t:module). +-target:appcontainerexe Erstellt eine ausführbare App-Containerdatei + (Kurzform: -t:appcontainerexe). +-target:winmdobj Erstellt eine Windows-Runtime-Zwischendatei, die + von WinMDExp verwendet wird (Kurzform: -t:winmdobj). +-doc:<Datei> Die zu generierende XML-Dokumentationsdatei. +-refout:<Datei> Die zu generierende Verweisassemblyausgabe. -platform:<Zeichenfolge> Schränkt ein, auf welchen Plattformen dieser Code ausgeführt werden kann: x86, - Itanium, x64, arm, arm64, anycpu32bitpreferred oder - anycpu. Die Standardeinstellung ist "anycpu". + Itanium, x64, arm, arm64, anycpu32bitpreferred oder + anycpu. Die Standardeinstellung ist "anycpu". - – EINGABEDATEIEN – + – EINGABEDATEIEN – -recurse:<Platzhalter> Schließt alle Dateien im aktuellen Verzeichnis und - in Unterverzeichnissen gemäß Platzhalter- - spezifikationen ein. + in Unterverzeichnissen gemäß Platzhalter- + spezifikationen ein. -reference:<Alias>=<Datei> Verweist auf Metadaten aus der angegebenen Assembly- - datei mithilfe eines angegebenen Alias (Kurzform: -r) --reference:<Dateiliste> Verweist auf Metadaten aus angegebenen Assembly- - dateien (Kurzform: -r) + datei mithilfe eines angegebenen Alias (Kurzform: -r). +-reference:<Dateiliste> Verweist auf Metadaten aus den angegebenen Assembly- + dateien (Kurzform: -r). -addmodule:<Dateiliste> Verknüpft die angegebenen Module in dieser Assembly. -link:<Dateiliste> Bettet Metadaten der angegebenen Interop- - assemblydateien ein (Kurzform: -l) --analyzer:<Dateiliste> Führt die Analyse aus dieser Assembly aus. - (Kurzform: -a) + assemblydateien ein (Kurzform: -l). +-analyzer:<Dateiliste> Führt die Analyse aus dieser Assembly aus + (Kurzform: -a). -additionalfile:<Dateiliste> Zusätzliche Dateien, die sich nicht direkt auf die Code- - generierung auswirken, aber von der Analyse zum Generieren von - Fehlern oder Warnungen verwendet werden können. + generierung auswirken, aber von der Analyse zum Generieren von + Fehlern oder Warnungen verwendet werden können. -embed Bettet alle Quelldateien in die PDB-Datei ein. -embed:<Dateiliste> Bettet bestimmte Dateien in die PDB-Datei ein. - – RESSOURCEN – + – RESSOURCEN – -win32res:<Datei> Gibt eine Win32-Ressourcendatei (RES-Datei) an. -win32icon:<Datei> Verwendet dieses Symbol für die Ausgabe. -win32manifest:<Datei> Gibt eine Win32-Manifestdatei (XML-Datei) an. -nowin32manifest Schließt das Win32-Standardmanifest nicht ein. --resource:<resinfo> Bettet die angegebene Ressource ein (Kurzform: -res) +-resource:<resinfo> Bettet die angegebene Ressource ein (Kurzform: -res). -linkresource:<resinfo> Verknüpft die angegebene Ressource mit dieser Assembly - (Kurzform: -linkres). Dabei lautet das resinfo-Format - <Datei>[,<Zeichenfolgenname>[,public|private]] + (Kurzform: -linkres). Dabei lautet das resinfo-Format + <Datei>[,<Zeichenfolgenname>[,public|private]] - – CODEGENERIERUNG – + – CODEGENERIERUNG – -debug[+|-] Gibt Debuginformationen aus. -debug:{full|pdbonly|portable|embedded} - Gibt den Debugtyp an ("full" ist der Standardwert, - "portable" ist ein plattformübergreifendes Format, - "embedded" ist ein plattformübergreifendes Format, das in die - Ziel-DLL oder -EXE eingebettet ist). + Gibt den Debugtyp an ("full" ist der Standardwert, + "portable" ist ein plattformübergreifendes Format, + "embedded" ist ein plattformübergreifendes Format, das in die + Ziel-DLL oder -EXE eingebettet ist). -optimize[+|-] Aktiviert Optimierungen (Kurzform: -o) --deterministic Generiert eine deterministische Assembly - (einschließlich Modulversion-GUID und Zeitstempel) --refonly Erstellt eine Referenzassembly anstelle der Hauptausgabe. --instrument:TestCoverage Generiert eine Assembly, die für die - Erfassung von Code Coverage-Informationen instrumentiert ist. +-deterministic Generiert eine deterministische Assembly + (einschließlich Modulversion-GUID und Zeitstempel). +-refonly Generiert eine Referenzassembly anstelle der Hauptausgabe. +-instrument:TestCoverage Generiert eine Assembly, die für die Erfassung + von Code Coverage-Informationen instrumentiert ist. -sourcelink:<Datei> Quelllinkinformationen zum Einbetten in PDB-Dateien. - – FEHLER UND WARNUNGEN – + – FEHLER UND WARNUNGEN – -warnaserror[+|-] Meldet alle Warnungen als Fehler. -warnaserror[+|-]:<Warnungsliste> Meldet bestimmte Warnungen als Fehler. --warn:<n> Legt die Warnstufe fest (0–4) (Kurzform: -w) +-warn:<n> Legt die Warnstufe fest (0–4) (Kurzform: -w). -nowarn:<Warnungsliste> Deaktiviert bestimmte Warnmeldungen. --ruleset:<Datei> Gibt eine Rulesetdatei an, die bestimmte Diagnosevorgänge - deaktiviert. +-ruleset:<Datei> Gibt eine Regelsatzdatei an, die bestimmte Diagnosevorgänge + deaktiviert. -errorlog:<Datei> Gibt eine Datei zur Protokollierung aller Diagnosevorgänge von Compiler und - Analyzer an. --reportanalyzer Berichtet zusätzliche Analyseinformationen wie etwa die - Ausführungszeit. + Analyzer an. +-reportanalyzer Meldet zusätzliche Analyseinformationen wie etwa die + Ausführungszeit. - – SPRACHE – --checked[+|-] Generiert Überlaufüberprüfungen + – SPRACHE – +-checked[+|-] Generiert Überlaufüberprüfungen. -unsafe[+|-] Lässt "unsicheren" Code zu. -define:<Symbolliste> Definiert bedingte Kompilationssymbole (Kurz- - form: -d) + form: -d). -langversion:? Zeigt die zulässigen Werte für die Sprachversion an. -langversion:<Zeichenfolge> Gibt die Sprachversion an: - "default" (neueste Hauptversion) oder - "latest" (neueste Version, einschließlich Nebenversionen) - oder bestimmte Versionen wie "6" oder "7.1" + "latest" (neueste Version, einschließlich Nebenversionen), + "default" (die gleiche Version wie bei "latest"), + "latestmajor" (neueste Version, außer Nebenversionen), + "preview" (neueste Version, einschließlich Features in der nicht unterstützten Vorschauversion) + oder bestimmte Versionen wie "6" oder "7.1". -nullable[+|-] Legt die Option für Nullwerte zulassenden Kontext fest: enable|disable. --nullable:{enable|disable|warnings} - Legt die Option für Nullwerte zulassenden Kontext fest: enable|disable|warnings. +-nullable:{enable|disable|warnings|annotations} + Legt die Option für Nullwerte zulassenden Kontext fest: enable|disable|warnings|annotations. – SICHERHEIT – -delaysign[+|-] Signiert die Assembly verzögert nur mit dem öffentlichen - Teil des starken Namensschlüssels. + Teil des starken Namensschlüssels. -publicsign[+|-] Signiert die Assembly öffentlich nur mit dem öffentlichen - Teil des starken Namensschlüssels. + Teil des starken Namensschlüssels. -keyfile:<Datei> Gibt eine Datei für den starken Namensschlüssel an. -keycontainer:<Zeichenfolge> Gibt einen Container für den starken Namensschlüssel an. -highentropyva[+|-] Aktiviert ASLR mit hoher Entropie. - – VERSCHIEDENES – - @<Datei> Weitere Optionen finden Sie in der Antwortdatei. --help Zeigt diese Syntaxmeldung an (Kurzform: -?) + – VERSCHIEDENES – +@<Datei> Weitere Optionen finden Sie in der Antwortdatei. +-help Zeigt diese Syntaxmeldung an (Kurzform: -?). -nologo Unterdrückt die Copyrightmeldung des Compilers. -noconfig Schließt die CSC.RSP-Datei nicht automatisch ein. --parallel[+|-] Gleichzeitige Erstellung. +-parallel[+|-] Paralleler Build. -version Zeigt die Compilerversionsnummer und die Beendigung an. - – ERWEITERT – + – ERWEITERT – -baseaddress:<Adresse> Die Basisadresse für die zu erstellende Bibliothek. -checksumalgorithm:<alg> Gibt einen Algorithmus für das Berechnen der Quelldatei- - prüfsumme an, die in der PDB-Datei gespeichert ist. Unterstützte Werte: - SHA1 oder SHA256 (Standard). + prüfsumme an, die in der PDB-Datei gespeichert ist. Unterstützte Werte: + SHA1 oder SHA256 (Standard). -codepage:<n> Gibt die beim Öffnen von Quelldateien zu verwendende - Codepage an. --utf8output Ausgabecompilermeldungen in UTF-8-Codierung + Codepage an. +-utf8output Gibt Compilermeldungen in UTF-8-Codierung aus. -main:<Typ> Gibt den Typ an, der den Einstiegspunkt enthält - (alle anderen möglichen Einstiegspunkte werden ignoriert) (Kurz- - form: -m) + (alle anderen möglichen Einstiegspunkte werden ignoriert) (Kurz- + form: -m). -fullpaths Der Compiler generiert vollqualifizierte Pfade. -filealign:<n> Gibt die Ausrichtung an, die für Ausgabedateiabschnitte - verwendet werden soll. + verwendet werden soll. -pathmap:<K1>=<V1>,<K2>=<V2>,... - Gibt eine Zuordnung für die Quellpfadnamen an, die vom - Compiler ausgegeben werden. + Gibt eine Zuordnung für die Quellpfadnamen an, die vom + Compiler ausgegeben werden. -pdb:<Datei> Gibt den Namen der Debuginformationsdatei an (Standard: - Ausgabe des Dateinamens mit PDB-Erweiterung) --errorendlocation Gibt für jeden Fehler die Zeile und Spalte - des Endpunkts aus. + Ausgabe des Dateinamens mit PDB-Erweiterung). +-errorendlocation Gibt für jeden Fehler die Zeile und Spalte + des Endpunkts aus. -preferreduilang Gibt den Namen der bevorzugten Ausgabesprache an. -nosdkpath Deaktiviert die Suche nach dem SDK-Standardpfad für Standardbibliotheksassemblys. -nostdlib[+|-] Kein Verweis auf die Standardbibliothek (mscorlib.dll). -subsystemversion:<Zeichenfolge> Gibt die Subsystemversion dieser Assembly an. -lib:<Dateiliste> Gibt zusätzliche Verzeichnisse an, in denen nach Verweisen - gesucht werden soll. + gesucht werden soll. -errorreport:<Zeichenfolge> Gibt die Verarbeitung interner Compilerfehler an: - "prompt", "send", "queue" oder "none". Der Standardwert lautet - "queue". + "prompt", "send", "queue" oder "none". Der Standardwert lautet + "queue". -appconfig:<Datei> Gibt eine Anwendungskonfigurationsdatei - mit Assemblybindungseinstellungen an. + mit Assemblybindungseinstellungen an. -moduleassemblyname:<Zeichenfolge> Der Name der Assembly, zu der dieses Modul - gehören wird. + gehören wird. -modulename:<Zeichenfolge> Gibt den Quellmodulnamen an. Visual C# Compiler Options default interface implementation - default interface implementation + Standardschnittstellenimplementierung @@ -886,7 +888,7 @@ <switch expression> - <switch expression> + <switch-Ausdruck> @@ -1411,12 +1413,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + Die Anmerkung für Nullable-Verweistypen darf nur in Code innerhalb eines #nullable-Anmerkungskontexts verwendet werden. The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + Die Anmerkung für Nullable-Verweistypen darf nur in Code innerhalb eines #nullable-Anmerkungskontexts verwendet werden. @@ -1581,7 +1583,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + Die NULL-Zulässigkeit von Verweistypen im Typ des Parameters "{0}" von "{1}" entspricht nicht dem implizit implementierten Member "{2}". @@ -1631,7 +1633,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + Die NULL-Zulässigkeit von Verweistypen im Rückgabetyp von "{0}" entspricht nicht dem implizit implementierten Member "{1}". @@ -1661,7 +1663,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + Die NULL-Zulässigkeit von Verweistypen im Typ "{0}" entspricht nicht dem implizit implementierten Member "{1}". @@ -1671,12 +1673,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + Die NULL-Zulässigkeit von Verweistypen im Typ entspricht nicht dem außer Kraft gesetzten Member. Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + Die NULL-Zulässigkeit von Verweistypen im Typ entspricht nicht dem außer Kraft gesetzten Member. @@ -1801,12 +1803,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - Nicht-Nullable-{0} "{1}" wurde nicht initialisiert. + Das {0} "{1}" lässt keine NULL-Werte zu und ist nicht initialisiert. Deklarieren Sie das {0} ggf. als "Nullable". Non-nullable field is uninitialized. Consider declaring as nullable. - Das Nicht-Nullable-Feld wurde nicht initialisiert. + Das Feld lässt keine NULL-Werte zu und ist nicht initialisiert. Deklarieren Sie das Feld ggf. als "Nullable". @@ -5829,12 +5831,12 @@ Ein catch()-Block nach einem catch (System.Exception e)-Block kann nicht-CLS-Aus Expected 'disable' or 'restore' - "disable", "restore", "enable" oder "safeonly" erwartet + "disable" oder "restore" erwartet. Expected 'disable' or 'restore' after #pragma warning - Nach "#pragma warning" wurde "disable", "restore", "enable" oder "safeonly" erwartet + "disable" oder " restore" erwartet nach #pragma-Warnung diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf index af390a2729979..fa206f9d04464 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.es.xlf @@ -37,6 +37,11 @@ No se puede usar el tipo "{0}?" que acepta valores NULL en una expresión as; use en su lugar el tipo "{0}" subyacente. + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + El atributo "{0}" no es válido en descriptores de acceso de eventos. Solo es válido en declaraciones "{1}". + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. La propiedad implementada automáticamente "{0}" no se puede marcar como "readonly" porque tiene un descriptor de acceso "set". @@ -47,11 +52,6 @@ El descriptor de acceso "set" implementado automáticamente "{0}" no puede marcarse como "readonly". - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - El atributo "{0}" no es válido en descriptores de acceso de eventos. Solo es válido en declaraciones "{1}". - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' Una instrucción foreach asincrónica no puede funcionar en variables de tipo "{0}", porque "{0}" no contiene una definición de instancia pública adecuada para "{1}". @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + Opción no válida "{0}" para /nullable; debe ser "deshabilitar", ·"habilitar"', "advertencias" o "anotaciones" @@ -124,7 +124,7 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + Duplicar el operador de supresión de tipo null ("!") @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + Se esperaban "advertencias", "anotaciones" o el final de la directiva @@ -354,7 +354,7 @@ '{0}': 'readonly' can only be used on accessors if the property or indexer has both a get and a set accessor - "{0}": "readonly" solo se puede usar en los descriptores de acceso si la propiedad o el indizador tienen un descriptor de acceso get y set + "{0}": "readonly" solo se puede usar en los descriptores de acceso si la propiedad o el indexador tienen un descriptor de acceso get y set @@ -615,7 +615,7 @@ Opciones del compilador de Visual C# - ARCHIVOS DE SALIDA - - -out:<archivo> Especifica el nombre del archivo de salida (el valor predeterminado: nombre base del archivo + -out:<file> Especifica el nombre del archivo de salida (el valor predeterminado: nombre base del archivo con la clase principal o el primer archivo) -target:exe Compila un archivo ejecutable de consola (predeterminado) (forma corta: -t:exe) @@ -628,40 +628,40 @@ -t:appcontainerexe) -target:winmdobj Compila un archivo intermedio de Windows Runtime para que consuma WinMDExp (forma corta: -t:winmdobj) - -doc:<archivo> Archivo de documentación XML que se va a generar + -doc:<file> Archivo de documentación XML que se va a generar -refout:<file> Salida de ensamblado de referencia para generar - -platform:<cadena> Limita en qué plataformas se puede ejecutar este código: x86, + -platform:<string> Limita en qué plataformas se puede ejecutar este código: x86, Itanium, x64, arm, anycpu32bitpreferred o anycpu. La predeterminada es anycpu. - ARCHIVOS DE ENTRADA - - -recurse:<comodín> Incluye todos los archivos del directorio actual y los + -recurse:<wildcard> Incluye todos los archivos del directorio actual y los subdirectorios de acuerdo con las especificaciones del comodín - -reference:<alias>=<archivo> Metadatos de referencia del archivo de + -reference:<alias>=<file> Metadatos de referencia del archivo de ensamblado especificado mediante el alias dado (forma corta: -r) - -reference:<lista de archivos> Metadatos de referencia de los archivos de + -reference:<file list> Metadatos de referencia de los archivos de ensamblado especificados (forma corta: -r) - -addmodule:<lista de archivos> Vincula los módulos especificados en este ensamblado - -link:<lista de archivos> Inserta metadatos de los archivos de ensamblado de + -addmodule:<file list> Vincula los módulos especificados en este ensamblado + -link:<file list> Inserta metadatos de los archivos de ensamblado de interoperabilidad especificados (forma corta: -l) - -analyzer:<lista de archivos> Ejecuta los analizadores de este ensamblado + -analyzer:<file list> Ejecuta los analizadores de este ensamblado (forma corta: -a) - -additionalfile:<lista de archivos> Archivos adicionales que no afectan directamente a la generación de código + -additionalfile:<file list> Archivos adicionales que no afectan directamente a la generación de código pero que pueden usar los analizadores para producir errores o advertencias. -embed Inserta todos los archivos de origen en el PDB. - -embed:<lista de archivos> Inserta los archivos especificados en el PDB + -embed:<file list> Inserta los archivos especificados en el PDB - RECURSOS - - -win32res:<archivo> Especifica un archivo de recursos Win32 (.res) - -win32icon:<archivo> Usa este icono para la salida - -win32manifest:<archivo> Especifica un archivo de manifiesto Win32 (.xml) + -win32res:<file> Especifica un archivo de recursos Win32 (.res) + -win32icon:<file> Usa este icono para la salida + -win32manifest:<file> Especifica un archivo de manifiesto Win32 (.xml) -nowin32manifest No incluye el manifiesto Win32 predeterminado - -resource:<info recurso> Insertar el recurso especificado (forma corta: -res) - -linkresource:<info recurso> Vincula el recurso especificado con este ensamblado + -resource:<resinfo> Insertar el recurso especificado (forma corta: -res) + -linkresource:<resinfo> Vincula el recurso especificado con este ensamblado (forma corta: -linkres) Donde el formato de resinfo - es <archivo>[,<nombre de cadena>[,public|private]] + es <file>[,<string name>[,public|private]] - GENERACIÓN DE CÓDIGO - -debug[+|-] Emite información de depuración @@ -676,16 +676,16 @@ -refonly Produce un ensamblado de referencia en lugar de la salida principal -instrument:TestCoverage Produce un ensamblado instrumentado para volver a copiar información de cobertura - -sourcelink:<archivo> Información del vínculo de origen para insertar en el PDB portátil. + -sourcelink:<file> Información del vínculo de origen para insertar en el PDB portátil. - ERRORES Y ADVERTENCIAS - -warnaserror[+|-] Notifica todas las advertencias como errores - -warnaserror[+|-]:<lista de advertencias> Notifica advertencias específicas como errores + -warnaserror[+|-]:<warn list> Notifica advertencias específicas como errores -warn:<n> Establece el nivel de advertencia (0-4) (forma corta: -w) - -nowarn:<lista de advertencias> Deshabilita mensajes de advertencia específicos - -ruleset:<archivo> Especifica un archivo de conjunto de reglas que deshabilite + -nowarn:<warn list> Deshabilita mensajes de advertencia específicos + -ruleset:<file> Especifica un archivo de conjunto de reglas que deshabilite diagnósticos específicos. - -errorlog:<archivo> Especifica un archivo para registrar todos los diagnósticos del compilador y el + -errorlog:<file> Especifica un archivo para registrar todos los diagnósticos del compilador y el analizador. -reportanalyzer Notifica información adicional del analizador, como el tiempo de ejecución. @@ -693,28 +693,31 @@ - LENGUAJE - -checked[+|-] Genera comprobaciones de desbordamiento -unsafe[+|-] Permite código "no seguro" - -define:<lista de símbolos> Define símbolo(s) de compilación condicional (forma + -define:<symbol list> Define símbolo(s) de compilación condicional (forma corta: -d) -langversion:? Muestra los valores permitidos para la versión de lenguaje\ r --langversion:<cadena> Especifica la versión de lenguaje como +-langversion:<string> Especifica la versión de lenguaje como `default` (versión importante más reciente), o `latest` (versión más reciente, incluidas las menos importantes), + `default` (igual que `latest`), + `latestmajor` (versión más reciente, excluidas las versiones menos importantes), + `preview` (versión más reciente, incluidas las características en la versión preliminar no compatible), o versiones específicas como `6` o `7.1` -nullable[+|-] Especifique la opción de contexto anulable en enable|disable. --nullable:{enable|disable|warnings} - Especifique la opción de contexto anulable enable|disable|warnings. +-nullable:{enable|disable|warnings|annotations} + Especifique la opción de contexto anulable enable|disable|warnings|annotations. - SEGURIDAD - -delaysign[+|-] Retrasa la firma del ensamblado usando solo la parte pública de la clave de nombre seguro -publicsign[+|-] Publica la firma del ensamblado usando solo la parte pública de la clave de nombre seguro - -keyfile:<archivo> Especifica un archivo de clave de nombre seguro - -keycontainer:<cadena> Especifica un contenedor de claves de nombres seguros + -keyfile:<file> Especifica un archivo de clave de nombre seguro + -keycontainer:<string> Especifica un contenedor de claves de nombres seguros -highentropyva[+|-] Habilita ASLR de alta entropía - VARIOS - - @<archivo> Lee el archivo de respuesta para ver más opciones + @<file> Lee el archivo de respuesta para ver más opciones -help Muestra este mensaje de uso (forma corta: -?) -nologo Suprime el mensaje de copyright del compilador -noconfig No incluye automáticamente el archivo CSC.RSP @@ -722,14 +725,14 @@ -version Muestra el número de versión del compilador y cierra. - AVANZADO - - -baseaddress:<dirección> Dirección base de la biblioteca que se compilará + -baseaddress:<address> Dirección base de la biblioteca que se compilará -checksumalgorithm:<alg> Especifica el algoritmo para calcular la suma de comprobación del archivo de origen almacenado en PDB. Los valores admitidos son: SHA1 (predeterminado) o SHA256. -codepage:<n> Especifica la página de código que se usará al abrir los archivos de origen -utf8output Mensajes de compilador de salida en codificación UTF-8 - -main:<tipo> Especifica el tipo que contiene el punto de entrada + -main:<type> Especifica el tipo que contiene el punto de entrada (ignora todos los demás puntos de entrada posibles) (Forma corta: -m) -fullpaths El compilador genera rutas de acceso completas @@ -738,30 +741,30 @@ -pathmap:<K1>=<V1>,<K2>=<V2>,... Especifica una asignación para los nombres de rutas de acceso de origen emitidos por el compilador. - -pdb:<archivo> Especifica el nombre de archivo de información de depuración (valor predeterminado: + -pdb:<file> Especifica el nombre de archivo de información de depuración (valor predeterminado: nombre de archivo de salida con la extensión .pdb) -errorendlocation Línea y columna de salida de la ubicación final de cada error -preferreduilang Especifica el nombre del lenguaje de salida preferido. -nosdkpath Deshabilita la búsqueda de la ruta del SDK predeterminada para los ensamblados de biblioteca estándar. -nostdlib[+|-] No hace referencia a la biblioteca estándar (mscorlib.dll) - -subsystemversion:<cadena> Especifica la versión del subsistema de este ensamblado - -lib:<lista de archivos> Especifica directorios adicionales en los que buscar + -subsystemversion:<string> Especifica la versión del subsistema de este ensamblado + -lib:<file list> Especifica directorios adicionales en los que buscar referencias - -errorreport:<cadena> Especifica cómo tratar los errores internos del compilador: + -errorreport:<string> Especifica cómo tratar los errores internos del compilador: avisar, enviar, poner en cola o ninguno. El valor predeterminado es poner en cola. - -appconfig:<archivo> Especifica un archivo de configuración de aplicación + -appconfig:<file> Especifica un archivo de configuración de aplicación que contenga opciones de enlace de ensamblado - -moduleassemblyname:<cadena> Nombre del ensamblado del que esté módulo + -moduleassemblyname:<string> Nombre del ensamblado del que esté módulo formará parte - -modulename:<cadena> Especifica el nombre del módulo de origen + -modulename:<string> Especifica el nombre del módulo de origen Visual C# Compiler Options default interface implementation - default interface implementation + implementación de interfaz predeterminada @@ -886,7 +889,7 @@ <switch expression> - <switch expression> + <expresión switch> @@ -1411,12 +1414,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + La anotación para tipos de referencia que aceptan valores NULL solo debe usarse en el código dentro de un contexto de anotaciones "#nullable". The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + La anotación para tipos de referencia que aceptan valores NULL solo debe usarse en el código dentro de un contexto de anotaciones "#nullable". @@ -1491,22 +1494,22 @@ Argument of type '{0}' cannot be used for parameter '{2}' of type '{1}' in '{3}' due to differences in the nullability of reference types. - El argumento de tipo "{0}" no se puede usar para el parámetro "{2}" de tipo "{1}" en "{3}" debido a las diferencias en la nulabilidad de tipos de referencia. + El argumento de tipo "{0}" no se puede usar para el parámetro "{2}" de tipo "{1}" en "{3}" debido a las diferencias en la nulabilidad de los tipos de referencia. Argument of type '{0}' cannot be used as an output of type '{1}' for parameter '{2}' in '{3}' due to differences in the nullability of reference types. - El argumento de tipo "{0}" no se puede usar como salida de tipo "{1}" para el parámetro "{2}" en "{3}" debido a las diferencias en la nulabilidad de tipos de referencia. + El argumento de tipo "{0}" no se puede usar como salida de tipo "{1}" para el parámetro "{2}" en "{3}" debido a las diferencias en la nulabilidad de los tipos de referencia. Argument cannot be used as an output for parameter due to differences in the nullability of reference types. - El argumento no se puede usar como salida para el parámetro debido a las diferencias en la nulabilidad de tipos de referencia. + El argumento no se puede usar como salida para el parámetro debido a las diferencias en la nulabilidad de los tipos de referencia. Argument cannot be used for parameter due to differences in the nullability of reference types. - El argumento no se puede usar para el parámetro debido a las diferencias en la nulabilidad de tipos de referencia. + El argumento no se puede usar para el parámetro debido a las diferencias en la nulabilidad de los tipos de referencia. @@ -1581,7 +1584,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + La nulabilidad de los tipos de referencia del tipo de parámetro"{0}" de "{1}" no coincide con el miembro "{2}" implementado de forma implícita. @@ -1631,7 +1634,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + La nulabilidad de los tipos de referencia del tipo de valor devuelto de "{0}" no coincide con el miembro "{1}" implementado de forma implícita. @@ -1661,7 +1664,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + La nulabilidad de los tipos de referencia del tipo de "{0}" no coincide con el miembro "{1}" implementado de forma implícita. @@ -1671,12 +1674,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + La nulabilidad de los tipos de referencia del tipo no coincide con el miembro reemplazado. Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + La nulabilidad de los tipos de referencia del tipo no coincide con el miembro reemplazado @@ -1801,12 +1804,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - Se ha anulado la inicialización del {0} "{1}" que no acepta valores NULL. + {0} que acepta valores NULL "{1}" está sin inicializar. Considere la posibilidad de declarar {0} como que acepta valores NULL. Non-nullable field is uninitialized. Consider declaring as nullable. - Se ha anulado la inicialización de un campo que no acepta valores NULL + El campo que acepta valores NULL está sin inicializar. Considere la posibilidad de declararlo como que acepta valores NULL. @@ -5829,12 +5832,12 @@ Un bloque catch() después de un bloque catch (System.Exception e) puede abarcar Expected 'disable' or 'restore' - Se esperaba "disable", "restore", "enable" o "safeonly" + Se esperaba "disable" o "restore" Expected 'disable' or 'restore' after #pragma warning - Se esperaba "disable", "restore", "enable" o "safeonly" después de la advertencia de #pragma + Se esperaba "disable" o "restore" después de la advertencia de #pragma @@ -8083,11 +8086,11 @@ Considere la posibilidad de suprimir la advertencia solo si tiene la seguridad d To embed interop type information for both assemblies, use /link for references to each assembly (set the Embed Interop Types property to True). To remove the warning, you can use /reference instead (set the Embed Interop Types property to False). In this case, a primary interop assembly (PIA) provides interop type information. - Ha añadido una referencia a un ensamblaje con /link (con la propiedad Embed Interop Types establecida como verdadera). Esto instruye al compilador para que inserte información del tipo de interoperabilidad desde ese ensamblaje. Sin embargo, el compilador no puede insertar información del tipo de interoperabilidad desde ese ensamblaje porque hay otro ensamblaje que ha referenciado que hace referencia a ese ensamblaje con /reference (con la propiedad Embed Interop Types establecida como falsa). + Ha añadido una referencia a un ensamblado con /link (con la propiedad Embed Interop Types establecida como verdadera). Esto instruye al compilador para que inserte información del tipo de interoperabilidad desde ese ensamblado. Sin embargo, el compilador no puede insertar información del tipo de interoperabilidad desde ese ensamblado porque hay otro ensamblado que ha referenciado que hace referencia a ese ensamblado con /reference (con la propiedad Embed Interop Types establecida como falsa). -Para insertar información del tipo de interoperabilidad en ambos ensamblajes, use /link para las referencias de ambos ensamblajes (establezca la propiedad Embed Interop Types como verdadera). +Para insertar información del tipo de interoperabilidad en ambos ensamblados, use /link para las referencias de ambos ensamblados (establezca la propiedad Embed Interop Types como verdadera). -Para eliminar la advertencia puede usar /reference (establezca la propiedad Embed Interop Types como falsa). En este caso, un ensamblaje de interoperabilidad primario (PIA) provee información del tipo de interoperabilidad. +Para eliminar la advertencia puede usar /reference (establezca la propiedad Embed Interop Types como falsa). En este caso, un ensamblado de interoperabilidad primario (PIA) provee información del tipo de interoperabilidad. diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf index 89848fd809552..d138b239411b0 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.fr.xlf @@ -37,6 +37,11 @@ Il n'est pas correct d'utiliser le type de référence Nullable '{0}?' dans une expression as. Utilisez le type sous-jacent '{0}' à la place. + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + L'attribut '{0}' est non valide sur les accesseurs d'événement. Il est valide uniquement sur les déclarations '{1}'. + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. La propriété implémentée automatiquement '{0}' ne peut pas être marquée 'readonly', car elle a un accesseur 'set'. @@ -47,11 +52,6 @@ L'accesseur 'set' '{0}' implémenté automatiquement ne peut pas être marqué 'readonly'. - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - L'attribut '{0}' est non valide sur les accesseurs d'événement. Il est valide uniquement sur les déclarations '{1}'. - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' L'instruction foreach asynchrone ne peut pas fonctionner sur des variables de type '{0}', car '{0}' ne contient aucune définition d'instance publique appropriée pour '{1}' @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + Option '{0}' non valide pour /nullable ; utilisez 'disable', 'enable', 'warnings' ou 'annotations' @@ -124,7 +124,7 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + Opérateur de suppression de valeur null dupliqué ('!') @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + 'warnings', 'annotations' ou fin de directive attendu @@ -638,20 +638,20 @@ -recurse:<générique> Inclure tous les fichiers dans le répertoire et les sous-répertoires actifs en fonction des spécifications de caractères génériques --reference:<alias>=<fichier> Référencer les métadonnées à partir du - fichier d'assembly spécifié à l'aide de l'alias indiqué (forme abrégée : -r) --reference:<liste_fichiers> Référencer les métadonnées à partir +-reference:<alias>=<fichier> Référencer les métadonnées à partir du + fichier d'assembly spécifié via l'alias indiqué (forme abrégée : -r) +-reference:<liste_fichiers> Référencer les métadonnées à partir des fichiers d'assembly spécifiés (forme abrégée : -r) --addmodule:<liste_fichiers> Lier les modules spécifiés dans cet assembly --link:<liste_fichiers> Incorporer les métadonnées à partir des +-addmodule:<liste_fichiers> Lier les modules spécifiés dans cet assembly +-link:<liste_fichiers> Incorporer les métadonnées à partir des fichiers d'assembly d'interopérabilité spécifiés (forme abrégée : -l) --analyzer:<liste_fichiers> Exécuter les analyseurs à partir de cet assembly +-analyzer:<liste_fichiers> Exécuter les analyseurs à partir de cet assembly (Forme abrégée : -a) --additionalfile:<liste_fichiers> Fichiers supplémentaires qui n'affectent pas directement +-additionalfile:<liste_fich.> Fichiers supplémentaires qui n'affectent pas directement la génération de code mais qui peuvent être utilisés par les analyseurs pour produire des erreurs ou des avertissements. -embed Incorporer tous les fichiers sources dans le fichier PDB. --embed:<liste_fichiers> Incorporer des fichiers spécifiques dans le fichier PDB. +-embed:<liste_fichiers> Incorporer des fichiers spécifiques dans le fichier PDB. - RESSOURCES - -win32res:<fichier> Spécifier un fichier de ressources Win32 (.res) @@ -687,7 +687,7 @@ diagnostics spécifiques. -errorlog:<fichier> Spécifier un fichier pour journaliser tous les diagnostics du compilateur et de l'analyseur. --reportanalyzer Signaler des informations supplémentaires sur l'analyseur, comme +-reportanalyzer Signaler des informations supplémentaires sur l'analyseur, par exemple la durée d'exécution. - LANGAGE - @@ -697,12 +697,14 @@ abrégée : -d) -langversion:? Afficher les valeurs autorisées pour la version du langage -langversion:<chaîne> Spécifier la version du langage, par exemple - 'default' (dernière version principale) ou 'latest' (dernière version, en incluant les versions mineures), + 'default' (identique à 'latest'), + 'latestmajor' (dernière version, en excluant les versions mineures), + 'preview' (dernière version, en incluant les fonctionnalités de la préversion non prise en charge), ou des versions spécifiques comme '6' ou '7.1' -nullable[+|-] Spécifiez l'option de contexte Nullable enable|disable. --nullable:{enable|disable|warnings} - Spécifiez l'option de contexte Nullable enable|disable|warnings. +-nullable:{enable|disable|warnings|annotations} + Spécifiez l'option de contexte Nullable enable|disable|warnings|annotations. - SÉCURITÉ - -delaysign[+|-] Différer la signature de l'assembly en utilisant uniquement @@ -732,7 +734,7 @@ -main:<type> Spécifier le type qui contient le point d'entrée (ignorer tous les autres points d'entrée possibles) (forme abrégée : -m) --fullpaths Le compilateur génère des chemins qualifiés complets +-fullpaths Le compilateur génère des chemins complets -filealign:<n> Spécifier l'alignement utilisé pour les sections du fichier de sortie -pathmap:<K1>=<V1>,<K2>=<V2>,... @@ -761,7 +763,7 @@ default interface implementation - default interface implementation + implémentation d'interface par défaut @@ -886,7 +888,7 @@ <switch expression> - <switch expression> + <expression switch> @@ -1411,12 +1413,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + L'annotation pour les types référence Nullable doit être utilisée uniquement dans le code au sein d'un contexte d'annotations '#nullable'. The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + L'annotation pour les types référence Nullable doit être utilisée uniquement dans le code au sein d'un contexte d'annotations '#nullable'. @@ -1581,7 +1583,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + La nullabilité des types référence dans le type de paramètre '{0}' de '{1}' ne correspond pas au membre implémenté implicitement '{2}'. @@ -1631,7 +1633,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + La nullabilité des types référence dans le type de retour de '{0}' ne correspond pas au membre implémenté implicitement '{1}'. @@ -1661,7 +1663,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + La nullabilité des types référence dans le type de '{0}' ne correspond pas au membre implémenté implicitement '{1}'. @@ -1671,12 +1673,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + La nullabilité des types référence dans le type ne correspond pas au membre substitué. Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + La nullabilité des types référence dans le type ne correspond pas au membre substitué. @@ -1801,12 +1803,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - Le {0} '{1}' non Nullable n'est pas initialisé. + Initialisation annulée du {0} '{1}' non Nullable. Déclarez {0} comme étant Nullable. Non-nullable field is uninitialized. Consider declaring as nullable. - Le champ non Nullable n'est pas initialisé. + Le champ non Nullable n'est pas initialisé. Déclarez-le comme étant Nullable. @@ -5829,12 +5831,12 @@ Un bloc catch() après un bloc catch (System.Exception e) peut intercepter des e Expected 'disable' or 'restore' - Disable, restore, enable ou safeonly attendu + 'disable' ou 'restore' attendu Expected 'disable' or 'restore' after #pragma warning - Disable, restore, enable ou safeonly attendu après un avertissement #pragma + 'disable' ou 'restore' attendu après l'avertissement #pragma diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf index b3af4f625071b..2c715c13ca235 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.it.xlf @@ -37,6 +37,11 @@ Non è consentito usare il tipo riferimento nullable '{0}?' in un'espressione as. Usare il tipo sottostante '{0}'. + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + L'attributo '{0}' non è valido nelle funzioni di accesso a eventi. È valido solo nelle dichiarazioni di '{1}'. + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. La proprietà implementata automaticamente '{0}' non può essere contrassegnata come 'readonly' perché include una funzione di accesso 'set'. @@ -47,11 +52,6 @@ La funzione di accesso 'set' '{0}' implementata automaticamente non può essere contrassegnata come 'readonly'. - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - L'attributo '{0}' non è valido nelle funzioni di accesso a eventi. È valido solo nelle dichiarazioni di '{1}'. - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' L'istruzione foreach asincrona non può funzionare con variabili di tipo '{0}' perché '{0}' non contiene una definizione di istanza pubblica idonea per '{1}' @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + L'opzione '{0}' non è valida per /nullable. Deve essere 'disable', 'enable', 'warnings' o 'annotations' @@ -124,7 +124,7 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + Operatore di eliminazione Null duplicato ('!') @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + È previsto 'warnings', 'annotations' o la fine della direttiva @@ -630,38 +630,38 @@ usato da WinMDExp. Forma breve: -t:winmdobj -doc:<file> File di documentazione XML da generare -refout:<file> Output dell'assembly di riferimento da generare --platform:<stringa> Limita le piattaforme in cui è possibile eseguire il codice: x86, +-platform:<string> Limita le piattaforme in cui è possibile eseguire il codice: x86, Itanium, x64, arm, arm64, anycpu32bitpreferred o anycpu. Il valore predefinito è anycpu. - FILE DI INPUT - --recurse:<caratteri_jolly> Include tutti i file presenti nella directory corrente e +-recurse:<wildcard> Include tutti i file presenti nella directory corrente e nelle relative sottodirectory in base ai caratteri jolly specificati -reference:<alias>=<file> Crea un riferimento ai metadati dal file di assembly specificato usando l'alias indicato. Forma breve: -r --reference:<elenco file> Crea un riferimento ai metadati dai file di assembly +-reference:<file list> Crea un riferimento ai metadati dai file di assembly specificati. Forma breve: -r --addmodule:<elenco file> Collega i moduli specificati in questo assembly --link:<elenco file> Incorpora metadati dai file di assembly di +-addmodule:<file list> Collega i moduli specificati in questo assembly +-link:<file list> Incorpora metadati dai file di assembly di interoperabilità specificati. Forma breve: -l --analyzer:<elenco file> Esegue gli analizzatori dall'assembly. +-analyzer:<file list> Esegue gli analizzatori dall'assembly. Forma breve: -a --additionalfile:<elenco file> File aggiuntivi che non influiscono +-additionalfile:<file list> File aggiuntivi che non influiscono direttamente sulla generazione del codice ma possono essere usati dagli analizzatori per produrre errori o avvisi. -embed Incorpora tutti i file di origine nel file PDB. --embed:<elenco file> Incorpora file specifici nel file PDB. +-embed:<file list> Incorpora file specifici nel file PDB. - RISORSE - -win32res:<file> Consente di specificare un file di risorse Win32 (.res) -win32icon:<file> Usa questa icona per l'output -win32manifest:<file> Consente di specificare un file manifesto Win32 (.xml) -nowin32manifest Non include il manifesto Win32 predefinito --resource:<info_risorsa> Incorpora la risorsa specificata. Forma breve: -res --linkresource:<info_risorsa> Collega la risorsa specificata all'assembly. +-resource:<resinfo> Incorpora la risorsa specificata. Forma breve: -res +-linkresource:<resinfo> Collega la risorsa specificata all'assembly. Forma breve: -linkres. Il formato di info_risorsa - è <file>[,<nome stringa>[,public|private]] + è <file>[,<string name>[,public|private]] - GENERAZIONE DEL CODICE - -debug[+|-] Crea le informazioni di debug @@ -680,9 +680,9 @@ - ERRORI E AVVISI - -warnaserror[+|-] Segnala tutti gli avvisi come errori --warnaserror[+|-]:<elenco avvisi> Segnala determinati avvisi come errori +-warnaserror[+|-]:<warn list> Segnala determinati avvisi come errori -warn:<n> Imposta il livello di avviso (0-4). Forma breve: -w --nowarn:<elenco avvisi> Disabilita messaggi di avviso specifici +-nowarn:<warn list> Disabilita messaggi di avviso specifici -ruleset:<file> Consente di specificare un file di set di regole che disabilita diagnostica specifica. -errorlog:<file> Consente di specificare un file in cui registrare tutte le diagnostiche del @@ -693,16 +693,18 @@ - LINGUAGGIO - -checked[+|-] Genera controlli dell'overflow -unsafe[+|-] Consente codice 'unsafe' --define:<elenco simboli> Consente di definire simboli di compilazione condizionale. Forma +-define:<symbol list> Consente di definire simboli di compilazione condizionale. Forma breve: -d -langversion:? Visualizza i valori consentiti per la versione del linguaggio --langversion:<stringa> Consente di specificare la versione del linguaggio, ad esempio - `default` (ultima versione principale), o +-langversion:<string> Consente di specificare la versione del linguaggio, ad esempio `latest` (ultima versione che include versioni secondarie), - oppure versioni specifiche, come `6` o `7.1` + `default` (uguale a `latest`), + `latestmajor` (ultima versione, escluse le versioni secondarie), + `preview` (ultima versione, incluse le funzionalità nell'anteprima non supportata), + o versioni specifiche come `6` o `7.1` -nullable[+|-] Consente di specificare l'opzione di contesto nullable enable|disable. --nullable:{enable|disable|warnings} - Consente di specificare l'opzione di contesto nullable enable|disable|warnings. +-nullable:{enable|disable|warnings|annotations} + Consente di specificare l'opzione di contesto nullable enable|disable|warnings|annotations. - SICUREZZA - -delaysign[+|-] Ritarda la firma dell'assembly usando solo la parte pubblica della @@ -710,7 +712,7 @@ -publicsign[+|-] Firma pubblicamente l'assembly usando solo la parte pubblica della chiave con nome sicuro -keyfile:<file> Consente di specificare un file di chiave con nome sicuro --keycontainer:<stringa> Consente di specificare un contenitore di chiavi con nome sicuro +-keycontainer:<string> Consente di specificare un contenitore di chiavi con nome sicuro -highentropyva[+|-] Abilita ASLR a entropia elevata - VARIE - @@ -723,13 +725,13 @@ - AVANZATE - -baseaddress:<indirizzo> Indirizzo di base della libreria da compilare --checksumalgorithm:<alg> Consente di specificare l'algoritmo per calcolare il checksum +-checksumalgorithm:<alg> Consente di specificare l'algoritmo per calcolare il checksum del file di origine archiviato nel file PDB. I valori supportati sono: - SHA1 o SHA256 (impostazione predefinita). + SHA1 o SHA256 (predefinito). -codepage:<n> Consente di specificare la tabella codici da usare all'apertura dei file di origine -utf8output Restituisce i messaggi del compilatore usando la codifica UTF-8 --main:<tipo> Consente di specificare il tipo che contiene il punto di ingresso, +-main:<type> Consente di specificare il tipo che contiene il punto di ingresso, ignorando tutti gli altri punti di ingresso possibili. Forma breve: -m -fullpaths Il compilatore genera percorsi completi @@ -745,23 +747,23 @@ -preferreduilang Consente di specificare il nome del linguaggio di output preferito. -nosdkpath Disabilita la ricerca di assembly di librerie standard nel percorso predefinito dell'SDK. -nostdlib[+|-] Omette i riferimenti alla libreria standard (mscorlib.dll) --subsystemversion:<stringa> Consente di specificare la versione del sottosistema di questo assembly --lib:<elenco file> Consente di specificare le directory aggiuntive in cui cercare i +-subsystemversion:<string> Consente di specificare la versione del sottosistema di questo assembly +-lib:<file list> Consente di specificare le directory aggiuntive in cui cercare i riferimenti --errorreport:<stringa> Consente di specificare la modalità di gestione degli errori interni del compilatore: +-errorreport:<string> Consente di specificare la modalità di gestione degli errori interni del compilatore: prompt, send, queue o none. L'impostazione predefinita è queue. -appconfig:<file> Consente di specificare un file di configurazione dell'applicazione contenente le impostazioni di binding dell'assembly --moduleassemblyname:<stringa> Nome dell'assembly di cui farà parte +-moduleassemblyname:<string> Nome dell'assembly di cui farà parte questo modulo --modulename:<stringa> Consente di specificare il nome del modulo di origine +-modulename:<string> Consente di specificare il nome del modulo di origine Visual C# Compiler Options default interface implementation - default interface implementation + implementazione di interfaccia predefinita @@ -886,7 +888,7 @@ <switch expression> - <switch expression> + <espressione switch> @@ -1411,12 +1413,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + L'annotazione per i tipi riferimento nullable deve essere usata solo nel codice in un contesto di annotations '#nullable'. The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + L'annotazione per i tipi riferimento nullable deve essere usata solo nel codice in un contesto di annotations '#nullable'. @@ -1581,7 +1583,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + Il supporto dei valori Null dei tipi riferimento nel tipo di parametro '{0}' di '{1}' non corrisponde al membro implementato in modo implicito '{2}'. @@ -1631,7 +1633,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + Il supporto dei valori Null dei tipi riferimento nel tipo restituito di '{0}' non corrisponde al membro implementato in modo implicito '{1}'. @@ -1661,7 +1663,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + Il supporto dei valori Null dei tipi riferimento nel tipo di '{0}' non corrisponde al membro implementato in modo implicito '{1}'. @@ -1671,12 +1673,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + Il supporto dei valori Null dei tipi riferimento nel tipo non corrisponde al membro di cui è stato eseguito l'override. Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + Il supporto dei valori Null dei tipi riferimento nel tipo non corrisponde al membro di cui è stato eseguito l'override. @@ -1801,12 +1803,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - L'elemento {0} non nullable '{1}' non è inizializzato. + L'elemento {0} '{1}' non nullable non è inizializzato. Provare a dichiarare {0} come nullable. Non-nullable field is uninitialized. Consider declaring as nullable. - Il campo non nullable non è inizializzato. + Il campo non nullable non è inizializzato. Provare a dichiararlo come nullable. @@ -5829,12 +5831,12 @@ Un blocco catch() dopo un blocco catch (System.Exception e) è in grado di rilev Expected 'disable' or 'restore' - È previsto disable, restore, enable o safeonly + È previsto 'disable' o 'restore' Expected 'disable' or 'restore' after #pragma warning - Dopo l'avviso della direttiva #pragma è previsto disable, restore, enable o safeonly + Dopo l'avviso della direttiva #pragma è previsto 'disable' o 'restore' diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.ja.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.ja.xlf index 3f8ca3759cae7..70f000a4b9700 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.ja.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.ja.xlf @@ -37,6 +37,11 @@ as 式で Null 許容参照型 '{0}?' を使用することはできません。代わりに基になる型 '{0}' をご使用ください。 + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + 属性 '{0}' はイベント アクセサーでは無効です。'{1}' 宣言でのみ有効です。 + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. 'set' アクセサーがあるため、自動実装プロパティ '{0}' を 'readonly' とマークすることはできません。 @@ -47,11 +52,6 @@ 自動実装の 'set' アクセサー '{0}' を 'readonly' とマークすることはできません。 - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - 属性 '{0}' はイベント アクセサーでは無効です。'{1}' 宣言でのみ有効です。 - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' '{0}' は '{1}' の適切なパブリック インスタンス定義を含んでいないため、型 '{0}' の変数に対して非同期 foreach ステートメントを使用することはできません @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + /nullable のオプション '{0}' が無効です。'disable'、'enable'、'warnings'、'annotations' のいずれかにする必要があります @@ -124,7 +124,7 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + Null 抑制演算子 ('!') が重複しています @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + 'warnings'、'annotations'、またはディレクティブの終わりが必要です @@ -615,35 +615,35 @@ Visual C# コンパイラのオプション - 出力ファイル - - -out:<file> 出力ファイル名を指定します (既定: メイン クラスを含むファイル +-out:<file> 出力ファイル名を指定します (既定: メイン クラスを含むファイル または最初のファイルのベース名) - -target:exe コンソール実行可能ファイルをビルドします (既定) (短い +-target:exe コンソール実行可能ファイルをビルドします (既定) (短い 形式: -t:exe) - -target:winexe Windows 実行可能ファイルをビルドします (短い形式: +-target:winexe Windows 実行可能ファイルをビルドします (短い形式: -t:winexe) -target:library ライブラリをビルドします (短い形式: -t:library) -target:module 別のアセンブリに追加できるモジュールを - ビルドします (短い形式: -t:module) + ビルドします (短い形式: -t:module) -target:appcontainerexe Appcontainer 実行可能ファイルをビルドします (短い形式: -t:appcontainerexe) -target:winmdobj WinMDExp で使用される - Windows ランタイムの中間ファイルをビルドします (短い形式: -t:winmdobj) + Windows ランタイムの中間ファイルをビルドします (短い形式: -t:winmdobj) -doc:<file> 生成する XML ドキュメント ファイル --refout:<file> 生成する参照アセンブリの出力 --platform:<string> このコードを実行できるプラットフォームを - Itx86、Itanium、x64、arm、arm64、anycpu32bitpreferred、 +-refout:<file> 生成する参照アセンブリの出力 +-platform:<string> このコードを実行できるプラットフォームを x86、 + Itanium、x64、arm、arm64、anycpu32bitpreferred、 anycpu に限定します。既定は anycpu です。 - 入力ファイル - -recurse:<wildcard> ワイルドカードの指定に従い、現行ディレクトリおよび サブディレクトリ内のすべてのファイルを - インクルードします + インクルードします -reference:<alias>=<file> 指定されたエイリアスを使用して、指定された アセンブリ ファイルのメタデータを参照します (短い形式: -r) - -reference:<file list> 指定されたアセンブリ ファイルのメタデータを +-reference:<file list> 指定されたアセンブリ ファイルのメタデータを 参照します (短い形式: -r) - -addmodule:<file list> 指定されたモジュールをこのアセンブリにリンクします - -link:<file list> 指定された相互運用アセンブリ ファイルの +-addmodule:<file list> 指定されたモジュールをこのアセンブリにリンクします +-link:<file list> 指定された相互運用アセンブリ ファイルの メタデータを埋め込みます (短い形式: -l) -analyzer:<file list> このアセンブリからアナライザーを実行します (短い形式: -a) @@ -652,7 +652,7 @@ 生成するときに使用する可能性のある追加ファイル。 -embed すべてのソース ファイルを PDB に埋め込みます。 -embed:<file list> 特定のファイルを PDB に埋め込みます。 - + - リソース - -win32res:<file> Win32 リソース ファイル (.res) を指定します -win32icon:<file> 出力にこのアイコンを使用します @@ -684,36 +684,38 @@ -warn:<n> 警告レベル (0-4) を設定します (短い形式: -w) -nowarn:<warn list> 特定の警告メッセージを無効にします -ruleset:<file> 特定の診断を無効にするルールセット ファイルを - 指定します。 + 指定します。 -errorlog:<file> すべてのコンパイラとアナライザーの診断をログに記録するための - ファイルを指定します。 + ファイルを指定します。 -reportanalyzer 追加のアナライザー情報を報告します - (実行時間など)。 - - - 言語 - + (実行時間など)。 + + - 言語 - -checked[+|-] オーバーフロー検査を生成します -unsafe[+|-] '安全でない' コードを許可します --define:<symbol list> 条件付きコンパイル シンボルを定義します (短い - 形式: -d) +-define:<symbol list> 条件付きコンパイル シンボルを定義します (短い + 形式: -d) -langversion:? 許容される言語バージョンの値を表示します。 --langversion:<string> `default` (最新のメジャー バージョン)、 - `latest` (マイナー バージョンを含む最新バージョン)、 - `6` や `7.1` などの特定のバージョンなど、 +-langversion:<string> `latest` (マイナー バージョンを含む最新バージョン)、 + `default` (`latest` と同様)、 + `latestmajor` (マイナー バージョンを除く最新バージョン)、 + `preview` (サポートされないプレビューの機能を含む、最新バージョン)、 + または `6` や `7.1` などの特定のバージョンなど、 言語バージョンを指定します -nullable[+|-] Null 許容コンテキスト オプションの enable|disable を指定します。 --nullable:{enable|disable|warnings} - Null 許容コンテキストオプションの enable|disable|warnings を指定します。 +-nullable:{enable|disable|warnings|annotations} + Null 許容コンテキスト オプションの enable|disable|warnings|annotations を指定します。 - - セキュリティ - + - セキュリティ - -delaysign[+|-] 厳密な名前キーのパブリックな部分のみを使って - アセンブリを遅延署名します + アセンブリを遅延署名します -publicsign[+|-] 厳密な名前キーのパブリックな部分のみを使って - アセンブリを公開署名します + アセンブリを公開署名します -keyfile:<file> 厳密な名前キーのファイルを指定します -keycontainer:<string> 厳密な名前キーのコンテナーを指定します -highentropyva[+|-] 高エントロピ ASLR を有効にします - - その他 - + - その他 - @<file> 応答ファイルを読み取り、オプションを追加します -help この使用法に関するメッセージを表示します (短い形式: -?) -nologo コンパイラの著作権メッセージを表示しません @@ -721,47 +723,47 @@ -parallel[+|-] ビルドを並列処理します。 -version コンパイラ バージョンの数字を表示して終了します。 - - 高度なオプション - + - 高度なオプション - -baseaddress:<address> ビルドするライブラリのベース アドレスです --checksumalgorithm:<alg> PDB に格納されているソース ファイルのチェックサム - を計算するアルゴリズムを指定します。サポートされる値: - SHA1 または SHA256 (既定)。 +-checksumalgorithm:<alg> PDB に格納されているソース ファイルのチェックサム + を計算するアルゴリズムを指定します。サポートされる値: + SHA1 または SHA256 (既定)。 -codepage:<n> ソース ファイルを開くときに使用するコード ページを - 指定します + 指定します -utf8output コンパイラ メッセージを UTF-8 エンコードで出力します -main:<type> エントリ ポイントを含む型を指定します - (他のエントリ ポイントはすべて無視します) (短い - 形式: -m) + (他のエントリ ポイントはすべて無視します) (短い + 形式: -m) -fullpaths コンパイラは完全修飾パスを生成します -filealign:<n> 出力ファイル セクションで使用する配置を - 指定します + 指定します -pathmap:<K1>=<V1>,<K2>=<V2>,... - コンパイラが出力するソース パス名のマッピングを - 指定します。 --pdb:<file> デバッグ情報ファイル名を指定します (既定: - .pdb 拡張子の付いた出力ファイル名) + コンパイラが出力するソース パス名のマッピングを + 指定します。 +-pdb:<file> デバッグ情報ファイル名を指定します (既定: + .pdb 拡張子の付いた出力ファイル名) -errorendlocation 各エラーの終了位置の出力行と - 出力列 + 出力列 -preferreduilang 出力用の言語名を指定します。 -nosdkpath 標準ライブラリ アセンブリの既定の SDK パスの検索を無効にします。 -nostdlib[+|-] 標準ライブラリ (mscorlib.dll) は参照しません -subsystemversion:<string> このアセンブリのサブシステム バージョンを指定します -lib:<file list> 参照を検索する追加ディレクトリを - 指定します --errorreport:<string> 内部コンパイラ エラーの処理方法 - (prompt、send、queue、none) を指定します。既定値は - queue です。 + 指定します +-errorreport:<string> 内部コンパイラ エラーの処理方法: + (prompt、send、queue、none) を指定します。既定値は + queue です。 -appconfig:<file> アセンブリ バインド設定を含む - アプリケーション構成ファイルを指定します --moduleassemblyname:<string> このモジュールが一部となる - アセンブリ名です + アプリケーション構成ファイルを指定します +-moduleassemblyname:<string> このモジュールが含められる + アセンブリの名前 -modulename:<string> ソース モジュールの名前を指定します Visual C# Compiler Options default interface implementation - default interface implementation + 既定のインターフェイスの実装 @@ -886,7 +888,7 @@ <switch expression> - <switch expression> + <switch 式> @@ -1411,12 +1413,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + '#nullable' 注釈コンテキスト内のコードでのみ、Null 許容参照型の注釈を使用する必要があります。 The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + '#nullable' 注釈コンテキスト内のコードでのみ、Null 許容参照型の注釈を使用する必要があります。 @@ -1581,7 +1583,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + '{1}' のパラメーター '{0}' の型における参照型の Null 許容性が、暗黙的に実装されるメンバー '{2}' と一致しません。 @@ -1631,7 +1633,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + '{0}' の戻り値の型における参照型の Null 許容性が、暗黙的に実装されるメンバー '{1}' と一致しません。 @@ -1661,7 +1663,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + '{0}' の型における参照型の Null 許容性が、暗黙的に実装されるメンバー '{1}' と一致しません。 @@ -1671,12 +1673,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + 型における参照型の Null 許容性が、オーバーライドされるメンバーと一致しません。 Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + 型における参照型の Null 許容性が、オーバーライドされるメンバーと一致しません。 @@ -1801,12 +1803,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - Null 非許容 {0} '{1}' が初期化されていません。 + Null 非許容の {0} '{1}' が初期化されていません。{0} を null 許容として宣言することを検討してください。 Non-nullable field is uninitialized. Consider declaring as nullable. - Null 非許容フィールドが初期化されていません。 + Null 非許容フィールドは初期化されていません。null 許容として宣言することを検討してください。 @@ -5829,12 +5831,12 @@ AssemblyInfo.cs ファイルで RuntimeCompatibilityAttribute が false に設 Expected 'disable' or 'restore' - disable、restore、enable、または safeonly が必要です + 'disable' または 'restore' を指定してください Expected 'disable' or 'restore' after #pragma warning - #pragma 警告の後に disable、restore、enable、または safeonly が必要です + #pragma 警告の後に、'disable' または 'restore' が必要です diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.ko.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.ko.xlf index 1c3dc9a156a4f..388a9091d38ed 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.ko.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.ko.xlf @@ -37,6 +37,11 @@ 식에 nullable 참조 형식 '{0}'을(를) 사용하는 것은 올바르지 않습니다. 대신 기본 형식 '{0}'을(를) 사용하세요. + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + 이벤트 접근자에서 '{0}' 특성이 유효하지 않습니다. 이 특성은 '{1}' 선언에만 유효합니다. + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. 'set' 접근자가 포함되어 있으므로 자동 구현 속성 '{0}'을(를) 'readonly'로 표시할 수 없습니다. @@ -47,11 +52,6 @@ 자동 구현 'set' 접근자 '{0}'을(를) 'readonly'로 표시할 수 없습니다. - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - 이벤트 접근자에서 '{0}' 특성이 유효하지 않습니다. 이 특성은 '{1}' 선언에만 유효합니다. - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' '{0}' 형식 변수에서 비동기 foreach 문을 수행할 수 없습니다. '{0}'에는 '{1}'의 적합한 공용 인스턴스 정의가 없기 때문입니다. @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + /nullable의 '{0}' 옵션이 잘못되었습니다. 'disable', 'enable', 'warnings' 또는 'annotations'여야 합니다. @@ -124,7 +124,7 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + 중복 null 비표시 오류(Suppression) 연산자('!') @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + 'warnings', 'annotations' 또는 지시문의 끝이 필요합니다. @@ -329,7 +329,7 @@ Both partial method declarations must be readonly or neither may be readonly - 두 부분 메서드(Partial Method) 선언 모두 readonly이거나 readonly가 아니어야 합니다. + 두 부분 메서드(Partial method) 선언 모두 readonly이거나 readonly가 아니어야 합니다. @@ -615,53 +615,53 @@ Visual C# 컴파일러 옵션 - 출력 파일 - --out:<파일> 출력 파일 이름을 지정합니다(기본값: 주 클래스가 +-out:<file> 출력 파일 이름을 지정합니다(기본값: 주 클래스가 있는 파일 또는 첫째 파일의 기본 이름). -target:exe 콘솔 실행 파일을 빌드합니다(기본값). (약식: -t:exe) --target:winexe Windows 실행 파일을 빌드합니다. +-target:winexe Windows 실행 파일을 빌드합니다. (약식: -t:winexe) -target:library 라이브러리를 빌드합니다. (약식: -t:library) -target:module 다른 어셈블리에 추가될 수 있는 모듈을 빌드합니다. (약식: -t:module) --target:appcontainerexe Appcontainer 실행 파일을 빌드합니다. +-target:appcontainerexe Appcontainer 실행 파일을 빌드합니다. (약식: -t:appcontainerexe) -target:winmdobj WinMDExp에서 사용되는 Windows 런타임 중간 파일을 빌드합니다. (약식: -t:winmdobj) --doc:<파일> 생성할 XML 문서 파일입니다. --refout:<파일> 생성할 참조 어셈블리 출력입니다. --platform:<문자열> 이 코드를 실행할 수 있는 플랫폼을 x86, +-doc:<file> 생성할 XML 문서 파일입니다. +-refout:<file> 생성할 참조 어셈블리 출력입니다. +-platform:<string> 이 코드를 실행할 수 있는 플랫폼을 x86, Itanium, x64, arm, arm64, anycpu32bitpreferred 또는 anycpu로 제한합니다. 기본값은 anycpu입니다. - 입력 파일 - --recurse:<와일드카드> 와일드카드 지정에 따라 현재 디렉터리와 +-recurse:<wildcard> 와일드카드 지정에 따라 현재 디렉터리와 하위 디렉터리에 있는 모든 파일을 포함합니다. --reference:<별칭>=<파일> 지정한 어셈블리 파일에서 해당 별칭을 사용하여 +-reference:<alias>=<file> 지정한 어셈블리 파일에서 해당 별칭을 사용하여 메타데이터를 참조합니다. (약식: -r) --reference:<파일 목록> 지정한 어셈블리 파일에서 메타데이터를 +-reference:<file list> 지정한 어셈블리 파일에서 메타데이터를 참조합니다. (약식: -r) --addmodule:<파일 목록> 지정한 모듈을 이 어셈블리에 링크합니다. --link:<파일 목록> 지정된 interop 어셈블리 파일의 메타데이터를 +-addmodule:<file list> 지정한 모듈을 이 어셈블리에 링크합니다. +-link:<file list> 지정된 interop 어셈블리 파일의 메타데이터를 포함합니다. (약식: -l) --analyzer:<파일 목록> 이 어셈블리에서 분석기를 실행합니다. +-analyzer:<file list> 이 어셈블리에서 분석기를 실행합니다. (약식: -a) --additionalfile:<파일 목록> 코드 생성에 직접 영향을 주지 않지만 오류 또는 +-additionalfile:<file list> 코드 생성에 직접 영향을 주지 않지만 오류 또는 경고 생성을 위해 분석기에서 사용될 수 있는 추가 파일입니다. -embed PDB에 모든 소스 파일을 포함합니다. --embed:<파일 목록> PDB에 특정 파일을 포함합니다. +-embed:<file list> PDB에 특정 파일을 포함합니다. - 리소스 - --win32res:<파일> Win32 리소스 파일(.res)을 지정합니다. --win32icon:<파일> 이 아이콘을 출력에 사용합니다. --win32manifest:<파일> Win32 매니페스트 파일(.xml)을 지정합니다. +-win32res:<file> Win32 리소스 파일(.res)을 지정합니다. +-win32icon:<file> 이 아이콘을 출력에 사용합니다. +-win32manifest:<file> Win32 매니페스트 파일(.xml)을 지정합니다. -nowin32manifest 기본 Win32 매니페스트는 포함하지 않습니다. -resource:<resinfo> 지정된 리소스를 포함합니다. (약식: -res) -linkresource:<resinfo> 지정된 리소스를 이 어셈블리에 링크합니다. (약식: -linkres) 여기서, resinfo 형식은 - <파일>[,<문자열 이름>[,public|private]]입니다. + <file>[,<string name>[,public|private]]입니다. - 코드 생성 - -debug[+|-] 디버깅 정보를 내보냅니다. @@ -676,16 +676,16 @@ -refonly 주 출력 대신 참조 어셈블리를 생성합니다. -instrument:TestCoverage 검사 정보를 수집하기 위해 계측한 어셈블리를 생성합니다. --sourcelink:<파일> PDB에 포함할 소스 링크 정보입니다. +-sourcelink:<file> PDB에 포함할 소스 링크 정보입니다. - 오류 및 경고 - -warnaserror[+|-] 모든 경고를 오류로 보고합니다. --warnaserror[+|-]:<경고 목록> 특정 경고를 오류로 보고합니다. +-warnaserror[+|-]:<warn list> 특정 경고를 오류로 보고합니다. -warn:<n> 경고 수준(0-4)을 설정합니다. (약식: -w) --nowarn:<경고 목록> 특정 경고 메시지를 사용하지 않습니다. --ruleset:<파일> 특정 진단을 사용하지 않도록 하는 규칙 집합 +-nowarn:<warn list> 특정 경고 메시지를 사용하지 않습니다. +-ruleset:<file> 특정 진단을 사용하지 않도록 하는 규칙 세트 파일을 지정합니다. --errorlog:<파일> 모든 컴파일러 및 분석기 진단을 기록할 파일을 +-errorlog:<file> 모든 컴파일러 및 분석기 진단을 기록할 파일을 지정합니다. -reportanalyzer 추가 분석기 정보(예: 실행 시간)를 보고합니다. @@ -693,28 +693,30 @@ - 언어 - -checked[+|-] 오버플로 검사를 생성합니다. -unsafe[+|-] 'unsafe' 코드를 사용할 수 있습니다. --define:<기호 목록> 조건부 컴파일 기호를 정의합니다. +-define:<symbol list> 조건부 컴파일 기호를 정의합니다. (약식: -d) -langversion:? 언어 버전에 허용되는 값을 표시합니다. --langversion:<문자열> 언어 버전을 - 'default'(최신 주 버전), +-langversion:<string> 언어 버전을 'latest'(최신 버전, 부 버전 포함) + 'default'(최신 주 버전), + 'latestmajor'(최신 버전, 부 버전 제외) + 'preview'(최신 버전, 지원되지 않는 미리 보기의 기능 포함) 또는 특정 버전(예: '6' 또는 '7.1')으로 지정합니다. -nullable[+|-] nullable 컨텍스트 옵션 enable|disable을 지정합니다. --nullable:{enable|disable|safeonly|warnings|safeonlywarnings} - nullable 컨텍스트 옵션 enable|disable|safeonly|warnings|safeonlywarnings를 지정합니다. +-nullable:{enable|disable|warnings|annotations} + nullable 컨텍스트 옵션 enable|disable|warnings|annotations를 지정합니다. - 보안 - -delaysign[+|-] 강력한 이름 키의 공개 부분만 사용하여 어셈블리 서명을 연기합니다. -publicsign[+|-] 강력한 이름 키의 공개 부분만 사용하여 어셈블리를 공개 서명합니다. --keyfile:<파일> 강력한 이름 키 파일을 지정합니다. --keycontainer:<문자열> 강력한 이름 키 컨테이너를 지정합니다. +-keyfile:<file> 강력한 이름 키 파일을 지정합니다. +-keycontainer:<string> 강력한 이름 키 컨테이너를 지정합니다. -highentropyva[+|-] 높은 엔트로피 ASLR을 사용합니다. - 기타 - -@<파일> 추가 옵션에 대한 지시 파일을 읽습니다. +@<file> 추가 옵션에 대한 지시 파일을 읽습니다. -help 사용법 메시지를 표시합니다. (약식: -?) -nologo 컴파일러 저작권 메시지를 표시하지 않습니다. -noconfig CSC.RSP 파일을 자동으로 포함하지 않습니다. @@ -722,14 +724,14 @@ -version 컴파일러 버전 번호를 표시하고 종료합니다. - 고급 - --baseaddress:<주소> 빌드할 라이브러리의 기준 주소입니다. +-baseaddress:<address> 빌드할 라이브러리의 기준 주소입니다. -checksumalgorithm:<alg> PDB에 저장된 소스 파일 체크섬을 계산하기 위한 알고리즘을 지정합니다. 지원되는 값은 SHA1 또는 SHA256(기본값)입니다. -codepage:<n> 소스 파일을 열 때 사용할 코드 페이지를 지정합니다. -utf8output 컴파일러 메시지를 UTF-8 인코딩으로 출력합니다. --main:<형식> 진입점이 포함되어 있는 형식을 지정합니다(다른 +-main:<type> 진입점이 포함되어 있는 형식을 지정합니다(다른 모든 가능한 진입점 무시). (약식: -m) -fullpaths 컴파일러가 정규화된 경로를 생성합니다. @@ -738,30 +740,30 @@ -pathmap:<K1>=<V1>,<K2>=<V2>,... 컴파일러별 소스 경로 이름 출력에 사용할 매핑을 지정합니다. --pdb:<파일> 디버그 정보 파일 이름을 지정합니다(기본값: +-pdb:<file> 디버그 정보 파일 이름을 지정합니다(기본값: 확장명이 .pdb인 출력 파일 이름) -errorendlocation 각 오류의 끝 위치에 해당하는 줄과 열을 출력합니다. -preferreduilang 기본 출력 언어 이름을 지정합니다. -nosdkpath 표준 라이브러리 어셈블리의 기본 SDK 경로를 찾지 않도록 설정합니다. -nostdlib[+|-] 표준 라이브러리(mscorlib.dll)를 참조하지 않습니다. --subsystemversion:<문자열> 이 어셈블리의 하위 시스템 버전을 지정합니다. --lib:<파일 목록> 참조를 위해 검색할 추가 디렉터리를 +-subsystemversion:<string> 이 어셈블리의 하위 시스템 버전을 지정합니다. +-lib:<file list> 참조를 위해 검색할 추가 디렉터리를 지정합니다. --errorreport:<문자열> 내부 컴파일러 오류를 처리하는 방법을 지정합니다. +-errorreport:<string> 내부 컴파일러 오류를 처리하는 방법을 지정합니다. prompt, send, queue 또는 none입니다. 기본값은 queue입니다. --appconfig:<파일> 어셈블리 바인딩 설정을 포함하는 +-appconfig:<file> 어셈블리 바인딩 설정을 포함하는 애플리케이션 구성 파일을 지정합니다. --moduleassemblyname:<문자열> 이 모듈이 속할 어셈블리의 +-moduleassemblyname:<string> 이 모듈이 속할 어셈블리의 이름입니다. --modulename:<문자열> 소스 모듈의 이름을 지정합니다. +-modulename:<string> 소스 모듈의 이름을 지정합니다. Visual C# Compiler Options default interface implementation - default interface implementation + 기본 인터페이스 구현 @@ -886,7 +888,7 @@ <switch expression> - <switch expression> + <switch 식> @@ -1411,12 +1413,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + nullable 참조 형식에 대한 주석은 코드에서 '#nullable' 주석 컨텍스트 내에만 사용되어야 합니다. The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + nullable 참조 형식에 대한 주석은 코드에서 '#nullable' 주석 컨텍스트 내에만 사용되어야 합니다. @@ -1531,12 +1533,12 @@ Partial method declarations of '{0}' have inconsistent nullability in constraints for type parameter '{1}' - '{0}'의 partial 메서드 선언에 '{1}' 형식 매개 변수의 제약 조건에 Null 허용 여부 일관성이 없습니다. + '{0}'의 부분 메서드(Partial method) 선언의 형식 매개 변수 '{1}'에 대한 제약 조건에 Null 허용 여부가 일관되지 않습니다. Partial method declarations have inconsistent nullability in constraints for type parameter - partial 메서드 선언에 형식 매개 변수의 제약 조건에 Null 허용 여부 일관성이 없음 + 부분 메서드(Partial method) 선언의 형식 매개 변수에 대한 제약 조건에 Null 허용 여부가 일관되지 않음 @@ -1581,7 +1583,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + '{1}'의 '{0}' 매개 변수 형식에 있는 참조 형식의 Null 허용 여부가 암시적으로 구현된 멤버 '{2}'과(와) 일치하지 않습니다. @@ -1631,7 +1633,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + '{0}' 반환 형식에 있는 참조 형식의 Null 허용 여부가 암시적으로 구현된 멤버 '{1}'과(와) 일치하지 않습니다. @@ -1661,7 +1663,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + '{0}' 형식에 있는 참조 형식의 Null 허용 여부가 암시적으로 구현된 멤버 '{1}'과(와) 일치하지 않습니다. @@ -1671,12 +1673,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + 형식에 있는 참조 형식 Null 허용 여부가 재정의된 멤버와 일치하지 않습니다. Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + 형식에 있는 참조 형식 Null 허용 여부가 재정의된 멤버와 일치하지 않습니다. @@ -1801,12 +1803,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - nullable이 아닌 {0} '{1}'이(가) 초기화되지 않았습니다. + nullable이 아닌 {0} '{1}'이(가) 초기화되지 않았습니다. {0}을(를) nullable로 선언하는 것이 좋습니다. Non-nullable field is uninitialized. Consider declaring as nullable. - nullable이 아닌 필드가 초기화되지 않았습니다. + nullable이 아닌 필드가 초기화되지 않았습니다. nullable로 선언하는 것이 좋습니다. @@ -4675,7 +4677,7 @@ If such a class is used as a base class and if the deriving class defines a dest A partial method must be declared within a partial class, partial struct, or partial interface - 부분 메서드(Partial Method)는 partial 클래스, partial 구조체 또는 partial 인터페이스 내에 선언해야 합니다. + 부분 메서드(Partial method)는 partial 클래스, partial 구조체 또는 partial 인터페이스 내에 선언해야 합니다. @@ -4720,7 +4722,7 @@ If such a class is used as a base class and if the deriving class defines a dest Partial method declarations of '{0}' have inconsistent constraints for type parameter '{1}' - '{0}'의 partial 메서드 선언에 '{1}' 형식 매개 변수의 제약 조건에 일관성이 없습니다. + '{0}'의 부분 메서드(Partial method) 선언의 '{1}' 형식 매개 변수에 대한 제약 조건이 일관되지 않습니다. @@ -5829,12 +5831,12 @@ catch (System.Exception e) 블록 뒤의 catch() 블록은 RuntimeCompatibilityA Expected 'disable' or 'restore' - disable, restore, enable 또는 safeonly가 필요합니다. + 'disable' 또는 'restore'가 필요합니다. Expected 'disable' or 'restore' after #pragma warning - #pragma warning 뒤에 disable, restore, enable 또는 safeonly가 필요합니다. + #pragma warning 뒤에 'disable' 또는 'restore'가 필요합니다. @@ -9722,7 +9724,7 @@ To remove the warning, you can use /reference instead (set the Embed Interop Typ Interface member '{0}' does not have a most specific implementation. Neither '{1}', nor '{2}' are most specific. - 인터페이스 멤버 '{0}'에 가장 한정적인 구현이 없습니다. '{1}'도 '{2}'도 가장 한정적이지 않습니다. + 인터페이스 멤버 '{0}'에 가장 한정적인 구현이 없습니다. '{1}', '{2}' 모두 가장 한정적이지 않습니다. diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.pl.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.pl.xlf index 37ca36799989c..c5bc2360ea49a 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.pl.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.pl.xlf @@ -37,6 +37,11 @@ Użycie typu odwołania dopuszczającego wartość null „{0}?” w wyrażeniu „as” jest niedozwolone. Zamiast tego użyj bazowego typu „{0}”. + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + Atrybut „{0}” nie jest prawidłowy w metodach dostępu zdarzenia. Jest on prawidłowy tylko w deklaracjach „{1}”. + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. Właściwość implementowana automatycznie „{0}” nie może być zadeklarowana jako „readonly”, ponieważ ma metodę dostępu „set”. @@ -47,11 +52,6 @@ Automatycznie implementowana metoda dostępu „set” „{0}” nie może być zadeklarowana jako „readonly”. - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - Atrybut „{0}” nie jest prawidłowy w metodach dostępu zdarzenia. Jest on prawidłowy tylko w deklaracjach „{1}”. - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' Asynchroniczna instrukcja foreach nie może operować na zmiennych typu „{0}”, ponieważ typ „{0}” nie zawiera odpowiedniej publicznej definicji wystąpienia elementu „{1}” @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + Nieprawidłowa opcja „{0}” dla parametru /nullable; należy użyć opcji „disable”, „enable”, „warnings” lub „annotations” @@ -124,7 +124,7 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + Zduplikowany operator pomijania wartości null („!”) @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + Oczekiwano opcji „warnings” lub „annotations” albo końca dyrektywy @@ -616,42 +616,42 @@ - PLIKI WYJŚCIOWE - -out:<plik> Określ nazwę pliku wyjściowego (domyślnie: nazwa podstawowa - pliku z klasą główną lub pierwszym plikiem) + pliku z klasą główną lub pierwszym plikiem) -target:exe Kompiluj plik wykonywalny konsoli (domyślnie) (krótka - wersja: -t:exe) + wersja: -t:exe) -target:winexe Kompiluj plik wykonywalny systemu Windows (krótka wersja: - -t:winexe) + -t:winexe) -target:library Kompiluj bibliotekę (krótka wersja: -t:library) -target:module Kompiluj moduł, który można dodać do innego - zestawu (krótka wersja: -t:module) + zestawu (krótka wersja: -t:module) -target:appcontainerexe Kompiluj plik wykonywalny kontenera aplikacji (krótka wersja: - -t:appcontainerexe) + -t:appcontainerexe) -target:winmdobj Kompiluj plik pośredni środowiska uruchomieniowego systemu Windows - przeznaczony dla narzędzia WinMDExp (krótka wersja: -t:winmdobj) + przeznaczony dla narzędzia WinMDExp (krótka wersja: -t:winmdobj) -doc:<plik> Plik dokumentacji XML do wygenerowania -refout:<plik> Dane wyjściowe zestawu odwołania do wygenerowania -platform:<ciąg> Ogranicz platformy, na których można uruchamiać ten kod: x86, - Itanium, x64, arm, anycpu32bitpreferred lub - anycpu. Wartość domyślna to anycpu. + Itanium, x64, arm, arm64, anycpu32bitpreferred lub + anycpu. Wartość domyślna to anycpu. - PLIKI WEJŚCIOWE - --recurse:<symbol wieloznaczny> Dołącz wszystkie pliki zawarte w bieżącym katalogu i - jego podkatalogach zgodnie ze specyfikacją określoną przy użyciu +-recurse:<symbol wieloznaczny> Uwzględnij wszystkie pliki zawarte w bieżącym katalogu i + podkatalogach zgodnie ze specyfikacją określoną przy użyciu symboli wieloznacznych -reference:<alias>=<plik> Odwołuj się do metadanych z określonego pliku - zestawu przy użyciu podanego aliasu (krótka wersja: -r) + zestawu przy użyciu podanego aliasu (krótka wersja: -r) -reference:<lista plików> Odwołuj się do metadanych z określonych - plików zestawów (krótka wersja: -r) + plików zestawów (krótka wersja: -r) -addmodule:<lista plików> Połącz określone moduły z tym zestawem -link:<lista plików> Osadź metadane z określonych plików - zestawów międzyoperacyjnych (krótka wersja: -l) + zestawów międzyoperacyjnych (krótka wersja: -l) -analyzer:<lista plików> Uruchom analizatory z tego zestawu - (krótka wersja: -a) + (krótka wersja: -a) -additionalfile:<lista plików> Dodatkowe pliki, które nie mają bezpośredniego wpływu na generowanie kodu, ale mogą być używane przez analizatory w celu tworzenia komunikatów o błędach lub ostrzeżeń. -embed Osadź wszystkie pliki źródłowe w pliku PDB. --embed:<lista plików> Osadź określone pliki w pliku PDB +-embed:<lista plików> Osadź określone pliki w pliku PDB - ZASOBY - -win32res:<plik> Określ plik zasobu Win32 (res) @@ -666,49 +666,51 @@ - GENEROWANIE KODU - -debug[+|-] Emituj informacje o debugowaniu -debug:{full|pdbonly|portable|embedded} - Określ typ debugowania (wartość domyślna to „full”, - wartość „portable” to format międzyplatformowy, - a wartość „embedded” to format międzyplatformowy wbudowany w - docelowym pliku DLL lub EXE) + Określ typ debugowania (wartość domyślna to „full”, + wartość „portable” to format międzyplatformowy, + a wartość „embedded” to format międzyplatformowy wbudowany w + docelowym pliku DLL lub EXE) -optimize[+|-] Włącz optymalizacje (krótka wersja: -o) -deterministic Utwórz zestaw deterministyczny - (w tym sygnaturę czasową i identyfikator GUID wersji modułu) + (zawierający sygnaturę czasową i identyfikator GUID wersji modułu) -refonly Utwórz zestaw odwołania zamiast głównych danych wyjściowych -instrument:TestCoverage Utwórz zestaw instrumentowany w celu gromadzenia - informacji o pokryciu + informacji o pokryciu -sourcelink:<plik> Informacje o linku źródłowym na potrzeby osadzenia w pliku PDB. - BŁĘDY I OSTRZEŻENIA - -warnaserror[+|-] Zgłaszaj wszystkie ostrzeżenia jako błędy -warnaserror[+|-]:<lista ostrzeżeń> Zgłaszaj określone ostrzeżenia jako błędy --warn:<n> Ustaw poziom ostrzeżenia (0–4) (krótka wersja: -w) +-warn:<n> Ustaw poziom ostrzeżeń (0–4) (krótka wersja: -w) -nowarn:<lista ostrzeżeń> Wyłącz określone komunikaty ostrzeżeń -ruleset:<plik> Określ plik zestawu reguł wyłączający określone - funkcje diagnostyczne. --errorlog:<plik> Określ plik, w którym mają zostać zarejestrowane dane diagnostyczne - wszystkich kompilatorów i analizatorów. + funkcje diagnostyczne. +-errorlog:<plik> Określ plik w celu rejestrowania wszystkich + danych diagnostycznych kompilatora i analizatora. -reportanalyzer Zgłaszaj dodatkowe informacje analizatora, takie jak - czas wykonywania. + czas wykonywania. -JĘZYK - -checked[+|-] Generuj operacje sprawdzenia przepełnienia -unsafe[+|-] Zezwalaj na niebezpieczny kod --define:<lista symboli> Definiuj symbole kompilacji warunkowej (krótka - wersja: -d) +-define:<lista symboli> Zdefiniuj symbole kompilacji warunkowej (krótka + wersja: -d) -langversion:? Wyświetl dozwolone wartości dla wersji języka --langversion:<ciąg> Określ wersję języka, na przykład - „default” (najnowsza wersja główna) - lub „latest” (najnowsza wersja z uwzględnieniem wersji pomocniczych) +-langversion:<ciąg> Określ wersję języka, na przykład + „latest” (najnowsza wersja z uwzględnieniem wersji pomocniczych), + „default” (to samo co „latest”), + „latestmajor” (najnowsza wersja z pominięciem wersji pomocniczych), + „preview” (najnowsza wersja z uwzględnieniem funkcji w nieobsługiwanej wersji zapoznawczej), lub konkretną wersję, taką jak „6” lub „7.1” -nullable[+|-] Określ, czy opcja kontekstu dopuszczającego wartość null jest włączona, czy wyłączona. --nullable:{enable|disable|safeonly|warnings|safeonlywarnings} - Określ opcję kontekstu dopuszczającego wartość null: enable|disable|safeonly|warnings|safeonlywarnings. +-nullable:{enable|disable|warnings|annotations} + Określ opcję kontekstu dopuszczającego wartość null: enable|disable|warnings|annotations. - ZABEZPIECZENIA - -delaysign[+|-] Podpisz z opóźnieniem zestaw, używając tylko - części publicznej klucza o silnej nazwie + części publicznej klucza o silnej nazwie -publicsign[+|-] Podpisz publicznie zestaw, używając tylko - części publicznej klucza o silnej nazwie + części publicznej klucza o silnej nazwie -keyfile:<plik> Określ plik klucza o silnej nazwie -keycontainer:<ciąg> Określ kontener klucza o silnej nazwie -highentropyva[+|-] Włącz losowe generowanie układu przestrzeni adresowej o wysokiej entropii @@ -718,50 +720,50 @@ -help Wyświetl ten komunikat dotyczący użycia (krótka wersja: -?) -nologo Pomiń komunikat kompilatora o prawach autorskich -noconfig Nie dołączaj automatycznie pliku CSC.RSP --parallel[+|-] Współbieżna kompilacja. --version Wyświetl numer wersji kompilatora i wyjdź. +-parallel[+|-] Kompilacja współbieżna +-version Wyświetl numer wersji kompilatora i zakończ - ZAAWANSOWANE - -baseaddress:<adres> Adres podstawowy dla biblioteki do skompilowania -checksumalgorithm:<algorytm> Określ algorytm do obliczania sumy kontrolnej - pliku źródłowego przechowywanej w pliku PDB. Obsługiwane są następujące wartości: - SHA1 (domyślnie) lub SHA256. + pliku źródłowego przechowywanej w pliku PDB. + Obsługiwane wartości: SHA1 lub SHA256 (domyślnie). -codepage:<n> Określ stronę kodową do użycia podczas otwierania - plików źródłowych + plików źródłowych -utf8output Wyprowadź komunikaty kompilatora przy użyciu kodowania UTF-8 -main:<typ> Określ typ zawierający punkt wejścia - (wszystkie pozostałe możliwe punkty wejścia zostaną zignorowane) (krótka - wersja: -m) + (zignoruj wszystkie pozostałe możliwe punkty wejścia) (krótka + wersja: -m) -fullpaths Kompilator generuje w pełni kwalifikowane ścieżki -filealign:<n> Określ wyrównanie stosowane dla sekcji - plików wyjściowych + plików wyjściowych -pathmap:<K1>=<W1>,<K2>=<W2>,... - Określ mapowanie dla nazw ścieżek źródłowych wyprowadzanych przez - kompilator. + Określ mapowanie dla nazw ścieżek źródłowych wyprowadzanych przez + kompilator. -pdb:<plik> Określ nazwę pliku z informacjami o debugowaniu (domyślnie: - nazwa pliku wyjściowego z rozszerzeniem pdb) + nazwa pliku wyjściowego z rozszerzeniem pdb) -errorendlocation Wyprowadź wiersz i kolumnę lokalizacji końcowej dla - każdego błędu + każdego błędu -preferreduilang Określ nazwę preferowanego języka wyjściowego. -nosdkpath Wyłącz przeszukiwanie domyślnej ścieżki zestawu SDK dla zestawów biblioteki standardowej. -nostdlib[+|-] Nie odwołuj się do biblioteki standardowej (mscorlib.dll) -subsystemversion:<ciąg> Określ wersję podsystemu tego zestawu -lib:<lista plików> Określ dodatkowe katalogi do przeszukania pod kątem - odwołań + odwołań -errorreport:<ciąg> Określ, w jaki sposób obsługiwać wewnętrzne błędy kompilatora: - prompt, send, queue lub none. Wartość domyślna to - queue. + prompt, send, queue lub none. Wartość domyślna to + queue. -appconfig:<plik> Określ plik konfiguracji aplikacji - zawierający ustawienia powiązania zestawu + zawierający ustawienia powiązania zestawu -moduleassemblyname:<ciąg> Nazwa zestawu, którego częścią - ma być ten moduł + ma być ten moduł -modulename:<ciąg> Określ nazwę modułu źródłowego Visual C# Compiler Options default interface implementation - default interface implementation + domyślna implementacja interfejsu @@ -886,7 +888,7 @@ <switch expression> - <switch expression> + <wyrażenie przełącznika> @@ -1411,12 +1413,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + Adnotacja dla typów referencyjnych dopuszczających wartość null powinna być używana tylko w kodzie z kontekstem adnotacji „#nullable”. The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + Adnotacja dla typów referencyjnych dopuszczających wartość null powinna być używana tylko w kodzie z kontekstem adnotacji „#nullable”. @@ -1581,7 +1583,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + Obsługa wartości null dla typów referencyjnych w typie parametru „{0}” „{1}” jest niezgodna z niejawnie implementowaną składową „{2}”. @@ -1631,7 +1633,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + Obsługa wartości null dla typów referencyjnych w typie zwracanym „{0}” jest niezgodna z niejawnie implementowaną składową „{1}”. @@ -1661,7 +1663,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + Obsługa wartości null dla typów referencyjnych w typie „{0}” jest niezgodna z niejawnie implementowaną składową „{1}”. @@ -1671,12 +1673,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + Obsługa wartości null dla typów referencyjnych w typie jest niezgodna z przesłoniętą składową. Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + Obsługa wartości null dla typów referencyjnych w typie jest niezgodna z przesłoniętą składową. @@ -1801,12 +1803,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - Element {0} „{1}” niedopuszczający wartości null jest niezainicjowany. + Element {0} „{1}” niedopuszczający wartości null jest niezainicjowany. Rozważ zadeklarowanie elementu {0} jako dopuszczającego wartości null. Non-nullable field is uninitialized. Consider declaring as nullable. - Pole niedopuszczające wartości null jest niezainicjowane. + Pole niedopuszczające wartości null jest niezainicjowane. Rozważ zadeklarowanie go jako dopuszczającego wartości null. @@ -5829,12 +5831,12 @@ Blok catch() po bloku catch (System.Exception e) może przechwytywać wyjątki n Expected 'disable' or 'restore' - Oczekiwano wartości disable, restore, enable lub safeonly + Oczekiwano elementu „disable” lub „restore” Expected 'disable' or 'restore' after #pragma warning - Po dyrektywie #pragma warning oczekiwano wartości disable, restore, enable lub safeonly + Oczekiwano elementu „disable” lub „restore” po ostrzeżeniu #pragma diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.pt-BR.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.pt-BR.xlf index 514027d2335fc..2c77831e37e9f 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.pt-BR.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.pt-BR.xlf @@ -37,6 +37,11 @@ É ilegal usar o tipo de referência anulável '{0}?' em uma expressão as; use o tipo subjacente '{0}' em seu lugar. + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + O atributo '{0}' não é válido em acessadores de evento. Ele é válido somente em declarações '{1}'. + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. A propriedade autoimplementada '{0}' não pode ser marcada como 'readonly' porque ela tem um acessador 'set'. @@ -47,11 +52,6 @@ O acessador 'set' autoimplementado '{0}' não pode ser marcado como 'readonly'. - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - O atributo '{0}' não é válido em acessadores de evento. Ele é válido somente em declarações '{1}'. - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' A instrução foreach assíncrona não pode operar em variáveis do tipo '{0}' porque '{0}' não contém uma definição da instância pública adequada para '{1}' @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + Opção inválida '{0}' para /nullable; precisa ser 'disable', 'enable', 'safeonly', 'warnings' ou 'safeonlywarnings' @@ -124,7 +124,7 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + Operador de supressão nulo duplicado ('!') @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + 'Warnings', 'annotations' ou fim de diretiva esperado @@ -369,7 +369,7 @@ Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface. - O tempo de execução de destino não é compatível com a acessibilidade 'protected', 'protected internal' ou 'private protected' para um membro de uma interface. + O runtime de destino não é compatível com a acessibilidade 'protected', 'protected internal' ou 'private protected' para um membro de uma interface. @@ -614,121 +614,123 @@ Opções do Compilador do Visual C# - – ARQUIVOS DE SAÍDA - --out:<file> Especificar o nome do arquivo de saída (padrão: nome base do + - ARQUIVOS DE SAÍDA - +-out:<file> Especificar o nome do arquivo de saída (padrão: nome de base do arquivo com a classe principal ou do primeiro arquivo) --target:exe Compilar um executável de console (padrão) (Forma - abreviada: -t:exe) --target:winexe Compilar um executável do Windows (Forma abreviada: +-target:exe Criar um executável do console (padrão) (Forma + abreviada: -t:exe) +-target:winexe Criar um executável do Windows (Forma abreviada: -t:winexe) --target:library Compilar uma biblioteca (Forma abreviada: -t:library) --target:module Compilar um módulo que pode ser adicionado a outro +-target:library Criar uma biblioteca (Forma abreviada: -t:library) +-target:module Criar um módulo que possa ser adicionado a outro assembly (Forma abreviada: -t:module) --target:appcontainerexe Compilar um executável do Appcontainer (Forma abreviada: +-target:appcontainerexe Criar um executável do Appcontainer (Forma abreviada: -t:appcontainerexe) --target:winmdobj Compilar um arquivo intermediário do Windows Runtime que - seja consumido pelo WinMDExp (Forma abreviada: -t:winmdobj) --doc:<file> Arquivo da Documentação XML a ser gerado --refout:<file> Saída do assembly de referência a ser gerado --platform:<string> Limitar em qual plataforma este código pode ser executado: x86, +-target:winmdobj Criar um arquivo intermediário do Windows Runtime que + seja consumido por WinMDExp (Forma abreviada: -t:winmdobj) +-doc:<file> Arquivo de documentação XML a ser gerado +-refout:<file> Saída do assembly de referência a ser gerada +-platform:<string> Limitar em quais plataformas esse código pode ser executado: x86, Itanium, x64, arm, arm64, anycpu32bitpreferred ou anycpu. O padrão é anycpu. - – ARQUIVOS DE ENTRADA - --recurse:<wildcard> Incluir todos os arquivos no diretório e nos - subdiretórios atuais de acordo com as especificações do + - ARQUIVOS DE ENTRADA - +-recurse:<wildcard> Incluir todos os arquivos no diretório atual e + subdiretórios conforme as especificações do curinga --reference:<alias>=<file> Fazer referência a metadados do arquivo de assembly especificado - usando o alias fornecido (Forma abreviada: -r) --reference:<file list> Fazer referência a metadados dos arquivos de assembly especificados - (Forma abreviada: -r) --addmodule:<file list> Vincular os módulos especificados a este assembly +-reference:<alias>=<file> Referenciar metadados do arquivo de assembly + especificado usando o alias informado (Forma abreviada: -r) +-reference:<file list> Referenciar metadados dos arquivos de assembly + especificados (Forma abreviada: -r) +-addmodule:<file list> Vincular os módulos especificados a esse assembly -link:<file list> Inserir metadados dos arquivos de assembly de interoperabilidade especificados (Forma abreviada: -l) --analyzer:<file list> Executar os analisadores deste assembly +-analyzer:<file list> Executar os analisadores desse assembly (Forma abreviada: -a) --additionalfile:<file list> Arquivos adicionais que não afetam a geração de código diretamente, - mas podem ser usados pelos analisadores para produzir +-additionalfile:<file list> Arquivos adicionais que não afetam diretamente a geração do + código, mas podem ser usados por analisadores para produzir erros ou avisos. -embed Inserir todos os arquivos de origem no PDB. -embed:<file list> Inserir arquivos específicos no PDB. - – RECURSOS - --win32res:<file> Especificar um arquivo de recurso do Win32 (.res) --win32icon:<file> Use este ícone para a saída --win32manifest:<file> Especificar um arquivo de manifesto do Win32 (.xml) --nowin32manifest Não incluir o recurso de manifesto padrão do Win32 --resource:<resinfo> Inserir o recurso especificado (Forma abreviada: -res) --linkresource:<resinfo> Vincular o recurso especificado a este assembly - (Forma abreviada: -linkres) Em que o formato de resinfo + - RECURSOS - +-win32res:<file> Especificar um arquivo de recurso Win32 (.res) +-win32icon:<file> Usar esse ícone para a saída +-win32manifest:<file> Especificar um arquivo de manifesto Win32 (.xml) +-nowin32manifest Não incluir o manifesto Win32 padrão +-resource:<resinfo> Integrar o recurso especificado (Forma abreviada: -res) +-linkresource:<resinfo> Vincular o recurso especificado a esse assembly + (Forma abreviada: -linkres), Em que o formato resinfo é <file>[,<string name>[,public|private]] - – GERAÇÃO DE CÓDIGO - --debug[+|-] Emitir informações de depuração + - GERAÇÃO DE CÓDIGO - +-debug[+|-] Emitir informações de depuração -debug:{full|pdbonly|portable|embedded} - Especificar o tipo de depuração ('full' é o padrão, - 'portable' é um formato multiplataforma, - 'embedded' é um formato multiplataforma inserido no - .dll ou .exe de destino) --optimize[+|-] Habilitar as otimizações (Forma abreviada: -o) + Especificar o tipo de depuração (''full' é o padrão, + 'portable' é um formato multiplataforma, + 'embedded' é um formato multiplataforma integrado no + .dll ou.exe de destino) +-optimize[+|-] Habilitar otimizações (Forma abreviada: -o) -deterministic Produzir um assembly determinístico - (incluindo o GUID de versão do módulo e o carimbo de data/hora) + (incluindo GUID e carimbo de data/hora da versão do módulo) -refonly Produzir um assembly de referência no lugar da saída principal -instrument:TestCoverage Produzir um assembly instrumentado para coletar informações de cobertura -sourcelink:<file> Informações do link de origem a serem inseridas no PDB. - – ERROS E AVISOS - --warnaserror[+|-] Relatar todos os avisos e erros --warnaserror[+|-]:<warn list> Relatar avisos específicos como erros --warn:<n> Definir o nível de aviso (0 a 4) (Forma abreviada: -w) --nowarn:<warn list> Desabilitar mensagens de aviso específicas --ruleset:<file> Especificar um arquivo de conjunto de regras que desabilita um diagnóstico - específico. --errorlog:<file> Especificar um arquivo para registrar todos os diagnósticos do compilador e do + - ERROS E AVISOS - +-warnaserror[+|-] Relatar todos os avisos como erros +-warnaserror[+|-]:<warn list> Relatar avisos específicos como erros +-warn:<n> Definir o nível de aviso (0-4) (Forma abreviada: -w) +-nowarn:<warn list> Desabilitar mensagens de aviso específicas +-ruleset:<file> Especificar um arquivo de conjunto de regras que desabilite + diagnóstico específico. +-errorlog:<file> Especificar um arquivo para registrar todo o diagnóstico do compilador e do analisador. --reportanalyzer Relatar informações do analisador adicionais, como - o tempo de execução. +-reportanalyzer Relatar informações adicionais do analisador, como o + tempo de execução. - – LINGUAGEM - --checked[+|-] Gerar verificações de estouro + - IDIOMA - +-checked[+|-] Gerar verificações de estouro -unsafe[+|-] Permitir código 'unsafe' -define:<symbol list> Definir símbolos de compilação condicionais (Forma abreviada: -d) --langversion:? Exibir os valores permitidos para a versão da linguagem --langversion:<string> Especificar a versão da linguagem, como - 'default' (a versão principal mais recente) ou - 'latest' (a versão mais recente, incluindo as versões secundárias) - ou versões específicas como a '6' ou a '7.1' --nullable[+|-] Especificar uma opção de contexto que permite valor enable|disable nulo. --nullable:{enable|disable|warnings} - Especificar uma opção de contexto que permite valor enable|disable|warnings nulo. +-langversion:? Exibir os valores permitidos para a versão do idioma +-langversion:<string> Especificar a versão do idioma como + `latest` (versão mais recente, incluindo versões secundárias), + `default` (mesmo que `latest`), + `latestmajor` (versão mais recente, excluindo versões secundárias), + `preview` (versão mais recente, incluindo recursos em versão prévia sem suporte), + ou versões específicas, como `6` ou `7.1` +-nullable[+|-] Especificar opção de contexto anulável enable|disable. +-nullable:{enable|disable|warnings|annotations} + Especificar opção de contexto anulável enable|disable|warnings|annotations. - – SECURITY - --delaysign[+|-] Atrasar a assinatura do assembly usando somente a parte pública - da chave de nome forte --publicsign[+|-] Assinar publicamente o assembly usando somente a parte + - SEGURANÇA - +-delaysign[+|-] Assinar com atraso o assembly usando apenas a parte pública da chave de nome forte +-publicsign[+|-] Assinar de modo público o assembly usando apenas a parte pública + da chave de nome forte -keyfile:<file> Especificar um arquivo de chave de nome forte -keycontainer:<string> Especificar um contêiner de chave de nome forte -highentropyva[+|-] Habilitar ASLR de alta entropia - – DIVERSOS - -@<file> Ler o arquivo de resposta para obter mais opções + - DIVERSOS - +@<file> Ler o arquivo de resposta para mais opções -help Exibir esta mensagem de uso (Forma abreviada: -?) --nologo Suprimir a mensagem de direitos autorais do compilador --noconfig Não incluir o arquivo CSC.RSP automaticamente --parallel[+|-] Build simultâneo. +-nologo Suprimir mensagem de direitos autorais do compilador +-noconfig Não incluir automaticamente o arquivo CSC.RSP +-parallel[+|-] Build concomitante. -version Exibir o número de versão do compilador e sair. - – AVANÇADO - --baseaddress:<address> Endereço básico da biblioteca a ser criada + - ADVANCED - +-baseaddress:<address> Endereço básico da biblioteca a ser compilada -checksumalgorithm:<alg> Especificar o algoritmo para calcular a soma de verificação do arquivo de origem - armazenado no PDB. Os valores com suporte são: + armazenado em PDB. Os valores com suporte são: SHA1 ou SHA256 (padrão). --codepage:<n> Especificar a página de código a ser usada ao abrir arquivos de - origem --utf8output Emitir as mensagens do compilador na codificação UTF-8 +-codepage:<n> Especificar a página de código a ser usada ao abrir os arquivos + de origem +-utf8output Produzir mensagens do compilador em codificação UTF-8 -main:<type> Especificar o tipo que contém o ponto de entrada (ignorar todos os outros pontos de entrada possíveis) (Forma abreviada: -m) @@ -736,32 +738,32 @@ -filealign:<n> Especificar o alinhamento usado para as seções do arquivo de saída -pathmap:<K1>=<V1>,<K2>=<V2>,... - Especificar um mapeamento para a saída de nomes de caminho de origem pelo + Especificar um mapeamento para a saída de nomes do caminho de origem pelo compilador. -pdb:<file> Especificar o nome do arquivo de informações de depuração (padrão: - nome do arquivo de saída com a extensão .pdb) --errorendlocation Linha e coluna de saída do local final de - cada erro --preferreduilang Especificar o nome da linguagem de saída preferencial. --nosdkpath Desabilitar a pesquisa do caminho do SDK padrão para os assemblies de biblioteca padrão. --nostdlib[+|-] Não fazer referência à biblioteca padrão (mscorlib.dll) --subsystemversion:<string> Especificar a versão do subsistema deste assembly + nome do arquivo de saída com a extensão .pd) +-errorendlocation Gerar linha e coluna do local final de cada + erro +-preferreduilang Especificar o nome do idioma de saída preferencial. +-nosdkpath Desabilitar a pesquisa do caminho de SDK padrão para assemblies de biblioteca padrão. +-nostdlib[+|-] Não referenciar a biblioteca padrão (mscorlib.dll) +-subsystemversion:<string> Especificar uma versão de subsistema desse assembly -lib:<file list> Especificar diretórios adicionais nos quais pesquisar referências --errorreport:<string> Especificar como manipular erros internos do compilador: - prompt, send, queue ou none. O padrão é - queue. +-errorreport:<string> Especificar como lidar com erros internos do compilador: + avisar, enviar, colocar na fila ou nenhum. O padrão é + colocar na fila. -appconfig:<file> Especificar um arquivo de configuração de aplicativo - que contenha as configurações de associação do assembly --moduleassemblyname:<string> Nome do assembly do qual este módulo fará - parte + contendo as configurações de associação do assembly +-moduleassemblyname:<string> Nome do assembly do qual esse módulo + fará parte -modulename:<string> Especificar o nome do módulo de origem Visual C# Compiler Options default interface implementation - default interface implementation + implementação de interface padrão @@ -886,7 +888,7 @@ <switch expression> - <switch expression> + <expressão switch> @@ -1411,12 +1413,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + A anotação para tipos de referência anuláveis deve ser usada apenas em código dentro de um contexto de anotações '#nullable'. The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + A anotação para tipos de referência anuláveis deve ser usada apenas em código dentro de um contexto de anotações '#nullable'. @@ -1581,7 +1583,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + A nulidade de tipos de referência no tipo de parâmetro '{0}' de '{1}' não corresponde ao membro implicitamente implementado '{2}'. @@ -1631,7 +1633,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + A nulidade de tipos de referência no tipo de retorno de '{0}' não corresponde ao membro implicitamente implementado '{1}'. @@ -1661,7 +1663,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + A nulidade de tipos de referência no tipo de '{0}' não corresponde ao membro implicitamente implementado '{1}'. @@ -1671,12 +1673,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + A anulabilidade de tipos de referência em tipo não corresponde ao membro substituído. Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + A anulabilidade de tipos de referência em tipo não corresponde ao membro substituído. @@ -1801,12 +1803,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - O {0} não nulo '{1}' é não inicializado. + O {0} não anulável '{1}' não foi inicializado. Considere declarar o {0} como anulável. Non-nullable field is uninitialized. Consider declaring as nullable. - O campo não nulo é não inicializado. + O campo não anulável não foi inicializado. Considere declará-lo como anulável. @@ -2706,7 +2708,7 @@ Using '{0}' as a ref or out value or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class - Usar '{0}' como um valor ref ou out ou obter seu endereço pode gerar uma exceção de tempo de execução porque ele é um campo de uma classe mashal por referência + Usar '{0}' como um valor ref ou out ou obter seu endereço pode gerar uma exceção de runtime porque ele é um campo de uma classe mashal por referência @@ -5829,12 +5831,12 @@ Um bloco catch() depois de um bloco catch (System.Exception e) poderá capturar Expected 'disable' or 'restore' - Esperado disable, restore, enable ou safeonly + 'disable' ou 'restore' esperado Expected 'disable' or 'restore' after #pragma warning - Esperado disable, restore, enable ou safeonly após #pragma warning + 'disable' ou 'restore' esperado após o aviso #pragma @@ -6164,7 +6166,7 @@ Um bloco catch() depois de um bloco catch (System.Exception e) poderá capturar Accessing a member on '{0}' may cause a runtime exception because it is a field of a marshal-by-reference class - Acessar um membro em "{0}" pode causar uma exceção de tempo de execução porque é um campo de uma classe marshal por referência + Acessar um membro em "{0}" pode causar uma exceção de runtime porque é um campo de uma classe marshal por referência @@ -6259,7 +6261,7 @@ Um bloco catch() depois de um bloco catch (System.Exception e) poderá capturar Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy - Presumindo que a referência de assembly "{0}" usada por "{1}" corresponde a identidade "{2}" de "{3}", talvez seja necessário fornecer a diretiva de tempo de execução + Presumindo que a referência de assembly "{0}" usada por "{1}" corresponde a identidade "{2}" de "{3}", talvez seja necessário fornecer a diretiva de runtime @@ -6274,7 +6276,7 @@ Um bloco catch() depois de um bloco catch (System.Exception e) poderá capturar Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy - Presumindo que a referência de assembly "{0}" usada por "{1}" corresponde a identidade "{2}" de "{3}", talvez seja necessário fornecer a diretiva de tempo de execução + Presumindo que a referência de assembly "{0}" usada por "{1}" corresponde a identidade "{2}" de "{3}", talvez seja necessário fornecer a diretiva de runtime @@ -6683,7 +6685,7 @@ Um bloco catch() depois de um bloco catch (System.Exception e) poderá capturar Although C# distinguishes between out and ref, the CLR sees them as the same. When deciding which method implements the interface, the CLR just picks one. Give the compiler some way to differentiate the methods. For example, you can give them different names or provide an additional parameter on one of them. - Esse aviso pode ser gerado quando dois métodos de interface são diferenciados somente por se um determinado parâmetro é marcado com ref ou out. É aconselhável alterar o código para evitar este aviso porque não fica óbvio ou garantido qual método é chamado no tempo de execução. + Esse aviso pode ser gerado quando dois métodos de interface são diferenciados somente por se um determinado parâmetro é marcado com ref ou out. É aconselhável alterar o código para evitar este aviso porque não fica óbvio ou garantido qual método é chamado no runtime. Embora C# faça a distinção entre out e ref, o CLR os vê da mesma forma. Ao decidir qual método implementa a interface, o CLR simplesmente escolhe um deles. @@ -7924,7 +7926,7 @@ Você pode suprimir o aviso se tiver certeza de que não vai querer aguardar a c The dynamically dispatched call to method '{0}' may fail at runtime because one or more applicable overloads are conditional methods. - A chamada dinamicamente despachada para o método "{0}" pode falhar em tempo de execução porque um ou mais sobrecargas aplicáveis são métodos condicionais. + A chamada dinamicamente despachada para o método "{0}" pode falhar em runtime porque um ou mais sobrecargas aplicáveis são métodos condicionais. @@ -7974,7 +7976,7 @@ Você pode suprimir o aviso se tiver certeza de que não vai querer aguardar a c '{0}' cannot implement '{1}' because '{2}' is a Windows Runtime event and '{3}' is a regular .NET event. - '"{0}" não pode implementar "{1}" porque "{2}" é um evento de Tempo de Execução do Windows e "{3}" é um evento regular do .NET. + '{0}' não pode implementar '{1}' porque '{2}' é um evento de Windows Runtime e '{3}' é um evento regular do .NET. @@ -8029,7 +8031,7 @@ Você pode suprimir o aviso se tiver certeza de que não vai querer aguardar a c A Windows Runtime event may not be passed as an out or ref parameter. - Um evento de Tempo de Execução do Windows não pode ser passado como parâmetro out ou ref. + Um evento de Windows Runtime não pode ser passado como parâmetro out ou ref. @@ -8087,7 +8089,7 @@ To remove the warning, you can use /reference instead (set the Embed Interop Typ Para incorporar informações de tipo de interoperabilidade para os dois assemblies, use /link para fazer referência a cada assembly (defina a propriedade Incorporar Tipos de Interoperabilidade para Verdadeiro). - Para remover o aviso, você pode usar o /reference em vez disso (defina a propriedade Incorporar Tipos de Interoperabilidade como Falso). Nesse caso, um assembly de interoperabilidade primária (PIA) fornece informações de tipo de interoperabilidade. + Para remover o aviso, você pode usar o /reference em vez disso (defina a propriedade Incorporar Tipos de Interoperabilidade como Falso). Nesse caso, um PIA (assembly de interoperabilidade primário) fornece informações de tipo de interoperabilidade. @@ -8137,7 +8139,7 @@ Para incorporar informações de tipo de interoperabilidade para os dois assembl Attribute '{0}' given in a source file conflicts with option '{1}'. - Atributo "{0}" fornecido em um arquivo de origem com a opção "{1}". + O atributo '{0}' fornecido em um arquivo de origem conflita com a opção '{1}'. @@ -9702,12 +9704,12 @@ Para incorporar informações de tipo de interoperabilidade para os dois assembl Target runtime doesn't support default interface implementation. - O tempo de execução de destino não é compatível com a implementação de interface padrão. + O runtime de destino não é compatível com a implementação de interface padrão. '{0}' cannot implement interface member '{1}' in type '{2}' because the target runtime doesn't support default interface implementation. - '{0}' não pode implementar o membro de interface '{1}' no tipo '{2}' porque o tempo de execução de destino não dá suporte à implementação de interface padrão. + '{0}' não pode implementar o membro de interface '{1}' no tipo '{2}' porque o runtime de destino não dá suporte à implementação de interface padrão. diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.ru.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.ru.xlf index f29d3e67a25d2..7c88ba5028ec6 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.ru.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.ru.xlf @@ -37,6 +37,11 @@ Недопустимо использовать ссылочный тип "{0}", допускающий значения NULL, в выражении "as". Используйте вместо него базовый тип "{0}". + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + Атрибут "{0}" запрещено использовать в методах доступа к событиям. Он допустим только для объявлений "{1}". + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. Автоматически реализуемое свойство "{0}" не может быть помечено как readonly, так как имеет метод доступа set. @@ -47,11 +52,6 @@ Автоматически реализуемый метод доступа set "{0}" не может быть помечен как readonly. - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - Атрибут "{0}" запрещено использовать в методах доступа к событиям. Он допустим только для объявлений "{1}". - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' Асинхронный оператор foreach не работает с переменными типа "{0}", так как "{0}" не содержит подходящее открытое определение экземпляра для "{1}". @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + Недопустимый параметр "{0}" для /nullable. Допустимые значения: "disable", "enable", "warnings" или "annotations" @@ -124,12 +124,12 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + Оператор подавления повторяющихся значений NULL ("!") Cannot specify 'readonly' modifiers on both accessors of property or indexer '{0}'. Instead, put a 'readonly' modifier on the property itself. - Запрещено указывать модификаторы readonly для обоих методов доступа свойства или индексатора "{0}". Вместо этого укажите модификатор modifier для самого свойства. + Запрещено указывать модификаторы readonly для обоих методов доступа свойства или индексатора "{0}". Вместо этого укажите модификатор readonly для самого свойства. @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + Ожидаемые значения: "warnings", "annotations" или конец директивы @@ -615,24 +615,24 @@ Параметры компилятора Visual C# - Выходные файлы - --out:<file> Указывает имя выходного файла (по умолчанию: базовое имя +-out:<file> Указать имя выходного файла (по умолчанию: базовое имя файла с классом main или имя первого файла) -target:exe По умолчанию выполняет сборку консольного исполняемого файла (краткая форма: -t:exe) --target:winexe Выполняет сборку исполняемого файла Windows (краткая форма: +-target:winexe Выполнить сборку исполняемого файла Windows (краткая форма: -t:winexe) --target:library Выполняет сборку библиотеки (краткая форма: -t:library) --target:module Выполняет сборку модуля, который может быть добавлен в другую +-target:library Выполнить сборку библиотеки (краткая форма: -t:library) +-target:module Выполнить сборку модуля, который может быть добавлен в другую сборку (краткая форма: -t:module) --target:appcontainerexe Выполняет сборку исполняемого файла контейнера приложений (краткая форма: +-target:appcontainerexe Выполнить сборку исполняемого файла контейнера приложений (краткая форма: -t:appcontainerexe) --target:winmdobj Выполняет сборку промежуточного файла среды выполнения Windows, +-target:winmdobj Выполнить сборку промежуточного файла среды выполнения Windows, используемого в WinMDExp (краткая форма: -t:winmdobj) -doc:<file> Создаваемый XML-файл документации -refout:<file> Создаваемые выходные данные базовой сборки -platform:<string> Ограничить платформы, на которых может выполняться этот код: x86, Itanium, x64, arm, arm64, anycpu32bitpreferred или - anycpu. Значение по умолчанию — anycpu. + anycpu. Значение по умолчанию — anycpu. - Входные файлы - -recurse:<wildcard> Включить все файлы в текущем каталоге и @@ -654,9 +654,9 @@ -embed:<file list> Внедрить указанные файлы в PDB. - Ресурсы - --win32res:<file> Задает файл ресурсов Win32 (RES-файл) +-win32res:<file> Задать файл ресурсов Win32 (RES-файл) -win32icon:<file> Использовать этот значок для вывода --win32manifest:<file> Задает файл манифеста Win32 (XML-файл) +-win32manifest:<file> Задать файл манифеста Win32 (XML-файл) -nowin32manifest Не включать манифест Win32 по умолчанию -resource:<resinfo> Внедрить указанный ресурс (краткая форма: -res) -linkresource:<resinfo> Скомпоновать указанный ресурс вместе с этой сборкой @@ -666,9 +666,9 @@ - Создание кода - -debug[+|-] Выдать отладочную информацию -debug:{full|pdbonly|portable|embedded} - Задать тип отладки (по умолчанию —full, - portable — кроссплатформенный формат, - embedded — кроссплатформенный формат, внедряемый в + Задать тип отладки (по умолчанию — "full", + "portable"  — кроссплатформенный формат, + "embedded" — кроссплатформенный формат, внедряемый в целевой DLL- или EXE-файл) -optimize[+|-] Включить оптимизацию (краткая форма: -o) -deterministic Создать детерминированную сборку @@ -697,12 +697,14 @@ форма: -d) -langversion:? Отобразить разрешенные значения для версии языка -langversion:<string> Указать версию языка, например - default (последний основной номер версии) или - latest (последняя версия, включая дополнительные номера версии), + "latest" (последняя версия, включая дополнительные номера версии), + "default" (то же что и "latest"), + "latestmajor" (последняя версия, исключая дополнительные номера версии), + "preview" (последняя версия, включая функции в неподдерживаемой предварительной версии) либо конкретные версии, например "6" или "7.1" -nullable[+|-] Указать параметр допускающего значение NULL контекста enable|disable. --nullable:{enable|disable|warnings} - Указать параметр допускающего значение NULL контекста enable|disable|warnings. +-nullable:{enable|disable|warnings|annotations} + Указать параметр допускающего значение NULL контекста enable|disable|warnings|annotations. - Безопасность - -delaysign[+|-] Использовать отложенную подпись для сборки, применяя только открытую @@ -735,7 +737,7 @@ -fullpaths Компилятор создает полные пути -filealign:<n> Задать выравнивание для разделов выходных файлов --pathmap:<K1>=<V1>,<K2>=<V2>,… +-pathmap:<K1>=<V1>,<K2>=<V2>,... Задать сопоставление для выходных данных имен исходного пути по компилятору. -pdb:<file> Задать имя файла для отладочной информации (по умолчанию: @@ -761,7 +763,7 @@ default interface implementation - default interface implementation + реализация интерфейса по умолчанию @@ -886,7 +888,7 @@ <switch expression> - <switch expression> + <выражения для выбора вариантов> @@ -1411,12 +1413,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + Аннотацию для ссылочных типов, допускающих значения NULL, следует использовать в коде только в контексте аннотаций "#nullable". The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + Аннотацию для ссылочных типов, допускающих значения NULL, следует использовать в коде только в контексте аннотаций "#nullable". @@ -1581,7 +1583,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + Допустимость значений NULL для ссылочных типов в типе параметра "{0}" объекта "{1}" не совпадает с явно реализованным членом "{2}". @@ -1631,7 +1633,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + Допустимость значений NULL для ссылочных типов в типе возвращаемого значения объекта "{0}" не совпадает с явно реализованным членом "{1}". @@ -1661,7 +1663,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + Допустимость значений NULL для ссылочных типов в типе объекта "{0}" не совпадает с явно реализованным членом "{1}". @@ -1671,12 +1673,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + Допустимость значения NULL для ссылочных типов в типе не совпадает с переопределенным членом. Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + Допустимость значения NULL для ссылочных типов в типе не совпадает с переопределенным членом. @@ -1801,12 +1803,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - Не инициализировано {0} "{1}", не допускающее значение NULL. + {0} "{1}", не допускающий значение NULL, не инициализирован. Рекомендуется объявить {0} как допускающий значение NULL. Non-nullable field is uninitialized. Consider declaring as nullable. - Не инициализировано поле, не допускающее значение NULL. + Поле, не допускающее значение NULL, не инициализировано. Рекомендуется объявить его как допускающее значение NULL. @@ -5829,12 +5831,12 @@ A catch() block after a catch (System.Exception e) block can catch non-CLS excep Expected 'disable' or 'restore' - Ожидается disable, restore, enable или safeonly. + Ожидается "disable" или "restore" Expected 'disable' or 'restore' after #pragma warning - После #pragma warning ожидается disable, restore, enable или safeonly. + После предупреждения #pragma ожидается "disable" или "restore" diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.tr.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.tr.xlf index e21c1729ab37f..a0dbb24c1034c 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.tr.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.tr.xlf @@ -37,6 +37,11 @@ Boş değer atanabilir '{0}?' başvuru türünün bir as ifadesinde kullanılması yasaktır; bunun yerine temel alınan '{0}' türünü kullanın. + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + '{0}' özniteliği olay erişimcilerinde geçerli değil. Bu öznitelik yalnızca '{1}' bildirimlerinde geçerlidir. + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. Otomatik olarak uygulanan '{0}' özelliği 'set' erişimcisine sahip olduğundan 'readonly' olarak işaretlenemez. @@ -47,11 +52,6 @@ Otomatik olarak uygulanan '{0}' 'set' erişimcisi, 'readonly' olarak işaretlenemez. - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - '{0}' özniteliği olay erişimcilerinde geçerli değil. Bu öznitelik yalnızca '{1}' bildirimlerinde geçerlidir. - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' '{0}', '{1}' için uygun bir genel örnek tanımı içermediğinden zaman uyumsuz foreach deyimi '{0}' türündeki değişkenlerle çalışmaz @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + /nullable için geçersiz '{0}' seçeneği; 'disable', 'enable', 'warnings' veya 'annotations' olmalıdır @@ -124,7 +124,7 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + Yinelenen null gizleme işleci ('!') @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + 'Uyarılar', 'ek açıklama' veya yönergenin sonu bekleniyordu @@ -612,156 +612,158 @@ -modulename:<string> Specify the name of the source module - Visual C# Derleyici Seçenekleri + Visual C# Derleyici Seçenekleri - ÇIKIŞ DOSYALARI - --out:<dosya> Çıkış dosyası adını belirt (varsayılan: ana - sınıfın olduğu dosyanın veya ilk dosyanın temel adı) --target:exe Konsol yürütülebilir dosyası derle (varsayılan) (Kısa +-out:<dosya> Çıkış dosyası adını belirtin (varsayılan: ana sınıfı + içeren dosyanın veya ilk dosyanın temel adı) +-target:exe Konsol yürütülebilir dosyası oluşturun (varsayılan) (Kısa biçim: -t:exe) --target:winexe Windows yürütülebilir dosyası derle (Kısa biçim: +-target:winexe Windows yürütülebilir dosyası oluşturun (Kısa biçim: -t:winexe) --target:library Kitaplık derle (Kısa biçim: -t:library) --target:module Başka bir bütünleştirilmiş koda eklenebilecek bir - modül derle (Kısa biçim: -t:module) --target:appcontainerexe Appcontainer yürütülebilir dosyası derle (Kısa biçim: +-target:library Kitaplık derleyin (Kısa biçim: -t:library) +-target:module Başka bir derlemeye eklenebilecek bir + modül oluşturun (Kısa biçim: -t:module) +-target:appcontainerexe Appcontainer yürütülebilir dosyası oluşturun (Kısa biçim: -t:appcontainerexe) -target:winmdobj WinMDExp tarafından kullanılan bir Windows Çalışma Zamanı - ara dosyası derle (Kısa biçim: -t:winmdobj) --doc:<dosya> Oluşturulacak XML Belge dosyası --refout:<dosya> Oluşturulacak başvuru bütünleştirilmiş kodu çıkışı --platform:<dize> Bu kodun çalıştırılabileceği platformları sınırla: x86, + ara dosyası oluşturun (Kısa biçim: -t:winmdobj) +-doc:<dosya> Oluşturulacak XML Belgesi dosyası +-refout:<dosya> Oluşturulacak başvuru derlemesi çıkışı +-platform:<dize> Bu kodun çalıştırılabileceği platformları sınırlandırın: x86, Itanium, x64, arm, arm64, anycpu32bitpreferred veya anycpu. Varsayılan: anycpu. - GİRİŞ DOSYALARI - -recurse:<joker karakter> Joker karakter belirtimlerine göre, geçerli dizindeki ve alt dizinlerdeki tüm dosyaları - dahil et --reference:<diğer ad>=<dosya> Belirtilen bütünleştirilmiş kod dosyasındaki meta verilere - belirtilen diğer adla başvur (Kısa biçim: -r) --reference:<dosya listesi> Belirtilen bütünleştirilmiş kod dosyalarındaki meta verilere - başvur (Kısa biçim: -r) --addmodule:<dosya listesi> Belirtilen modülleri bu bütünleştirilmiş koda bağla --link:<dosya listesi> Belirtilen birlikte çalışma derleme dosyalarından - meta veri ekle (Kısa biçim: -l) --analyzer:<dosya listesi> Çözümleyicileri bu bütünleştirilmiş koddan çalıştır + dahil edin +-reference:<diğer ad>=<dosya> Verilen diğer adı kullanan belirtilen derleme dosyasındaki + meta verilere başvurun (Kısa biçim: -r) +-reference:<dosya listesi> Belirtilen derleme dosyalarındaki meta verilere + başvurun (Kısa biçim: -r) +-addmodule:<dosya listesi> Belirtilen modülleri bu derlemeye bağlayın +-link:<dosya listesi> Belirtilen birlikte çalışma derleme dosyalarındaki + meta verileri ekleyin (Kısa biçim: -l) +-analyzer:<dosya listesi> Çözümleyicileri bu derlemeden çalıştırın (Kısa biçim: -a) -additionalfile:<dosya listesi> Kod oluşturmayı doğrudan etkilemeyen ancak hata ve uyarılar oluşturmak için çözümleyicilerin kullanabileceği ek dosyalar. --embed Tüm kaynak dosyalarını PDB'ye ekle. --embed:<dosya listesi> Belirli dosyaları PDB'ye ekle. +-embed Tüm kaynak dosyalarını PDB'ye ekleyin. +-embed:<dosya listesi> Belirli dosyaları PDB'ye ekleyin. - KAYNAKLAR - --win32res:<dosya> Bir Win32 kaynak dosyası (.res) belirt --win32icon:<dosya> Çıkış için bu simgeyi kullan --win32manifest:<dosya> Bir Win32 bildirim dosyası (.xml) belirt --nowin32manifest Varsayılan Win32 bildirimini dahil etme --resource:<kaynak bilgileri> Belirtilen kaynağı ekle (Kısa biçim: -res) --linkresource:<kaynak bilgileri> Belirtilen kaynağı bu bütünleştirilmiş koda bağla - (Kısa biçim: -linkres) Kaynak bilgisi biçimi: - <dosya>[,<dize adı>[,public|private]] +-win32res:<dosya> Bir Win32 kaynak dosyası (.res) belirtin +-win32icon:<dosya> Çıkış için bu simgeyi kullanın +-win32manifest:<dosya> Bir Win32 bildirim dosyası (.xml) belirtin +-nowin32manifest Varsayılan Win32 bildirimini dahil etmeyin +-resource:<kaynak bilgileri> Belirtilen kaynağı ekleyin (Kısa biçim: -res) +-linkresource:<kaynak bilgileri> Belirtilen kaynağı bu derlemeye bağlayın + (Kısa biçim: -linkres) Kaynak bilgisi biçimi + <dosya>[,<dize adı>[,public|private]] olduğunda - KOD OLUŞTURMA - --debug[+|-] Hata ayıklama bilgilerini yayınla +-debug[+|-] Hata ayıklama bilgilerini yayımlayın -debug:{full|pdbonly|portable|embedded} - Hata ayıklama türünü belirt (varsayılan: 'full', - 'portable': platformlar arası bir biçim, - 'embedded': hedef .dll veya .exe dosyasına - eklenmiş platformlar arası bir biçim) --optimize[+|-] İyileştirmeleri etkinleştir (Kısa biçim: -o) --deterministic Belirlenimci bir bütünleştirilmiş kod oluştur + Hata ayıklama türünü belirtin ('full' varsayılan, + 'portable' platformlar arası biçim, + 'embedded' ise hedef .dll veya .exe dosyasına + eklenmiş platformlar arası bir biçimdir) +-optimize[+|-] İyileştirmeleri etkinleştirin (Kısa biçim: -o) +-deterministic Belirlenimci bir derleme oluşturun (modül sürümü GUID'si ve zaman damgası dahil) --refonly Ana çıkış yerine bir başvuru bütünleştirilmiş kodu oluştur +-refonly Ana çıkış yerine bir başvuru derlemesi oluşturun -instrument:TestCoverage Kapsam bilgilerini toplamak üzere - izleme eklenmiş bir bütünleştirilmiş kod üret + izleme eklenmiş bir derleme oluşturun -sourcelink:<dosya> PDB'ye eklenecek kaynak bağlantı bilgileri. - HATALAR VE UYARILAR - --warnaserror[+|-] Tüm uyarıları hata olarak bildir --warnaserror[+|-]:<uyarı listesi> Belirli uyarıları hata olarak bildir --warn:<n> Uyarı düzeyini belirle (0-4) (Kısa biçim: -w) --nowarn:<uyarı listesi> Belirli uyarı iletilerini devre dışı bırak +-warnaserror[+|-] Tüm uyarıları hata olarak bildirin +-warnaserror[+|-]:<uyarı listesi> Belirli uyarıları hata olarak bildirin +-warn:<n> Uyarı düzeyini ayarlayın (0-4) (Kısa biçim: -w) +-nowarn:<uyarı listesi> Belirli uyarı iletilerini devre dışı bırakın -ruleset:<dosya> Belirli tanılamaları devre dışı bırakan bir - kural kümesi dosyası belirt. + kural kümesi dosyası belirtin. -errorlog:<dosya> Tüm derleyici ve çözümleyici tanılamalarını günlüğe kaydetmek için - bir dosya belirt. + bir dosya belirtin. -reportanalyzer Yürütme zamanı gibi ek çözümleyici - bilgilerini bildir. + bilgilerini bildirin. - DİL - --checked[+|-] Taşma denetimleri oluştur --unsafe[+|-] 'Güvensiz' koda izin ver --define:<sembol listesi> Koşullu derleme sembolleri tanımla (Kısa +-checked[+|-] Taşma denetimleri oluşturun +-unsafe[+|-] 'Güvensiz' koda izin verin +-define:<sembol listesi> Koşullu derleme sembolleri tanımlayın (Kısa biçim: -d) --langversion:? Dil sürümü için izin verilen değerleri görüntüle --langversion:<dize> ‘default’ (en son ana sürüm) veya - ‘latest’ (alt sürümlerin dahil olduğu en son sürüm) - gibi dil sürümlerini ya da `6` veya `7.1` - gibi belirli sürümleri belirt --nullable[+|-] Boş değer atanabilir bağlamı enable|disable olarak belirt. --nullable:{enable|disable|warnings} - Boş değer atanabilir bağlamı enable|disable|warnings olarak belirt. +-langversion:? Dil sürümü için izin verilen değerleri görüntüleyin +-langversion:<dize> `latest` (alt sürümlerin dahil olduğu en son sürüm), + `default` (`latest` ile aynı) + `latestmajor` (alt sürümler hariç en son sürüm), + `preview` (desteklenmeyen önizleme sürümündeki özellikleri içeren en son sürüm) + ya da `6` veya `7.1` + gibi belirli sürümleri belirtin +-nullable[+|-] Null değer atanabilir bağlam seçeneğini enable|disable olarak belirtin. +-nullable:{enable|disable|warnings|annotations} + Null değer atanabilir bağlam seçeneğini enable|disable|warnings|annotations olarak belirtin. - GÜVENLİK - --delaysign[+|-] Bütünleştirilmiş kodu, tanımlayıcı ad anahtarının yalnızca genel - kısmını kullanarak gecikmeli imzala --publicsign[+|-] Bütünleştirilmiş kodu, tanımlayıcı ad anahtarının yalnızca genel - kısmını kullanarak genel olarak imzala --keyfile:<dosya> Bir tanımlayıcı ad anahtarı dosyası belirt --keycontainer:<dize> Bir tanımlayıcı ad anahtarı kapsayıcısı belirt --highentropyva[+|-] Yüksek entropili ASLR'yi etkinleştir +-delaysign[+|-] Derlemeyi, tanımlayıcı ad anahtarının yalnızca genel + kısmını kullanarak gecikmeli imzalayın +-publicsign[+|-] Derlemeyi, tanımlayıcı ad anahtarının yalnızca genel + kısmını kullanarak genel olarak imzalayın +-keyfile:<dosya> Bir tanımlayıcı ad anahtarı dosyası belirtin +-keycontainer:<dize> Bir tanımlayıcı ad anahtarı kapsayıcısı belirtin +-highentropyva[+|-] Yüksek entropili ASLR'yi etkinleştirin - ÇEŞİTLİ - -@<dosya> Daha fazla seçenek için yanıt dosyasını oku --help Bu kullanım iletisini görüntüle (Kısa biçim: -?) --nologo Derleyici telif hakkı iletisini gösterme --noconfig CSC.RSP dosyasını otomatik olarak dahil etme +@<dosya> Daha fazla seçenek için yanıt dosyasının okunmasını sağlayın +-help Bu kullanım iletisini gösterin (Kısa biçim: -?) +-nologo Derleyici telif hakkı iletisini gösterilmemesini sağlayın +-noconfig CSC.RSP dosyasını otomatik olarak dahil etmeyin -parallel[+|-] Eşzamanlı derleme. --version Derleyici sürüm numarasını görüntüle ve çık. +-version Derleyici sürüm numarasını görüntüleyin ve çıkın. - GELİŞMİŞ - --baseaddress:<adres> Derlenecek kitaplığın taban adresi --checksumalgorithm:<alg> PDB'de depolanan kaynak dosya sağlama toplamını - hesaplama algoritmasını belirt. Desteklenen değerler: +-baseaddress:<adres> Oluşturulacak kitaplığın taban adresi +-checksumalgorithm:<alg> PDB'de depolanan kaynak dosyanın sağlama toplamını + hesaplama algoritmasını belirtin. Desteklenen değerler: SHA1 veya SHA256 (varsayılan). --codepage:<n> Kaynak dosyalarını açarken kullanılacak kod - sayfasını belirt --utf8output Derleyici iletilerini UTF-8 kodlamasında görüntüle --main:<tür> Giriş noktasını içeren türü belirt - (diğer tüm olası giriş noktalarını yoksay) (Kısa +-codepage:<n> Kaynak dosyalarını açarken kullanılacak kod + sayfasını belirtin +-utf8output Derleyici iletilerini UTF-8 kodlamasında görüntüleyin +-main:<tür> Giriş noktasını içeren türü belirtin + (diğer tüm olası giriş noktalarını yoksayar) (Kısa biçim: -m) --fullpaths Derleyici tam yollar oluşturur --filealign:<n> Çıkış dosyasının bölümleri için kullanılan - hizalamayı belirt +-fullpaths Derleyici, tam yollar oluşturur +-filealign:<n> Çıkış dosyasının bölümleri için kullanılan + hizalamayı belirtin -pathmap:<A1>=<D1>,<A2>=<D2>,... Derleyici tarafından gösterilen kaynak yolu adları için bir eşleme - belirt. --pdb:<dosya> Hata ayıklama bilgileri dosyasının adını belirt (varsayılan: + belirtin. +-pdb:<dosya> Hata ayıklama bilgileri dosyasının adını belirtin (varsayılan: .pdb uzantılı çıkış dosyasının adı) -errorendlocation Her hatanın bitiş konumunun satır ve sütununu - göster --preferreduilang Tercih edilen çıkış dilinin adını belirt. --nosdkpath Standart kitaplık bütünleştirilmiş kodlar için varsayılan SDK yolu aramayı devre dışı bırak. --nostdlib[+|-] Standart kitaplığa (mscorlib.dll) başvurma --subsystemversion:<dize> Bu bütünleştirilmiş kodun alt sistem sürümünü belirt + gösterin +-preferreduilang Tercih edilen çıkış dilinin adını belirtin. +-nosdkpath Standart kitaplık derlemeleri için varsayılan SDK yolunu aramayı devre dışı bırakın. +-nostdlib[+|-] Standart kitaplığa (mscorlib.dll) başvuru yapmayın +-subsystemversion:<dize> Bu derlemenin alt sistem sürümünü belirtin -lib:<dosya listesi> İçinde başvuruların aranacağı ek dizinleri - belirt --errorreport:<dize> İç derleyici hatalarının nasıl işleneceğini belirt: - prompt, send, queue veya none. Varsayılan: - queue. --appconfig:<dosya> Bütünleştirilmiş kod bağlama ayarlarını içeren - bir uygulama yapılandırma dosyası belirt --moduleassemblyname:<dize> Bu modülün parçası olacağı bütünleştirilmiş kodun + belirtin +-errorreport:<dize> İç derleyici hatalarının nasıl işleneceğini belirtin: + sor, gönder, kuyruğa al veya hiçbiri. Varsayılan olarak + kuyruğa alınır. +-appconfig:<dosya> Derleme bağlama ayarlarını içeren + bir uygulama yapılandırma dosyası belirtin +-moduleassemblyname:<dize> Bu modülün parçası olacağı derlemenin adı --modulename:<dize> Kaynak modülün adını belirt +-modulename:<dize> Kaynak modülün adını belirtin Visual C# Compiler Options default interface implementation - default interface implementation + varsayılan arabirim uygulaması @@ -886,7 +888,7 @@ <switch expression> - <switch expression> + <switch expression> @@ -1411,12 +1413,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + Boş değer atanabilir başvuru türleri için ek açıklama kodda yalnızca bir '#nullable' ek açıklama bağlamı içinde kullanılmalıdır. The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + Boş değer atanabilir başvuru türleri için ek açıklama kodda yalnızca bir '#nullable' ek açıklama bağlamı içinde kullanılmalıdır. @@ -1581,7 +1583,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + '{1}' içinde '{0}' parametre türündeki başvuru türlerinin boş değer atanabilirliği, örtük olarak uygulanan '{2}' üyesi ile eşleşmiyor. @@ -1631,7 +1633,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + '{0}' dönüş türündeki başvuru türlerinin boş değer atanabilirliği, örtük olarak uygulanan '{1}' üyesi ile eşleşmiyor. @@ -1661,7 +1663,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + '{0}' türündeki başvuru türlerinin boş değer atanabilirliği, örtük olarak uygulanan '{1}' üyesi ile eşleşmiyor. @@ -1671,12 +1673,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + Türdeki başvuru türlerinin boş değer atanabilirliği, geçersiz kılınan üye ile eşleşmiyor. Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + Türdeki başvuru türlerinin boş değer atanabilirliği, geçersiz kılınan üye ile eşleşmiyor. @@ -1801,12 +1803,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - Boş değer atanamaz {0} '{1}' başlatılmadı. + Null değer atanamayan {0} '{1}' başlatılmadı. {0} alanını null değer atanabilir olarak tanımlamayı deneyin. Non-nullable field is uninitialized. Consider declaring as nullable. - Boş değer atanamaz alan başlatılmadı. + Null değer atanamayan alan başlatılmadı. Bunu null değer atanabilir olarak tanımlamayı deneyin. @@ -5829,12 +5831,12 @@ RuntimeCompatibilityAttribute AssemblyInfo.cs dosyasında false olarak ayarlanm Expected 'disable' or 'restore' - Disable, restore, enable veya safeonly beklendi + Beklenen: 'disable' veya 'restore' Expected 'disable' or 'restore' after #pragma warning - #pragma uyarısından sonra disable, restore, enable veya safeonly beklendi + #pragma uyarısından sonra beklenen: 'disable' veya 'restore' @@ -8087,7 +8089,7 @@ To remove the warning, you can use /reference instead (set the Embed Interop Typ Birlikte çalışma türü bilgilerini her iki derlemeden de katıştırmak için, her bir derlemeye başvurular için /link kullanın (Birlikte Çalışma Türlerini Katıştır özelliğini True olarak ayarlayın). -Uyarıyı kaldırmak için, /reference kullanabilirsiniz (Birlikte Çalışma Türlerini Katıştır özelliğini False olarak ayarlayın). Bu durumda, birincil birlikte çalışma derlemesi (PIA) birlikte çalışma türü bilgilerini sağlar. +Uyarıyı kaldırmak için, /reference kullanabilirsiniz (Birlikte Çalışma Türlerini Katıştır özelliğini False olarak ayarlayın). Bu durumda, birincil birlikte çalışma bütünleştirilmiş kodu (PIA), birlikte çalışma türü bilgilerini sağlar. diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hans.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hans.xlf index 18fa3fc5c3756..8929eddb793ee 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hans.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hans.xlf @@ -37,6 +37,11 @@ 在 as 表达式中使用可以为 null 的引用类型“{0}?”是非法的;请改用基础类型“{0}”。 + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + 特性“{0}”对事件访问器无效。它仅对“{1}”声明有效。 + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. 无法将自动实现的属性 "{0}" 标记为 "readonly",因为它具有 "set" 访问器。 @@ -47,11 +52,6 @@ 自动实现的的 "set" 访问器 "{0}" 不能标记为 "readonly"。 - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - 特性“{0}”对事件访问器无效。它仅对“{1}”声明有效。 - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' “{0}”不包含“{1}”的适当公共实例定义,因此异步 foreach 语句不能作用于“{0}”类型的变量 @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + /nullable 的选项“{0}”无效;必须为“禁用”、“启用”、“警告”或“注释” @@ -124,7 +124,7 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + Null 抑制运算符("!")重复 @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + 应为“警告”、“注释”或指令结束 @@ -614,11 +614,11 @@ Visual C# 编译器选项 - - OUTPUT FILES - + - 输出文件 - -out:<file> 指定输出文件名称(默认: 具有主类的文件或 第一个文件的基名称) -target:exe 生成控制台可执行文件(默认)(缩 - form: -t:exe) + 写: -t:exe) -target:winexe 生成 Windows 可执行文件(缩写: -t:winexe) -target:library 生成库(缩写: -t:library) @@ -634,7 +634,7 @@ Itanium、x64、arm、arm64、anycpu32bitpreferred 或 anycpu。默认平台为 anycpu。 - - 输入文件- + - 输入文件 - -recurse:<wildcard> 根据通配符规范包括当前目录和 子目录中的所有 文件 @@ -685,7 +685,8 @@ -nowarn:<warn list> 禁用特定警告消息 -ruleset:<file> 指定禁用特定诊断的 规则集文件。 --errorlog:<file> 指定用于记录所有编译器和分析器诊断的 +-errorlog:<file> 指定用于记录所有编译器 + 和分析器诊断的 文件。 -reportanalyzer 报告其他分析器信息,如 执行时间。 @@ -696,7 +697,7 @@ -define:<symbol list> 定义条件编译符号(缩 写: -d) -langversion:? 显示允许使用的语言版本值 --langversion:<string> S指定语言版本,例如 +-langversion:<string> 指定语言版本,例如 `default` (最新主要版本),或 `latest` (最新版本,包括次要版本), 或者特定版本,如 `6` 或 `7.1` @@ -713,7 +714,7 @@ -keycontainer:<string> 指定强名称密钥容器 -highentropyva[+|-] 启用高平均信息量 ASLR - - 杂项 - + - 其他 - @<file> 读取响应文件以获取更多选项 -help 显示此用法消息(缩写: -?) -nologo 取消显示编译器版权消息 @@ -743,14 +744,15 @@ -errorendlocation 输出每个错误的结束位置 行和列 -preferreduilang 指定首选输出语言名称。 --nosdkpath 禁止搜索标准库程序集的默认 SDK 路径。 +-nosdkpath 禁止搜索标准库程序集 + 的默认 SDK 路径。 -nostdlib[+|-] 不引用标准库(mscorlib.dll) -subsystemversion:<string> 指定此程序集的子系统版本 -lib:<file list> 指定要在其中搜索引用的附加 目录 -errorreport:<string> 指定如何处理内部编译器错误: prompt、send、queue 或 none。默认为 - queue. + queue。 -appconfig:<file> 指定包含程序集绑定设置的 应用程序配置文件 -moduleassemblyname:<string> 此模块所属程序集 @@ -759,6 +761,11 @@ Visual C# Compiler Options + + default interface implementation + 默认接口实现 + + disposable 可处置的 @@ -881,7 +888,7 @@ <switch expression> - <switch expression> + <switch expression> @@ -1406,12 +1413,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + 只能在 "#nullable" 注释上下文内的代码中使用可为 null 的引用类型的注释。 The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + 只能在 "#nullable" 注释上下文内的代码中使用可为 null 的引用类型的注释。 @@ -1576,7 +1583,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + “{1}”的参数“{0}”类型中引用类型的为 Null 性与隐式实现的成员“{2}”不匹配。 @@ -1626,7 +1633,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + “{0}”的返回类型中引用类型的为 Null 性与隐式实现的成员“{1}”不匹配。 @@ -1656,7 +1663,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + “{0}”的类型中引用类型的为 Null 性与隐式实现的成员“{1}”不匹配。 @@ -1666,12 +1673,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + 类型中引用类型的为 Null 性与重写成员不匹配。 Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + 类型中引用类型的为 Null 性与重写成员不匹配。 @@ -1796,12 +1803,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - 未初始化不可以为 null 的 {0}“{1}”。 + 不可为 null 的 {0} "{1}" 未初始化。请考虑将 {0} 声明为可以为 null。 Non-nullable field is uninitialized. Consider declaring as nullable. - 未初始化不可以为 null 的字段。 + 不可为 null 的字段未初始化。请考虑声明为可以为 null。 @@ -5824,12 +5831,12 @@ A catch() block after a catch (System.Exception e) block can catch non-CLS excep Expected 'disable' or 'restore' - 应为 disable、restore、enable 或 safeonly + 应为 disable 或 restore Expected 'disable' or 'restore' after #pragma warning - 应在 #pragma warning 之后为 disable、restore、enable 或 safeonly + #pragma 警告后应为 "disable" 或 "restore" @@ -9695,11 +9702,6 @@ To remove the warning, you can use /reference instead (set the Embed Interop Typ 接口不能包含转换、相等或不相等运算符 - - default interface implementation - 默认接口实现 - - Target runtime doesn't support default interface implementation. 目标运行时不支持默认接口实现。 diff --git a/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hant.xlf b/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hant.xlf index 7910a1a3b62b0..94948e810312f 100644 --- a/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hant.xlf +++ b/src/Compilers/CSharp/Portable/xlf/CSharpResources.zh-Hant.xlf @@ -37,6 +37,11 @@ 在運算式中使用可為 Null 的參考型別 '{0}?' 不合法,請改用基礎類型 '{0}'。 + + Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. + 屬性 '{0}' 在事件存取子上無效。其只有在 '{1}' 宣告上才有效。 + + Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor. 因為自動實作屬性 '{0}' 有 'set' 存取子,所以無法將其標記為 'readonly'。 @@ -47,11 +52,6 @@ 無法將自動實作 'set' 存取子 '{0}' 標記為 'readonly'。 - - Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations. - 屬性 '{0}' 在事件存取子上無效。其只有在 '{1}' 宣告上才有效。 - - Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance definition for '{1}' 因為 '{0}' 不包含適用於 '{1}' 的公用執行個體定義,所以非同步的 foreach 陳述式無法在類型為 '{0}' 的變數上運作 @@ -69,7 +69,7 @@ Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' - Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations' + /nullable 的選項 '{0}' 無效; 必須為 'disable'、'enable'、'warnings' 或 'annotations' @@ -124,7 +124,7 @@ Duplicate null suppression operator ('!') - Duplicate null suppression operator ('!') + 重複 Null 隱藏運算子 ('!') @@ -299,7 +299,7 @@ Expected 'warnings', 'annotations', or end of directive - Expected 'warnings', 'annotations', or end of directive + 必須是 'warnings'、'annotations' 或指示詞結尾 @@ -615,7 +615,7 @@ Visual C# 編譯器選項 - 輸出檔案 - --out:<檔案> 指定輸出檔案名稱 (預設: 具有主要類別的檔案或 +-out:<file> 指定輸出檔案名稱 (預設: 具有主要類別的檔案或 第一個檔案的基底名稱) -target:exe 建置主控台可執行檔 (預設) (簡短 形式: -t:exe) @@ -628,40 +628,40 @@ -t:appcontainerexe) -target:winmdobj 建置 WinMDExp 所取用的 Windows 執行階段 中繼檔案 (簡短形式: -t:winmdobj) --doc:<檔案> 要產生的 XML 文件檔案 --refout:<檔案> 要產生的參考組件輸出 --platform:<字串> 限制此程式碼可執行的平台: x86、 +-doc:<file> 要產生的 XML 文件檔案 +-refout:<file> 要產生的參考組件輸出 +-platform:<string> 限制此程式碼可執行的平台: x86、 Itanium、x64、arm、arm64、anycpu32bitpreferred 或 anycpu。預設為 anycpu。 - 輸入檔案 - --recurse:<萬用字元> 依據萬用字元的規格,納入 +-recurse:<wildcard> 依據萬用字元的規格,納入 目前目錄和子目錄中的所有 檔案 --reference:<別名>=<檔案> 使用給定的別名,參考指定組件檔 +-reference:<alias>=<file> 使用給定的別名,參考指定組件檔 的中繼資料 (簡短形式: -r) --reference:<檔案清單> 參考指定組件檔的中繼資料 +-reference:<file list> 參考指定組件檔的中繼資料 (簡短形式: -r) --addmodule:<檔案清單> 將指定的模組連結至這個組件 --link:<檔案清單> 從指定的 Interop 組件檔, +-addmodule:<file list> 將指定的模組連結至這個組件 +-link:<file list> 從指定的 Interop 組件檔, 內嵌中繼資料 (簡短形式: -l) --analyzer:<檔案清單> 從這個組件執行分析器 +-analyzer:<file list> 從這個組件執行分析器 (簡短形式: -a) --additionalfile:<檔案清單> 不會直接影響程式碼產生, +-additionalfile:<file list> 不會直接影響程式碼產生, 但分析器可用以產生錯誤或警告的 其他檔案。 -embed 在 PDB 中內嵌所有來源檔案。 --embed:<檔案清單> 在 PDB 中內嵌特定檔案。 +-embed:<file list> 在 PDB 中內嵌特定檔案。 - 資源 - --win32res:<檔案> 指定 Win32 資源檔 (.res) --win32icon:<檔案> 使用此圖示進行輸出 --win32manifest:<檔案> 指定 Win32 資訊清單檔案 (.xml) +-win32res:<file> 指定 Win32 資源檔 (.res) +-win32icon:<file> 使用此圖示進行輸出 +-win32manifest:<file> 指定 Win32 資訊清單檔案 (.xml) -nowin32manifest 不要納入預設 Win32 資訊清單 -resource:<resinfo> 內嵌指定的資源 (簡短形式: -res) -linkresource:<resinfo> 將指定的資源連結至這個組件 (簡短形式: -linkres) 其中 resinfo 的格式為 - <檔案>[,<字串名稱>[,public|private]] + <file>[,<string name>[,public|private]] - 產生程式碼 - -debug[+|-] 發出偵錯資訊 @@ -676,16 +676,16 @@ -refonly 產生代替主要輸出的參考組件 -instrument:TestCoverage 產生已檢測的組件以收集 涵蓋範圍資訊 --sourcelink:<檔案> 要內嵌至 PDB 中的來源連結資訊。 +-sourcelink:<file> 要內嵌至 PDB 中的來源連結資訊。 - 錯誤及警告 - -warnaserror[+|-] 將所有警告回報為錯誤 --warnaserror[+|-]:<警告清單> 將特定警告回報為錯誤 +-warnaserror[+|-]:<warn list> 將特定警告回報為錯誤 -warn:<n> 設定警告層級 (0-4) (簡短形式: -w) --nowarn:<警告清單> 停用特定的警告訊息 --ruleset:<檔案> 指定停用特定診斷的規則集 +-nowarn:<warn list> 停用特定的警告訊息 +-ruleset:<file> 指定停用特定診斷的規則集 檔案。 --errorlog:<檔案> 指定要記錄所有編譯器和分析器診斷的 +-errorlog:<file> 指定要記錄所有編譯器和分析器診斷的 檔案。 -reportanalyzer 回報其他分析器資訊,例如 執行時間。 @@ -693,12 +693,14 @@ - 語言 - -checked[+|-] 產生溢位核對 -unsafe[+|-] 允許 'unsafe' 程式碼 --define:<符號清單> 定義條件式編譯符號 (簡短 +-define:<symbol list> 定義條件式編譯符號 (簡短 形式: -d) -langversion:? 顯示適用於語言版本的允許值 --langversion:<字串> 指定語言版本,例如 - `default` (最新主要版本),或 - `latest` (最新版本,包括次要版本), +-langversion:<string> 指定語言版本,例如 + `latest` (最新版本,包括次要版本)、 + `default` (與 `latest` 相同)、 + `latestmajor` (最新版本,不含次要版本)、 + `preview` (最新版本,包括未支援的預覽版功能) 或特定版本如 `6` 或 `7.1` -nullable[+|-] 指定可為 Null 的內容選項 enable|disable。 -nullable:{enable|disable|warnings} @@ -709,12 +711,12 @@ 延遲簽署組件 -publicsign[+|-] 只使用強式名稱金鑰的公開 部分,公開簽署組件 --keyfile:<檔案> 指定強式名稱金鑰檔 --keycontainer:<字串> 指定強式名稱金鑰容器 +-keyfile:<file> 指定強式名稱金鑰檔 +-keycontainer:<string> 指定強式名稱金鑰容器 -highentropyva[+|-] 啟用高度 Entropy ASLR - 其他 - -@<檔案> 讀取回應檔以取得更多選項 +@<file> 讀取回應檔以取得更多選項 -help 顯示本使用方式訊息 (簡短形式: -?) -nologo 隱藏編譯器著作權訊息 -noconfig 不自動包含 CSC.RSP 檔 @@ -722,14 +724,14 @@ -version 顯示編譯器版本號碼並結束。 - 進階 - --baseaddress:<位址> 要建置的程式庫基底位址 --checksumalgorithm:<演算法> 為計算儲存在 PDB 中的原始程式檔總和檢查碼, +-baseaddress:<address> 要建置的程式庫基底位址 +-checksumalgorithm:<alg> 為計算儲存在 PDB 中的原始程式檔總和檢查碼, 指定演算法。支援的值為: SHA1 或 SHA256 (預設)。 -codepage:<n> 指定開啟原始程式檔時要使用的 字碼頁 -utf8output 以 UTF-8 編碼方式輸出編譯器訊息 --main:<類型> 指定包含進入點 +-main:<type> 指定包含進入點 (忽略所有其他可能的進入點) 的類型 (簡短 形式: -m) -fullpaths 編譯器產生完整路徑 @@ -738,30 +740,30 @@ -pathmap:<K1>=<V1>,<K2>=<V2>,... 為編譯器輸出的來源路徑名稱, 指定對應。 --pdb:<檔案> 指定偵錯資訊檔案名稱 (預設: +-pdb:<file> 指定偵錯資訊檔案名稱 (預設: 副檔名為 .pdb 的輸出檔案名稱) -errorendlocation 輸出每個錯誤之結束位置的 行與資料行 -preferreduilang 指定慣用的輸出語言名稱。 -nosdkpath 停用搜尋標準程式庫組件的預設 SDK 路徑。 -nostdlib[+|-] 不參考標準程式庫 (mscorlib.dll) --subsystemversion:<字串> 指定這個組件的子系統版本 --lib:<檔案清單> 指定要搜尋的其他目錄 +-subsystemversion:<string> 指定這個組件的子系統版本 +-lib:<file list> 指定要搜尋的其他目錄 以供參考 --errorreport:<字串> 指定如何處理內部編譯器錯誤: +-errorreport:<string> 指定如何處理內部編譯器錯誤: prompt、send、queue 或 none。預設為 queue. --appconfig:<檔案> 指定包含組件繫結設定的 +-appconfig:<file> 指定包含組件繫結設定的 應用程式組態檔 --moduleassemblyname:<字串> 將包含此模組的 +-moduleassemblyname:<string> 將包含此模組的 組件之名稱 --modulename:<字串> 指定來源模組的名稱 +-modulename:<string> 指定來源模組的名稱 Visual C# Compiler Options default interface implementation - default interface implementation + 預設介面實作 @@ -886,7 +888,7 @@ <switch expression> - <switch expression> + <切換運算式> @@ -1411,12 +1413,12 @@ The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + 可為 Null 的參考型別註釋應只用於 '#nullable' 註釋內容中的程式碼。 The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. - The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. + 可為 Null 的參考型別註釋應只用於 '#nullable' 註釋內容中的程式碼。 @@ -1581,7 +1583,7 @@ Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. - Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'. + 參數 '{1}' 之 '{0}' 型別中參考型別的可 Null 性與隱含實作的成員 '{2}' 不符合。 @@ -1631,7 +1633,7 @@ Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'. + 傳回型別 '{0}' 中參考型別的可 Null 性與隱含實作的成員 '{1}' 不符合。 @@ -1661,7 +1663,7 @@ Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. - Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'. + '{0}' 的型別中參考型別的可 Null 性與隱含實作的成員 '{1}' 不符合。 @@ -1671,12 +1673,12 @@ Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + 型別中參考型別的可 Null 性與覆寫的成員不符合。 Nullability of reference types in type doesn't match overridden member. - Nullability of reference types in type doesn't match overridden member. + 型別中參考型別的可 Null 性與覆寫的成員不符合。 @@ -1801,12 +1803,12 @@ Non-nullable {0} '{1}' is uninitialized. Consider declaring the {0} as nullable. - 不可為 Null 的型別 {0} '{1}' 未初始化。 + 不可為 null 的 {0} '{1}' 未初始化。請考慮將 {0} 宣告為可為 null。 Non-nullable field is uninitialized. Consider declaring as nullable. - 不可為 Null 的型別欄位未初始化。 + 不可為 null 的欄位未初始化。請考慮宣告為可為 null。 @@ -5829,12 +5831,12 @@ A catch() block after a catch (System.Exception e) block can catch non-CLS excep Expected 'disable' or 'restore' - 必須是 disable、restore、enable 或 safeonly + 應為 'disable' 或 'restore' Expected 'disable' or 'restore' after #pragma warning - #pragma warning 後面必須有 disable、restore、enable 或 safeonly + #pragma 警告後應有 'disable' 或 'restore' diff --git a/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs b/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs index 2d701abec16ff..4073837fbc38b 100644 --- a/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs +++ b/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs @@ -10968,7 +10968,7 @@ public void InvalidPathCharacterInPdbPath() } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] - [Fact] + [Fact(Skip = "https://github.com/dotnet/roslyn/issues/38454")] public void TestSuppression_CompilerParserWarningAsError() { string source = @" @@ -11017,7 +11017,7 @@ long M(int i) } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] - [Fact] + [Fact(Skip = "https://github.com/dotnet/roslyn/issues/38454")] public void TestSuppression_CompilerSyntaxWarning() { // warning CS1522: Empty switch block @@ -11077,7 +11077,7 @@ void M(int i) } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] - [Fact] + [Fact(Skip = "https://github.com/dotnet/roslyn/issues/38454")] public void TestSuppression_CompilerSemanticWarning() { string source = @" @@ -11180,7 +11180,7 @@ void M(UndefinedType x) { } } [WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")] - [Fact] + [Fact(Skip = "https://github.com/dotnet/roslyn/issues/38454")] public void TestSuppression_AnalyzerWarning() { string source = @" diff --git a/src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.cs b/src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.cs index 61a8e2a0580e0..a27f9ec08f813 100644 --- a/src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.cs +++ b/src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.cs @@ -10304,7 +10304,7 @@ .maxstack 2 "); } - [ConditionalFact(typeof(WindowsDesktopOnly), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/37047")] + [Fact(Skip = "https://github.com/dotnet/roslyn/issues/37047")] public void OutVar_InSwitchExpression() { var source0 = MarkedSource(@" diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.cs.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.cs.xlf index 2481a1ae8c98c..09db93e234a6c 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.cs.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.cs.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + Potlačené ID diagnostiky {0} neodpovídá potlačitelnému ID {1} pro daný popisovač potlačení. @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + Neohlášená diagnostika s ID {0} se nedá potlačit. @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + Analyzátor {0} má v SupportedSuppressions popisovač s hodnotou null. Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + Diagnostika {0}: {1} se programově potlačila pomocí DiagnosticSuppressor s ID potlačení {2} a odůvodněním {3}. Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + Programové potlačení diagnostiky analyzátoru A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + SuppressionDescriptor musí mít ID, které není null, prázdný řetězec ani řetězec obsahující jenom prázdné znaky. If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + Pokud jsou zadané anotace prvků řazené kolekce členů s možnou hodnotou null, musí se počet anotací shodovat s kardinalitou této řazené kolekce členů. @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + Ohlášené potlačení s ID {0} se v potlačovacím modulu nepodporuje. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.de.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.de.xlf index 430df93b6c63e..264ee5df4b30c 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.de.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.de.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + Die unterdrückte Diagnose-ID "{0}" entspricht nicht der unterdrückbaren ID "{1}" für den angegebenen Deskriptor zur Unterdrückung. @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + Die nicht gemeldete Diagnose mit der ID "{0}" kann nicht unterdrückt werden. @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + Das Analysetool "{0}" enthält einen NULL-Deskriptor in "SupportedDiagnostics". Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + Die Diagnose "{0}: {1}" wurde durch einen DiagnosticSuppressor mit der Unterdrückungs-ID "{2}" und der Begründung "{3}" programmgesteuert unterdrückt. Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + Programmgesteuerte Unterdrückung einer Analysetooldiagnose A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + Ein SuppressionDescriptor muss eine ID aufweisen, die weder NULL noch eine leere Zeichenfolge noch eine Zeichenfolge ist, die nur Leerzeichen enthält. If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + Wenn Nullable-Anmerkungen für Tupelelemente angegeben werden, muss die Anzahl von Anmerkungen der Kardinalität des Tupels entsprechen. @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + Die gemeldete Unterdrückung mit der ID "{0}" wird vom Unterdrückungsmodul nicht unterstützt. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.es.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.es.xlf index 1c1a36feb40a7..c0c221f3960c2 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.es.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.es.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + El id. de diagnóstico "{0}" suprimido no coincide con el id. "{1}" que se puede suprimir para el descriptor de supresión dado. @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + No se puede suprimir el diagnóstico no notificado con el id. "{0}". @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + El analizador "{0}" contiene un descriptor NULL en "SupportedDiagnostics". Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + Un elemento DiagnosticSuppressor con el id. de supresión "{2}" y la justificación "{3}" ha suprimido mediante programación el diagnóstico "{0}: {1}". Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + Supresión mediante programación de un diagnóstico del analizador A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + Un elemento SuppressionDescriptor debe tener un id. que no sea NULL, una cadena vacía ni una cadena que solo contenga un espacio en blanco. If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + Si se especifican las anotaciones que aceptan valores NULL de los elementos de tupla, el número de anotaciones debe coincidir con la cardinalidad de la tupla. @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + El supresor no admite la supresión notificada con el id. "{0}". diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.fr.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.fr.xlf index 70cc58cbedfab..25b36a3725e66 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.fr.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.fr.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + L'ID de diagnostic supprimé '{0}' ne correspond pas à l'ID supprimable '{1}' pour le descripteur de suppression spécifié. @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + Impossible de supprimer le diagnostic non signalé ayant l'ID '{0}'. @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + L'analyseur '{0}' contient un descripteur ayant une valeur null dans 'SupportedSuppressions'. Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + Le diagnostic '{0} : {1}' a été supprimé par programmation par un DiagnosticSuppressor ayant l'ID de suppression '{2}' et la justification '{3}' Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + Suppression programmatique d'un diagnostic d'analyseur A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + SuppressionDescriptor doit avoir un ID qui n'est ni une valeur null, ni une chaîne vide, ni une chaîne contenant uniquement des espaces blancs. If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + Si des annotations de type Nullable pour des éléments de tuples sont spécifiées, le nombre d'annotations doit correspondre à la cardinalité du tuple. @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + La suppression signalée ayant l'ID '{0}' n'est pas prise en charge par le suppresseur. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.it.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.it.xlf index 5c396c15d9049..e3ad1a30c35d5 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.it.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.it.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + L'ID diagnostica '{0}' eliminato non corrisponde all'ID eliminabile '{1}' per il descrittore di eliminazione specificato. @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + Non è possibile eliminare la diagnostica non restituita con ID '{0}'. @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + L'analizzatore '{0}' contiene un descrittore Null nel relativo elemento 'SupportedSuppressions'. Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + La diagnostica '{0}: {1}' è stata eliminata a livello di codice da un elemento DiagnosticSuppressor con ID eliminazione '{2}' e giustificazione '{3}' Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + Eliminazione a livello di codice di una diagnostica dell'analizzatore A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + L'ID di un elemento SuppressionDescriptor non deve essere Null, né una stringa vuota o una stringa composta solo da spazi vuoti. If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + Se si specificano annotazioni nullable di elementi di tupla, il numero delle annotazioni deve corrispondere alla cardinalità della tupla. @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + L'eliminazione restituita con ID '{0}' non è supportata dall'elemento di eliminazione. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ja.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ja.xlf index 565d411b35548..036c56c721f4f 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ja.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ja.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + 抑制された診断 ID '{0}' が、指定された抑制記述子の抑制可能な ID '{1}' と一致しません。 @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + ID '{0}' を持つ未報告の診断を抑制することはできません。 @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + アナライザー '{0}' の 'SupportedSuppressions' に null 記述子が含まれています。 Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + 診断 '{0}: {1}' は、抑制 ID '{2}' と理由 '{3}' で DiagnosticSuppressor によってプログラムで抑制されました Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + アナライザー診断のプログラムによる抑制 A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + SuppressionDescriptor では、null でも、空の文字列でも、空白のみの文字列でもない ID が必要です。 If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + タプル要素の Null 許容の注釈を指定する場合、注釈の数はタプルの基数と一致する必要があります。 @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + ID '{0}' の報告済みの抑制はサプレッサーによってサポートされていません。 diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ko.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ko.xlf index f2dcef1ddcae9..42fccfb4c41b4 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ko.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ko.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + 표시되지 않는 진단 ID '{0}'이(가) 지정된 비표시 설명자의 표시하지 않을 수 있는 ID '{1}'과(와) 일치하지 않습니다. @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + ID가 '{0}'인 보고되지 않는 진단은 표시되지 않도록 설정할 수 없습니다. @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + '{0}' 분석기의 'SupportedSuppressions'에 null 설명자가 포함되어 있습니다. Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + 진단 '{0}:{1}'은(는) 비표시 ID가 '{2}'이고 근거가 '{3}'인 DiagnosticSuppressor에서 프로그래밍 방식으로 표시되지 않았습니다. Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + 분석기 진단의 프로그래밍 방식 비표시 A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + SuppressionDescriptor에 null, 빈 문자열 및 공백만 포함된 문자열이 아닌 ID가 있어야 합니다. If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + 튜플 요소 nullable 주석이 지정된 경우, 주석 수는 튜플의 카디널리티와 일치해야 합니다. @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + ID가 '{0}'인 보고된 비표시가 억제 장치에서 지원되지 않습니다. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pl.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pl.xlf index 3f4716f204eec..9901a0832320c 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pl.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pl.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + Pominięty identyfikator diagnostyki „{0}” nie pasuje do możliwego do pominięcia identyfikatora „{1}” dla danego deskryptora pomijania. @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + Nie można pominąć niezgłoszonej diagnostyki o identyfikatorze „{0}”. @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + Analizator „{0}” zawiera deskryptor null we właściwości „SupportedSuppressions” Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + Diagnostyka „{0}: {1}” została programowo pominięta przez interfejs DiagnosticSuppressor z identyfikatorem pominięcia „{2}” i uzasadnieniem „{3}” Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + Programowe pomijanie diagnostyki analizatora A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + Interfejs DiagnosticDescriptor musi mieć identyfikator, który nie ma wartości null, nie jest ciągiem pustym ani nie jest ciągiem zawierającym tylko białe znaki. If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + Jeśli określono adnotacje elementów krotki z możliwością ustawiania wartości null, liczba adnotacji musi zgadzać się z kardynalnością krotki. @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + Zgłoszone pominięcie o identyfikatorze „{0}” nie jest obsługiwane przez eliminator. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pt-BR.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pt-BR.xlf index 523ebf8558a60..040c89cf8b3c7 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pt-BR.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.pt-BR.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + A ID de diagnóstico suprimida '{0}' não corresponde à ID suprimível '{1}' para o descritor de supressão fornecido. @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + O diagnóstico não relatado com a ID '{0}' não pode ser suprimido. @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + O analisador '{0}' contém um descritor nulo em seu 'SupportedSuppressions'. Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + O diagnóstico '{0}: {1}' foi programaticamente suprimido por meio de um DiagnosticSuppressor com a ID de supressão '{2}' e a justificativa '{3}' Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + Supressão programática de um diagnóstico do analisador A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + A ID do SuppressionDescriptor não pode ser nula, não deve ser uma cadeia de caracteres vazia nem deve ser uma cadeia de caracteres que contenha apenas espaços em branco. If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + Se as anotações anuláveis de elementos de tupla forem especificadas, o número de anotações deverá corresponder à cardinalidade da tupla. @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + O supressor não dá suporte à supressão relatada com a ID '{0}'. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ru.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ru.xlf index fc20d74601d41..0c1f4c9f32283 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ru.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.ru.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + Подавленный идентификатор диагностики "{0}" не соответствует подавленному идентификатору "{1}" для заданного дескриптора подавления. @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + Невозможно подавить невыводимую диагностику с идентификатором "{0}". @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + Анализатор "{0}" содержит дескриптор null в разделе "SupportedSuppressions". Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + Диагностика "{0}: {1}" была программно подавлена DiagnosticSuppressor с идентификатором подавления "{2}" и обоснованием "{3}" Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + Программное подавление диагностики анализатора A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + SuppressionDescriptor должен иметь идентификатор, который не является значением NULL, пустой строкой или строкой, состоящей из одного пробела. If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + Если указаны аннотации элементов кортежа, допускающих значения null, то число аннотаций должно соответствовать кратности кортежа. @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + Зарегистрированное подавление с идентификатором "{0}" не поддерживается подавителем. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.tr.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.tr.xlf index 80ebf48e831db..80c8da35c90a8 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.tr.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.tr.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + '{0}' gizlenmiş tanılama kimliği, belirtilen gizleme tanımlayıcısı için gizlenebilir '{1}' kimliği ile eşleşmiyor. @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + '{0}' kimlikli raporlanamayan tanılama gizlenemiyor. @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + '{0}' çözümleyicisi, 'SupportedSuppressions' içinde boş bir tanımlayıcı içeriyor. Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + '{0}: {1}' Tanılaması, '{2}' gizleme kimliği ve '{3}' gerekçelendirmesi ile DiagnosticSuppressor tarafından programlı bir şekilde gizlendi Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + Bir çözümleyici tanılamasının programlı bir şekilde gizlenmesi A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + SuppressionDescriptor türünün null veya boş dize ya da yalnızca boşluk içeren dize olmayan bir kimliğinin olması gerekir. If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + Demet öğelerine yönelik boş değer atanabilir ek açıklamalar belirtildiyse, ek açıklamaların sayısı demetin kardinalitesiyle eşleşmelidir. @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + '{0}' kimliği ile bildirilen gizleme, gizleyici tarafından desteklenmiyor. diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hans.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hans.xlf index c013ecad8f330..2f36f9a79f014 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hans.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hans.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + 对于给定的禁止显示描述符,禁止显示的诊断 ID“{0}”与可禁止显示的 ID“{1}”不匹配。 @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + 不可禁止显示 ID 为“{0}”的未报告的诊断。 @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + 分析器“{0}”在其 "SupportedSuppressions" 中包含 null 描述符。 Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + 具有禁止显示 ID“{2}”和理由“{3}”的 DiagnosticSuppressor 已以编程方式禁止显示诊断“{0}: {1}” Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + 以编程方式禁止显示分析器诊断 A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + A SuppressionDescriptor 必须具有一个 ID,且该 ID 不为 null、不是空字符串且不是仅包含空格的字符串。 If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + 如果已指定元组元素可以为 null 的注释,则注释的数量必须与元组基数相匹配。 @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + 抑制器不支持已报告的 ID 为“{0}”的诊断。 diff --git a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hant.xlf b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hant.xlf index 1ced7d37bd18e..b458cb9b1e72b 100644 --- a/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hant.xlf +++ b/src/Compilers/Core/Portable/xlf/CodeAnalysisResources.zh-Hant.xlf @@ -21,7 +21,7 @@ Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. - Suppressed diagnostic ID '{0}' does not match suppressable ID '{1}' for the given suppression descriptor. + 隱藏的診斷識別碼 '{0}' 不符合指定隱藏描述項的可隱藏識別碼 '{1}'。 @@ -41,7 +41,7 @@ Non-reported diagnostic with ID '{0}' cannot be suppressed. - Non-reported diagnostic with ID '{0}' cannot be suppressed. + 無法隱藏識別碼為 '{0}' 的非回報診斷。 @@ -86,27 +86,27 @@ Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. - Analyzer '{0}' contains a null descriptor in its 'SupportedSuppressions'. + 分析器 '{0}' 在其 'SupportedSuppressions' 中包含一個 null 描述項。 Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' - Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppresion ID '{2}' and justification '{3}' + 隱藏識別碼為 '{2}' 且理由為 '{3}' 的 DiagnosticSuppressor,以程式設計的方式隱藏了診斷 '{0}: {1}' Programmatic suppression of an analyzer diagnostic - Programmatic suppression of an analyzer diagnostic + 以程式設計方式隱藏分析器診斷 A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. - A SuppressionDescriptor must have an Id that is neither null nor an empty string nor a string that only contains white space. + SuppressionDescriptor 的識別碼不得為 null、空白字串或只包含空白字元的字串。 If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. - If tuple element nullable annotations are specified, the number of annotations must match the cardinality of the tuple. + 如果指定元組元素可為 Null 的註釋,註釋數目就必須符合元組的基數。 @@ -241,7 +241,7 @@ Reported suppression with ID '{0}' is not supported by the suppressor. - Reported suppression with ID '{0}' is not supported by the suppressor. + 隱藏器不支援識別碼為 '{0}' 的回報隱藏。 diff --git a/src/Compilers/Test/Utilities/CSharp/EditAndContinueTestUtilities.cs b/src/Compilers/Test/Utilities/CSharp/EditAndContinueTestUtilities.cs index afa25f0d34ab5..dd66c310aa262 100644 --- a/src/Compilers/Test/Utilities/CSharp/EditAndContinueTestUtilities.cs +++ b/src/Compilers/Test/Utilities/CSharp/EditAndContinueTestUtilities.cs @@ -27,6 +27,9 @@ public static IEnumerable InspectClosures(this EditAndContinueMethodDebu => debugInfo.Closures.IsDefault ? null : debugInfo.Closures.Select(c => $"Offset={c.SyntaxOffset} Id={c.ClosureId.Generation}#{c.ClosureId.Ordinal}"); + public static EmitBaseline GetInitialEmitBaseline(this EmitBaseline baseline) + => baseline.InitialBaseline; + #endregion } } diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.es.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.es.xlf index 9ab7e47600032..43cbcf8b549db 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.es.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.es.xlf @@ -6054,7 +6054,7 @@ Property or event implicitly declares member, which conflicts with a member implicitly declared for property or event in the base type - La propiedad o el evento declaran implícitamente al miembro, lo que es incompatible con la declaración implícita de un miembro para la propiedad o el evento del tipo base + La propiedad o el evento declaran implícitamente al miembro, lo que crea un conflicto con la declaración implícita de un miembro para la propiedad o el evento del tipo base diff --git a/src/Compilers/VisualBasic/Portable/xlf/VBResources.pt-BR.xlf b/src/Compilers/VisualBasic/Portable/xlf/VBResources.pt-BR.xlf index f29b325de890e..e70b6ef52f6e5 100644 --- a/src/Compilers/VisualBasic/Portable/xlf/VBResources.pt-BR.xlf +++ b/src/Compilers/VisualBasic/Portable/xlf/VBResources.pt-BR.xlf @@ -3375,7 +3375,7 @@ {0} '{1}' conflicts with a Visual Basic Runtime {2} '{3}'. - {0} "{1}" está em conflito com um Tempo de Execução do Visual Basic {2} "{3}". + {0} '{1}' está em conflito com um Visual Basic Runtime {2} '{3}'. @@ -5227,7 +5227,7 @@ Requested operation is not available because the runtime library function '{0}' is not defined. - Operação solicitada não está disponível porque a função de biblioteca de tempo de execução "{0}" não está definida. + Operação solicitada não está disponível porque a função de biblioteca em tempo de execução "{0}" não está definida. @@ -6548,7 +6548,7 @@ Operands of type Object used for operator '{0}'; runtime errors could occur. - Operandos do tipo objeto usados pelo operador "{0}"; erros de tempo de execução poderiam ocorrer. + Operandos do tipo objeto usados pelo operador "{0}"; erros de runtime poderiam ocorrer. @@ -6658,7 +6658,7 @@ Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. - Variável "{0}" é passada por referência antes de receber um valor. Uma exceção de referência nula poderia resultar em tempo de execução. + Variável "{0}" é passada por referência antes de receber um valor. Uma exceção de referência nula poderia resultar em runtime. @@ -6778,7 +6778,7 @@ Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime. - Variável "{0}" é usada antes de receber um valor. Uma exceção de referência nula poderia resultar em tempo de execução. + Variável "{0}" é usada antes de receber um valor. Uma exceção de referência nula poderia resultar em runtime. @@ -6818,7 +6818,7 @@ Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use - Variável "{0}" é passada por referência antes de receber um valor. Uma exceção de referência nula poderia resultar em tempo de execução. Certifique-se que a estrutura ou todos os membros de referência são inicializados antes do uso + Variável "{0}" é passada por referência antes de receber um valor. Uma exceção de referência nula poderia resultar em runtime. Certifique-se que a estrutura ou todos os membros de referência são inicializados antes do uso @@ -6828,7 +6828,7 @@ Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use - Variável "{0}" é usada antes de receber um valor. Uma exceção de referência nula poderia resultar em tempo de execução. Certifique-se que a estrutura ou todos os membros de referência são inicializados antes do uso + Variável "{0}" é usada antes de receber um valor. Uma exceção de referência nula poderia resultar em runtime. Certifique-se que a estrutura ou todos os membros de referência são inicializados antes do uso @@ -7078,7 +7078,7 @@ Runtime errors might occur when converting '{0}' to '{1}'. - Podem ocorrer erros de tempo de execução ao converter "{0}" para "{1}". + Podem ocorrer erros de runtime ao converter '{0}' para '{1}'. @@ -8150,7 +8150,7 @@ Event '{0}' cannot implement a Windows Runtime event '{1}' and a regular .NET event '{2}' - Evento "{0}" não pode implementar um evento de Tempo de Execução do Windows "{1}" e um evento .NET regular "{2}" + Evento '{0}' não pode implementar um evento de Windows Runtime '{1}' e um evento .NET regular '{2}' @@ -8165,17 +8165,17 @@ In a Windows Runtime event, the type of the 'RemoveHandler' method parameter must be 'EventRegistrationToken' - Em um evento do Tempo de Execução do Windows, o tipo do parâmetro do método 'RemoveHandler' deve ser 'EventRegistrationToken' + Em um evento do Windows Runtime, o tipo do parâmetro do método 'RemoveHandler' deve ser 'EventRegistrationToken' '{0}.{1}' from 'implements {2}' is already implemented by the base class '{3}'. Re-implementation of Windows Runtime Interface '{4}' is not allowed - '{0}.{1}' de 'implementa {2}' já foi implementado pela classe base '{3}'. A reimplementação da Interface do Tempo de Execução do Windows '{4}' não é permitida + '{0}.{1}' de 'implementa {2}' já foi implementado pela classe base '{3}'. A reimplementação da Interface do Windows Runtime '{4}' não é permitida '{0}.{1}' is already implemented by the base class '{2}'. Re-implementation of Windows Runtime Interface '{3}' is not allowed - '{0}.{1}' já foi implementado pela classe base '{2}'. A reimplementação da Interface do Tempo de Execução do Windows '{3}' não é permitida + '{0}.{1}' já foi implementado pela classe base '{2}'. A reimplementação da Interface do Windows Runtime '{3}' não é permitida @@ -8210,12 +8210,12 @@ The AddHandler for Windows Runtime event '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement? - O AddHandler para evento de Tempo de Execução do Windows "{0}" não retorna um valor em todos os caminhos de código. Está faltando uma instrução "Return"? + O AddHandler para evento de Windows Runtime '{0}' não retorna um valor em todos os caminhos de código. Está faltando uma instrução 'Return'? The AddHandler for Windows Runtime event doesn't return a value on all code paths - O AddHandler para Tempo de Execução do Windows não retorna um valor em todos os caminhos de código + O AddHandler para Windows Runtime não retorna um valor em todos os caminhos de código @@ -8250,7 +8250,7 @@ Attribute '{0}' given in a source file conflicts with option '{1}'. - Atributo "{0}" fornecido em um arquivo de origem com a opção "{1}". + O atributo '{0}' fornecido em um arquivo de origem conflita com a opção '{1}'. diff --git a/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb b/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb index 2ae614f62a649..6580992e9b493 100644 --- a/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb +++ b/src/Compilers/VisualBasic/Test/CommandLine/CommandLineTests.vb @@ -9338,7 +9338,7 @@ End Class").Path End Sub - + Public Sub TestSuppression_CompilerWarning() ' warning BC40008 : 'C' is obsolete Dim source = " @@ -9383,7 +9383,7 @@ End Class" End Sub - + Public Sub TestSuppression_CompilerWarningAsError() ' warning BC40008 : 'C' is obsolete Dim source = " @@ -9461,7 +9461,7 @@ End Class" End Sub - + Public Sub TestSuppression_AnalyzerWarning() Dim source = " Class C diff --git a/src/EditorFeatures/CSharp.Wpf/Microsoft.CodeAnalysis.CSharp.EditorFeatures.Wpf.csproj b/src/EditorFeatures/CSharp.Wpf/Microsoft.CodeAnalysis.CSharp.EditorFeatures.Wpf.csproj index a6462dc4ea1f2..87d6b93db80d1 100644 --- a/src/EditorFeatures/CSharp.Wpf/Microsoft.CodeAnalysis.CSharp.EditorFeatures.Wpf.csproj +++ b/src/EditorFeatures/CSharp.Wpf/Microsoft.CodeAnalysis.CSharp.EditorFeatures.Wpf.csproj @@ -32,7 +32,9 @@ + + diff --git a/src/EditorFeatures/CSharp/ChangeSignature/CSharpChangeSignatureCommandHandler.cs b/src/EditorFeatures/CSharp/ChangeSignature/CSharpChangeSignatureCommandHandler.cs index 844d4fd35e2dc..280f09546461a 100644 --- a/src/EditorFeatures/CSharp/ChangeSignature/CSharpChangeSignatureCommandHandler.cs +++ b/src/EditorFeatures/CSharp/ChangeSignature/CSharpChangeSignatureCommandHandler.cs @@ -2,6 +2,7 @@ using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.ChangeSignature; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; @@ -13,7 +14,8 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.ChangeSignature internal class CSharpChangeSignatureCommandHandler : AbstractChangeSignatureCommandHandler { [ImportingConstructor] - public CSharpChangeSignatureCommandHandler() + public CSharpChangeSignatureCommandHandler(IThreadingContext threadingContext) + : base(threadingContext) { } } diff --git a/src/EditorFeatures/CSharp/EncapsulateField/EncapsulateFieldCommandHandler.cs b/src/EditorFeatures/CSharp/EncapsulateField/EncapsulateFieldCommandHandler.cs index 4b6b0c8739723..bfd7b1fa359de 100644 --- a/src/EditorFeatures/CSharp/EncapsulateField/EncapsulateFieldCommandHandler.cs +++ b/src/EditorFeatures/CSharp/EncapsulateField/EncapsulateFieldCommandHandler.cs @@ -1,9 +1,8 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; -using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.EncapsulateField; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; @@ -19,9 +18,10 @@ internal class EncapsulateFieldCommandHandler : AbstractEncapsulateFieldCommandH { [ImportingConstructor] public EncapsulateFieldCommandHandler( + IThreadingContext threadingContext, ITextBufferUndoManagerProvider undoManager, IAsynchronousOperationListenerProvider listenerProvider) - : base(undoManager, listenerProvider) + : base(threadingContext, undoManager, listenerProvider) { } } diff --git a/src/EditorFeatures/CSharp/ExtractMethod/ExtractMethodCommandHandler.cs b/src/EditorFeatures/CSharp/ExtractMethod/ExtractMethodCommandHandler.cs index 438746bf80fb5..01037f565234c 100644 --- a/src/EditorFeatures/CSharp/ExtractMethod/ExtractMethodCommandHandler.cs +++ b/src/EditorFeatures/CSharp/ExtractMethod/ExtractMethodCommandHandler.cs @@ -2,6 +2,7 @@ using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Implementation.ExtractMethod; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; @@ -17,10 +18,10 @@ internal class ExtractMethodCommandHandler : { [ImportingConstructor] public ExtractMethodCommandHandler( + IThreadingContext threadingContext, ITextBufferUndoManagerProvider undoManager, - IEditorOperationsFactoryService editorOperationsFactoryService, - IInlineRenameService renameService) - : base(undoManager, editorOperationsFactoryService, renameService) + IInlineRenameService renameService) + : base(threadingContext, undoManager, renameService) { } } diff --git a/src/EditorFeatures/CSharp/Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj b/src/EditorFeatures/CSharp/Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj index 0ea28e4eb83d2..dbf7ded213c38 100644 --- a/src/EditorFeatures/CSharp/Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj +++ b/src/EditorFeatures/CSharp/Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj @@ -46,6 +46,7 @@ + diff --git a/src/EditorFeatures/CSharpTest/ChangeSignature/RemoveParametersTests.cs b/src/EditorFeatures/CSharpTest/ChangeSignature/RemoveParametersTests.cs index 227cdab3942ee..e38210d5534aa 100644 --- a/src/EditorFeatures/CSharpTest/ChangeSignature/RemoveParametersTests.cs +++ b/src/EditorFeatures/CSharpTest/ChangeSignature/RemoveParametersTests.cs @@ -7,6 +7,7 @@ using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.CSharp.ChangeSignature; using Microsoft.CodeAnalysis.Editor.Implementation.Interactive; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; @@ -295,7 +296,7 @@ class C var textView = workspace.Documents.Single().GetTextView(); - var handler = new CSharpChangeSignatureCommandHandler(); + var handler = new CSharpChangeSignatureCommandHandler(workspace.GetService()); var state = handler.GetCommandState(new RemoveParametersCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); diff --git a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs index 1a8ab2e0e8301..a3b1d320c46a6 100644 --- a/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs +++ b/src/EditorFeatures/CSharpTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.cs @@ -1280,7 +1280,7 @@ class C var markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.CSharp); await VerifyTypeImportItemIsAbsentAsync(markup, "Bar", inlineDescription: "NS1"); } - + private static void AssertRelativeOrder(List expectedTypesInRelativeOrder, ImmutableArray allCompletionItems) { var hashset = new HashSet(expectedTypesInRelativeOrder); diff --git a/src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs b/src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs index a7a79344b7b10..1be43d2a5d2fa 100644 --- a/src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs +++ b/src/EditorFeatures/CSharpTest/EditAndContinue/CSharpEditAndContinueAnalyzerTests.cs @@ -427,7 +427,7 @@ public static void Main() Assert.False(result.HasChanges); Assert.False(result.HasChangesAndErrors); Assert.False(result.HasChangesAndCompilationErrors); - Assert.True(result.RudeEditErrors.IsDefaultOrEmpty); + Assert.True(result.RudeEditErrors.IsEmpty); } } diff --git a/src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.cs index 8872340539e70..775867d010c0c 100644 --- a/src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.cs +++ b/src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.cs @@ -4,6 +4,7 @@ using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.CSharp.EncapsulateField; using Microsoft.CodeAnalysis.Editor.Implementation.Interactive; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.TestHooks; @@ -214,8 +215,10 @@ class C var textView = workspace.Documents.Single().GetTextView(); - var handler = new EncapsulateFieldCommandHandler(workspace.GetService(), - workspace.ExportProvider.GetExportedValue()); + var handler = new EncapsulateFieldCommandHandler( + workspace.GetService(), + workspace.GetService(), + workspace.GetService()); var state = handler.GetCommandState(new EncapsulateFieldCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); diff --git a/src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldTestState.cs b/src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldTestState.cs index 07b494cfbb336..607b2859bf969 100644 --- a/src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldTestState.cs +++ b/src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldTestState.cs @@ -7,6 +7,7 @@ using Microsoft.CodeAnalysis.Editor.CSharp.EncapsulateField; using Microsoft.CodeAnalysis.Editor.Implementation.Notification; using Microsoft.CodeAnalysis.Editor.Shared; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; @@ -58,8 +59,10 @@ public static EncapsulateFieldTestState Create(string markup) public void Encapsulate() { var args = new EncapsulateFieldCommandArgs(_testDocument.GetTextView(), _testDocument.GetTextBuffer()); - var commandHandler = new EncapsulateFieldCommandHandler(Workspace.GetService(), - Workspace.ExportProvider.GetExportedValue()); + var commandHandler = new EncapsulateFieldCommandHandler( + Workspace.GetService(), + Workspace.GetService(), + Workspace.GetService()); commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()); } diff --git a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.cs b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.cs index 47d0dde9e4ba7..1b8eef4ec4cfa 100644 --- a/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.cs +++ b/src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.cs @@ -8,6 +8,7 @@ using Microsoft.CodeAnalysis.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.Editor.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.Editor.Implementation.Interactive; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ExtractMethod; @@ -10371,8 +10372,8 @@ public void ExtractMethodCommandDisabledInSubmission() var textView = workspace.Documents.Single().GetTextView(); var handler = new ExtractMethodCommandHandler( + workspace.GetService(), workspace.GetService(), - workspace.GetService(), workspace.GetService()); var state = handler.GetCommandState(new ExtractMethodCommandArgs(textView, textView.TextBuffer)); diff --git a/src/EditorFeatures/CSharpTest/ExtractMethod/MiscTests.cs b/src/EditorFeatures/CSharpTest/ExtractMethod/MiscTests.cs index c218825c8dcd4..562e15a7373e5 100644 --- a/src/EditorFeatures/CSharpTest/ExtractMethod/MiscTests.cs +++ b/src/EditorFeatures/CSharpTest/ExtractMethod/MiscTests.cs @@ -5,6 +5,7 @@ using Microsoft.CodeAnalysis.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.Editor.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.Editor.Host; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ExtractMethod; @@ -142,9 +143,9 @@ public void TestExtractMethodCommandHandlerErrorMessage() callBackService.NotificationCallback = (t, m, s) => called = true; var handler = new ExtractMethodCommandHandler( - workspace.ExportProvider.GetExportedValue(), - workspace.ExportProvider.GetExportedValue(), - workspace.ExportProvider.GetExportedValue()); + workspace.GetService(), + workspace.GetService(), + workspace.GetService()); handler.ExecuteCommand(new ExtractMethodCommandArgs(view, view.TextBuffer), TestCommandExecutionContext.Create()); diff --git a/src/EditorFeatures/CSharpTest/Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.csproj b/src/EditorFeatures/CSharpTest/Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.csproj index f6a983267f9e1..cca0c0d6a95ef 100644 --- a/src/EditorFeatures/CSharpTest/Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.csproj +++ b/src/EditorFeatures/CSharpTest/Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.csproj @@ -64,6 +64,7 @@ + diff --git a/src/EditorFeatures/CSharpTest/Organizing/OrganizeTypeDeclarationTests.cs b/src/EditorFeatures/CSharpTest/Organizing/OrganizeTypeDeclarationTests.cs index 8b56e0bff0a58..106eda2321ad3 100644 --- a/src/EditorFeatures/CSharpTest/Organizing/OrganizeTypeDeclarationTests.cs +++ b/src/EditorFeatures/CSharpTest/Organizing/OrganizeTypeDeclarationTests.cs @@ -6,6 +6,7 @@ using Microsoft.CodeAnalysis.Editor.Commanding.Commands; using Microsoft.CodeAnalysis.Editor.Implementation.Interactive; using Microsoft.CodeAnalysis.Editor.Implementation.Organizing; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; @@ -1097,7 +1098,7 @@ class C var textView = workspace.Documents.Single().GetTextView(); - var handler = new OrganizeDocumentCommandHandler(); + var handler = new OrganizeDocumentCommandHandler(exportProvider.GetExportedValue()); var state = handler.GetCommandState(new SortAndRemoveUnnecessaryImportsCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); diff --git a/src/EditorFeatures/CSharpTest2/Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests.csproj b/src/EditorFeatures/CSharpTest2/Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests.csproj index cc9a7c3079beb..858ee909ebdb7 100644 --- a/src/EditorFeatures/CSharpTest2/Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests.csproj +++ b/src/EditorFeatures/CSharpTest2/Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests.csproj @@ -49,6 +49,8 @@ + + diff --git a/src/EditorFeatures/Core.Wpf/InlineRename/CommandHandlers/RenameCommandHandler.cs b/src/EditorFeatures/Core.Wpf/InlineRename/CommandHandlers/RenameCommandHandler.cs index ccb32fd4a88c6..f9a2ea1e358fb 100644 --- a/src/EditorFeatures/Core.Wpf/InlineRename/CommandHandlers/RenameCommandHandler.cs +++ b/src/EditorFeatures/Core.Wpf/InlineRename/CommandHandlers/RenameCommandHandler.cs @@ -4,9 +4,9 @@ using System.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding; -using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; @@ -25,16 +25,16 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename [Order(Before = PredefinedCommandHandlerNames.EncapsulateField)] internal partial class RenameCommandHandler { + private readonly IThreadingContext _threadingContext; private readonly InlineRenameService _renameService; - private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; [ImportingConstructor] public RenameCommandHandler( - InlineRenameService renameService, - IEditorOperationsFactoryService editorOperationsFactoryService) + IThreadingContext threadingContext, + InlineRenameService renameService) { + _threadingContext = threadingContext; _renameService = renameService; - _editorOperationsFactoryService = editorOperationsFactoryService; } public string DisplayName => EditorFeaturesResources.Rename; diff --git a/src/EditorFeatures/Core.Wpf/InlineRename/CommandHandlers/RenameCommandHandler_RenameHandler.cs b/src/EditorFeatures/Core.Wpf/InlineRename/CommandHandlers/RenameCommandHandler_RenameHandler.cs index a6fc3ae84822e..faad437173e9d 100644 --- a/src/EditorFeatures/Core.Wpf/InlineRename/CommandHandlers/RenameCommandHandler_RenameHandler.cs +++ b/src/EditorFeatures/Core.Wpf/InlineRename/CommandHandlers/RenameCommandHandler_RenameHandler.cs @@ -1,14 +1,10 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; using System.Linq; -using System.Threading; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; -using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Notification; -using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; @@ -77,8 +73,8 @@ private void ExecuteRenameWorker(RenameCommandArgs args, CommandExecutionContext } var cancellationToken = context.OperationContext.UserCancellationToken; - var document = args.SubjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync( - context.OperationContext).WaitAndGetResult(cancellationToken); + var document = args.SubjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( + context.OperationContext, _threadingContext); if (document == null) { ShowErrorDialog(workspace, EditorFeaturesResources.You_must_rename_an_identifier); diff --git a/src/EditorFeatures/Core.Wpf/Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj b/src/EditorFeatures/Core.Wpf/Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj index 53965efb364c6..3307e8dccc803 100644 --- a/src/EditorFeatures/Core.Wpf/Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj +++ b/src/EditorFeatures/Core.Wpf/Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj @@ -47,6 +47,7 @@ + diff --git a/src/EditorFeatures/Core.Wpf/NavigateTo/NavigateToItemProvider.Searcher.cs b/src/EditorFeatures/Core.Wpf/NavigateTo/NavigateToItemProvider.Searcher.cs index c5757d889a93b..94cb04c4d1a72 100644 --- a/src/EditorFeatures/Core.Wpf/NavigateTo/NavigateToItemProvider.Searcher.cs +++ b/src/EditorFeatures/Core.Wpf/NavigateTo/NavigateToItemProvider.Searcher.cs @@ -6,9 +6,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.NavigateTo; -using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text.Shared.Extensions; @@ -91,7 +91,18 @@ internal async Task SearchAsync() } finally { - _callback.Done(); + var service = _solution.Workspace.Services.GetService(); + if (_callback is INavigateToCallback2 callback2 && + !await service.IsFullyLoadedAsync(_cancellationToken).ConfigureAwait(false)) + { + // providing this extra information will make UI to show indication to users + // that result might not contain full data + callback2.Done(IncompleteReason.SolutionLoading); + } + else + { + _callback.Done(); + } } } diff --git a/src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActionsSource.cs b/src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActionsSource.cs index 7d7915b4f44f9..48e34a3282af5 100644 --- a/src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActionsSource.cs +++ b/src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActionsSource.cs @@ -9,7 +9,6 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared; @@ -169,7 +168,9 @@ public IEnumerable GetSuggestedActions( // IWaitIndicator abstraction (which is a thin wrapper on top of IVsThreadedWaitDialog) directly // for now, we use the one LB created before calling us. meaning we don't update // text on the wait dialog window - _workspaceStatusService.WaitUntilFullyLoadedAsync(cancellationToken).Wait(cancellationToken); + // + // this also needs to run under threading context otherwise, we can deadlock on VS + ThreadingContext.JoinableTaskFactory.Run(() => _workspaceStatusService.WaitUntilFullyLoadedAsync(cancellationToken)); } using (Logger.LogBlock(FunctionId.SuggestedActions_GetSuggestedActions, cancellationToken)) @@ -349,7 +350,7 @@ private ImmutableArray GetCodeFixes( var fixes = Task.Run( () => _owner._codeFixService.GetFixesAsync( - document, range.Span.ToTextSpan(), includeSuppressionFixes, cancellationToken), + document, range.Span.ToTextSpan(), includeSuppressionFixes, isBlocking: true, cancellationToken), cancellationToken).WaitAndGetResult(cancellationToken); var filteredFixes = FilterOnUIThread(fixes, workspace); @@ -751,7 +752,7 @@ private ImmutableArray GetRefactorings( // the UI thread. var refactorings = Task.Run( () => _owner._codeRefactoringService.GetRefactoringsAsync( - document, selection, cancellationToken), + document, selection, isBlocking: true, cancellationToken), cancellationToken).WaitAndGetResult(cancellationToken); var filteredRefactorings = FilterOnUIThread(refactorings, workspace); @@ -1028,7 +1029,7 @@ private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e) OnSuggestedActionsChanged(e.Workspace, e.DocumentId, e.Solution.WorkspaceVersion); } - private void OnWorkspaceStatusChanged(object sender, bool fullyLoaded) + private void OnWorkspaceStatusChanged(object sender, EventArgs args) { var document = _subjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); if (document == null) diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.cs.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.cs.xlf index 510523352d641..f74ffc4930a1c 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.cs.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.cs.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + Nakonfigurovat nebo potlačit problémy diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.de.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.de.xlf index da9653117d5c9..b7911bccea813 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.de.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.de.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + Issues konfigurieren oder unterdrücken diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.es.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.es.xlf index 55a63223058f0..3e90eefbd708e 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.es.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.es.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + Configurar o suprimir incidencias diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.fr.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.fr.xlf index 5ff0a1c821111..50298ab515e52 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.fr.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.fr.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + Problèmes de configuration ou de suppression diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.it.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.it.xlf index 3c8e61751068d..c014a40601096 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.it.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.it.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + Configura o elimina problemi diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ja.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ja.xlf index 46030a72962b2..ed13293fce367 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ja.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ja.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + 問題の構成または抑制 diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ko.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ko.xlf index 2b6e21e074730..85cea0699d729 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ko.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ko.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + 문제 구성 또는 표시 안 함 diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pl.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pl.xlf index 035426943387f..0106db1912d0a 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pl.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pl.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + Konfiguruj lub pomijaj problemy diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pt-BR.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pt-BR.xlf index 8b52d5195cbca..e5f9689fa36cd 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pt-BR.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.pt-BR.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + Configurar ou Suprimir problemas diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ru.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ru.xlf index 9354c3b88f325..372fa1fddd1fb 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ru.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.ru.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + Настройка или подавление проблем diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.tr.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.tr.xlf index 141d070195ef3..593c1aa449640 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.tr.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.tr.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + Sorunları Yapılandır veya Gizle diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hans.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hans.xlf index 80f3fa7583759..1f070da57fb5b 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hans.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hans.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + 配置或禁止显示问题 diff --git a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hant.xlf b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hant.xlf index a6d53339ff925..d619c27b4628c 100644 --- a/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hant.xlf +++ b/src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.zh-Hant.xlf @@ -4,7 +4,7 @@ Configure or Suppress issues - Configure or Suppress issues + 設定或隱藏問題 diff --git a/src/EditorFeatures/Core/EditorFeaturesResources.Designer.cs b/src/EditorFeatures/Core/EditorFeaturesResources.Designer.cs index 4ad7bafba7b91..b42376b527eef 100644 --- a/src/EditorFeatures/Core/EditorFeaturesResources.Designer.cs +++ b/src/EditorFeatures/Core/EditorFeaturesResources.Designer.cs @@ -701,6 +701,24 @@ internal static string Execute_In_Interactive { } } + /// + /// Looks up a localized string similar to items from unimported namespaces. + /// + internal static string Expander_display_text { + get { + return ResourceManager.GetString("Expander_display_text", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expander. + /// + internal static string Expander_image_element { + get { + return ResourceManager.GetString("Expander_image_element", resourceCulture); + } + } + /// /// Looks up a localized string similar to Extract Interface. /// @@ -1936,36 +1954,32 @@ internal static string Toggle_Block_Comment { } /// - /// Looks up a localized string similar to Toggling block comment.... + /// Looks up a localized string similar to Toggle Line Comment. /// - internal static string Toggling_block_comment { + internal static string Toggle_Line_Comment { get { - return ResourceManager.GetString("Toggling_block_comment", resourceCulture); + return ResourceManager.GetString("Toggle_Line_Comment", resourceCulture); } } - + /// - /// Looks up a localized string similar to Toggle Line Comment. + /// Looks up a localized string similar to Toggling block comment.... /// - internal static string Toggle_Line_Comment - { - get - { - return ResourceManager.GetString("Toggle_Line_Comment", resourceCulture); + internal static string Toggling_block_comment { + get { + return ResourceManager.GetString("Toggling_block_comment", resourceCulture); } } - + /// /// Looks up a localized string similar to Toggling line comment.... /// - internal static string Toggling_line_comment - { - get - { + internal static string Toggling_line_comment { + get { return ResourceManager.GetString("Toggling_line_comment", resourceCulture); } } - + /// /// Looks up a localized string similar to Type Parts. /// diff --git a/src/EditorFeatures/Core/EditorFeaturesResources.resx b/src/EditorFeatures/Core/EditorFeaturesResources.resx index 835dc521debcd..602371ec92801 100644 --- a/src/EditorFeatures/Core/EditorFeaturesResources.resx +++ b/src/EditorFeatures/Core/EditorFeaturesResources.resx @@ -917,4 +917,10 @@ Do you want to proceed? Toggling line comment... + + items from unimported namespaces + + + Expander + diff --git a/src/EditorFeatures/Core/GoToImplementation/GoToImplementationCommandHandler.cs b/src/EditorFeatures/Core/GoToImplementation/GoToImplementationCommandHandler.cs index 9f1aa1e2f86d8..103a1cdbbc463 100644 --- a/src/EditorFeatures/Core/GoToImplementation/GoToImplementationCommandHandler.cs +++ b/src/EditorFeatures/Core/GoToImplementation/GoToImplementationCommandHandler.cs @@ -7,6 +7,7 @@ using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; @@ -14,7 +15,6 @@ using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Utilities; -using Roslyn.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; namespace Microsoft.CodeAnalysis.Editor.GoToImplementation @@ -24,12 +24,16 @@ namespace Microsoft.CodeAnalysis.Editor.GoToImplementation [Name(PredefinedCommandHandlerNames.GoToImplementation)] internal partial class GoToImplementationCommandHandler : VSCommanding.ICommandHandler { + private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingPresenter; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] - public GoToImplementationCommandHandler(IStreamingFindUsagesPresenter streamingPresenter) + public GoToImplementationCommandHandler( + IThreadingContext threadingContext, + IStreamingFindUsagesPresenter streamingPresenter) { + _threadingContext = threadingContext; _streamingPresenter = streamingPresenter; } @@ -61,8 +65,8 @@ public bool ExecuteCommand(GoToImplementationCommandArgs args, CommandExecutionC var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (caret.HasValue) { - var document = subjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync( - context.OperationContext).WaitAndGetResult(context.OperationContext.UserCancellationToken); + var document = subjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( + context.OperationContext, _threadingContext); if (document != null) { ExecuteCommand(document, caret.Value, findUsagesService, context); diff --git a/src/EditorFeatures/Core/Implementation/ChangeSignature/AbstractChangeSignatureCommandHandler.cs b/src/EditorFeatures/Core/Implementation/ChangeSignature/AbstractChangeSignatureCommandHandler.cs index eb3909c5f88f4..8c52abd8dfd4e 100644 --- a/src/EditorFeatures/Core/Implementation/ChangeSignature/AbstractChangeSignatureCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/ChangeSignature/AbstractChangeSignatureCommandHandler.cs @@ -2,17 +2,15 @@ using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Editor.Host; -using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; -using Roslyn.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; namespace Microsoft.CodeAnalysis.Editor.Implementation.ChangeSignature @@ -20,6 +18,13 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.ChangeSignature internal abstract class AbstractChangeSignatureCommandHandler : VSCommanding.ICommandHandler, VSCommanding.ICommandHandler { + private readonly IThreadingContext _threadingContext; + + protected AbstractChangeSignatureCommandHandler(IThreadingContext threadingContext) + { + _threadingContext = threadingContext; + } + public string DisplayName => EditorFeaturesResources.Change_Signature; public VSCommanding.CommandState GetCommandState(ReorderParametersCommandArgs args) @@ -57,8 +62,8 @@ private bool ExecuteCommand(ITextView textView, ITextBuffer subjectBuffer, Comma return false; } - var document = subjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync( - context.OperationContext).WaitAndGetResult(context.OperationContext.UserCancellationToken); + var document = subjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( + context.OperationContext, _threadingContext); if (document == null) { return false; diff --git a/src/EditorFeatures/Core/Implementation/CodeFixes/CodeFixService.cs b/src/EditorFeatures/Core/Implementation/CodeFixes/CodeFixService.cs index 5d0ecce1661a4..1c3489831af71 100644 --- a/src/EditorFeatures/Core/Implementation/CodeFixes/CodeFixService.cs +++ b/src/EditorFeatures/Core/Implementation/CodeFixes/CodeFixService.cs @@ -139,7 +139,12 @@ private async Task GetFirstDiagnosticWithFixAsync( return null; } - public async Task> GetFixesAsync(Document document, TextSpan range, bool includeConfigurationFixes, CancellationToken cancellationToken) + public Task> GetFixesAsync(Document document, TextSpan range, bool includeConfigurationFixes, CancellationToken cancellationToken) + { + return ((ICodeFixService)this).GetFixesAsync(document, range, includeConfigurationFixes, isBlocking: false, cancellationToken); + } + + async Task> ICodeFixService.GetFixesAsync(Document document, TextSpan range, bool includeConfigurationFixes, bool isBlocking, CancellationToken cancellationToken) { // REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back // current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information @@ -170,7 +175,7 @@ public async Task> GetFixesAsync(Document docu foreach (var spanAndDiagnostic in aggregatedDiagnostics) { await AppendFixesAsync( - document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, fixAllForInSpan: false, + document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, fixAllForInSpan: false, isBlocking, result, cancellationToken).ConfigureAwait(false); } @@ -221,7 +226,7 @@ public async Task GetDocumentFixAllForIdInSpanAsync(Document } using var resultDisposer = ArrayBuilder.GetInstance(out var result); - await AppendFixesAsync(document, range, diagnostics, fixAllForInSpan: true, result, cancellationToken).ConfigureAwait(false); + await AppendFixesAsync(document, range, diagnostics, fixAllForInSpan: true, isBlocking: false, result, cancellationToken).ConfigureAwait(false); // TODO: Just get the first fix for now until we have a way to config user's preferred fix // https://github.com/dotnet/roslyn/issues/27066 @@ -253,6 +258,7 @@ private async Task AppendFixesAsync( TextSpan span, IEnumerable diagnostics, bool fixAllForInSpan, + bool isBlocking, ArrayBuilder result, CancellationToken cancellationToken) { @@ -308,12 +314,12 @@ await AppendFixesOrConfigurationsAsync( if (fixAllForInSpan) { var primaryDiagnostic = dxs.First(); - return GetCodeFixesAsync(document, primaryDiagnostic.Location.SourceSpan, fixer, ImmutableArray.Create(primaryDiagnostic), cancellationToken); + return GetCodeFixesAsync(document, primaryDiagnostic.Location.SourceSpan, fixer, isBlocking, ImmutableArray.Create(primaryDiagnostic), cancellationToken); } else { - return GetCodeFixesAsync(document, span, fixer, dxs, cancellationToken); + return GetCodeFixesAsync(document, span, fixer, isBlocking, dxs, cancellationToken); } }, cancellationToken: cancellationToken).ConfigureAwait(false); @@ -324,7 +330,7 @@ await AppendFixesOrConfigurationsAsync( } private async Task> GetCodeFixesAsync( - Document document, TextSpan span, CodeFixProvider fixer, + Document document, TextSpan span, CodeFixProvider fixer, bool isBlocking, ImmutableArray diagnostics, CancellationToken cancellationToken) { using var fixesDisposer = ArrayBuilder.GetInstance(out var fixes); @@ -339,6 +345,7 @@ private async Task> GetCodeFixesAsync( } }, verifyArguments: false, + isBlocking, cancellationToken: cancellationToken); var task = fixer.RegisterCodeFixesAsync(context) ?? Task.CompletedTask; diff --git a/src/EditorFeatures/Core/Implementation/CommentSelection/CommentUncommentSelectionCommandHandler.cs b/src/EditorFeatures/Core/Implementation/CommentSelection/CommentUncommentSelectionCommandHandler.cs index ec1d617861228..f623bd41c994a 100644 --- a/src/EditorFeatures/Core/Implementation/CommentSelection/CommentUncommentSelectionCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/CommentSelection/CommentUncommentSelectionCommandHandler.cs @@ -264,7 +264,7 @@ private void UncommentContainingBlockComment(CommentSelectionInfo info, Snapshot } private void UncommentPosition(CommentSelectionInfo info, SnapshotSpan span, ArrayBuilder textChanges, - ArrayBuilder spansToSelect,int positionOfStart, int positionOfEnd) + ArrayBuilder spansToSelect, int positionOfStart, int positionOfEnd) { if (positionOfStart < 0 || positionOfEnd < 0) { diff --git a/src/EditorFeatures/Core/Implementation/EditAndContinue/ActiveStatementTrackingService.cs b/src/EditorFeatures/Core/Implementation/EditAndContinue/ActiveStatementTrackingService.cs index 92f6a3d013d7b..a0694957d06e4 100644 --- a/src/EditorFeatures/Core/Implementation/EditAndContinue/ActiveStatementTrackingService.cs +++ b/src/EditorFeatures/Core/Implementation/EditAndContinue/ActiveStatementTrackingService.cs @@ -120,7 +120,7 @@ public TrackingSession(ActiveStatementTrackingService service, EditSession editS // fire and forget on a background thread: try { - Task.Run(TrackActiveSpansAsync, _editSession.Cancellation.Token); + Task.Run(TrackActiveSpansAsync, _editSession.CancellationToken); } catch (TaskCanceledException) { @@ -148,7 +148,7 @@ private async Task DocumentOpenedAsync(Document document) { try { - var baseActiveStatements = await _editSession.BaseActiveStatements.GetValueAsync(_editSession.Cancellation.Token).ConfigureAwait(false); + var baseActiveStatements = await _editSession.BaseActiveStatements.GetValueAsync(_editSession.CancellationToken).ConfigureAwait(false); if (baseActiveStatements.DocumentMap.TryGetValue(document.Id, out var documentActiveStatements) && TryGetSnapshot(document, out var snapshot)) @@ -188,7 +188,7 @@ private async Task TrackActiveSpansAsync() { try { - var baseActiveStatements = await _editSession.BaseActiveStatements.GetValueAsync(_editSession.Cancellation.Token).ConfigureAwait(false); + var baseActiveStatements = await _editSession.BaseActiveStatements.GetValueAsync(_editSession.CancellationToken).ConfigureAwait(false); lock (_trackingSpans) { @@ -244,7 +244,7 @@ private async Task RefreshTrackingSpansAsync(Document document, ITextSnapshot sn { try { - var documentAnalysis = await _editSession.GetDocumentAnalysis(document).GetValueAsync(_editSession.Cancellation.Token).ConfigureAwait(false); + var documentAnalysis = await _editSession.GetDocumentAnalysis(document).GetValueAsync(_editSession.CancellationToken).ConfigureAwait(false); // Do nothing if the statements aren't available (in presence of compilation errors). if (!documentAnalysis.ActiveStatements.IsDefault) diff --git a/src/EditorFeatures/Core/Implementation/EditAndContinue/EditAndContinueDiagnosticUpdateSource.cs b/src/EditorFeatures/Core/Implementation/EditAndContinue/EditAndContinueDiagnosticUpdateSource.cs deleted file mode 100644 index 2343dc3613449..0000000000000 --- a/src/EditorFeatures/Core/Implementation/EditAndContinue/EditAndContinueDiagnosticUpdateSource.cs +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Composition; -using System.Diagnostics; -using System.Linq; -using System.Threading; -using Microsoft.CodeAnalysis.Collections; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.EditAndContinue; -using Microsoft.CodeAnalysis.PooledObjects; - -namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue -{ - internal sealed class EncErrorId : BuildToolId.Base - { - public EncErrorId(DebuggingSession session, object errorId) - : base(session, errorId) - { - } - - public override string BuildTool => PredefinedBuildTools.EnC; - } - - [Export(typeof(EditAndContinueDiagnosticUpdateSource))] - [Shared] - internal sealed class EditAndContinueDiagnosticUpdateSource : IDiagnosticUpdateSource - { - internal static readonly object InternalErrorId = new object(); - internal static readonly object EmitErrorId = new object(); - - [ImportingConstructor] - public EditAndContinueDiagnosticUpdateSource(IDiagnosticUpdateSourceRegistrationService registrationService) - { - registrationService.Register(this); - } - - public bool SupportGetDiagnostics => false; - - public event EventHandler DiagnosticsUpdated; - public event EventHandler DiagnosticsCleared { add { } remove { } } - - public ImmutableArray GetDiagnostics(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) - { - return ImmutableArray.Empty; - } - - public void ClearDiagnostics(EncErrorId errorId, Solution solution, ProjectId projectId, ImmutableArray documentIds) - { - // clear project diagnostics: - ClearDiagnostics(errorId, solution, projectId, null); - - // clear document diagnostics: - foreach (var documentIdOpt in documentIds) - { - ClearDiagnostics(errorId, solution, projectId, documentIdOpt); - } - } - - public void ClearDiagnostics(EncErrorId errorId, Solution solution, ProjectId projectId, DocumentId documentIdOpt) - { - DiagnosticsUpdated?.Invoke(this, DiagnosticsUpdatedArgs.DiagnosticsRemoved( - errorId, - solution.Workspace, - solution: solution, - projectId: projectId, - documentId: documentIdOpt)); - } - - /// - /// Reports diagnostics. - /// - /// Returns ids of documents that belong to and containing one or more diagnostics. - public ImmutableArray ReportDiagnostics(object errorId, Solution solution, ProjectId projectId, IEnumerable diagnostics) - { - Debug.Assert(errorId != null); - Debug.Assert(solution != null); - Debug.Assert(projectId != null); - - var updateEvent = DiagnosticsUpdated; - using var documentIdsDisposer = PooledHashSet.GetInstance(out var documentIds); - using var documentDiagnosticDataDisposer = ArrayBuilder.GetInstance(out var documentDiagnosticData); - using var projectDiagnosticDataDisposer = ArrayBuilder.GetInstance(out var projectDiagnosticData); - - foreach (var diagnostic in diagnostics) - { - var documentOpt = solution.GetDocument(diagnostic.Location.SourceTree); - - if (documentOpt != null) - { - if (updateEvent != null) - { - documentDiagnosticData.Add(DiagnosticData.Create(documentOpt, diagnostic)); - } - - // only add documents from the current project: - if (documentOpt.Project.Id == projectId) - { - documentIds.Add(documentOpt.Id); - } - } - else if (updateEvent != null) - { - projectDiagnosticData.Add(DiagnosticData.Create(solution.Workspace, diagnostic, projectId)); - } - } - - foreach (var documentDiagnostics in documentDiagnosticData.ToDictionary(data => data.DocumentId)) - { - updateEvent(this, DiagnosticsUpdatedArgs.DiagnosticsCreated( - errorId, - solution.Workspace, - solution, - projectId, - documentId: documentDiagnostics.Key, - diagnostics: documentDiagnostics.Value)); - } - - if (projectDiagnosticData.Count > 0) - { - updateEvent(this, DiagnosticsUpdatedArgs.DiagnosticsCreated( - errorId, - solution.Workspace, - solution, - projectId, - documentId: null, - diagnostics: projectDiagnosticData.ToImmutable())); - } - - return documentIds.AsImmutableOrEmpty(); - } - - internal ImmutableArray ReportDiagnostics(DebuggingSession session, object errorId, ProjectId projectId, Solution solution, IEnumerable diagnostics) - { - return ReportDiagnostics(new EncErrorId(session, errorId), solution, projectId, diagnostics); - } - - internal void ClearDiagnostics(DebuggingSession session, Workspace workspace, object errorId, ProjectId projectId, ImmutableArray documentIds) - { - ClearDiagnostics(new EncErrorId(session, errorId), workspace.CurrentSolution, projectId, documentIds); - } - } -} diff --git a/src/EditorFeatures/Core/Implementation/EditAndContinue/ReadOnlyDocumentTracker.cs b/src/EditorFeatures/Core/Implementation/EditAndContinue/ReadOnlyDocumentTracker.cs deleted file mode 100644 index 47f0f27784a20..0000000000000 --- a/src/EditorFeatures/Core/Implementation/EditAndContinue/ReadOnlyDocumentTracker.cs +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using Microsoft.CodeAnalysis.EditAndContinue; -using Microsoft.CodeAnalysis.Editor.Shared.Utilities; -using Microsoft.CodeAnalysis.Text; -using Microsoft.VisualStudio.Text; - -namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue -{ - internal sealed class ReadOnlyDocumentTracker : ForegroundThreadAffinitizedObject, IDisposable - { - private readonly IEditAndContinueService _encService; - private readonly Workspace _workspace; - - // null after the object is disposed - private Dictionary _readOnlyRegions; - - // invoked on UI thread - private readonly Action _onReadOnlyDocumentEditAttempt; - - public ReadOnlyDocumentTracker(IThreadingContext threadingContext, IEditAndContinueService encService, Action onReadOnlyDocumentEditAttempt) - : base(threadingContext, assertIsForeground: true) - { - Debug.Assert(encService.DebuggingSession != null); - - _encService = encService; - _readOnlyRegions = new Dictionary(); - _workspace = encService.DebuggingSession.InitialSolution.Workspace; - _onReadOnlyDocumentEditAttempt = onReadOnlyDocumentEditAttempt; - - _workspace.DocumentClosed += OnDocumentClosed; - _workspace.DocumentOpened += OnDocumentOpened; - - foreach (var documentId in _workspace.GetOpenDocumentIds()) - { - TrackDocument(documentId); - } - } - - public Workspace Workspace => _workspace; - - private void OnDocumentOpened(object sender, DocumentEventArgs e) - { - InvokeBelowInputPriorityAsync(() => TrackDocument(e.Document.Id)); - } - - private void OnDocumentClosed(object sender, DocumentEventArgs e) - { - // The buffer is gone by now, so we don't need to remove the read-only region from it, just clean up our dictionary. - InvokeBelowInputPriorityAsync(() => - { - if (_readOnlyRegions != null) - { - _readOnlyRegions.Remove(e.Document.Id); - } - }); - } - - private void TrackDocument(DocumentId documentId) - { - AssertIsForeground(); - - if (_readOnlyRegions == null || _readOnlyRegions.ContainsKey(documentId)) - { - return; - } - - var textBuffer = GetTextBuffer(_workspace, documentId); - using var readOnlyEdit = textBuffer.CreateReadOnlyRegionEdit(); - - _readOnlyRegions.Add(documentId, readOnlyEdit.CreateDynamicReadOnlyRegion(Span.FromBounds(0, readOnlyEdit.Snapshot.Length), SpanTrackingMode.EdgeInclusive, EdgeInsertionMode.Deny, - isEdit => IsRegionReadOnly(documentId, isEdit))); - - readOnlyEdit.Apply(); - } - - private bool IsRegionReadOnly(DocumentId documentId, bool isEdit) - { - AssertIsForeground(); - var isReadOnly = _encService.IsProjectReadOnly(documentId.ProjectId, out var sessionReason, out var projectReason); - - if (isEdit && isReadOnly) - { - _onReadOnlyDocumentEditAttempt?.Invoke(documentId, sessionReason, projectReason); - } - - return isReadOnly; - } - - public void Dispose() - { - AssertIsForeground(); - - _workspace.DocumentClosed -= OnDocumentClosed; - _workspace.DocumentOpened -= OnDocumentOpened; - - // event handlers may be queued after the disposal - they should be a no-op - foreach (var documentAndRegion in _readOnlyRegions) - { - RemoveReadOnlyRegionFromBuffer(documentAndRegion.Key, documentAndRegion.Value); - } - - _readOnlyRegions = null; - } - - private void RemoveReadOnlyRegionFromBuffer(DocumentId documentId, IReadOnlyRegion region) - { - AssertIsForeground(); - - var textBuffer = GetTextBuffer(_workspace, documentId); - using var readOnlyEdit = textBuffer.CreateReadOnlyRegionEdit(); - - readOnlyEdit.RemoveReadOnlyRegion(region); - readOnlyEdit.Apply(); - } - - private static ITextBuffer GetTextBuffer(Workspace workspace, DocumentId documentId) - { - var doc = workspace.CurrentSolution.GetDocument(documentId); - doc.TryGetText(out var text); - var snapshot = text.FindCorrespondingEditorTextSnapshot(); - return snapshot.TextBuffer; - } - } -} diff --git a/src/EditorFeatures/Core/Implementation/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs b/src/EditorFeatures/Core/Implementation/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs index 7b730078c1c54..bd485f6d137af 100644 --- a/src/EditorFeatures/Core/Implementation/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/EncapsulateField/AbstractEncapsulateFieldCommandHandler.cs @@ -1,16 +1,13 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; -using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Editor.Host; -using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.EncapsulateField; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; -using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; @@ -22,15 +19,18 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.EncapsulateField { internal abstract class AbstractEncapsulateFieldCommandHandler : VSCommanding.ICommandHandler { + private readonly IThreadingContext _threadingContext; private readonly ITextBufferUndoManagerProvider _undoManager; private readonly IAsynchronousOperationListener _listener; public string DisplayName => EditorFeaturesResources.Encapsulate_Field; public AbstractEncapsulateFieldCommandHandler( + IThreadingContext threadingContext, ITextBufferUndoManagerProvider undoManager, IAsynchronousOperationListenerProvider listenerProvider) { + _threadingContext = threadingContext; _undoManager = undoManager; _listener = listenerProvider.GetListener(FeatureAttribute.EncapsulateField); } @@ -50,10 +50,10 @@ public bool ExecuteCommand(EncapsulateFieldCommandArgs args, CommandExecutionCon private bool Execute(EncapsulateFieldCommandArgs args, IUIThreadOperationScope waitScope) { using var token = _listener.BeginAsyncOperation("EncapsulateField"); - + var cancellationToken = waitScope.Context.UserCancellationToken; - var document = args.SubjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync( - waitScope.Context).WaitAndGetResult(cancellationToken); + var document = args.SubjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( + waitScope.Context, _threadingContext); if (document == null) { return false; diff --git a/src/EditorFeatures/Core/Implementation/ExtractInterface/AbstractExtractInterfaceCommandHandler.cs b/src/EditorFeatures/Core/Implementation/ExtractInterface/AbstractExtractInterfaceCommandHandler.cs index 2d1f55c4c24f9..3ffa7350e7f0a 100644 --- a/src/EditorFeatures/Core/Implementation/ExtractInterface/AbstractExtractInterfaceCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/ExtractInterface/AbstractExtractInterfaceCommandHandler.cs @@ -1,14 +1,12 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; -using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExtractInterface; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; @@ -47,8 +45,8 @@ public bool ExecuteCommand(ExtractInterfaceCommandArgs args, CommandExecutionCon return false; } - var document = subjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync( - context.OperationContext).WaitAndGetResult(context.OperationContext.UserCancellationToken); + var document = subjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( + context.OperationContext, _threadingContext); if (document == null) { return false; diff --git a/src/EditorFeatures/Core/Implementation/ExtractMethod/AbstractExtractMethodCommandHandler.cs b/src/EditorFeatures/Core/Implementation/ExtractMethod/AbstractExtractMethodCommandHandler.cs index eeb2716a97eb8..97628bc668340 100644 --- a/src/EditorFeatures/Core/Implementation/ExtractMethod/AbstractExtractMethodCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/ExtractMethod/AbstractExtractMethodCommandHandler.cs @@ -3,8 +3,8 @@ using System; using System.Linq; using System.Threading; -using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; @@ -23,21 +23,21 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.ExtractMethod { internal abstract class AbstractExtractMethodCommandHandler : VSCommanding.ICommandHandler { + private readonly IThreadingContext _threadingContext; private readonly ITextBufferUndoManagerProvider _undoManager; - private readonly IEditorOperationsFactoryService _editorOperationsFactoryService; private readonly IInlineRenameService _renameService; public AbstractExtractMethodCommandHandler( + IThreadingContext threadingContext, ITextBufferUndoManagerProvider undoManager, - IEditorOperationsFactoryService editorOperationsFactoryService, IInlineRenameService renameService) { + Contract.ThrowIfNull(threadingContext); Contract.ThrowIfNull(undoManager); - Contract.ThrowIfNull(editorOperationsFactoryService); Contract.ThrowIfNull(renameService); + _threadingContext = threadingContext; _undoManager = undoManager; - _editorOperationsFactoryService = editorOperationsFactoryService; _renameService = renameService; } public string DisplayName => EditorFeaturesResources.Extract_Method; @@ -93,7 +93,8 @@ private bool Execute( return false; } - var document = textBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync(waitContext).WaitAndGetResult(cancellationToken); + var document = textBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( + waitContext, _threadingContext); if (document == null) { return false; diff --git a/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CommitManager.cs b/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CommitManager.cs index fc8c86beb1382..71f7a1646f6e4 100644 --- a/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CommitManager.cs +++ b/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CommitManager.cs @@ -124,11 +124,10 @@ public AsyncCompletionData.CommitResult TryCommit( return new AsyncCompletionData.CommitResult(isHandled: true, AsyncCompletionData.CommitBehavior.None); } - if (!session.Properties.TryGetProperty(CompletionSource.TriggerSnapshot, out ITextSnapshot triggerSnapshot)) + if (!Helpers.TryGetInitialTriggerLocation(session, out var triggerLocation)) { // Need the trigger snapshot to calculate the span when the commit changes to be applied. - // It should be inserted into a property bag within GetCompletionContextAsync for each item created by Roslyn. - // If not found here, Roslyn should not make a commit. + // They should always be available from VS. Just to be defensive, if it's not found here, Roslyn should not make a commit. return CommitResultUnhandled; } @@ -137,7 +136,7 @@ public AsyncCompletionData.CommitResult TryCommit( return CommitResultUnhandled; } - var triggerDocument = triggerSnapshot.GetOpenDocumentInCurrentContextWithChanges(); + var triggerDocument = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (triggerDocument == null) { return CommitResultUnhandled; @@ -148,7 +147,7 @@ public AsyncCompletionData.CommitResult TryCommit( { AsyncCompletionLogger.LogCommitWithTypeImportCompletionEnabled(); - if (roslynItem.IsCached) + if (roslynItem.Flags.IsCached()) { AsyncCompletionLogger.LogCommitOfTypeImportCompletionItem(); } @@ -169,7 +168,7 @@ public AsyncCompletionData.CommitResult TryCommit( var commitChar = typeChar == '\0' ? null : (char?)typeChar; var commitBehavior = Commit( triggerDocument, completionService, session.TextView, subjectBuffer, - roslynItem, completionListSpan, commitChar, triggerSnapshot, serviceRules, + roslynItem, completionListSpan, commitChar, triggerLocation.Snapshot, serviceRules, filterText, cancellationToken); _recentItemsManager.MakeMostRecentItem(roslynItem.FilterText); diff --git a/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CompletionSource.cs b/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CompletionSource.cs index d790e929c5871..74db0ce967ba6 100644 --- a/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CompletionSource.cs +++ b/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CompletionSource.cs @@ -3,6 +3,8 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Collections.Specialized; +using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; @@ -20,6 +22,7 @@ using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Core.Imaging; +using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; @@ -30,10 +33,9 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { - internal class CompletionSource : ForegroundThreadAffinitizedObject, IAsyncCompletionSource + internal class CompletionSource : ForegroundThreadAffinitizedObject, IAsyncExpandingCompletionSource { internal const string RoslynItem = nameof(RoslynItem); - internal const string TriggerSnapshot = nameof(TriggerSnapshot); internal const string CompletionListSpan = nameof(CompletionListSpan); internal const string InsertionText = nameof(InsertionText); internal const string HasSuggestionItemOptions = nameof(HasSuggestionItemOptions); @@ -53,12 +55,6 @@ internal class CompletionSource : ForegroundThreadAffinitizedObject, IAsyncCompl private static readonly ConditionalWeakTable> s_roslynItemToVsItemData = new ConditionalWeakTable>(); - // Cache all the VS completion filters which essentially make them singletons. - // Because all items that should be filtered using the same filter button must - // use the same reference to the instance of CompletionFilter. - private static readonly Dictionary s_filterCache = - new Dictionary(); - private readonly ITextView _textView; private readonly bool _isDebuggerTextView; private readonly ImmutableHashSet _roles; @@ -205,17 +201,47 @@ private static bool TryInvokeSnippetCompletion( return true; } - public async Task GetCompletionContextAsync( + public Task GetCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) + { + return GetCompletionContextWorkerAsync(session, trigger, triggerLocation, applicableToSpan, isExpanded: false, cancellationToken); + } + + public async Task GetExpandedCompletionContextAsync( + IAsyncCompletionSession session, + AsyncCompletionData.CompletionExpander expander, + AsyncCompletionData.CompletionTrigger intialTrigger, + SnapshotSpan applicableToSpan, + CancellationToken cancellationToken) + { + // We only want to provide expanded items for Roslyn's expander. + if ((object)expander == FilterSet.Expander) + { + if (Helpers.TryGetInitialTriggerLocation(session, out var initialTriggerLocation)) + { + return await GetCompletionContextWorkerAsync(session, intialTrigger, initialTriggerLocation, applicableToSpan, isExpanded: true, cancellationToken).ConfigureAwait(false); + } + } + + return AsyncCompletionData.CompletionContext.Empty; + } + + private async Task GetCompletionContextWorkerAsync( + IAsyncCompletionSession session, + AsyncCompletionData.CompletionTrigger trigger, + SnapshotPoint triggerLocation, + SnapshotSpan applicableToSpan, + bool isExpanded, + CancellationToken cancellationToken) { var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { - return new AsyncCompletionData.CompletionContext(ImmutableArray.Empty); + return AsyncCompletionData.CompletionContext.Empty; } var completionService = document.GetLanguageService(); @@ -224,73 +250,89 @@ private static bool TryInvokeSnippetCompletion( var workspace = document.Project.Solution.Workspace; - var completionList = await completionService.GetCompletionsAsync( + var options = _isDebuggerTextView ? workspace.Options.WithDebuggerCompletionOptions() : workspace.Options; + options = options.WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, isExpanded); + + var (completionList, expandItemsAvailable) = await completionService.GetCompletionsInternalAsync( document, triggerLocation, roslynTrigger, _roles, - _isDebuggerTextView ? workspace.Options.WithDebuggerCompletionOptions() : workspace.Options, + options, cancellationToken).ConfigureAwait(false); + ImmutableArray items; + AsyncCompletionData.SuggestionItemOptions suggestionItemOptions; + var filterSet = new FilterSet(); + if (completionList == null) { - return new AsyncCompletionData.CompletionContext(ImmutableArray.Empty); + items = ImmutableArray.Empty; + suggestionItemOptions = null; } - - var itemsBuilder = new ArrayBuilder(completionList.Items.Length); - foreach (var roslynItem in completionList.Items) + else { - cancellationToken.ThrowIfCancellationRequested(); - var item = Convert(document, roslynItem); - itemsBuilder.Add(item); - } - - var items = itemsBuilder.ToImmutableAndFree(); - - var suggestionItemOptions = completionList.SuggestionModeItem != null - ? new AsyncCompletionData.SuggestionItemOptions( - completionList.SuggestionModeItem.DisplayText, - completionList.SuggestionModeItem.Properties.TryGetValue(Description, out var description) - ? description - : string.Empty) - : null; - - // Have to store the snapshot to reuse it in some projections related scenarios - // where data and session in further calls are able to provide other snapshots. - session.Properties.AddProperty(TriggerSnapshot, triggerLocation.Snapshot); - - // Store around the span this completion list applies to. We'll use this later - // to pass this value in when we're committing a completion list item. - session.Properties.AddProperty(CompletionListSpan, completionList.Span); + var itemsBuilder = new ArrayBuilder(completionList.Items.Length); + foreach (var roslynItem in completionList.Items) + { + cancellationToken.ThrowIfCancellationRequested(); + var item = Convert(document, roslynItem, filterSet); + itemsBuilder.Add(item); + } - // This is a code supporting original completion scenarios: - // Controller.Session_ComputeModel: if completionList.SuggestionModeItem != null, then suggestionMode = true - // If there are suggestionItemOptions, then later HandleNormalFiltering should set selection to SoftSelection. - session.Properties.AddProperty(HasSuggestionItemOptions, suggestionItemOptions != null); + items = itemsBuilder.ToImmutableAndFree(); + + suggestionItemOptions = completionList.SuggestionModeItem != null + ? new AsyncCompletionData.SuggestionItemOptions( + completionList.SuggestionModeItem.DisplayText, + completionList.SuggestionModeItem.Properties.TryGetValue(Description, out var description) + ? description + : string.Empty) + : null; + + // Store around the span this completion list applies to. We'll use this later + // to pass this value in when we're committing a completion list item. + // It's OK to overwrite this value when expanded items are requested. + session.Properties[CompletionListSpan] = completionList.Span; + + // This is a code supporting original completion scenarios: + // Controller.Session_ComputeModel: if completionList.SuggestionModeItem != null, then suggestionMode = true + // If there are suggestionItemOptions, then later HandleNormalFiltering should set selection to SoftSelection. + if (!session.Properties.TryGetProperty(HasSuggestionItemOptions, out bool hasSuggestionItemOptionsBefore) || !hasSuggestionItemOptionsBefore) + { + session.Properties[HasSuggestionItemOptions] = suggestionItemOptions != null; + } - var excludedCommitCharacters = GetExcludedCommitCharacters(completionList.Items); - if (excludedCommitCharacters.Length > 0) - { - session.Properties.AddProperty(ExcludedCommitCharacters, excludedCommitCharacters); + var excludedCommitCharacters = GetExcludedCommitCharacters(completionList.Items); + if (excludedCommitCharacters.Length > 0) + { + if (session.Properties.TryGetProperty(ExcludedCommitCharacters, out ImmutableArray excludedCommitCharactersBefore)) + { + excludedCommitCharacters = excludedCommitCharacters.Union(excludedCommitCharactersBefore).ToImmutableArray(); + } + session.Properties[ExcludedCommitCharacters] = excludedCommitCharacters; + } } + // It's possible that some providers can provide expanded items, in which case we will need to show expander as unselected. return new AsyncCompletionData.CompletionContext( items, suggestionItemOptions, suggestionItemOptions == null ? AsyncCompletionData.InitialSelectionHint.RegularSelection - : AsyncCompletionData.InitialSelectionHint.SoftSelection); + : AsyncCompletionData.InitialSelectionHint.SoftSelection, + filterSet.GetFilterStatesInSet(addUnselectedExpander: expandItemsAvailable)); } public async Task GetDescriptionAsync(IAsyncCompletionSession session, VSCompletionItem item, CancellationToken cancellationToken) { if (!item.Properties.TryGetProperty(RoslynItem, out RoslynCompletionItem roslynItem) || - !session.Properties.TryGetProperty(TriggerSnapshot, out ITextSnapshot triggerSnapshot)) + !Helpers.TryGetInitialTriggerLocation(session, out var triggerLocation)) { return null; } - var document = triggerSnapshot.GetOpenDocumentInCurrentContextWithChanges(); + var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return null; @@ -327,11 +369,12 @@ public async Task GetDescriptionAsync(IAsyncCompletionSession session, V /// private readonly struct VSCompletionItemData { - public VSCompletionItemData(string displayText, ImageElement icon, ImmutableArray filters, ImmutableArray attributeIcons, string insertionText) + public VSCompletionItemData(string displayText, ImageElement icon, ImmutableArray filters, int filterSetData, ImmutableArray attributeIcons, string insertionText) { DisplayText = displayText; Icon = icon; Filters = filters; + FilterSetData = filterSetData; AttributeIcons = attributeIcons; InsertionText = insertionText; } @@ -342,6 +385,11 @@ public VSCompletionItemData(string displayText, ImageElement icon, ImmutableArra public ImmutableArray Filters { get; } + /// + /// This is the bit vector value from the FilterSet of this item. + /// + public int FilterSetData { get; } + public ImmutableArray AttributeIcons { get; } public string InsertionText { get; } @@ -349,18 +397,20 @@ public VSCompletionItemData(string displayText, ImageElement icon, ImmutableArra private VSCompletionItem Convert( Document document, - RoslynCompletionItem roslynItem) + RoslynCompletionItem roslynItem, + FilterSet filterSet) { VSCompletionItemData itemData; - if (roslynItem.IsCached && s_roslynItemToVsItemData.TryGetValue(roslynItem, out var boxedItemData)) + if (roslynItem.Flags.IsCached() && s_roslynItemToVsItemData.TryGetValue(roslynItem, out var boxedItemData)) { itemData = boxedItemData.Value; + filterSet.CombineData(itemData.FilterSetData); } else { var imageId = roslynItem.Tags.GetFirstGlyph().GetImageId(); - var filters = GetFilters(roslynItem); + var (filters, filterSetData) = filterSet.GetFiltersAndAddToSet(roslynItem); // roslynItem generated by providers can contain an insertionText in a property bag. // We will not use it but other providers may need it. @@ -377,12 +427,13 @@ private VSCompletionItem Convert( displayText: roslynItem.GetEntireDisplayText(), icon: new ImageElement(new ImageId(imageId.Guid, imageId.Id), roslynItem.DisplayText), filters: filters, + filterSetData: filterSetData, attributeIcons: attributeImages, insertionText: insertionText); // It doesn't make sense to cache VS item data for those Roslyn items created from scratch for each session, // since CWT uses object identity for comparison. - if (roslynItem.IsCached) + if (roslynItem.Flags.IsCached()) { s_roslynItemToVsItemData.Add(roslynItem, new StrongBox(itemData)); } @@ -425,30 +476,6 @@ private ImmutableArray GetExcludedCommitCharacters(ImmutableArray GetFilters(RoslynCompletionItem item) - { - var listBuilder = new ArrayBuilder(); - foreach (var filter in CompletionItemFilter.AllFilters) - { - if (filter.Matches(item)) - { - if (!s_filterCache.TryGetValue(filter.DisplayText, out var itemFilter)) - { - var imageId = filter.Tags.GetFirstGlyph().GetImageId(); - itemFilter = new AsyncCompletionData.CompletionFilter( - filter.DisplayText, - filter.AccessKey.ToString(), - new ImageElement(new ImageId(imageId.Guid, imageId.Id), EditorFeaturesResources.Filter_image_element)); - s_filterCache[filter.DisplayText] = itemFilter; - } - - listBuilder.Add(itemFilter); - } - } - - return listBuilder.ToImmutableAndFree(); - } - internal static bool QuestionMarkIsPrecededByIdentifierAndWhitespace( SourceText text, int questionPosition, ISyntaxFactsService syntaxFacts) { @@ -477,5 +504,141 @@ internal static bool QuestionMarkIsPrecededByIdentifierAndWhitespace( return current == questionPosition; } + + /// + /// Provides an efficient way to compute a set of completion filters associated with a collection of completion items. + /// Presence of expander and filter in the set have different meanings. Set contains a filter means the filter is + /// available but unselected, whereas it means available and selected for an expander. Note that even though VS supports + /// having multiple expanders, we only support one. + /// + private class FilterSet + { + // Cache all the VS completion filters which essentially make them singletons. + // Because all items that should be filtered using the same filter button must + // use the same reference to the instance of CompletionFilter. + private static readonly Dictionary s_filterCache = + new Dictionary(); + + private BitVector32 _vector; + private static readonly ImmutableArray s_filterMasks; + private static readonly int s_expanderMask; + private static AsyncCompletionData.CompletionExpander _expander = null; + + public static ImmutableArray Filters => CompletionItemFilter.AllFilters; + + public static AsyncCompletionData.CompletionExpander Expander + { + get + { + if (_expander == null) + { + var addImageId = Shared.Extensions.GlyphExtensions.GetImageCatalogImageId(KnownImageIds.ExpandScope); + _expander = new AsyncCompletionData.CompletionExpander( + EditorFeaturesResources.Expander_display_text, + accessKey: "a", + new ImageElement(addImageId, EditorFeaturesResources.Expander_image_element)); + } + + return _expander; + } + } + + public int Data => _vector.Data; + + static FilterSet() + { + var length = Filters.Length; + Debug.Assert(length <= 32); + + var previousMask = 0; + var builder = ArrayBuilder.GetInstance(length); + for (var i = 0; i < length; ++i) + { + previousMask = BitVector32.CreateMask(previousMask); + builder.Add(previousMask); + } + + s_filterMasks = builder.ToImmutableAndFree(); + + s_expanderMask = BitVector32.CreateMask(previousMask); + } + + public FilterSet(int data = 0) + { + _vector = new BitVector32(data); + } + + public (ImmutableArray filters, int data) GetFiltersAndAddToSet(RoslynCompletionItem item) + { + var listBuilder = new ArrayBuilder(); + var vectorForSingleItem = new BitVector32(); + + if (item.Flags.IsExpanded()) + { + listBuilder.Add(Expander); + vectorForSingleItem[s_expanderMask] = _vector[s_expanderMask] = true; + } + + for (var i = 0; i < Filters.Length; ++i) + { + var filter = Filters[i]; + if (filter.Matches(item)) + { + listBuilder.Add(GetFilter(filter)); + + var filterMask = s_filterMasks[i]; + vectorForSingleItem[filterMask] = _vector[filterMask] = true; + } + } + + return (listBuilder.ToImmutableAndFree(), vectorForSingleItem.Data); + } + + public void CombineData(int filterSetData) + { + _vector[filterSetData] = true; + } + + public ImmutableArray GetFilterStatesInSet(bool addUnselectedExpander) + { + var listBuilder = new ArrayBuilder(); + + // An unselected expander is only added if `addUnselectedExpander == true` and the expander is not in the set. + if (_vector[s_expanderMask]) + { + listBuilder.Add(new AsyncCompletionData.CompletionFilterWithState(Expander, isAvailable: true, isSelected: true)); + } + else if (addUnselectedExpander) + { + listBuilder.Add(new AsyncCompletionData.CompletionFilterWithState(Expander, isAvailable: true, isSelected: false)); + } + + for (var i = 0; i < Filters.Length; ++i) + { + if (_vector[s_filterMasks[i]]) + { + var vsFilter = GetFilter(Filters[i]); + listBuilder.Add(new AsyncCompletionData.CompletionFilterWithState(vsFilter, isAvailable: true, isSelected: false)); + } + } + + return listBuilder.ToImmutableAndFree(); + } + + private static AsyncCompletionData.CompletionFilter GetFilter(CompletionItemFilter roslynFilter) + { + if (!s_filterCache.TryGetValue(roslynFilter.DisplayText, out var vsFilter)) + { + var imageId = roslynFilter.Tags.GetFirstGlyph().GetImageId(); + vsFilter = new AsyncCompletionData.CompletionFilter( + roslynFilter.DisplayText, + roslynFilter.AccessKey.ToString(), + new ImageElement(new ImageId(imageId.Guid, imageId.Id), EditorFeaturesResources.Filter_image_element)); + s_filterCache[roslynFilter.DisplayText] = vsFilter; + } + + return vsFilter; + } + } } } diff --git a/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/Helpers.cs b/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/Helpers.cs index dec5df4ca3b88..7cdc3a1203fe3 100644 --- a/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/Helpers.cs +++ b/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/Helpers.cs @@ -2,7 +2,8 @@ using Microsoft.CodeAnalysis.Completion; using Microsoft.VisualStudio.Text; -using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; +using EditorAsyncCompletion = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; +using EditorAsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynTrigger = Microsoft.CodeAnalysis.Completion.CompletionTrigger; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; @@ -21,7 +22,7 @@ internal static class Helpers /// We retrieve this character from triggerLocation. /// /// Roslyn completion trigger - internal static RoslynTrigger GetRoslynTrigger(AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation) + internal static RoslynTrigger GetRoslynTrigger(EditorAsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation) { var completionTriggerKind = GetRoslynTriggerKind(trigger); if (completionTriggerKind == CompletionTriggerKind.Deletion) @@ -46,32 +47,32 @@ internal static RoslynTrigger GetRoslynTrigger(AsyncCompletionData.CompletionTri } } - internal static CompletionTriggerKind GetRoslynTriggerKind(AsyncCompletionData.CompletionTrigger trigger) + internal static CompletionTriggerKind GetRoslynTriggerKind(EditorAsyncCompletionData.CompletionTrigger trigger) { switch (trigger.Reason) { - case AsyncCompletionData.CompletionTriggerReason.InvokeAndCommitIfUnique: + case EditorAsyncCompletionData.CompletionTriggerReason.InvokeAndCommitIfUnique: return CompletionTriggerKind.InvokeAndCommitIfUnique; - case AsyncCompletionData.CompletionTriggerReason.Insertion: + case EditorAsyncCompletionData.CompletionTriggerReason.Insertion: return CompletionTriggerKind.Insertion; - case AsyncCompletionData.CompletionTriggerReason.Deletion: - case AsyncCompletionData.CompletionTriggerReason.Backspace: + case EditorAsyncCompletionData.CompletionTriggerReason.Deletion: + case EditorAsyncCompletionData.CompletionTriggerReason.Backspace: return CompletionTriggerKind.Deletion; - case AsyncCompletionData.CompletionTriggerReason.SnippetsMode: + case EditorAsyncCompletionData.CompletionTriggerReason.SnippetsMode: return CompletionTriggerKind.Snippets; default: return CompletionTriggerKind.Invoke; } } - internal static CompletionFilterReason GetFilterReason(AsyncCompletionData.CompletionTrigger trigger) + internal static CompletionFilterReason GetFilterReason(EditorAsyncCompletionData.CompletionTrigger trigger) { switch (trigger.Reason) { - case AsyncCompletionData.CompletionTriggerReason.Insertion: + case EditorAsyncCompletionData.CompletionTriggerReason.Insertion: return CompletionFilterReason.Insertion; - case AsyncCompletionData.CompletionTriggerReason.Deletion: - case AsyncCompletionData.CompletionTriggerReason.Backspace: + case EditorAsyncCompletionData.CompletionTriggerReason.Deletion: + case EditorAsyncCompletionData.CompletionTriggerReason.Backspace: return CompletionFilterReason.Deletion; default: return CompletionFilterReason.Other; @@ -113,6 +114,18 @@ internal static bool IsFilterCharacter(RoslynCompletionItem item, char ch, strin return false; } + internal static bool TryGetInitialTriggerLocation(EditorAsyncCompletion.IAsyncCompletionSession session, out SnapshotPoint initialTriggerLocation) + { + if (session is EditorAsyncCompletion.IAsyncCompletionSessionOperations sessionOperations) + { + initialTriggerLocation = sessionOperations.InitialTriggerLocation; + return true; + } + + initialTriggerLocation = default; + return false; + } + // This is a temporarily method to support preference of IntelliCode items comparing to non-IntelliCode items. // We expect that Editor will intorduce this support and we will get rid of relying on the "★" then. internal static bool IsPreferredItem(this RoslynCompletionItem completionItem) diff --git a/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/ItemManager.cs b/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/ItemManager.cs index 5b5d15f2503e8..6a3e78289db0f 100644 --- a/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/ItemManager.cs +++ b/src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/ItemManager.cs @@ -112,16 +112,23 @@ private FilteredCompletionModel UpdateCompletionList( } } - // We need to filter if a non-empty strict subset of filters are selected - var selectedFilters = data.SelectedFilters.Where(f => f.IsSelected).Select(f => f.Filter).ToImmutableArray(); - var needToFilter = selectedFilters.Length > 0 && selectedFilters.Length < data.SelectedFilters.Length; + // We need to filter if + // 1. a non-empty strict subset of filters are selected + // 2. a non-empty set of expanders are unselected + var nonExpanderFilterStates = data.SelectedFilters.WhereAsArray(f => !(f.Filter is CompletionExpander)); + + var selectedNonExpanderFilters = nonExpanderFilterStates.Where(f => f.IsSelected).SelectAsArray(f => f.Filter); + var needToFilter = selectedNonExpanderFilters.Length > 0 && selectedNonExpanderFilters.Length < nonExpanderFilterStates.Length; + + var unselectedExpanders = data.SelectedFilters.Where(f => !f.IsSelected && f.Filter is CompletionExpander).SelectAsArray(f => f.Filter); + var needToFilterExpanded = unselectedExpanders.Length > 0; if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled) { // Telemetry: Want to know % of sessions with the "Target type matches" filter where that filter is actually enabled if (needToFilter && !session.Properties.ContainsProperty(_targetTypeCompletionFilterChosenMarker) && - selectedFilters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) + selectedNonExpanderFilters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)) { AsyncCompletionLogger.LogTargetTypeFilterChosenInSession(); @@ -134,10 +141,9 @@ private FilteredCompletionModel UpdateCompletionList( // If the session was created/maintained out of Roslyn, e.g. in debugger; no properties are set and we should use data.Snapshot. // However, we prefer using the original snapshot in some projection scenarios. - if (!session.Properties.TryGetProperty(CompletionSource.TriggerSnapshot, out ITextSnapshot snapshotForDocument)) - { - snapshotForDocument = data.Snapshot; - } + var snapshotForDocument = Helpers.TryGetInitialTriggerLocation(session, out var triggerLocation) + ? triggerLocation.Snapshot + : data.Snapshot; var document = snapshotForDocument.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); var completionService = document?.GetLanguageService(); @@ -149,7 +155,12 @@ private FilteredCompletionModel UpdateCompletionList( { cancellationToken.ThrowIfCancellationRequested(); - if (needToFilter && ShouldBeFilteredOutOfCompletionList(item, selectedFilters)) + if (needToFilter && ShouldBeFilteredOutOfCompletionList(item, selectedNonExpanderFilters)) + { + continue; + } + + if (needToFilterExpanded && ShouldBeFilteredOutOfExpandedCompletionList(item, unselectedExpanders)) { continue; } @@ -240,6 +251,39 @@ private FilteredCompletionModel UpdateCompletionList( highlightedList, completionHelper, hasSuggestedItemOptions); + + static bool ShouldBeFilteredOutOfCompletionList(VSCompletionItem item, ImmutableArray activeNonExpanderFilters) + { + if (item.Filters.Any(filter => activeNonExpanderFilters.Contains(filter))) + { + return false; + } + + return true; + } + + static bool ShouldBeFilteredOutOfExpandedCompletionList(VSCompletionItem item, ImmutableArray unselectedExpanders) + { + var associatedWithUnselectedExpander = false; + foreach (var itemFilter in item.Filters) + { + if (itemFilter is CompletionExpander) + { + if (!unselectedExpanders.Contains(itemFilter)) + { + // If any of the associated expander is selected, the item should be included in the expanded list. + return false; + } + + associatedWithUnselectedExpander = true; + } + } + + // at this point, the item either: + // 1. has no expander filter, therefore should be included + // 2. or, all associated expanders are unselected, therefore should be excluded + return associatedWithUnselectedExpander; + } } private static bool IsAfterDot(ITextSnapshot snapshot, ITrackingSpan applicableToSpan) @@ -460,21 +504,9 @@ private static ImmutableArray GetUpdatedFilters( // See which filters might be enabled based on the typed code var textFilteredFilters = filteredList.SelectMany(n => n.VSCompletionItem.Filters).ToImmutableHashSet(); - // When no items are available for a given filter, it becomes unavailable - return ImmutableArray.CreateRange(filters.Select(n => n.WithAvailability(textFilteredFilters.Contains(n.Filter)))); - } - - private static bool ShouldBeFilteredOutOfCompletionList(VSCompletionItem item, ImmutableArray activeFilters) - { - foreach (var itemFilter in item.Filters) - { - if (activeFilters.Contains(itemFilter)) - { - return false; - } - } - - return true; + // When no items are available for a given filter, it becomes unavailable. + // Expanders always appear available as long as it's presented. + return filters.SelectAsArray(n => n.WithAvailability(n.Filter is CompletionExpander ? true : textFilteredFilters.Contains(n.Filter))); } /// diff --git a/src/EditorFeatures/Core/Implementation/Organizing/OrganizeDocumentCommandHandler.cs b/src/EditorFeatures/Core/Implementation/Organizing/OrganizeDocumentCommandHandler.cs index 6d52399725cf9..6a5f8fe4764e8 100644 --- a/src/EditorFeatures/Core/Implementation/Organizing/OrganizeDocumentCommandHandler.cs +++ b/src/EditorFeatures/Core/Implementation/Organizing/OrganizeDocumentCommandHandler.cs @@ -4,8 +4,8 @@ using System.ComponentModel.Composition; using System.Threading; using Microsoft.CodeAnalysis.Editor.Commanding.Commands; -using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.OrganizeImports; using Microsoft.CodeAnalysis.Organizing; using Microsoft.CodeAnalysis.RemoveUnnecessaryImports; @@ -30,9 +30,12 @@ internal class OrganizeDocumentCommandHandler : VSCommanding.ICommandHandler, VSCommanding.ICommandHandler { + private readonly IThreadingContext _threadingContext; + [ImportingConstructor] - public OrganizeDocumentCommandHandler() + public OrganizeDocumentCommandHandler(IThreadingContext threadingContext) { + _threadingContext = threadingContext; } public string DisplayName => EditorFeaturesResources.Organize_Document; @@ -47,8 +50,8 @@ public bool ExecuteCommand(OrganizeDocumentCommandArgs args, CommandExecutionCon using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Organizing_document)) { var cancellationToken = context.OperationContext.UserCancellationToken; - var document = args.SubjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync(context.OperationContext) - .WaitAndGetResult(cancellationToken); + var document = args.SubjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( + context.OperationContext, _threadingContext); if (document != null) { var newDocument = OrganizingService.OrganizeAsync(document, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); @@ -144,7 +147,8 @@ private void SortImports(ITextBuffer subjectBuffer, IUIThreadOperationContext op private void SortAndRemoveUnusedImports(ITextBuffer subjectBuffer, IUIThreadOperationContext operationContext) { var cancellationToken = operationContext.UserCancellationToken; - var document = subjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync(operationContext).WaitAndGetResult(cancellationToken); + var document = subjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( + operationContext, _threadingContext); if (document != null) { var newDocument = document.GetLanguageService().RemoveUnnecessaryImportsAsync(document, cancellationToken).WaitAndGetResult(cancellationToken); diff --git a/src/EditorFeatures/Core/Implementation/RenameTracking/AbstractRenameTrackingCodeFixProvider.cs b/src/EditorFeatures/Core/Implementation/RenameTracking/AbstractRenameTrackingCodeFixProvider.cs index 38cbd5f0c5abc..727bcd8fc8545 100644 --- a/src/EditorFeatures/Core/Implementation/RenameTracking/AbstractRenameTrackingCodeFixProvider.cs +++ b/src/EditorFeatures/Core/Implementation/RenameTracking/AbstractRenameTrackingCodeFixProvider.cs @@ -5,9 +5,7 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.VisualStudio.Text.Operations; -using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { @@ -46,5 +44,10 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) return Task.CompletedTask; } + + public override FixAllProvider GetFixAllProvider() + { + return null; + } } } diff --git a/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj b/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj index a4e8d370f428d..96e95b52af05a 100644 --- a/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj +++ b/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj @@ -36,6 +36,7 @@ + diff --git a/src/EditorFeatures/Core/Shared/Extensions/GlyphExtensions.cs b/src/EditorFeatures/Core/Shared/Extensions/GlyphExtensions.cs index 2bd8af38344c4..d514c1bd416c4 100644 --- a/src/EditorFeatures/Core/Shared/Extensions/GlyphExtensions.cs +++ b/src/EditorFeatures/Core/Shared/Extensions/GlyphExtensions.cs @@ -15,6 +15,9 @@ internal static class GlyphExtensions // https://github.com/dotnet/roslyn/issues/26642 private static readonly Guid ImageCatalogGuid = Guid.Parse("ae27a6b0-e345-4288-96df-5eaf394ee369"); + public static ImageId GetImageCatalogImageId(int imageId) + => new ImageId(ImageCatalogGuid, imageId); + public static ImageId GetImageId(this Glyph glyph) { // VS for mac cannot refer to ImageMoniker diff --git a/src/EditorFeatures/Core/Shared/Extensions/ITextSnapshotExtensions.cs b/src/EditorFeatures/Core/Shared/Extensions/ITextSnapshotExtensions.cs index c76a41903c449..4e5ca9bee0c3e 100644 --- a/src/EditorFeatures/Core/Shared/Extensions/ITextSnapshotExtensions.cs +++ b/src/EditorFeatures/Core/Shared/Extensions/ITextSnapshotExtensions.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; @@ -60,6 +61,10 @@ private static IEnumerable GetFormattingRules(Document d /// /// Get from /// once returns + /// + /// for synchronous code path, make sure to use synchronous version + /// . + /// otherwise, one can get into a deadlock /// public static async Task GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync( this ITextSnapshot snapshot, IUIThreadOperationContext operationContext) @@ -87,5 +92,19 @@ public static async Task GetFullyLoadedOpenDocumentInCurrentContextWit return snapshot.GetOpenDocumentInCurrentContextWithChanges(); } } + + /// + /// Get from + /// once returns + /// + public static Document GetFullyLoadedOpenDocumentInCurrentContextWithChanges( + this ITextSnapshot snapshot, IUIThreadOperationContext operationContext, IThreadingContext threadingContext) + { + // make sure this is only called from UI thread + threadingContext.ThrowIfNotOnUIThread(); + + return threadingContext.JoinableTaskFactory.Run(() => + snapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync(operationContext)); + } } } diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.cs.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.cs.xlf index cb594e0a7faa6..d81f673d3a63e 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.cs.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.cs.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + Relace přejmenování na řádku je pro identifikátor {0} aktivní. Pokud chcete získat přístup k dalším možnostem, znovu volejte přejmenování na řádku. Můžete kdykoli pokračovat v úpravách identifikátoru, který se přejmenovává. For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ Chcete přesto pokračovat? Výsledkem může být poškozený kód. + + items from unimported namespaces + položky z neimportovaných oborů názvů + + + + Expander + Rozbalování + + Extract method encountered the following issues: Při extrahování metody došlo k následujícím problémům: @@ -89,17 +99,17 @@ Rename _file - Rename _file + Přejmenovat _soubor Rename _file (type does not match file name) - Rename _file (type does not match file name) + Přejmenovat _soubor (typ neodpovídá názvu souboru) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + Přejmenovat _soubor (nepovoleno pro dílčí typy) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + Tento symbol nemá žádný základ. Toggle Block Comment - Toggle Block Comment + Přepnout komentář k bloku Toggle Line Comment - Toggle Line Comment + Přepnout komentář k řádku Toggling block comment... - Toggling block comment... + Přepíná se komentář k bloku... Toggling line comment... - Toggling line comment... + Přepíná se komentář k řádku... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + Čeká se na dokončení aktivity na pozadí... @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + Základy {0} diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.de.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.de.xlf index d41799ccfdccf..8be7057b3fac8 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.de.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.de.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + Für den Bezeichner "{0}" ist eine Inline-Umbenennungssitzung aktiv. Rufen Sie die Inline-Umbenennung erneut auf, um auf zusätzliche Optionen zuzugreifen. Sie können den Bezeichner, der gerade umbenannt wird, jederzeit weiterbearbeiten. For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ Möchten Sie dennoch fortfahren? Möglicherweise wird fehlerhafter Code generiert. + + items from unimported namespaces + Elemente aus nicht importierten Namespaces + + + + Expander + Erweiterung + + Extract method encountered the following issues: Beim Extrahieren der Methode sind folgende Fehler aufgetreten: @@ -89,17 +99,17 @@ Rename _file - Rename _file + _Datei umbenennen Rename _file (type does not match file name) - Rename _file (type does not match file name) + _Datei umbenennen (Typ entspricht nicht dem Dateinamen) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + _Datei umbenennen (bei partiellen Typen nicht zulässig) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + Das Symbol verfügt über keine Basis. Toggle Block Comment - Toggle Block Comment + Kommentarblock ein/aus Toggle Line Comment - Toggle Line Comment + Kommentarzeile ein/aus Toggling block comment... - Toggling block comment... + Kommentarblock wird ein-/ausgeschaltet... Toggling line comment... - Toggling line comment... + Kommentarzeile wird ein-/ausgeschaltet... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + Es wird auf den Abschluss von Hintergrundaufgaben gewartet... @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + Basiswerte: "{0}" diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.es.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.es.xlf index e8591e2d8d81d..fa9430e92b528 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.es.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.es.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + Hay una sesión de cambio de nombre insertado que está activa para el identificador "{0}". Vuelva a invocar el cambio de nombre insertado para acceder a más opciones. Puede continuar editando el identificador cuyo nombre se va a cambiar en cualquier momento. For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ ¿Desea continuar? Esto puede producir código roto. + + items from unimported namespaces + elementos de espacios de nombres no importados + + + + Expander + Expansor + + Extract method encountered the following issues: El método de extracción detectó los siguientes problemas: @@ -89,17 +99,17 @@ Rename _file - Rename _file + Ca_mbiar nombre de archivo Rename _file (type does not match file name) - Rename _file (type does not match file name) + Ca_mbiar nombre de archivo (el tipo no coincide con el nombre de archivo) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + Ca_mbiar nombre de archivo (no se permite en tipos parciales) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + El símbolo no tiene base. Toggle Block Comment - Toggle Block Comment + Alternar comentario de bloque Toggle Line Comment - Toggle Line Comment + Alternar comentario de línea Toggling block comment... - Toggling block comment... + Alternando comentario de bloque... Toggling line comment... - Toggling line comment... + Alternando comentario de línea... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + Esperando a que finalice el trabajo en segundo plano... @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + Bases de "{0}" diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.fr.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.fr.xlf index 89aedd8c1281a..7f4a8f25ba223 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.fr.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.fr.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + Une session de renommage inline est active pour l'identificateur '{0}'. Appelez à nouveau le renommage inline pour accéder à des options supplémentaires. Vous pouvez continuer à modifier l'identificateur renommé à tout moment. For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ Voulez-vous continuer ? Le code sera interrompu. + + items from unimported namespaces + éléments provenant d'espaces de noms non importés + + + + Expander + Expander + + Extract method encountered the following issues: La méthode Extract a rencontré les problèmes suivants : @@ -89,17 +99,17 @@ Rename _file - Rename _file + Renommer le _fichier Rename _file (type does not match file name) - Rename _file (type does not match file name) + Renommer le _fichier (le type ne correspond pas au nom du fichier) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + Renommer le _fichier (non autorisé sur les types partiels) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + Le symbole n'a pas de base. Toggle Block Comment - Toggle Block Comment + Activer/désactiver le commentaire de bloc Toggle Line Comment - Toggle Line Comment + Activer/désactiver le commentaire de ligne Toggling block comment... - Toggling block comment... + Activation/désactivation du commentaire de bloc... Toggling line comment... - Toggling line comment... + Activation/désactivation du commentaire de ligne... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + En attente de la fin du travail en arrière-plan... @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + '{0}' bases @@ -919,7 +929,7 @@ The triggerSpan is not included in the given workspace. - TriggerSpan n'est pas inclus dans l'espace de travail donné. + triggerSpan n'est pas inclus dans l'espace de travail donné. diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.it.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.it.xlf index 654664758ee63..c7eff79a40c9f 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.it.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.it.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + Per l'identificatore '{0}' è attiva una sessione di ridenominazione inline. Richiamare nuovamente la ridenominazione inline per accedere alle opzioni aggiuntive. È possibile continuare a modificare l'identificatore da rinominare in qualsiasi momento. For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ Procedere comunque? Il codice ottenuto potrebbe essere danneggiato. + + items from unimported namespaces + elementi da spazi dei nomi non importati + + + + Expander + Expander + + Extract method encountered the following issues: Il metodo di estrazione ha rilevato i problemi seguenti: @@ -89,17 +99,17 @@ Rename _file - Rename _file + Rinomina _file Rename _file (type does not match file name) - Rename _file (type does not match file name) + Rinomina _file (il tipo non corrisponde al nome file) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + Rinomina _file (non consentito su tipi parziali) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + Non è presente alcuna base per il simbolo. Toggle Block Comment - Toggle Block Comment + Attiva/Disattiva commento per il blocco Toggle Line Comment - Toggle Line Comment + Attiva/Disattiva commento per la riga Toggling block comment... - Toggling block comment... + Attivazione/disattivazione del commento per il blocco... Toggling line comment... - Toggling line comment... + Attivazione/disattivazione del commento per la riga... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + In attesa del completamento dei processi in background... @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + Basi di '{0}' diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ja.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ja.xlf index 49b7c59681ff1..d6a2da1620753 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ja.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ja.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + 識別子 '{0}' のインラインの名前変更セッションがアクティブです。追加オプションにアクセスするには、インラインの名前変更をもう一度呼び出します。名前を変更する識別子はいつでも引き続き編集できます。 For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ 続行しますか。破損状態のコードが生成される可能性があります。 + + items from unimported namespaces + インポートされていない名前空間の項目 + + + + Expander + 展開コントロール + + Extract method encountered the following issues: メソッドの抽出で次の問題が発生しました: @@ -89,17 +99,17 @@ Rename _file - Rename _file + ファイル名の変更(_F) Rename _file (type does not match file name) - Rename _file (type does not match file name) + ファイル名の変更 (種類がファイル名と一致しません)(_F) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + ファイル名の変更 (部分型では許可されません)(_F) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + シンボルにベースがありません。 Toggle Block Comment - Toggle Block Comment + ブロック コメントの切り替え Toggle Line Comment - Toggle Line Comment + 行コメントの切り替え Toggling block comment... - Toggling block comment... + ブロック コメントを切り替えています... Toggling line comment... - Toggling line comment... + 行コメントを切り替えています... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + バックグラウンド作業が終了するのを待っています... @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + '{0}' ベース diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ko.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ko.xlf index bec5d50445728..f4f4278ff8e9e 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ko.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ko.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + 식별자 '{0}'의 인라인 이름 바꾸기 세션이 활성 상태입니다. 추가 옵션에 액세스하려면 인라인 이름 바꾸기를 다시 호출하세요. 언제든지 이름을 바꾸려는 식별자를 계속 편집할 수 있습니다. For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ 계속하시겠습니까? 계속하면 손상된 코드가 생성될 수 있습니다. + + items from unimported namespaces + 가져오지 않은 네임스페이스의 항목 + + + + Expander + 확장기 + + Extract method encountered the following issues: 메서드 추출에서 다음 문제가 발생했습니다. @@ -89,17 +99,17 @@ Rename _file - Rename _file + 파일 이름 바꾸기(_F) Rename _file (type does not match file name) - Rename _file (type does not match file name) + 파일 이름 바꾸기(형식이 파일 이름과 일치하지 않음)(_F) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + 파일 이름 바꾸기(부분 형식에서 허용되지 않음)(_F) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + 기호에 베이스가 없습니다. Toggle Block Comment - Toggle Block Comment + 블록 주석 토글 Toggle Line Comment - Toggle Line Comment + 줄 주석 토글 Toggling block comment... - Toggling block comment... + 블록 주석을 토글하는 중... Toggling line comment... - Toggling line comment... + 줄 주석을 토글하는 중... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + 백그라운드 작업이 완료될 때까지 대기 중... @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + '{0}' 기본 @@ -939,7 +949,7 @@ Can't compare positions from different text snapshots - 다른 텍스트 스냅숏에서 위치를 비교할 수 없습니다. + 다른 텍스트 스냅샷에서 위치를 비교할 수 없습니다. @@ -1141,7 +1151,7 @@ Do you want to proceed? IntelliSense Commit Formatting - Intellisense 커밋 서식 + IntelliSense 커밋 서식 diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pl.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pl.xlf index 337a42a74b532..0531ee0d5b941 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pl.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pl.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + Wbudowana sesja zmieniania nazwy jest aktywna dla identyfikatora „{0}”. Wywołaj ponownie wbudowane zmienianie nazwy, aby uzyskać dostęp do dodatkowych opcji. W dowolnym momencie możesz kontynuować edytowanie identyfikatora, którego nazwa jest zmieniana. For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ Czy nadal chcesz kontynuować? Może to spowodować uszkodzenie kodu. + + items from unimported namespaces + elementy z nieimportowanych przestrzeni nazw + + + + Expander + Ekspander + + Extract method encountered the following issues: Metoda ekstrakcji napotkała następujące problemy: @@ -89,17 +99,17 @@ Rename _file - Rename _file + Zmień nazwę _pliku Rename _file (type does not match file name) - Rename _file (type does not match file name) + Zmień nazwę _pliku (typ nie zgadza się z nazwą pliku) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + Zmień nazwę _pliku (niedozwolone dla typów częściowych) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + Symbol nie ma wartości podstawowej. Toggle Block Comment - Toggle Block Comment + Przełącz komentarz blokowy Toggle Line Comment - Toggle Line Comment + Przełącz komentarz wiersza Toggling block comment... - Toggling block comment... + Trwa przełączanie komentarza blokowego... Toggling line comment... - Toggling line comment... + Trwa przełączanie komentarza wiersza... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + Oczekiwanie na zakończenie pracy w tle... @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + Wartości podstawowe „{0}” diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pt-BR.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pt-BR.xlf index 1a6b5896149cb..6207ea154f6d0 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pt-BR.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.pt-BR.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + Uma sessão de renomeação embutida está ativa para o identificador '{0}'. Invoque a renomeação embutida novamente para acessar opções adicionais. Você pode continuar a editar o identificador que está sendo renomeado a qualquer momento. For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ Ainda quer continuar? Isso pode produzir código desfeito. + + items from unimported namespaces + itens de namespaces não importados + + + + Expander + Expansor + + Extract method encountered the following issues: O método de extração encontrou os seguintes problemas: @@ -89,17 +99,17 @@ Rename _file - Rename _file + Renomear _arquivo Rename _file (type does not match file name) - Rename _file (type does not match file name) + Renomear _arquivo (o tipo não corresponde ao nome do arquivo) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + Renomear _arquivo (não permitido em tipos parciais) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + O símbolo não tem nenhuma base. Toggle Block Comment - Toggle Block Comment + Ativar/Desativar Comentário de Bloco Toggle Line Comment - Toggle Line Comment + Ativar/Desativar Comentário de Linha Toggling block comment... - Toggling block comment... + Ativando/desativando o comentário de bloco... Toggling line comment... - Toggling line comment... + Ativando/desativando o comentário de linha... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + Aguardando a conclusão do trabalho em segundo plano... @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + Bases '{0}' diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.xlf index aac1a8cac006a..6e3bba1ab1e0c 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.ru.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + Встроенный сеанс переименования активен для идентификатора "{0}". Снова вызовите встроенное переименование, чтобы получить доступ к дополнительным параметрам. Вы можете в любое время продолжить изменение переименованного идентификатора. For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ Вы действительно хотите продолжить? Это может привести к появлению нерабочего кода. + + items from unimported namespaces + элементы из неимпортированных пространств имен + + + + Expander + Расширитель + + Extract method encountered the following issues: При работе метода извлечения возникли следующие ошибки: @@ -89,17 +99,17 @@ Rename _file - Rename _file + Переименовать фай_л Rename _file (type does not match file name) - Rename _file (type does not match file name) + Переименовать фай_л (тип не соответствует имени файла) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + Переименовать фай_л (недопустимо для разделяемых типов) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + У этого символа нет основания. Toggle Block Comment - Toggle Block Comment + Переключить комментарий блока Toggle Line Comment - Toggle Line Comment + Переключить комментарий строки Toggling block comment... - Toggling block comment... + Переключение комментария блока... Toggling line comment... - Toggling line comment... + Переключение комментария строки... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + Ожидание завершения фоновой работы… @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + Основания: "{0}" diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.tr.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.tr.xlf index 2dc35fbfe653d..00194ff36104c 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.tr.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.tr.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + '{0}' tanımlayıcısı için bir satır içi yeniden adlandırma oturumu etkin. Ek seçeneklere erişmek için satır içi yeniden adlandırmayı tekrar çağırın. İstediğiniz zaman yeniden adlandırılan tanımlayıcıyı düzenlemeye devam edebilirsiniz. For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ Yine de devam etmek istiyor musunuz? Bu işlem sonucunda bozuk kod oluşturulabilir. + + items from unimported namespaces + içeri aktarılmayan ad alanlarındaki öğeler + + + + Expander + Genişletici + + Extract method encountered the following issues: Ayıklama metodu aşağıdaki sorunlarla karşılaştı: @@ -89,17 +99,17 @@ Rename _file - Rename _file + Dosyayı _yeniden adlandır Rename _file (type does not match file name) - Rename _file (type does not match file name) + _Dosyayı yeniden adlandır (tür, dosya adıyla eşleşmiyor) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + _Dosya adını değiştir (kısmi türlerde izin verilmez) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + Sembolde taban yok. Toggle Block Comment - Toggle Block Comment + Blok Açıklamasını Aç/Kapat Toggle Line Comment - Toggle Line Comment + Satır Açıklamasını Aç/Kapat Toggling block comment... - Toggling block comment... + Blok açıklaması değiştiriliyor... Toggling line comment... - Toggling line comment... + Satır açıklaması değiştiriliyor... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + Arka plan çalışmasının bitmesi bekleniyor... @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + '{0}' tabanları diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hans.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hans.xlf index df5fc91745b74..d67c4e52c10b1 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hans.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hans.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + 标识符“{0}”的内联重命名会话处于活动状态。再次调用内联重命名以访问其他选项。可随时继续编辑正在重命名的标识符。 For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ 是否仍要继续? 这可能会导致代码损坏。 + + items from unimported namespaces + 未导入命名空间中的项 + + + + Expander + 扩展器 + + Extract method encountered the following issues: Extract 方法遇到以下问题: @@ -69,7 +79,7 @@ Operator - Overloaded - 运算符-超载 + 运算符-重载 @@ -89,17 +99,17 @@ Rename _file - Rename _file + 重命名文件(_F) Rename _file (type does not match file name) - Rename _file (type does not match file name) + 重命名文件(类型与文件名不匹配)(_F) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + 重命名文件(不允许在分部类型上使用)(_F) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + 符号没有基数。 Toggle Block Comment - Toggle Block Comment + 切换为块注释 Toggle Line Comment - Toggle Line Comment + 切换为行注释 Toggling block comment... - Toggling block comment... + 正在切换为块注释... Toggling line comment... - Toggling line comment... + 正在切换为行注释... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + 正在等待后台工作完成... @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + “{0}”基数 @@ -769,7 +779,7 @@ Formatting - 正在格式化 + 格式设置 diff --git a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hant.xlf b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hant.xlf index 91303d0e95826..45fbb66401c95 100644 --- a/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hant.xlf +++ b/src/EditorFeatures/Core/xlf/EditorFeaturesResources.zh-Hant.xlf @@ -4,7 +4,7 @@ An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. - An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time. + 識別碼 '{0}' 有正在使用的內嵌重新命名工作階段。再次叫用內嵌重新命名可存取其他選項。您隨時可以繼續編輯正在重新命名的識別碼。 For screenreaders. {0} is the identifier being renamed. @@ -37,6 +37,16 @@ 仍要繼續嗎? 這可能產生中斷的程式碼。 + + items from unimported namespaces + 來自未匯入命名空間的項目 + + + + Expander + 展開器 + + Extract method encountered the following issues: 擷取方法發生下列問題: @@ -89,17 +99,17 @@ Rename _file - Rename _file + 重新命名檔案(_F) Rename _file (type does not match file name) - Rename _file (type does not match file name) + 重新命名檔案 (類型不符合檔案名稱)(_F) Rename _file (not allowed on partial types) - Rename _file (not allowed on partial types) + 重新命名檔案 (在部分類型上不允許)(_F) Disabled text status for file rename @@ -114,27 +124,27 @@ The symbol has no base. - The symbol has no base. + 該符號沒有任何基底。 Toggle Block Comment - Toggle Block Comment + 切換區塊註解 Toggle Line Comment - Toggle Line Comment + 切換行註解 Toggling block comment... - Toggling block comment... + 正在切換區塊註解... Toggling line comment... - Toggling line comment... + 正在切換行註解... @@ -229,7 +239,7 @@ Waiting for background work to finish... - Waiting for background work to finish... + 正在等候背景工作完成... @@ -359,7 +369,7 @@ '{0}' bases - '{0}' bases + '{0}' 個基底 diff --git a/src/EditorFeatures/Test/EditAndContinue/DebuggeeModuleMetadataCacheTests.cs b/src/EditorFeatures/Test/EditAndContinue/DebuggeeModuleMetadataCacheTests.cs index e3f36e6fa0941..b9f08a9c6ab08 100644 --- a/src/EditorFeatures/Test/EditAndContinue/DebuggeeModuleMetadataCacheTests.cs +++ b/src/EditorFeatures/Test/EditAndContinue/DebuggeeModuleMetadataCacheTests.cs @@ -1,11 +1,10 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using Microsoft.CodeAnalysis.EditAndContinue; using Roslyn.Test.Utilities; using Xunit; -namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditAndContinue +namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public sealed class DebuggeeModuleMetadataCacheTests { diff --git a/src/EditorFeatures/Test/EditAndContinue/EditAndContinueDiagnosticDescriptorsTests.cs b/src/EditorFeatures/Test/EditAndContinue/EditAndContinueDiagnosticDescriptorsTests.cs new file mode 100644 index 0000000000000..de38ccf3b362a --- /dev/null +++ b/src/EditorFeatures/Test/EditAndContinue/EditAndContinueDiagnosticDescriptorsTests.cs @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Linq; +using Xunit; + +namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests +{ + public class EditAndContinueDiagnosticDescriptorsTests + { + [Fact] + public void GetDescriptor() + { + var d = EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.ActiveStatementUpdate); + Assert.Equal("ENC0001", d.Id); + Assert.Equal(FeaturesResources.EditAndContinue, d.Category); + Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable" }, d.CustomTags); + Assert.Equal("", d.Description); + Assert.Equal("", d.HelpLinkUri); + Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.RudeEdit), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title); + Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.Updating_an_active_statement_will_prevent_the_debug_session_from_continuing), + FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat); + + Assert.Equal("ENC0082", EditAndContinueDiagnosticDescriptors.GetDescriptor(RudeEditKind.ComplexQueryExpression).Id); + + d = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); + Assert.Equal("ENC1001", d.Id); + Assert.Equal(FeaturesResources.EditAndContinue, d.Category); + Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable" }, d.CustomTags); + Assert.Equal("", d.Description); + Assert.Equal("", d.HelpLinkUri); + Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinue), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title); + Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.ErrorReadingFile), + FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat); + + d = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(12); + Assert.Equal("ENC2012", d.Id); + Assert.Equal(FeaturesResources.EditAndContinue, d.Category); + Assert.Equal(new[] { "EditAndContinue", "Telemetry", "NotConfigurable" }, d.CustomTags); + Assert.Equal("", d.Description); + Assert.Equal("", d.HelpLinkUri); + Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinue), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.Title); + Assert.Equal(new LocalizableResourceString(nameof(FeaturesResources.EditAndContinueDisallowedByProject), FeaturesResources.ResourceManager, typeof(FeaturesResources)), d.MessageFormat); + } + + [Fact] + public void GetDescriptors() + { + var descriptors = EditAndContinueDiagnosticDescriptors.GetDescriptors(); + Assert.NotEmpty(descriptors); + Assert.True(descriptors.All(d => d != null)); + } + } +} diff --git a/src/EditorFeatures/Test/EditAndContinue/EditAndContinueDiagnosticUpdateSourceTests.cs b/src/EditorFeatures/Test/EditAndContinue/EditAndContinueDiagnosticUpdateSourceTests.cs index 389f65a896a03..93ceea771d4ee 100644 --- a/src/EditorFeatures/Test/EditAndContinue/EditAndContinueDiagnosticUpdateSourceTests.cs +++ b/src/EditorFeatures/Test/EditAndContinue/EditAndContinueDiagnosticUpdateSourceTests.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.TestHooks; @@ -21,18 +20,12 @@ public class EditAndContinueDiagnosticUpdateSourceTests [Fact] public void ReportDiagnostics() { - var service = new DiagnosticService( - AsynchronousOperationListenerProvider.NullProvider, Array.Empty>()); - var source = new EditAndContinueDiagnosticUpdateSource(service); + var source = new EditAndContinueDiagnosticUpdateSource(); var updates = new List(); - source.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs e) => - { - updates.Add($"{e.Kind} p={e.ProjectId} d={e.DocumentId}: {string.Join(",", e.Diagnostics.Select(d => d.Id.ToString()))}"); - }; - - var id = new object(); + source.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs e) + => updates.Add($"{e.Kind} p={e.ProjectId} d={e.DocumentId}: {string.Join(",", e.Diagnostics.Select(d => d.Id.ToString()))}"); var srcC1 = "class C1 {}"; var srcC2 = "class C2 {}"; @@ -65,26 +58,37 @@ public void ReportDiagnostics() Diagnostic.Create(new DiagnosticDescriptor("TST0002", "title2", "message2", "category", DiagnosticSeverity.Error, true), Location.Create(treeC1, new TextSpan(1, 2))), Diagnostic.Create(new DiagnosticDescriptor("TST0003", "title3", "message3", "category", DiagnosticSeverity.Error, true), Location.Create(treeD1, new TextSpan(1, 2))), Diagnostic.Create(new DiagnosticDescriptor("TST0004", "title4", "message4", "category", DiagnosticSeverity.Error, true), Location.Create(treeD2, new TextSpan(1, 2))), + Diagnostic.Create(new DiagnosticDescriptor("TST0005", "title5", "message5", "category", DiagnosticSeverity.Error, true), Location.None), }; updates.Clear(); - var actual = source.ReportDiagnostics(id, workspace.CurrentSolution, projC.Id, diagnostics); - AssertEx.Equal(new[] { docC1.Id }, actual); + source.ReportDiagnostics(workspace.CurrentSolution, projC.Id, diagnostics); AssertEx.Equal(new[] { $"DiagnosticsCreated p={projC.Id} d={docC1.Id}: TST0001,TST0002", $"DiagnosticsCreated p={projC.Id} d={docD1.Id}: TST0003", - $"DiagnosticsCreated p={projC.Id} d={docD2.Id}: TST0004" + $"DiagnosticsCreated p={projC.Id} d={docD2.Id}: TST0004", + $"DiagnosticsCreated p={projC.Id} d=: TST0005" }, updates); updates.Clear(); - actual = source.ReportDiagnostics(id, workspace.CurrentSolution, projD.Id, diagnostics); - AssertEx.SetEqual(new[] { docD1.Id, docD2.Id }, actual); + source.ReportDiagnostics(workspace.CurrentSolution, projD.Id, diagnostics); AssertEx.Equal(new[] - { + { $"DiagnosticsCreated p={projD.Id} d={docC1.Id}: TST0001,TST0002", $"DiagnosticsCreated p={projD.Id} d={docD1.Id}: TST0003", - $"DiagnosticsCreated p={projD.Id} d={docD2.Id}: TST0004" + $"DiagnosticsCreated p={projD.Id} d={docD2.Id}: TST0004", + $"DiagnosticsCreated p={projD.Id} d=: TST0005" + }, updates); + + updates.Clear(); + source.ReportDiagnostics(workspace.CurrentSolution, null, diagnostics); + AssertEx.Equal(new[] + { + $"DiagnosticsCreated p= d={docC1.Id}: TST0001,TST0002", + $"DiagnosticsCreated p= d={docD1.Id}: TST0003", + $"DiagnosticsCreated p= d={docD2.Id}: TST0004", + $"DiagnosticsCreated p= d=: TST0005" }, updates); } } diff --git a/src/EditorFeatures/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs b/src/EditorFeatures/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs new file mode 100644 index 0000000000000..79a529144179a --- /dev/null +++ b/src/EditorFeatures/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs @@ -0,0 +1,1337 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Editor.UnitTests; +using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Test.Utilities; +using Microsoft.CodeAnalysis.Text; +using Microsoft.CodeAnalysis.UnitTests; +using Moq; +using Roslyn.Test.Utilities; +using Xunit; + +namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests +{ + [UseExportProvider] + public sealed class EditAndContinueWorkspaceServiceTests : TestBase + { + private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; + private readonly Mock _mockDiagnosticService; + private readonly MockDebuggeeModuleMetadataProvider _mockDebugeeModuleMetadataProvider; + private readonly Mock _mockActiveStatementTrackingService; + private readonly MockCompilationOutputsProviderService _mockCompilationOutputsService; + + private Mock _mockActiveStatementProvider; + private readonly List _modulesPreparedForUpdate; + private readonly List _emitDiagnosticsUpdated; + private int _emitDiagnosticsClearedCount; + private readonly List _telemetryLog; + private int _telemetryId; + + public EditAndContinueWorkspaceServiceTests() + { + _modulesPreparedForUpdate = new List(); + _mockDiagnosticService = new Mock(MockBehavior.Strict); + _mockDiagnosticService.Setup(s => s.Reanalyze(It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny())); + + _diagnosticUpdateSource = new EditAndContinueDiagnosticUpdateSource(); + _emitDiagnosticsUpdated = new List(); + _diagnosticUpdateSource.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs args) => _emitDiagnosticsUpdated.Add(args); + _diagnosticUpdateSource.DiagnosticsCleared += (object sender, EventArgs args) => _emitDiagnosticsClearedCount++; + + _mockActiveStatementProvider = new Mock(MockBehavior.Strict); + _mockActiveStatementProvider.Setup(p => p.GetActiveStatementsAsync(It.IsAny())). + Returns(Task.FromResult(ImmutableArray.Empty)); + + _mockDebugeeModuleMetadataProvider = new MockDebuggeeModuleMetadataProvider + { + IsEditAndContinueAvailable = (Guid guid, out int errorCode, out string localizedMessage) => + { + errorCode = 0; + localizedMessage = null; + return true; + }, + PrepareModuleForUpdate = mvid => _modulesPreparedForUpdate.Add(mvid) + }; + + _mockActiveStatementTrackingService = new Mock(MockBehavior.Strict); + _mockActiveStatementTrackingService.Setup(s => s.StartTracking(It.IsAny())); + _mockActiveStatementTrackingService.Setup(s => s.EndTracking()); + + _mockCompilationOutputsService = new MockCompilationOutputsProviderService(); + _telemetryLog = new List(); + } + + private EditAndContinueWorkspaceService CreateEditAndContinueService(Workspace workspace) + => new EditAndContinueWorkspaceService( + workspace, + _mockActiveStatementTrackingService.Object, + _mockCompilationOutputsService, + _mockDiagnosticService.Object, + _diagnosticUpdateSource, + _mockActiveStatementProvider.Object, + _mockDebugeeModuleMetadataProvider, + reportTelemetry: data => EditAndContinueWorkspaceService.LogDebuggingSessionTelemetry(data, (id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId)); + + private void VerifyReanalyzeInvocation(params object[] expectedArgs) + => _mockDiagnosticService.Invocations.VerifyAndClear((nameof(IDiagnosticAnalyzerService.Reanalyze), expectedArgs)); + + internal static Guid ReadModuleVersionId(Stream stream) + { + using (var peReader = new PEReader(stream)) + { + var metadataReader = peReader.GetMetadataReader(); + var mvidHandle = metadataReader.GetModuleDefinition().Mvid; + return metadataReader.GetGuid(mvidHandle); + } + } + + [Fact] + public void ActiveStatementTracking() + { + using (var workspace = new TestWorkspace()) + { + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + service.StartEditSession(); + _mockActiveStatementTrackingService.Verify(ts => ts.StartTracking(It.IsAny()), Times.Once()); + + service.EndEditSession(); + _mockActiveStatementTrackingService.Verify(ts => ts.EndTracking(), Times.Once()); + + service.EndDebuggingSession(); + + _mockActiveStatementTrackingService.Verify(ts => ts.StartTracking(It.IsAny()), Times.Once()); + _mockActiveStatementTrackingService.Verify(ts => ts.EndTracking(), Times.Once()); + } + } + + [Fact] + public async Task RunMode_ProjectThatDoesNotSupportEnC() + { + var exportProviderFactory = ExportProviderCache.GetOrCreateExportProviderFactory( + TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic.WithPart(typeof(DummyLanguageService))); + + using (var workspace = new TestWorkspace(exportProvider: exportProviderFactory.CreateExportProvider())) + { + var solution = workspace.CurrentSolution; + var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); + var document = project.AddDocument("test", SourceText.From("dummy1")); + workspace.ChangeSolution(document.Project.Solution); + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + // no changes: + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, CancellationToken.None).ConfigureAwait(false); + Assert.Empty(diagnostics); + + // change the source: + workspace.ChangeDocument(document1.Id, SourceText.From("dummy2")); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + diagnostics = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + Assert.Empty(diagnostics); + } + } + + [Fact] + public async Task RunMode_ProjectNotBuilt() + { + using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) + { + var service = CreateEditAndContinueService(workspace); + + var project = workspace.CurrentSolution.Projects.Single(); + _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(Guid.Empty)); + + service.StartDebuggingSession(); + + // no changes: + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, CancellationToken.None).ConfigureAwait(false); + Assert.Empty(diagnostics); + + // change the source: + workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + diagnostics = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + Assert.Empty(diagnostics); + } + } + + [Fact] + public async Task RunMode_ErrorReadingFile() + { + var moduleFile = Temp.CreateFile(); + + using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) + { + var project = workspace.CurrentSolution.Projects.Single(); + + _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + // no changes: + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, CancellationToken.None).ConfigureAwait(false); + Assert.Empty(diagnostics); + + // change the source: + workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: + diagnostics = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + Assert.Empty(diagnostics); + + // validate solution update status and emit - changes made during run mode are ignored: + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, solutionStatus); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, solutionStatusEmit); + Assert.Empty(deltas); + } + } + + [Fact] + public async Task RunMode_Diagnostics() + { + var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); + + using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) + { + var project = workspace.CurrentSolution.Projects.Single(); + workspace.ChangeSolution(project.Solution.WithProjectOutputFilePath(project.Id, moduleFile.Path)); + + _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); + + var service = CreateEditAndContinueService(workspace); + + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, solutionStatus); + + service.StartDebuggingSession(); + + // no changes: + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, CancellationToken.None).ConfigureAwait(false); + Assert.Empty(diagnostics); + + solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, solutionStatus); + + // change the source: + workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + // validate solution update status and emit - changes made during run mode are ignored: + solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, solutionStatus); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, solutionStatusEmit); + Assert.Empty(deltas); + + diagnostics = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + AssertEx.Equal(new[] { "ENC1003" }, diagnostics.Select(d => d.Id)); + + service.EndDebuggingSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Create(document2.Id), false); + + AssertEx.Equal(new[] + { + "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" + }, _telemetryLog); + } + } + + [Fact] + public async Task BreakMode_ProjectThatDoesNotSupportEnC() + { + var exportProviderFactory = ExportProviderCache.GetOrCreateExportProviderFactory( + TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic.WithPart(typeof(DummyLanguageService))); + + using (var workspace = new TestWorkspace(exportProvider: exportProviderFactory.CreateExportProvider())) + { + var solution = workspace.CurrentSolution; + var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); + var document = project.AddDocument("test", SourceText.From("dummy1")); + workspace.ChangeSolution(document.Project.Solution); + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + service.StartEditSession(); + + // change the source: + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + workspace.ChangeDocument(document1.Id, SourceText.From("dummy2")); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + // validate solution update status and emit: + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, solutionStatus); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, solutionStatusEmit); + Assert.Empty(deltas); + } + } + + [Fact] + public async Task BreakMode_ErrorReadingFile() + { + var moduleFile = Temp.CreateFile(); + + using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) + { + var project = workspace.CurrentSolution.Projects.Single(); + _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + service.StartEditSession(); + + // change the source: + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: + var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + Assert.Empty(diagnostics); + + // validate solution update status and emit: + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, solutionStatus); + + Assert.Empty(_emitDiagnosticsUpdated); + Assert.Equal(0, _emitDiagnosticsClearedCount); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); + Assert.Empty(deltas); + + Assert.Equal(1, _emitDiagnosticsClearedCount); + var eventArgs = _emitDiagnosticsUpdated.Single(); + Assert.Null(eventArgs.DocumentId); + Assert.Equal(project.Id, eventArgs.ProjectId); + AssertEx.Equal(new[] { "ENC1001" }, eventArgs.Diagnostics.Select(d => d.Id)); + _emitDiagnosticsUpdated.Clear(); + _emitDiagnosticsClearedCount = 0; + + service.EndEditSession(); + Assert.Empty(_emitDiagnosticsUpdated); + Assert.Equal(0, _emitDiagnosticsClearedCount); + + service.EndDebuggingSession(); + Assert.Empty(_emitDiagnosticsUpdated); + Assert.Equal(1, _emitDiagnosticsClearedCount); + + AssertEx.Equal(new[] + { + "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", + "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", + "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" + }, _telemetryLog); + } + } + + [Fact] + public async Task BreakMode_ModuleDisallowsEditAndContinue() + { + var moduleId = Guid.NewGuid(); + + var source1 = @" +class C1 +{ + void M() + { + System.Console.WriteLine(1); + System.Console.WriteLine(2); + System.Console.WriteLine(3); + } +}"; + var source2 = @" +class C1 +{ + + void M() + { + System.Console.WriteLine(9); + System.Console.WriteLine(); + System.Console.WriteLine(30); + } +}"; + var expectedMessage = "ENC2123: " + string.Format(FeaturesResources.EditAndContinueDisallowedByProject, "Test", "*message*"); + + var expectedDiagnostics = new[] + { + "[17..19): " + expectedMessage, + "[66..67): " + expectedMessage, + "[101..101): " + expectedMessage, + "[136..137): " + expectedMessage, + }; + + string inspectDiagnostic(Diagnostic d) + => $"{d.Location.SourceSpan}: {d.Id}: {d.GetMessage()}"; + + using (var workspace = TestWorkspace.CreateCSharp(source1)) + { + var project = workspace.CurrentSolution.Projects.Single(); + _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(moduleId)); + + bool isEditAndContinueAvailableInvocationAllowed = true; + _mockDebugeeModuleMetadataProvider.IsEditAndContinueAvailable = (Guid guid, out int errorCode, out string localizedMessage) => + { + Assert.True(isEditAndContinueAvailableInvocationAllowed); + + Assert.Equal(moduleId, guid); + errorCode = 123; + localizedMessage = "*message*"; + return false; + }; + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + service.StartEditSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + // change the source: + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + workspace.ChangeDocument(document1.Id, SourceText.From(source2)); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + isEditAndContinueAvailableInvocationAllowed = true; + var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + AssertEx.Equal(expectedDiagnostics, diagnostics1.Select(inspectDiagnostic)); + + // the diagnostic should be cached and we should not invoke isEditAndContinueAvailable again: + isEditAndContinueAvailableInvocationAllowed = false; + var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + AssertEx.Equal(expectedDiagnostics, diagnostics2.Select(inspectDiagnostic)); + + // invalidate cache: + service.Test_GetEditSession().ModuleInstanceLoadedOrUnloaded(moduleId); + isEditAndContinueAvailableInvocationAllowed = true; + var diagnostics3 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + AssertEx.Equal(expectedDiagnostics, diagnostics3.Select(inspectDiagnostic)); + + // validate solution update status and emit: + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatus); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); + Assert.Empty(deltas); + + service.EndEditSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Create(document2.Id), false); + + service.EndDebuggingSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + AssertEx.Equal(new[] { moduleId }, _modulesPreparedForUpdate); + + AssertEx.Equal(new[] + { + "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", + "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", + "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2123" + }, _telemetryLog); + } + } + + [Fact] + public async Task BreakMode_RudeEdits() + { + var moduleId = Guid.NewGuid(); + + using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) + { + var project = workspace.CurrentSolution.Projects.Single(); + _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(moduleId)); + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + service.StartEditSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + // change the source (rude edit): + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M1() { System.Console.WriteLine(1); } }")); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_will_prevent_the_debug_session_from_continuing, FeaturesResources.method) }, + diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); + + // validate solution update status and emit: + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatus); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); + Assert.Empty(deltas); + + service.EndEditSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Create(document2.Id), false); + + service.EndDebuggingSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + AssertEx.Equal(new[] { moduleId }, _modulesPreparedForUpdate); + + AssertEx.Equal(new[] + { + "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", + "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0", + "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" + }, _telemetryLog); + } + } + + [Fact] + public async Task BreakMode_SyntaxError() + { + var moduleId = Guid.NewGuid(); + + using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) + { + var project = workspace.CurrentSolution.Projects.Single(); + _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(moduleId)); + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + service.StartEditSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + // change the source (compilation error): + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { ")); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + // compilation errors are not reported via EnC diagnostic analyzer: + var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + AssertEx.Empty(diagnostics1); + + // validate solution update status and emit: + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatus); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); + Assert.Empty(deltas); + + service.EndEditSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + service.EndDebuggingSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + AssertEx.Equal(new[] { moduleId }, _modulesPreparedForUpdate); + + AssertEx.Equal(new[] + { + "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", + "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0" + }, _telemetryLog); + } + } + + [Fact] + public async Task BreakMode_SemanticError() + { + var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; + var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll); + var (peImage, symReader) = SymReaderTestHelpers.EmitAndOpenDummySymReader(compilationV1, DebugInformationFormat.PortablePdb); + + var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); + var moduleId = moduleMetadata.GetModuleVersionId(); + var debuggeeModuleInfo = new DebuggeeModuleInfo(moduleMetadata, symReader); + + using (var workspace = TestWorkspace.CreateCSharp(sourceV1)) + { + var project = workspace.CurrentSolution.Projects.Single(); + _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(moduleId)); + _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => debuggeeModuleInfo; + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + service.StartEditSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + // change the source (compilation error): + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + // compilation errors are not reported via EnC diagnostic analyzer: + var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + AssertEx.Empty(diagnostics1); + + // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. + // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Ready, solutionStatus); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); + Assert.Empty(deltas); + + // TODO: https://github.com/dotnet/roslyn/issues/36061 + // Semantic errors should not be reported in emit diagnostics. + AssertEx.Equal(new[] { "CS0266" }, _emitDiagnosticsUpdated.Single().Diagnostics.Select(d => d.Id)); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); + _emitDiagnosticsUpdated.Clear(); + _emitDiagnosticsClearedCount = 0; + + service.EndEditSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + service.EndDebuggingSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + AssertEx.Equal(new[] { moduleId }, _modulesPreparedForUpdate); + + AssertEx.Equal(new[] + { + "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", + "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", + "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" + }, _telemetryLog); + } + } + + [Fact] + public async Task BreakMode_FileStatus_CompilationError() + { + using (var workspace = TestWorkspace.CreateCSharp("class Program { void Main() { System.Console.WriteLine(1); } }")) + { + var solution = workspace.CurrentSolution; + var projectA = solution.Projects.Single(); + + workspace.ChangeSolution(solution. + AddProject("B", "B", "C#"). + AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. + AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. + AddProject("C", "C", "C#"). + AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. + AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution); + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + service.StartEditSession(); + + // change C.cs to have a compilation error: + var projectC = workspace.CurrentSolution.GetProjectsByName("C").Single(); + var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); + workspace.ChangeDocument(documentC.Id, SourceText.From("class C { void M() { ")); + + // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: "Common.cs", CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatus); + + // No changes in project containing file B.cs. + solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: "B.cs", CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, solutionStatus); + + // All projects must have no errors. + solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatus); + + service.EndEditSession(); + service.EndDebuggingSession(); + } + } + + [Fact] + public async Task BreakMode_ValidSignificantChange_EmitError() + { + var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; + var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll); + var (peImage, symReader) = SymReaderTestHelpers.EmitAndOpenDummySymReader(compilationV1, DebugInformationFormat.PortablePdb); + + var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); + var moduleFile = Temp.CreateFile().WriteAllBytes(peImage); + var moduleId = moduleMetadata.GetModuleVersionId(); + var debuggeeModuleInfo = new DebuggeeModuleInfo(moduleMetadata, symReader); + + using (var workspace = TestWorkspace.CreateCSharp(sourceV1)) + { + var project = workspace.CurrentSolution.Projects.Single(); + _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); + + _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => debuggeeModuleInfo; + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + service.StartEditSession(); + var editSession = service.Test_GetEditSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + // change the source (valid edit but passing no encoding to emulate emit error): + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + AssertEx.Empty(diagnostics1); + + // validate solution update status and emit: + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Ready, solutionStatus); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + AssertEx.Equal(new[] { "CS8055" }, _emitDiagnosticsUpdated.Single().Diagnostics.Select(d => d.Id)); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); + _emitDiagnosticsUpdated.Clear(); + _emitDiagnosticsClearedCount = 0; + + // no emitted delta: + Assert.Empty(deltas); + + // no pending update: + Assert.Null(service.Test_GetPendingSolutionUpdate()); + + Assert.Throws(() => service.CommitSolutionUpdate()); + Assert.Throws(() => service.DiscardSolutionUpdate()); + + // no change in non-remappable regions since we didn't have any active statements: + Assert.Empty(editSession.DebuggingSession.NonRemappableRegions); + + // no open module readers since we didn't defer any module update: + Assert.Empty(editSession.DebuggingSession.GetBaselineModuleReaders()); + + // solution update status after discarding an update (still has update ready): + var commitedUpdateSolutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Ready, commitedUpdateSolutionStatus); + + service.EndEditSession(); + Assert.Empty(_emitDiagnosticsUpdated); + Assert.Equal(0, _emitDiagnosticsClearedCount); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + service.EndDebuggingSession(); + Assert.Empty(_emitDiagnosticsUpdated); + Assert.Equal(1, _emitDiagnosticsClearedCount); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + AssertEx.Equal(new[] + { + "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", + "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", + "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" + }, _telemetryLog); + } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task BreakMode_ValidSignificantChange_EmitSuccessful(bool commitUpdate) + { + var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; + var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll); + var (peImage, symReader) = SymReaderTestHelpers.EmitAndOpenDummySymReader(compilationV1, DebugInformationFormat.PortablePdb); + + var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); + var moduleFile = Temp.CreateFile().WriteAllBytes(peImage); + var moduleId = moduleMetadata.GetModuleVersionId(); + var debuggeeModuleInfo = new DebuggeeModuleInfo(moduleMetadata, symReader); + + using (var workspace = TestWorkspace.CreateCSharp(sourceV1)) + { + var project = workspace.CurrentSolution.Projects.Single(); + _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path)); + + var diagnosticUpdateSource = new EditAndContinueDiagnosticUpdateSource(); + var emitDiagnosticsUpdated = new List(); + diagnosticUpdateSource.DiagnosticsUpdated += (object sender, DiagnosticsUpdatedArgs args) => emitDiagnosticsUpdated.Add(args); + + _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => debuggeeModuleInfo; + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + service.StartEditSession(); + var editSession = service.Test_GetEditSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + // change the source (valid edit): + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, CancellationToken.None).ConfigureAwait(false); + AssertEx.Empty(diagnostics1); + + // validate solution update status and emit: + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Ready, solutionStatus); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + AssertEx.Empty(emitDiagnosticsUpdated); + Assert.Equal(SolutionUpdateStatus.Ready, solutionStatusEmit); + + // check emitted delta: + var delta = deltas.Single(); + Assert.Empty(delta.ActiveStatementsInUpdatedMethods); + Assert.NotEmpty(delta.IL.Value); + Assert.NotEmpty(delta.Metadata.Bytes); + Assert.NotEmpty(delta.Pdb.Stream); + Assert.Equal(0x06000001, delta.Pdb.UpdatedMethods.Single()); + Assert.Equal(moduleId, delta.Mvid); + Assert.Empty(delta.NonRemappableRegions); + Assert.Empty(delta.LineEdits); + + // the update should be stored on the service: + var pendingUpdate = service.Test_GetPendingSolutionUpdate(); + var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); + AssertEx.Equal(deltas, pendingUpdate.Deltas); + Assert.Empty(pendingUpdate.ModuleReaders); + Assert.Equal(project.Id, baselineProjectId); + Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); + + if (commitUpdate) + { + // all update providers either provided updates or had no change to apply: + service.CommitSolutionUpdate(); + + Assert.Null(service.Test_GetPendingSolutionUpdate()); + + // no change in non-remappable regions since we didn't have any active statements: + Assert.Empty(editSession.DebuggingSession.NonRemappableRegions); + + // no open module readers since we didn't defer any module update: + Assert.Empty(editSession.DebuggingSession.GetBaselineModuleReaders()); + + // verify that baseline is added: + Assert.Same(newBaseline, editSession.DebuggingSession.Test_GetProjectEmitBaseline(project.Id)); + + // solution update status after committing an update: + var commitedUpdateSolutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, commitedUpdateSolutionStatus); + } + else + { + // another update provider blocked the update: + service.DiscardSolutionUpdate(); + + Assert.Null(service.Test_GetPendingSolutionUpdate()); + + // solution update status after committing an update: + var discardedUpdateSolutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Ready, discardedUpdateSolutionStatus); + } + + service.EndEditSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + service.EndDebuggingSession(); + VerifyReanalyzeInvocation(workspace, null, ImmutableArray.Empty, false); + + AssertEx.Equal(new[] { moduleId }, _modulesPreparedForUpdate); + } + + // the debugger disposes the module metadata and SymReader: + debuggeeModuleInfo.Dispose(); + Assert.True(moduleMetadata.IsDisposed); + Assert.Null(debuggeeModuleInfo.SymReader); + + AssertEx.Equal(new[] + { + "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", + "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0", + }, _telemetryLog); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task BreakMode_ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) + { + var dir = Temp.CreateDirectory(); + + var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; + var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); + + var pdbStream = new MemoryStream(); + var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); + pdbStream.Position = 0; + + var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); + var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); + var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbStream.ToArray()); + var moduleId = moduleMetadata.GetModuleVersionId(); + + using var workspace = TestWorkspace.CreateCSharp(sourceV1); + + var project = workspace.CurrentSolution.Projects.Single(); + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + _mockCompilationOutputsService.Outputs.Add(project.Id, new CompilationOutputFiles(moduleFile.Path, pdbFile.Path)); + + // set up an active statement in the first method, so that we can test preservaton of local signature. + _mockActiveStatementProvider = new Mock(MockBehavior.Strict); + _mockActiveStatementProvider.Setup(p => p.GetActiveStatementsAsync(It.IsAny())). + Returns(Task.FromResult(ImmutableArray.Create(new ActiveStatementDebugInfo( + new ActiveInstructionId(moduleId, methodToken: 0x06000001, methodVersion: 1, ilOffset: 0), + documentNameOpt: document1.Name, + linePositionSpan: new LinePositionSpan(new LinePosition(0, 15), new LinePosition(0, 16)), + threadIds: ImmutableArray.Create(Guid.NewGuid()), + ActiveStatementFlags.IsLeafFrame)))); + + // module not loaded + _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => null; + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + service.StartEditSession(); + var editSession = service.Test_GetEditSession(); + + // change the source (valid edit): + workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); + var document2 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + + // validate solution update status and emit: + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Ready, solutionStatus); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Ready, solutionStatusEmit); + + // delta to apply: + var delta = deltas.Single(); + Assert.Empty(delta.ActiveStatementsInUpdatedMethods); + Assert.NotEmpty(delta.IL.Value); + Assert.NotEmpty(delta.Metadata.Bytes); + Assert.NotEmpty(delta.Pdb.Stream); + Assert.Equal(0x06000002, delta.Pdb.UpdatedMethods.Single()); + Assert.Equal(moduleId, delta.Mvid); + Assert.Empty(delta.NonRemappableRegions); + Assert.Empty(delta.LineEdits); + + // the update should be stored on the service: + var pendingUpdate = service.Test_GetPendingSolutionUpdate(); + var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); + + var readers = pendingUpdate.ModuleReaders; + Assert.Equal(2, readers.Length); + Assert.NotNull(readers[0]); + Assert.NotNull(readers[1]); + + Assert.Equal(project.Id, baselineProjectId); + Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); + + if (commitUpdate) + { + service.CommitSolutionUpdate(); + Assert.Null(service.Test_GetPendingSolutionUpdate()); + + // no change in non-remappable regions since we didn't have any active statements: + Assert.Empty(editSession.DebuggingSession.NonRemappableRegions); + + // deferred module readers tracked: + var baselineReaders = editSession.DebuggingSession.GetBaselineModuleReaders(); + Assert.Equal(2, baselineReaders.Length); + Assert.Same(readers[0], baselineReaders[0]); + Assert.Same(readers[1], baselineReaders[1]); + + // verify that baseline is added: + Assert.Same(newBaseline, editSession.DebuggingSession.Test_GetProjectEmitBaseline(project.Id)); + + // solution update status after committing an update: + var commitedUpdateSolutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, commitedUpdateSolutionStatus); + + service.EndEditSession(); + + // make another update: + service.StartEditSession(); + + // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. + // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. + // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. + var document3 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + workspace.ChangeDocument(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); + + (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Ready, solutionStatusEmit); + + service.EndEditSession(); + service.EndDebuggingSession(); + + // open module readers should be disposed when the debugging session ends: + Assert.Throws(() => ((MetadataReaderProvider)readers.First(r => r is MetadataReaderProvider)).GetMetadataReader()); + Assert.Throws(() => ((DebugInformationReaderProvider)readers.First(r => r is DebugInformationReaderProvider)).CreateEditAndContinueMethodDebugInfoReader()); + } + else + { + service.DiscardSolutionUpdate(); + Assert.Null(service.Test_GetPendingSolutionUpdate()); + + // no open module readers since we didn't defer any module update: + Assert.Empty(editSession.DebuggingSession.GetBaselineModuleReaders()); + + Assert.Throws(() => ((MetadataReaderProvider)readers.First(r => r is MetadataReaderProvider)).GetMetadataReader()); + Assert.Throws(() => ((DebugInformationReaderProvider)readers.First(r => r is DebugInformationReaderProvider)).CreateEditAndContinueMethodDebugInfoReader()); + + service.EndEditSession(); + service.EndDebuggingSession(); + } + } + + /// + /// Emulates two updates to Multi-TFM project. + /// + [Fact] + public async Task TwoUpdatesWithLoadedAndUnloadedModule() + { + var dir = Temp.CreateDirectory(); + + var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; + var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; + var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; + var compilationA = CSharpTestBase.CreateCompilationWithMscorlib40(source1, options: TestOptions.DebugDll, assemblyName: "A"); + var compilationB = CSharpTestBase.CreateCompilationWithMscorlib45(source1, options: TestOptions.DebugDll, assemblyName: "B"); + + var (peImageA, symReaderA) = SymReaderTestHelpers.EmitAndOpenDummySymReader(compilationA, DebugInformationFormat.PortablePdb); + + var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); + var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); + var moduleIdA = moduleMetadataA.GetModuleVersionId(); + var debuggeeModuleInfoA = new DebuggeeModuleInfo(moduleMetadataA, symReaderA); + + var pdbStreamB = new MemoryStream(); + var peImageB = compilationB.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStreamB); + pdbStreamB.Position = 0; + + var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); + var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); + var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbStreamB.ToArray()); + var moduleIdB = moduleMetadataB.GetModuleVersionId(); + + using (var workspace = TestWorkspace.CreateCSharp(source1)) + { + var solution = workspace.CurrentSolution; + var projectA = solution.Projects.Single(); + var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1).Project; + workspace.ChangeSolution(projectB.Solution); + + _mockCompilationOutputsService.Outputs.Add(projectA.Id, new CompilationOutputFiles(moduleFileA.Path)); + _mockCompilationOutputsService.Outputs.Add(projectB.Id, new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path)); + + // only module A is loaded + _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = + mvid => (mvid == moduleIdA) ? debuggeeModuleInfoA : null; + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + service.StartEditSession(); + var editSession = service.Test_GetEditSession(); + + // + // First update. + // + + workspace.ChangeDocument(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); + workspace.ChangeDocument(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); + + // validate solution update status and emit: + var solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Ready, solutionStatus); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Ready, solutionStatusEmit); + + var deltaA = deltas.Single(d => d.Mvid == moduleIdA); + var deltaB = deltas.Single(d => d.Mvid == moduleIdB); + Assert.Equal(2, deltas.Length); + + // the update should be stored on the service: + var pendingUpdate = service.Test_GetPendingSolutionUpdate(); + var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); + var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); + + var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); + var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); + + var readers = pendingUpdate.ModuleReaders; + Assert.Equal(2, readers.Length); + Assert.NotNull(readers[0]); + Assert.NotNull(readers[1]); + + Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); + Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); + + service.CommitSolutionUpdate(); + Assert.Null(service.Test_GetPendingSolutionUpdate()); + + // no change in non-remappable regions since we didn't have any active statements: + Assert.Empty(editSession.DebuggingSession.NonRemappableRegions); + + // deferred module readers tracked: + var baselineReaders = editSession.DebuggingSession.GetBaselineModuleReaders(); + Assert.Equal(2, baselineReaders.Length); + Assert.Same(readers[0], baselineReaders[0]); + Assert.Same(readers[1], baselineReaders[1]); + + // verify that baseline is added for both modules: + Assert.Same(newBaselineA1, editSession.DebuggingSession.Test_GetProjectEmitBaseline(projectA.Id)); + Assert.Same(newBaselineB1, editSession.DebuggingSession.Test_GetProjectEmitBaseline(projectB.Id)); + + // solution update status after committing an update: + var commitedUpdateSolutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, commitedUpdateSolutionStatus); + + service.EndEditSession(); + service.StartEditSession(); + editSession = service.Test_GetEditSession(); + + // + // Second update. + // + + workspace.ChangeDocument(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); + workspace.ChangeDocument(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); + + // validate solution update status and emit: + solutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Ready, solutionStatus); + + (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.Ready, solutionStatusEmit); + + deltaA = deltas.Single(d => d.Mvid == moduleIdA); + deltaB = deltas.Single(d => d.Mvid == moduleIdB); + Assert.Equal(2, deltas.Length); + + // the update should be stored on the service: + pendingUpdate = service.Test_GetPendingSolutionUpdate(); + var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); + var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); + + Assert.NotSame(newBaselineA1, newBaselineA2); + Assert.NotSame(newBaselineB1, newBaselineB2); + Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); + Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); + Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); + Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); + + // no new module readers: + Assert.Empty(pendingUpdate.ModuleReaders); + + service.CommitSolutionUpdate(); + Assert.Null(service.Test_GetPendingSolutionUpdate()); + + // no change in non-remappable regions since we didn't have any active statements: + Assert.Empty(editSession.DebuggingSession.NonRemappableRegions); + + // module readers tracked: + baselineReaders = editSession.DebuggingSession.GetBaselineModuleReaders(); + Assert.Equal(2, baselineReaders.Length); + Assert.Same(readers[0], baselineReaders[0]); + Assert.Same(readers[1], baselineReaders[1]); + + // verify that baseline is updated for both modules: + Assert.Same(newBaselineA2, editSession.DebuggingSession.Test_GetProjectEmitBaseline(projectA.Id)); + Assert.Same(newBaselineB2, editSession.DebuggingSession.Test_GetProjectEmitBaseline(projectB.Id)); + + // solution update status after committing an update: + commitedUpdateSolutionStatus = await service.GetSolutionUpdateStatusAsync(sourceFilePath: null, CancellationToken.None).ConfigureAwait(false); + Assert.Equal(SolutionUpdateStatus.None, commitedUpdateSolutionStatus); + + service.EndEditSession(); + + service.EndDebuggingSession(); + + // open deferred module readers should be dispose when the debugging session ends: + Assert.Throws(() => ((MetadataReaderProvider)readers.First(r => r is MetadataReaderProvider)).GetMetadataReader()); + Assert.Throws(() => ((DebugInformationReaderProvider)readers.First(r => r is DebugInformationReaderProvider)).CreateEditAndContinueMethodDebugInfoReader()); + } + } + + [Fact] + public void GetSpansInNewDocument() + { + // 012345678901234567890 + // 012___890_3489____0 + var changes = new[] + { + new TextChange(new TextSpan(3, 5), "___"), + new TextChange(new TextSpan(11, 2), "_"), + new TextChange(new TextSpan(15, 3), ""), + new TextChange(new TextSpan(20, 0), "____"), + }; + + Assert.Equal("012___890_3489____0", SourceText.From("012345678901234567890").WithChanges(changes).ToString()); + + AssertEx.Equal(new[] + { + "[3..6)", + "[9..10)", + "[12..12)", + "[14..18)" + }, EditAndContinueWorkspaceService.GetSpansInNewDocument(changes).Select(s => s.ToString())); + } + + [Fact] + public async Task GetDocumentTextChangesAsync() + { + var source1 = @" +class C1 +{ + void M() + { + System.Console.WriteLine(1); + System.Console.WriteLine(2); + System.Console.WriteLine(3); + } +}"; + var source2 = @" +class C1 +{ + + void M() + { + System.Console.WriteLine(9); + System.Console.WriteLine(); + System.Console.WriteLine(30); + } +}"; + + var oldTree = SyntaxFactory.ParseSyntaxTree(source1); + var newTree = SyntaxFactory.ParseSyntaxTree(source2); + var changes = await EditAndContinueWorkspaceService.GetDocumentTextChangesAsync(oldTree, newTree, CancellationToken.None).ConfigureAwait(false); + + AssertEx.Equal(new[] + { + "[17..17) '\r\n'", + "[64..65) '9'", + "[98..99) ''", + "[133..133) '0'" + }, changes.Select(s => $"{s.Span} '{s.NewText}'")); + } + + [Fact] + public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_NoStream() + { + using (var workspace = TestWorkspace.CreateCSharp("class C1 { void M() { System.Console.WriteLine(1); } }")) + { + var project = workspace.CurrentSolution.Projects.Single(); + _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(Guid.NewGuid()) + { + OpenPdbStreamImpl = () => null, + OpenAssemblyStreamImpl = () => null, + }); + + // module not loaded + _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => null; + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + service.StartEditSession(); + + // change the source (valid edit): + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + AssertEx.Equal(new[] { "ENC1001" }, _emitDiagnosticsUpdated.Single().Diagnostics.Select(d => d.Id)); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); + } + } + + [Fact] + public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() + { + var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; + var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); + + var pdbStream = new MemoryStream(); + var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); + pdbStream.Position = 0; + + using (var workspace = TestWorkspace.CreateCSharp(sourceV1)) + { + var project = workspace.CurrentSolution.Projects.Single(); + _mockCompilationOutputsService.Outputs.Add(project.Id, new MockCompilationOutputs(Guid.NewGuid()) + { + OpenPdbStreamImpl = () => pdbStream, + OpenAssemblyStreamImpl = () => throw new IOException(), + }); + + // module not loaded + _mockDebugeeModuleMetadataProvider.TryGetBaselineModuleInfo = mvid => null; + + var service = CreateEditAndContinueService(workspace); + + service.StartDebuggingSession(); + + service.StartEditSession(); + + // change the source (valid edit): + var document1 = workspace.CurrentSolution.Projects.Single().Documents.Single(); + workspace.ChangeDocument(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); + + var (solutionStatusEmit, deltas) = await service.EmitSolutionUpdateAsync(CancellationToken.None).ConfigureAwait(false); + AssertEx.Equal(new[] { "ENC1001" }, _emitDiagnosticsUpdated.Single().Diagnostics.Select(d => d.Id)); + Assert.Equal(SolutionUpdateStatus.Blocked, solutionStatusEmit); + + service.EndEditSession(); + service.EndDebuggingSession(); + + AssertEx.Equal(new[] + { + "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", + "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", + "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" + }, _telemetryLog); + } + } + } +} diff --git a/src/EditorFeatures/CSharpTest/EditAndContinue/EditSessionTests.cs b/src/EditorFeatures/Test/EditAndContinue/EditSessionActiveStatementsTests.cs similarity index 95% rename from src/EditorFeatures/CSharpTest/EditAndContinue/EditSessionTests.cs rename to src/EditorFeatures/Test/EditAndContinue/EditSessionActiveStatementsTests.cs index ef20d4027b8d9..342e73e7a74b3 100644 --- a/src/EditorFeatures/CSharpTest/EditAndContinue/EditSessionTests.cs +++ b/src/EditorFeatures/Test/EditAndContinue/EditSessionActiveStatementsTests.cs @@ -6,20 +6,21 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.EditAndContinue; -using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; +using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; +using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; +using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; -namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests +namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { [UseExportProvider] - public class EditSessionTests : TestBase + public class EditSessionActiveStatementsTests : TestBase { internal sealed class TestActiveStatementProvider : IActiveStatementProvider { @@ -92,36 +93,32 @@ IEnumerable Enumerate() ImmutableDictionary> nonRemappableRegions = null, Func adjustSolution = null) { - var exportProviderFactory = ExportProviderCache.GetOrCreateExportProviderFactory( TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic.WithPart(typeof(CSharpEditAndContinueAnalyzer)).WithPart(typeof(DummyLanguageService))); var exportProvider = exportProviderFactory.CreateExportProvider(); - using var workspace = TestWorkspace.CreateCSharp( - ActiveStatementsDescription.ClearTags(markedSource), - exportProvider: exportProvider); + using var workspace = TestWorkspace.CreateCSharp(ActiveStatementsDescription.ClearTags(markedSource), exportProvider: exportProvider); - var baseSolution = workspace.CurrentSolution; if (adjustSolution != null) { - baseSolution = adjustSolution(baseSolution); + workspace.ChangeSolution(adjustSolution(workspace.CurrentSolution)); } - var docsIds = from p in baseSolution.Projects + var docsIds = from p in workspace.CurrentSolution.Projects from d in p.DocumentIds select d; - var debuggingSession = new DebuggingSession(baseSolution); var activeStatementProvider = new TestActiveStatementProvider(activeStatements); + var mockDebuggeModuleProvider = new Mock(); + var mockCompilationOutputsProvider = new Mock(); + + var debuggingSession = new DebuggingSession(workspace, mockDebuggeModuleProvider.Object, activeStatementProvider, mockCompilationOutputsProvider.Object); + + debuggingSession.Test_SetNonRemappableRegions(nonRemappableRegions ?? ImmutableDictionary>.Empty); - var editSession = new EditSession( - baseSolution, - debuggingSession, - activeStatementProvider, - ImmutableDictionary.Empty, - nonRemappableRegions ?? ImmutableDictionary>.Empty, - stoppedAtException: false); + var telemetry = new EditSessionTelemetry(); + var editSession = new EditSession(debuggingSession, telemetry); return (await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false), await editSession.BaseActiveExceptionRegions.GetValueAsync(CancellationToken.None).ConfigureAwait(false), @@ -322,7 +319,7 @@ static void Main() // Test2.M2: adding a line in front of try-catch. // Test2.F2: moving the entire method 2 lines down. - static LinePositionSpan AddDelta(LinePositionSpan span, int lineDelta) + LinePositionSpan AddDelta(LinePositionSpan span, int lineDelta) => new LinePositionSpan(new LinePosition(span.Start.Line + lineDelta, span.Start.Character), new LinePosition(span.End.Line + lineDelta, span.End.Character)); var newActiveStatementsInChangedDocuments = ImmutableArray.Create( @@ -341,11 +338,11 @@ static LinePositionSpan AddDelta(LinePositionSpan span, int lineDelta) ) ); - EditSession.TestAccessor.GetActiveStatementAndExceptionRegionSpans( + EditSession.GetActiveStatementAndExceptionRegionSpans( module2, baseActiveStatements, baseExceptionRegions, - updatedMethodTokens: new[] { 0x06000004 }, // contains only recompiled methods in the project we are interested in (module2) + updatedMethodTokens: ImmutableArray.Create(0x06000004), // contains only recompiled methods in the project we are interested in (module2) ImmutableDictionary>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, @@ -441,11 +438,11 @@ static void F2() ) ); - EditSession.TestAccessor.GetActiveStatementAndExceptionRegionSpans( + EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, baseExceptionRegions, - updatedMethodTokens: new[] { 0x06000001 }, // F1 + updatedMethodTokens: ImmutableArray.Create(0x06000001), // F1 ImmutableDictionary>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, @@ -623,11 +620,11 @@ static void F4() ) ); - EditSession.TestAccessor.GetActiveStatementAndExceptionRegionSpans( + EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, baseExceptionRegions, - updatedMethodTokens: new[] { 0x06000002, 0x06000004 }, // F2, F4 + updatedMethodTokens: ImmutableArray.Create(0x06000002, 0x06000004), // F2, F4 initialNonRemappableRegions, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, diff --git a/src/EditorFeatures/CSharpTest/EditAndContinue/Helpers/DummyLanguageService.cs b/src/EditorFeatures/Test/EditAndContinue/Helpers/DummyLanguageService.cs similarity index 90% rename from src/EditorFeatures/CSharpTest/EditAndContinue/Helpers/DummyLanguageService.cs rename to src/EditorFeatures/Test/EditAndContinue/Helpers/DummyLanguageService.cs index 389e06012ca51..63fd217c35633 100644 --- a/src/EditorFeatures/CSharpTest/EditAndContinue/Helpers/DummyLanguageService.cs +++ b/src/EditorFeatures/Test/EditAndContinue/Helpers/DummyLanguageService.cs @@ -4,7 +4,7 @@ using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; -namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests +namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal interface IDummyLanguageService : ILanguageService { } @@ -19,5 +19,6 @@ public DummyLanguageService() } // do nothing + } } diff --git a/src/EditorFeatures/Test/EditAndContinue/Helpers/MockCompilationOutputs.cs b/src/EditorFeatures/Test/EditAndContinue/Helpers/MockCompilationOutputs.cs new file mode 100644 index 0000000000000..268e3bee6ec37 --- /dev/null +++ b/src/EditorFeatures/Test/EditAndContinue/Helpers/MockCompilationOutputs.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; +using System.IO; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests +{ + internal class MockCompilationOutputs : CompilationOutputs + { + private readonly Guid _mvid; + + public Func OpenAssemblyStreamImpl { get; set; } + public Func OpenPdbStreamImpl { get; set; } + + public MockCompilationOutputs(Guid mvid) + { + _mvid = mvid; + } + + public override string AssemblyDisplayPath => "test-assembly"; + public override string PdbDisplayPath => "test-pdb"; + + protected override Stream OpenAssemblyStream() + => (OpenAssemblyStreamImpl ?? throw new NotImplementedException())(); + + protected override Stream OpenPdbStream() + => (OpenPdbStreamImpl ?? throw new NotImplementedException())(); + + internal override Guid ReadAssemblyModuleVersionId() + => _mvid; + } +} diff --git a/src/EditorFeatures/Test/EditAndContinue/Helpers/MockCompilationOutputsProviderService.cs b/src/EditorFeatures/Test/EditAndContinue/Helpers/MockCompilationOutputsProviderService.cs new file mode 100644 index 0000000000000..4e0f9f8edba4c --- /dev/null +++ b/src/EditorFeatures/Test/EditAndContinue/Helpers/MockCompilationOutputsProviderService.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests +{ + internal sealed class MockCompilationOutputsProviderService : ICompilationOutputsProviderService + { + public readonly Dictionary Outputs = new Dictionary(); + + public CompilationOutputs GetCompilationOutputs(ProjectId projectId) + => Outputs.ContainsKey(projectId) ? Outputs[projectId] : new MockCompilationOutputs(Guid.NewGuid()); + } +} diff --git a/src/EditorFeatures/Test/EditAndContinue/Helpers/MockDebuggeeModuleMetadataProvider.cs b/src/EditorFeatures/Test/EditAndContinue/Helpers/MockDebuggeeModuleMetadataProvider.cs new file mode 100644 index 0000000000000..469ce744d4e5d --- /dev/null +++ b/src/EditorFeatures/Test/EditAndContinue/Helpers/MockDebuggeeModuleMetadataProvider.cs @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; + +namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests +{ + internal class MockDebuggeeModuleMetadataProvider : IDebuggeeModuleMetadataProvider + { + public FuncInOutOut IsEditAndContinueAvailable; + public Action PrepareModuleForUpdate; + public Func TryGetBaselineModuleInfo; + + bool IDebuggeeModuleMetadataProvider.IsEditAndContinueAvailable(Guid mvid, out int errorCode, out string localizedMessage) + => (IsEditAndContinueAvailable ?? throw new NotImplementedException())(mvid, out errorCode, out localizedMessage); + + void IDebuggeeModuleMetadataProvider.PrepareModuleForUpdate(Guid mvid) + => (PrepareModuleForUpdate ?? throw new NotImplementedException())(mvid); + + DebuggeeModuleInfo IDebuggeeModuleMetadataProvider.TryGetBaselineModuleInfo(Guid mvid) + => (TryGetBaselineModuleInfo ?? throw new NotImplementedException())(mvid); + } +} diff --git a/src/EditorFeatures/Test/EditAndContinue/Helpers/SymReaderTestHelpers.cs b/src/EditorFeatures/Test/EditAndContinue/Helpers/SymReaderTestHelpers.cs new file mode 100644 index 0000000000000..7b641ac9b5c75 --- /dev/null +++ b/src/EditorFeatures/Test/EditAndContinue/Helpers/SymReaderTestHelpers.cs @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; +using System.Collections.Immutable; +using System.IO; +using System.Reflection; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Test.Utilities; +using Microsoft.DiaSymReader; +using Microsoft.DiaSymReader.PortablePdb; +using Xunit; + +namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests +{ + internal static class SymReaderTestHelpers + { + private class DummyMetadataImportProvider : IMetadataImportProvider + { + public object GetMetadataImport() => throw new NotImplementedException(); + } + + private class DummySymReaderMetadataProvider : ISymReaderMetadataProvider + { + public unsafe bool TryGetStandaloneSignature(int standaloneSignatureToken, out byte* signature, out int length) + => throw new NotImplementedException(); + + public bool TryGetTypeDefinitionInfo(int typeDefinitionToken, out string namespaceName, out string typeName, out TypeAttributes attributes) + => throw new NotImplementedException(); + + public bool TryGetTypeReferenceInfo(int typeReferenceToken, out string namespaceName, out string typeName) + => throw new NotImplementedException(); + } + + public static (ImmutableArray PEImage, ISymUnmanagedReader5 SymReader) EmitAndOpenDummySymReader(Compilation compilation, DebugInformationFormat pdbFormat) + { + var symBinder = new SymBinder(); + var metadataImportProvider = new DummyMetadataImportProvider(); + + var pdbStream = new MemoryStream(); + var peImage = compilation.EmitToArray(new EmitOptions(debugInformationFormat: pdbFormat), pdbStream: pdbStream); + pdbStream.Position = 0; + + var pdbStreamCom = SymUnmanagedStreamFactory.CreateStream(pdbStream); + + ISymUnmanagedReader5 symReader5; + if (pdbFormat == DebugInformationFormat.PortablePdb) + { + int hr = symBinder.GetReaderFromPdbStream(metadataImportProvider, pdbStreamCom, out var symReader); + Assert.Equal(0, hr); + symReader5 = (ISymUnmanagedReader5)symReader; + } + else + { + symReader5 = SymUnmanagedReaderFactory.CreateReader(pdbStream, new DummySymReaderMetadataProvider()); + } + + return (peImage, symReader5); + } + + + } +} diff --git a/src/EditorFeatures/Test/EditAndContinue/RudeEditDiagnosticTests.cs b/src/EditorFeatures/Test/EditAndContinue/RudeEditDiagnosticTests.cs index 902b5bc2af6f7..fcb112bc28169 100644 --- a/src/EditorFeatures/Test/EditAndContinue/RudeEditDiagnosticTests.cs +++ b/src/EditorFeatures/Test/EditAndContinue/RudeEditDiagnosticTests.cs @@ -3,12 +3,10 @@ using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Text; -using Roslyn.Test.Utilities; using Xunit; -namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditAndContinue +namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public class RudeEditDiagnosticTests { diff --git a/src/EditorFeatures/Test/EditAndContinue/TraceLogTests.cs b/src/EditorFeatures/Test/EditAndContinue/TraceLogTests.cs index dd46499ab1cda..15f76c1a744ca 100644 --- a/src/EditorFeatures/Test/EditAndContinue/TraceLogTests.cs +++ b/src/EditorFeatures/Test/EditAndContinue/TraceLogTests.cs @@ -1,11 +1,10 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; -using Microsoft.CodeAnalysis.EditAndContinue; using Roslyn.Test.Utilities; using Xunit; -namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditAndContinue +namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public class TraceLogTests { @@ -17,7 +16,7 @@ public void Write() log.Write("a"); log.Write("b {0} {1} {2}", 1, "x", 3); log.Write("c"); - log.Write("d {0} {1}", null, null); + log.Write("d {0} {1}", (string)null, (string)null); log.Write("e"); log.Write("f"); diff --git a/src/EditorFeatures/Test/Emit/CompilationOutputsTests.cs b/src/EditorFeatures/Test/Emit/CompilationOutputsTests.cs index 343c6a6bd8547..68f485604ed1b 100644 --- a/src/EditorFeatures/Test/Emit/CompilationOutputsTests.cs +++ b/src/EditorFeatures/Test/Emit/CompilationOutputsTests.cs @@ -108,6 +108,18 @@ public void AssemblyAndPdb(DebugInformationFormat format) var mdReader = metadata.GetMetadataReader(); Assert.Equal("lib", mdReader.GetString(mdReader.GetAssemblyDefinition().Name)); } + + Assert.NotEqual(Guid.Empty, outputs.ReadAssemblyModuleVersionId()); + } + + [Fact] + public void ReadAssemblyModuleVersionId_NoAssembly() + { + var outputs = new TestCompilationOutputs( + openAssemblyStream: () => null, + openPdbStream: () => null); + + Assert.Equal(Guid.Empty, outputs.ReadAssemblyModuleVersionId()); } } } diff --git a/src/EditorFeatures/Test/Microsoft.CodeAnalysis.EditorFeatures.UnitTests.csproj b/src/EditorFeatures/Test/Microsoft.CodeAnalysis.EditorFeatures.UnitTests.csproj index 094fe9803322b..976d5772789aa 100644 --- a/src/EditorFeatures/Test/Microsoft.CodeAnalysis.EditorFeatures.UnitTests.csproj +++ b/src/EditorFeatures/Test/Microsoft.CodeAnalysis.EditorFeatures.UnitTests.csproj @@ -5,6 +5,7 @@ Library Microsoft.CodeAnalysis.Editor.UnitTests net472 + true @@ -70,6 +71,7 @@ + diff --git a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb index 860d81008d865..7aa7e085fcfe5 100644 --- a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb +++ b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests.vb @@ -5316,18 +5316,244 @@ namespace NS2 public class Bar { } } " - ' Enable import completion and disable timebox. + state.Workspace.Options = state.Workspace.Options _ .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True) _ - .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForImportCompletion, -1) + .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForImportCompletion, -1) ' disable timebox for import completion state.SendInvokeCompletionList() - Await state.AssertSelectedCompletionItem(displayText:="Bar", isHardSelected:=True, inlineDescription:="NS2") + Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") state.SendTab() Assert.Equal(expectedText, state.GetDocumentText()) End Using End Function + + Public Async Function TestExpanderWithImportCompletionDisabled() As Task + Using state = TestStateFactory.CreateCSharpTestState(CompletionImplementation.Modern, + ) + + state.Workspace.Options = state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, False) + + ' trigger completion with import completion disabled + state.SendInvokeCompletionList() + Await state.WaitForUIRenderedAsync() + + state.AssertCompletionItemsDoNotContainAny(displayText:={"Bar"}) + state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=False) + + ' select expander + state.SetCompletionItemExpanderState(isSelected:=True) + Await state.WaitForAsynchronousOperationsAsync() + Await state.WaitForUIRenderedAsync() + + Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") + state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) + + ' unselect expander + state.SetCompletionItemExpanderState(isSelected:=False) + Await state.WaitForAsynchronousOperationsAsync() + Await state.WaitForUIRenderedAsync() + + state.AssertCompletionItemsDoNotContainAny(displayText:={"Bar"}) + state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=False) + + ' select expander again + state.SetCompletionItemExpanderState(isSelected:=True) + Await state.WaitForAsynchronousOperationsAsync() + Await state.WaitForUIRenderedAsync() + + Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") + state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) + End Using + End Function + + + Public Async Function TestExpanderWithImportCompletionEnabled() As Task + Using state = TestStateFactory.CreateCSharpTestState(CompletionImplementation.Modern, + ) + + state.Workspace.Options = state.Workspace.Options _ + .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True) _ + .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForImportCompletion, -1) ' disable timebox for import completion + + ' trigger completion with import completion enabled + state.SendInvokeCompletionList() + Await state.WaitForUIRenderedAsync() + + Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") + state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) + + ' unselect expander + state.SetCompletionItemExpanderState(isSelected:=False) + Await state.WaitForAsynchronousOperationsAsync() + Await state.WaitForUIRenderedAsync() + + state.AssertCompletionItemsDoNotContainAny(displayText:={"Bar"}) + state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=False) + + ' select expander + state.SetCompletionItemExpanderState(isSelected:=True) + Await state.WaitForAsynchronousOperationsAsync() + Await state.WaitForUIRenderedAsync() + + Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") + state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) + + ' unselect expander again + state.SetCompletionItemExpanderState(isSelected:=False) + Await state.WaitForAsynchronousOperationsAsync() + Await state.WaitForUIRenderedAsync() + + state.AssertCompletionItemsDoNotContainAny(displayText:={"Bar"}) + state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=False) + End Using + End Function + + + Public Async Function TestExpanderAndTimeboxWithImportCompletionEnabled() As Task + Using state = TestStateFactory.CreateCSharpTestState(CompletionImplementation.Modern, + ) + + ' Enable import completion and set timeout to 0 (so always timeout) + state.Workspace.Options = state.Workspace.Options _ + .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True) _ + .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForImportCompletion, 0) + + ' trigger completion with import completion enabled, this should timeout so no unimport types should be shown and expander should be unselected + ' (but the caculation should continue in background) + state.SendInvokeCompletionList() + Await state.WaitForUIRenderedAsync() + + state.AssertCompletionItemsDoNotContainAny(displayText:={"Bar"}) + state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=False) + + ' select expander + state.SetCompletionItemExpanderState(isSelected:=True) + Await state.WaitForAsynchronousOperationsAsync() + Await state.WaitForUIRenderedAsync() + + ' timeout is ignored if user asked for unimport types explicitly (via expander) + Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") + state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) + + End Using + End Function + + + Public Async Function TestExpanderAndTimeboxWithImportCompletionDisabled() As Task + Using state = TestStateFactory.CreateCSharpTestState(CompletionImplementation.Modern, + ) + + ' Disable import completion + state.Workspace.Options = state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, False) + + ' trigger completion with import completion disabled + state.SendInvokeCompletionList() + Await state.WaitForUIRenderedAsync() + + state.AssertCompletionItemsDoNotContainAny(displayText:={"Bar"}) + state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=False) + + ' set timeout to 0 (always timeout) + state.Workspace.Options = state.Workspace.Options.WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForImportCompletion, 0) + + ' select expander + state.SetCompletionItemExpanderState(isSelected:=True) + Await state.WaitForAsynchronousOperationsAsync() + Await state.WaitForUIRenderedAsync() + + ' timeout should be ignored since user asked for unimport types explicitly (via expander) + Await state.AssertSelectedCompletionItem(displayText:="Bar", inlineDescription:="NS2") + state.AssertCompletionItemExpander(isAvailable:=True, isSelected:=True) + + End Using + End Function + + + Public Async Function NoExpanderAvailableWhenNotInTypeContext() As Task + Using state = TestStateFactory.CreateCSharpTestState(CompletionImplementation.Modern, + ) + + state.Workspace.Options = state.Workspace.Options.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True) + + ' trigger completion with import completion enabled + state.SendInvokeCompletionList() + Await state.WaitForUIRenderedAsync() + + state.AssertCompletionItemExpander(isAvailable:=False, isSelected:=False) + End Using + End Function + @@ -5644,6 +5870,199 @@ class C state.AssertCompletionItemsContainAll({"Length"}) End Using End Function + + + + + Public Async Function NonExpandedItemShouldAlwaysBePreferred_DisplayTextMatch(completionImplementation As CompletionImplementation) As Task + Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, + + { + } +} + +namespace NS2 +{ + public class Bar + { + } +} +]]>) + + Dim expectedText = " +namespace NS1 +{ + class C + { + public void Foo() + { + Bar + } + } + + public class Bar + { + } +} + +namespace NS2 +{ + public class Bar + { + } +} +" + + state.Workspace.Options = state.Workspace.Options _ + .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True) _ + .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForImportCompletion, -1) + + state.SendInvokeCompletionList() + Await state.AssertSelectedCompletionItem(displayText:="Bar", displayTextSuffix:="<>") + state.SendTab() + Assert.Equal(expectedText, state.GetDocumentText()) + End Using + End Function + + + + + Public Async Function NonExpandedItemShouldAlwaysBePreferred_FullDisplayTextMatch(completionImplementation As CompletionImplementation) As Task + Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, + ) + + Dim expectedText = " +namespace NS1 +{ + class C + { + public void Foo() + { + Bar + } + } + + public class Bar + { + } +} + +namespace NS2 +{ + public class Bar + { + } +} +" + + state.Workspace.Options = state.Workspace.Options _ + .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True) _ + .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForImportCompletion, -1) + + state.SendInvokeCompletionList() + Await state.AssertSelectedCompletionItem(displayText:="Bar") + state.SendTab() + Assert.Equal(expectedText, state.GetDocumentText()) + End Using + End Function + + + + + Public Async Function NonExpandedItemShouldAlwaysBePreferred_ExpandedItemHasBetterMatch(completionImplementation As CompletionImplementation) As Task + Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, + ) + + Dim expectedText = " +namespace NS1 +{ + class C + { + public void Foo() + { + BitArrayReceiver + } + } + + public class BitArrayReceiver + { + } +} + +namespace NS2 +{ + public class Bar + { + } +} +" + + state.Workspace.Options = state.Workspace.Options _ + .WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, True) _ + .WithChangedOption(CompletionServiceOptions.TimeoutInMillisecondsForImportCompletion, -1) + + state.SendInvokeCompletionList() + Await state.AssertSelectedCompletionItem(displayText:="BitArrayReceiver") + state.SendTab() + Assert.Equal(expectedText, state.GetDocumentText()) + End Using + End Function + Private Class MultipleChangeCompletionProvider Inherits CompletionProvider @@ -5689,9 +6108,10 @@ class C Public Overrides Function ProvideCompletionsAsync(context As CompletionContext) As Task Dim intelliCodeItem = CompletionItem.Create(displayText:="★ Length", filterText:="Length") intelliCodeItem.AutomationText = AutomationTextString - context.AddItem(intelliCodeItem) + context.AddItem(CompletionItem.Create(displayText:="★ Normalize", filterText:="Normalize", displayTextSuffix:="()")) + context.AddItem(CompletionItem.Create(displayText:="Normalize", filterText:="Normalize")) context.AddItem(CompletionItem.Create(displayText:="Length", filterText:="Length")) context.AddItem(CompletionItem.Create(displayText:="ToString", filterText:="ToString", displayTextSuffix:="()")) context.AddItem(CompletionItem.Create(displayText:="First", filterText:="First", displayTextSuffix:="()")) diff --git a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_Regex.vb b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_Regex.vb index c8da372fb1cb8..37d43d5be3801 100644 --- a/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_Regex.vb +++ b/src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_Regex.vb @@ -58,7 +58,7 @@ class c End Function - + Public Async Function TestCaretPlacement(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateCSharpTestState(completionImplementation, - + Public Async Function TestCaretPlacement(completionImplementation As CompletionImplementation) As Task Using state = TestStateFactory.CreateVisualBasicTestState(completionImplementation, + diff --git a/src/EditorFeatures/Test2/Rename/RenameCommandHandlerTests.vb b/src/EditorFeatures/Test2/Rename/RenameCommandHandlerTests.vb index fbef73e975de8..a8edb9db89870 100644 --- a/src/EditorFeatures/Test2/Rename/RenameCommandHandlerTests.vb +++ b/src/EditorFeatures/Test2/Rename/RenameCommandHandlerTests.vb @@ -5,6 +5,7 @@ Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename Imports Microsoft.CodeAnalysis.Editor.Implementation.Interactive Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions +Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.VisualStudio.Commanding @@ -18,8 +19,9 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> Public Class RenameCommandHandlerTests Private Function CreateCommandHandler(workspace As TestWorkspace) As RenameCommandHandler - Return New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Return New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) End Function @@ -152,8 +154,10 @@ End Class Dim view = workspace.Documents.Single().GetTextView() view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value)) - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) + Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) Dim session = StartSession(workspace) @@ -209,8 +213,8 @@ End Class Dim renameService = workspace.GetService(Of InlineRenameService)() Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Dim session = StartSession(workspace) @@ -243,8 +247,8 @@ End Class Dim renameService = workspace.GetService(Of InlineRenameService)() Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Dim session = StartSession(workspace) @@ -289,8 +293,8 @@ Goo f; Dim renameService = workspace.GetService(Of InlineRenameService)() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Assert.True(view.Selection.IsEmpty()) Dim session = StartSession(workspace) @@ -334,8 +338,8 @@ class [|$$Goo|] // comment Dim renameService = workspace.GetService(Of InlineRenameService)() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Dim session = StartSession(workspace) Await WaitForRename(workspace) @@ -391,8 +395,8 @@ Goo f; Dim renameService = workspace.GetService(Of InlineRenameService)() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Dim session = StartSession(workspace) Await WaitForRename(workspace) @@ -483,8 +487,9 @@ Goo f; Dim view = workspace.Documents.Single().GetTextView() view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value)) - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) Dim session = StartSession(workspace) @@ -516,8 +521,9 @@ Goo f; Dim view = workspace.Documents.Single().GetTextView() - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) Dim session = StartSession(workspace) Await WaitForRename(workspace) @@ -568,8 +574,9 @@ Goo f; Dim view = workspace.Documents.Single().GetTextView() - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) Dim session = StartSession(workspace) view.Selection.Clear() @@ -607,8 +614,9 @@ Goo f; Dim view = workspace.Documents.Single().GetTextView() - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) Dim session = StartSession(workspace) view.Selection.Clear() @@ -645,8 +653,9 @@ Goo f; Dim view = workspace.Documents.Single().GetTextView() - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) Dim session = StartSession(workspace) view.Selection.Clear() @@ -700,8 +709,9 @@ Goo f; Dim view = workspace.Documents.ElementAt(0).GetTextView() - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) Dim session = StartSession(workspace) view.Selection.Clear() @@ -766,8 +776,9 @@ Goo f; Dim view = workspace.Documents.ElementAt(0).GetTextView() - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) Dim session = StartSession(workspace) view.Selection.Clear() @@ -823,8 +834,10 @@ class Program Dim view = workspace.Documents.Single().GetTextView() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) + view.Caret.MoveTo(New SnapshotPoint(view.TextBuffer.CurrentSnapshot, workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value)) commandHandler.ExecuteCommand(New RenameCommandArgs(view, view.TextBuffer), Sub() Exit Sub, Utilities.TestCommandExecutionContext.Create()) @@ -862,8 +875,9 @@ partial class [|Program|] Dim view = workspace.Documents.First(Function(d) d.Name = "Test.cs").GetTextView() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) Dim closedDocument = workspace.Documents.First(Function(d) d.Name = "Test2.cs") closedDocument.CloseTextView() @@ -898,8 +912,8 @@ partial class [|Program|] Dim renameService = workspace.GetService(Of InlineRenameService)() Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Dim session = StartSession(workspace) Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) @@ -938,8 +952,8 @@ partial class [|Program|] Dim renameService = workspace.GetService(Of InlineRenameService)() Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Dim session = StartSession(workspace) Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) @@ -981,8 +995,8 @@ partial class [|Program|] Dim renameService = workspace.GetService(Of InlineRenameService)() Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Dim session = StartSession(workspace) Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) @@ -1019,8 +1033,8 @@ partial class [|Program|] Dim renameService = workspace.GetService(Of InlineRenameService)() Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Dim session = StartSession(workspace) Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) @@ -1056,8 +1070,8 @@ partial class [|Program|] Dim renameService = workspace.GetService(Of InlineRenameService)() Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Dim session = StartSession(workspace) Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) @@ -1092,8 +1106,9 @@ partial class [|Program|] Dim view = workspace.Documents.Single().GetTextView() - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) Dim session = StartSession(workspace) Await WaitForRename(workspace) @@ -1230,8 +1245,8 @@ class [|C$$|] Dim renameService = workspace.GetService(Of InlineRenameService)() Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Dim session = StartSession(workspace) Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) @@ -1275,8 +1290,8 @@ class [|C$$|] Dim renameService = workspace.GetService(Of InlineRenameService)() Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Dim session = StartSession(workspace) Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) @@ -1310,8 +1325,8 @@ class [|C$$|] Dim renameService = workspace.GetService(Of InlineRenameService)() Dim commandHandler As New RenameCommandHandler( - renameService, - workspace.GetService(Of IEditorOperationsFactoryService)) + workspace.GetService(Of IThreadingContext)(), + renameService) Dim session = StartSession(workspace) Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService)().GetEditorOperations(view) diff --git a/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb b/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb index 7fbf0b8fd24d3..7e949afdf196f 100644 --- a/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb +++ b/src/EditorFeatures/Test2/Rename/RenameTagProducerTests.vb @@ -5,6 +5,7 @@ Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags +Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text.Shared.Extensions Imports Microsoft.VisualStudio.Text @@ -565,8 +566,9 @@ class C Dim textBuffer = workspace.Documents.Single().TextBuffer Dim renameService = workspace.GetService(Of InlineRenameService)() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) Dim session = StartSession(workspace) textBuffer.Replace(New Span(location, 3), "Goo") @@ -1072,8 +1074,9 @@ End Class Dim view = workspace.Documents.Single().GetTextView() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) Dim textViewService = New TextBufferAssociatedViewService() Dim buffers = New Collection(Of ITextBuffer) @@ -1155,8 +1158,9 @@ End Class Dim view = workspace.Documents.Single().GetTextView() Dim editorOperations = workspace.GetService(Of IEditorOperationsFactoryService).GetEditorOperations(view) - Dim commandHandler As New RenameCommandHandler(workspace.GetService(Of InlineRenameService), - workspace.GetService(Of IEditorOperationsFactoryService)) + Dim commandHandler As New RenameCommandHandler( + workspace.GetService(Of IThreadingContext)(), + workspace.GetService(Of InlineRenameService)) Dim textViewService = New TextBufferAssociatedViewService() Dim buffers = New Collection(Of ITextBuffer) diff --git a/src/EditorFeatures/TestUtilities/Remote/InProcRemostHostClient.cs b/src/EditorFeatures/TestUtilities/Remote/InProcRemostHostClient.cs index 142b26a0b354c..764b2a5375e67 100644 --- a/src/EditorFeatures/TestUtilities/Remote/InProcRemostHostClient.cs +++ b/src/EditorFeatures/TestUtilities/Remote/InProcRemostHostClient.cs @@ -9,6 +9,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Remote; +using Microsoft.CodeAnalysis.Remote.Services; using Microsoft.VisualStudio.LanguageServices.Remote; using Nerdbank; using Roslyn.Utilities; @@ -79,6 +80,11 @@ public void RegisterService(string name, Func RequestServiceAsync(string serviceName) + { + return _inprocServices.RequestServiceAsync(serviceName); + } + public override string ClientId { get; } public override async Task TryCreateConnectionAsync( @@ -142,23 +148,25 @@ public object GetService(Type serviceType) private class InProcRemoteServices { private readonly ServiceProvider _serviceProvider; - private readonly Dictionary> _creatorMap; + private readonly Dictionary> _creatorMap; public InProcRemoteServices(bool runCacheCleanup) { _serviceProvider = new ServiceProvider(runCacheCleanup); - _creatorMap = new Dictionary>(); + _creatorMap = new Dictionary>(); RegisterService(WellKnownRemoteHostServices.RemoteHostService, (s, p) => new RemoteHostService(s, p)); RegisterService(WellKnownServiceHubServices.CodeAnalysisService, (s, p) => new CodeAnalysisService(s, p)); RegisterService(WellKnownServiceHubServices.SnapshotService, (s, p) => new SnapshotService(s, p)); RegisterService(WellKnownServiceHubServices.RemoteSymbolSearchUpdateEngine, (s, p) => new RemoteSymbolSearchUpdateEngine(s, p)); + RegisterService(WellKnownServiceHubServices.CSharpLanguageServer, (s, p) => new CSharpLanguageServer(s, p)); + RegisterService(WellKnownServiceHubServices.VisualBasicLanguageServer, (s, p) => new VisualBasicLanguageServer(s, p)); } public AssetStorage AssetStorage => _serviceProvider.AssetStorage; public TraceSource Logger { get; } = new TraceSource("Default"); - public void RegisterService(string name, Func serviceCreator) + public void RegisterService(string name, Func serviceCreator) { _creatorMap.Add(name, serviceCreator); } diff --git a/src/EditorFeatures/TestUtilities/Roslyn.Services.Test.Utilities.csproj b/src/EditorFeatures/TestUtilities/Roslyn.Services.Test.Utilities.csproj index 8bce83628698a..64bddc60d32ae 100644 --- a/src/EditorFeatures/TestUtilities/Roslyn.Services.Test.Utilities.csproj +++ b/src/EditorFeatures/TestUtilities/Roslyn.Services.Test.Utilities.csproj @@ -54,11 +54,15 @@ + + + + diff --git a/src/EditorFeatures/TestUtilities2/Intellisense/LegacyTestState.vb b/src/EditorFeatures/TestUtilities2/Intellisense/LegacyTestState.vb index e7788ed3d325a..846910ad3c01c 100644 --- a/src/EditorFeatures/TestUtilities2/Intellisense/LegacyTestState.vb +++ b/src/EditorFeatures/TestUtilities2/Intellisense/LegacyTestState.vb @@ -130,6 +130,14 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Return CurrentCompletionPresenterSession.CompletionItemFilters End Function + Public Overrides Sub AssertCompletionItemExpander(isAvailable As Boolean, isSelected As Boolean) + Throw New NotImplementedException() + End Sub + + Public Overrides Sub SetCompletionItemExpanderState(isSelected As Boolean) + Throw New NotImplementedException() + End Sub + Public Overrides Function HasSuggestedItem() As Boolean ' SuggestionModeItem is always not null but is displayed only when SuggestionMode = True Return CurrentCompletionPresenterSession.SuggestionMode diff --git a/src/EditorFeatures/TestUtilities2/Intellisense/MockCompletionPresenter.vb b/src/EditorFeatures/TestUtilities2/Intellisense/MockCompletionPresenter.vb index 28d79632e2e29..1f1ad96f5168b 100644 --- a/src/EditorFeatures/TestUtilities2/Intellisense/MockCompletionPresenter.vb +++ b/src/EditorFeatures/TestUtilities2/Intellisense/MockCompletionPresenter.vb @@ -62,7 +62,16 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense End Sub Public Function GetFilters() As ImmutableArray(Of CompletionFilterWithState) - Return _filters + Return _filters.WhereAsArray(Function(state) TypeOf state.Filter IsNot CompletionExpander) + End Function + + Public Sub SetExpander(isSelected As Boolean) + _filters = _filters.Select(Function(n) If(TypeOf n.Filter Is CompletionExpander, n.WithSelected(isSelected), n)).ToImmutableArray() + RaiseEvent FiltersChanged(Me, New CompletionFilterChangedEventArgs(_filters)) + End Sub + + Public Function GetExpander() As CompletionFilterWithState + Return _filters.SingleOrDefault(Function(state) TypeOf state.Filter Is CompletionExpander) End Function Public Sub TriggerFiltersChanged(sender As Object, args As CompletionFilterChangedEventArgs) diff --git a/src/EditorFeatures/TestUtilities2/Intellisense/ModernCompletionTestState.vb b/src/EditorFeatures/TestUtilities2/Intellisense/ModernCompletionTestState.vb index 9ad23faca5cce..07a16910b55d3 100644 --- a/src/EditorFeatures/TestUtilities2/Intellisense/ModernCompletionTestState.vb +++ b/src/EditorFeatures/TestUtilities2/Intellisense/ModernCompletionTestState.vb @@ -17,6 +17,7 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Inherits TestStateBase Private Const timeoutMs = 10000 + Private Const editorTimeoutMs = 20000 Friend Const RoslynItem = "RoslynItem" Friend ReadOnly EditorCompletionCommandHandler As VSCommanding.ICommandHandler Friend ReadOnly CompletionPresenterProvider As ICompletionPresenterProvider @@ -37,6 +38,10 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense includeFormatCommandHandler, workspaceKind:=workspaceKind) + ' The current default timeout defined in the Editor may not work on slow virtual test machines. + ' Need to use a safe timeout there to follow real code paths. + TextView.Options.GlobalOptions.SetOptionValue(DefaultOptions.ResponsiveCompletionThresholdOptionId, editorTimeoutMs) + CompletionPresenterProvider = GetExportedValues(Of ICompletionPresenterProvider)(). Single(Function(e As ICompletionPresenterProvider) e.GetType().FullName = "Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense.MockCompletionPresenterProvider") EditorCompletionCommandHandler = GetExportedValues(Of VSCommanding.ICommandHandler)(). @@ -319,6 +324,25 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Return presenter.GetFilters().Select(Function(f) New CompletionItemFilter(f.Filter.DisplayText, "", f.Filter.AccessKey(0))).ToImmutableArray() End Function + Public Overrides Sub AssertCompletionItemExpander(isAvailable As Boolean, isSelected As Boolean) + Dim presenter = DirectCast(CompletionPresenterProvider.GetOrCreate(Me.TextView), MockCompletionPresenter) + Dim expander = presenter.GetExpander() + If Not isAvailable Then + Assert.False(isSelected) + Assert.Null(expander) + Else + Assert.NotNull(expander) + Assert.Equal(expander.IsSelected, isSelected) + End If + End Sub + + Public Overrides Sub SetCompletionItemExpanderState(isSelected As Boolean) + Dim presenter = DirectCast(CompletionPresenterProvider.GetOrCreate(Me.TextView), MockCompletionPresenter) + Dim expander = presenter.GetExpander() + Assert.NotNull(expander) + presenter.SetExpander(isSelected) + End Sub + Public Overrides Function HasSuggestedItem() As Boolean AssertNoAsynchronousOperationsRunning() Dim session = GetExportedValue(Of IAsyncCompletionBroker)().GetSession(TextView) diff --git a/src/EditorFeatures/TestUtilities2/Intellisense/TestStateBase.vb b/src/EditorFeatures/TestUtilities2/Intellisense/TestStateBase.vb index a2dcb2c8625df..ce71cc639076e 100644 --- a/src/EditorFeatures/TestUtilities2/Intellisense/TestStateBase.vb +++ b/src/EditorFeatures/TestUtilities2/Intellisense/TestStateBase.vb @@ -195,6 +195,10 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Public MustOverride Function GetCompletionItemFilters() As ImmutableArray(Of CompletionItemFilter) + Public MustOverride Sub AssertCompletionItemExpander(isAvailable As Boolean, isSelected As Boolean) + + Public MustOverride Sub SetCompletionItemExpanderState(isSelected As Boolean) + Public MustOverride Function HasSuggestedItem() As Boolean Public MustOverride Function IsSoftSelected() As Boolean diff --git a/src/EditorFeatures/TestUtilities2/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.vbproj b/src/EditorFeatures/TestUtilities2/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.vbproj index bff562413c797..e5c54ef7f3fc2 100644 --- a/src/EditorFeatures/TestUtilities2/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.vbproj +++ b/src/EditorFeatures/TestUtilities2/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.vbproj @@ -48,6 +48,7 @@ + diff --git a/src/EditorFeatures/Text/Microsoft.CodeAnalysis.EditorFeatures.Text.csproj b/src/EditorFeatures/Text/Microsoft.CodeAnalysis.EditorFeatures.Text.csproj index de79705d3f673..f9b172acb21bd 100644 --- a/src/EditorFeatures/Text/Microsoft.CodeAnalysis.EditorFeatures.Text.csproj +++ b/src/EditorFeatures/Text/Microsoft.CodeAnalysis.EditorFeatures.Text.csproj @@ -23,6 +23,7 @@ + diff --git a/src/EditorFeatures/VisualBasic/ChangeSignature/VisualBasicChangeSignatureCommandHandler.vb b/src/EditorFeatures/VisualBasic/ChangeSignature/VisualBasicChangeSignatureCommandHandler.vb index 8e783554f6931..f008f60de3b55 100644 --- a/src/EditorFeatures/VisualBasic/ChangeSignature/VisualBasicChangeSignatureCommandHandler.vb +++ b/src/EditorFeatures/VisualBasic/ChangeSignature/VisualBasicChangeSignatureCommandHandler.vb @@ -2,6 +2,7 @@ Imports System.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Editor.Implementation.ChangeSignature +Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.VisualStudio.Utilities Imports VSCommanding = Microsoft.VisualStudio.Commanding @@ -13,7 +14,8 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.ChangeSignature Inherits AbstractChangeSignatureCommandHandler - Public Sub New() + Public Sub New(threadingContext As IThreadingContext) + MyBase.New(threadingContext) End Sub End Class End Namespace diff --git a/src/EditorFeatures/VisualBasic/EncapsulateField/EncapsulateFieldCommandHandler.vb b/src/EditorFeatures/VisualBasic/EncapsulateField/EncapsulateFieldCommandHandler.vb index 9ab592e65d24a..44dccee35abc5 100644 --- a/src/EditorFeatures/VisualBasic/EncapsulateField/EncapsulateFieldCommandHandler.vb +++ b/src/EditorFeatures/VisualBasic/EncapsulateField/EncapsulateFieldCommandHandler.vb @@ -2,6 +2,7 @@ Imports System.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Editor.Implementation.EncapsulateField +Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities @@ -16,9 +17,10 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EncapsulateField Inherits AbstractEncapsulateFieldCommandHandler - Public Sub New(undoManager As ITextBufferUndoManagerProvider, + Public Sub New(threadingContext As IThreadingContext, + undoManager As ITextBufferUndoManagerProvider, listenerProvider As IAsynchronousOperationListenerProvider) - MyBase.New(undoManager, listenerProvider) + MyBase.New(threadingContext, undoManager, listenerProvider) End Sub End Class End Namespace diff --git a/src/EditorFeatures/VisualBasic/ExtractMethod/ExtractMethodCommandHandler.vb b/src/EditorFeatures/VisualBasic/ExtractMethod/ExtractMethodCommandHandler.vb index dcf6a85186f62..67bbe94937960 100644 --- a/src/EditorFeatures/VisualBasic/ExtractMethod/ExtractMethodCommandHandler.vb +++ b/src/EditorFeatures/VisualBasic/ExtractMethod/ExtractMethodCommandHandler.vb @@ -2,6 +2,7 @@ Imports System.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Editor.Implementation.ExtractMethod +Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities Imports VSCommanding = Microsoft.VisualStudio.Commanding @@ -15,10 +16,10 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.ExtractMethod Inherits AbstractExtractMethodCommandHandler - Public Sub New(undoManager As ITextBufferUndoManagerProvider, - editorOperationsFactoryService As IEditorOperationsFactoryService, + Public Sub New(threadingContext As IThreadingContext, + undoManager As ITextBufferUndoManagerProvider, renameService As IInlineRenameService) - MyBase.New(undoManager, editorOperationsFactoryService, renameService) + MyBase.New(threadingContext, undoManager, renameService) End Sub End Class End Namespace diff --git a/src/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj b/src/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj index 653d4c03228bf..994fa4051feb2 100644 --- a/src/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj +++ b/src/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj @@ -34,6 +34,7 @@ + diff --git a/src/EditorFeatures/VisualBasicTest/ChangeSignature/RemoveParametersTests.vb b/src/EditorFeatures/VisualBasicTest/ChangeSignature/RemoveParametersTests.vb index 26b4631b0debf..ec227238c59b0 100644 --- a/src/EditorFeatures/VisualBasicTest/ChangeSignature/RemoveParametersTests.vb +++ b/src/EditorFeatures/VisualBasicTest/ChangeSignature/RemoveParametersTests.vb @@ -1,11 +1,13 @@ ' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Editor.Implementation.Interactive +Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.ChangeSignature +Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature @@ -116,7 +118,7 @@ End Module Dim textView = workspace.Documents.Single().GetTextView() - Dim handler = New VisualBasicChangeSignatureCommandHandler() + Dim handler = New VisualBasicChangeSignatureCommandHandler(exportProvider.GetExportedValue(Of IThreadingContext)()) Dim state = handler.GetCommandState(New ReorderParametersCommandArgs(textView, textView.TextBuffer)) Assert.True(state.IsUnspecified) diff --git a/src/EditorFeatures/VisualBasicTest/EditAndContinue/ActiveStatementTests.vb b/src/EditorFeatures/VisualBasicTest/EditAndContinue/ActiveStatementTests.vb index e696d22f15212..48955d476d26b 100644 --- a/src/EditorFeatures/VisualBasicTest/EditAndContinue/ActiveStatementTests.vb +++ b/src/EditorFeatures/VisualBasicTest/EditAndContinue/ActiveStatementTests.vb @@ -4270,7 +4270,7 @@ End Class Dim edits = GetTopEdits(src1, src2) Dim active = GetActiveStatements(src1, src2) edits.VerifyRudeDiagnostics(active, - Diagnostic(RudeEditKind.RUDE_EDIT_COMPLEX_QUERY_EXPRESSION, "Join", FeaturesResources.method)) + Diagnostic(RudeEditKind.ComplexQueryExpression, "Join", FeaturesResources.method)) End Sub @@ -4315,7 +4315,7 @@ End Class Dim edits = GetTopEdits(src1, src2) Dim active = GetActiveStatements(src1, src2) edits.VerifyRudeDiagnostics(active, - Diagnostic(RudeEditKind.RUDE_EDIT_COMPLEX_QUERY_EXPRESSION, "Join", FeaturesResources.method)) + Diagnostic(RudeEditKind.ComplexQueryExpression, "Join", FeaturesResources.method)) End Sub #End Region diff --git a/src/EditorFeatures/VisualBasicTest/EditAndContinue/RudeEditStatementTests.vb b/src/EditorFeatures/VisualBasicTest/EditAndContinue/RudeEditStatementTests.vb index 4af086637fc82..c9aebb32fc0ad 100644 --- a/src/EditorFeatures/VisualBasicTest/EditAndContinue/RudeEditStatementTests.vb +++ b/src/EditorFeatures/VisualBasicTest/EditAndContinue/RudeEditStatementTests.vb @@ -5602,7 +5602,7 @@ End Class" ' TODO (bug 1212) should report no error edits.VerifySemanticDiagnostics( - Diagnostic(RudeEditKind.RUDE_EDIT_COMPLEX_QUERY_EXPRESSION, "Group Join", "method")) + Diagnostic(RudeEditKind.ComplexQueryExpression, "Group Join", "method")) End Sub diff --git a/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.vb b/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.vb index 2d328bbc93ef7..4589155c15ebd 100644 --- a/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.vb +++ b/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.vb @@ -1,6 +1,7 @@ ' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Editor.Implementation.Interactive +Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.EncapsulateField @@ -153,8 +154,11 @@ End Class Dim textView = workspace.Documents.Single().GetTextView() - Dim handler = New EncapsulateFieldCommandHandler(workspace.GetService(Of ITextBufferUndoManagerProvider), - workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)()) + Dim handler = New EncapsulateFieldCommandHandler( + workspace.GetService(Of IThreadingContext), + workspace.GetService(Of ITextBufferUndoManagerProvider), + workspace.GetService(Of IAsynchronousOperationListenerProvider)()) + Dim state = handler.GetCommandState(New EncapsulateFieldCommandArgs(textView, textView.TextBuffer)) Assert.True(state.IsUnspecified) End Using diff --git a/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb b/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb index 3596bf1f4d08b..367c483649cc9 100644 --- a/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb +++ b/src/EditorFeatures/VisualBasicTest/EncapsulateField/EncapsulateFieldTestState.vb @@ -1,6 +1,7 @@ ' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Editor.Shared +Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces @@ -38,8 +39,10 @@ Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EncapsulateField Public Sub Encapsulate() Dim args = New EncapsulateFieldCommandArgs(_testDocument.GetTextView(), _testDocument.GetTextBuffer()) - Dim commandHandler = New EncapsulateFieldCommandHandler(Workspace.GetService(Of ITextBufferUndoManagerProvider)(), - Workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)) + Dim commandHandler = New EncapsulateFieldCommandHandler( + Workspace.ExportProvider.GetExportedValue(Of IThreadingContext)(), + Workspace.GetService(Of ITextBufferUndoManagerProvider)(), + Workspace.ExportProvider.GetExportedValue(Of IAsynchronousOperationListenerProvider)) commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create()) End Sub diff --git a/src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.LanguageInteraction.vb b/src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.LanguageInteraction.vb index a43670469f6dd..d2c13b1301f64 100644 --- a/src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.LanguageInteraction.vb +++ b/src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.LanguageInteraction.vb @@ -1,6 +1,7 @@ ' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Editor.Implementation.Interactive +Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.ExtractMethod @@ -3385,8 +3386,8 @@ End Namespace" Dim textView = workspace.Documents.Single().GetTextView() Dim handler = New ExtractMethodCommandHandler( + workspace.GetService(Of IThreadingContext)(), workspace.GetService(Of ITextBufferUndoManagerProvider)(), - workspace.GetService(Of IEditorOperationsFactoryService)(), workspace.GetService(Of IInlineRenameService)()) Dim state = handler.GetCommandState(New ExtractMethodCommandArgs(textView, textView.TextBuffer)) diff --git a/src/EditorFeatures/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests.vbproj b/src/EditorFeatures/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests.vbproj index 44bc875fdba9f..9bf9f737b8af7 100644 --- a/src/EditorFeatures/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests.vbproj +++ b/src/EditorFeatures/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests.vbproj @@ -57,6 +57,7 @@ + diff --git a/src/EditorFeatures/VisualBasicTest/Organizing/OrganizeTypeDeclarationTests.vb b/src/EditorFeatures/VisualBasicTest/Organizing/OrganizeTypeDeclarationTests.vb index 8e439587d5677..939dacf5a2127 100644 --- a/src/EditorFeatures/VisualBasicTest/Organizing/OrganizeTypeDeclarationTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Organizing/OrganizeTypeDeclarationTests.vb @@ -3,6 +3,7 @@ Imports Microsoft.CodeAnalysis.Editor.Commanding.Commands Imports Microsoft.CodeAnalysis.Editor.Implementation.Interactive Imports Microsoft.CodeAnalysis.Editor.Implementation.Organizing +Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces @@ -958,7 +959,7 @@ End Namespace Dim textView = workspace.Documents.Single().GetTextView() - Dim handler = New OrganizeDocumentCommandHandler() + Dim handler = New OrganizeDocumentCommandHandler(exportProvider.GetExportedValue(Of IThreadingContext)()) Dim state = handler.GetCommandState(New SortAndRemoveUnnecessaryImportsCommandArgs(textView, textView.TextBuffer)) Assert.True(state.IsUnspecified) diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.xlf index c1c0342457545..f5265d486b66f 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.xlf @@ -149,22 +149,22 @@ '{0}' is not null here. - '{0}' is not null here. + {0} tady není null. '{0}' may be null here. - '{0}' may be null here. + {0} tady může být null. asynchronous foreach statement - asynchronous foreach statement + asynchronní příkaz foreach {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + asynchronní deklarace using {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + deklarace lokální proměnné @@ -409,12 +409,12 @@ switch statement - switch statement + příkaz switch {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + klauzule case příkazu switch {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + deklarace using {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + příkaz yield break {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + příkaz yield return {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.de.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.de.xlf index 08acaa0914e30..632577f475be7 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.de.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.de.xlf @@ -159,12 +159,12 @@ asynchronous foreach statement - asynchronous foreach statement + asynchrone foreach-Anweisung {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + asynchrone using-Deklaration {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + Deklaration lokaler Variablen @@ -409,12 +409,12 @@ switch statement - switch statement + switch-Anweisung {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + case-Klausel für switch-Anweisung {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + using-Deklaration {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + yield break-Anweisung {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + yield return-Anweisung {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.es.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.es.xlf index b2df801e32e07..036c291f9b0a1 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.es.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.es.xlf @@ -149,22 +149,22 @@ '{0}' is not null here. - '{0}' is not null here. + "{0}" no es NULL aquí. '{0}' may be null here. - '{0}' may be null here. + "{0}" puede ser NULL aquí. asynchronous foreach statement - asynchronous foreach statement + instrucción foreach asincrónica {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + declaración using asincrónica {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + declaración de variable local @@ -409,12 +409,12 @@ switch statement - switch statement + instrucción switch {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + cláusula case de la instrucción switch {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + declaración using {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + instrucción yield break {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + instrucción yield return {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.xlf index 5bece36d22e86..16f5baf259ea2 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.xlf @@ -149,22 +149,22 @@ '{0}' is not null here. - '{0}' is not null here. + '{0}' n'a pas une valeur null ici. '{0}' may be null here. - '{0}' may be null here. + '{0}' a peut-être une valeur null ici. asynchronous foreach statement - asynchronous foreach statement + instruction foreach asynchrone {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + déclaration using asynchrone {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + déclaration de variable locale @@ -409,12 +409,12 @@ switch statement - switch statement + instruction switch {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + clause case d'une instruction switch {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + déclaration using {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + instruction yield break {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + instruction yield return {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.it.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.it.xlf index 1d198a195ddb5..26ae97ea53446 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.it.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.it.xlf @@ -89,7 +89,7 @@ Conflict(s) detected. - Sono stati rilevati conflitti + Sono stati rilevati conflitti. @@ -149,22 +149,22 @@ '{0}' is not null here. - '{0}' is not null here. + '{0}' non è Null in questo punto. '{0}' may be null here. - '{0}' may be null here. + '{0}' può essere Null in questo punto. asynchronous foreach statement - asynchronous foreach statement + istruzione foreach asincrona {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + dichiarazione using asincrona {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + dichiarazione di variabile locale @@ -409,12 +409,12 @@ switch statement - switch statement + istruzione switch {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + clausola case dell'istruzione switch {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + dichiarazione using {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + istruzione yield break {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + istruzione yield return {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf index b09ca29ab8f59..85bf29a614889 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf @@ -149,22 +149,22 @@ '{0}' is not null here. - '{0}' is not null here. + ここでは、'{0}' は null ではありません。 '{0}' may be null here. - '{0}' may be null here. + ここでは、'{0}' は null である可能性があります。 asynchronous foreach statement - asynchronous foreach statement + 非同期の foreach ステートメント {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + 非同期の using 宣言 {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + ローカル変数宣言 @@ -409,12 +409,12 @@ switch statement - switch statement + switch ステートメント {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + switch ステートメントの case 句 {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + using 宣言 {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + yield break ステートメント {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + yield return ステートメント {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ko.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ko.xlf index 06824e5558542..60cbc10b90bbb 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ko.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ko.xlf @@ -149,22 +149,22 @@ '{0}' is not null here. - '{0}' is not null here. + '{0}'은(는) 여기에서 null이 아닙니다. '{0}' may be null here. - '{0}' may be null here. + '{0}'은(는) 여기에서 null일 수 있습니다. asynchronous foreach statement - asynchronous foreach statement + 비동기 foreach 문 {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + 비동기 using 선언 {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + 지역 변수 선언 @@ -409,12 +409,12 @@ switch statement - switch statement + switch 문 {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + switch 문 case 절 {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + using 선언 {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + yield break 문 {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + yield return 문 {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf index 3e1c48b08e001..974b9480acb0d 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf @@ -149,22 +149,22 @@ '{0}' is not null here. - '{0}' is not null here. + Element „{0}” nie ma wartości null w tym miejscu. '{0}' may be null here. - '{0}' may be null here. + Element „{0}” może mieć wartość null w tym miejscu. asynchronous foreach statement - asynchronous foreach statement + asynchroniczna instrukcja foreach {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + asynchroniczna deklaracja using {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + deklaracja zmiennej lokalnej @@ -409,12 +409,12 @@ switch statement - switch statement + instrukcja switch {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + klauzula case instrukcji switch {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + deklaracja using {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + instrukcja yield break {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + instrukcja yield return {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pt-BR.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pt-BR.xlf index e0e42ab401339..28f77c3bedb47 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pt-BR.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pt-BR.xlf @@ -149,22 +149,22 @@ '{0}' is not null here. - '{0}' is not null here. + '{0}' não é nulo aqui. '{0}' may be null here. - '{0}' may be null here. + '{0}' pode ser nulo aqui. asynchronous foreach statement - asynchronous foreach statement + instrução foreach assíncrona {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + declaração using assíncrona {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + declaração de variável local @@ -409,12 +409,12 @@ switch statement - switch statement + instrução switch {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + cláusula case da instrução switch {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + declaração using {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + instrução yield break {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + instrução yield return {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ru.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ru.xlf index 7a65ea0c54ad3..f9dc22f20b1bc 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ru.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ru.xlf @@ -149,22 +149,22 @@ '{0}' is not null here. - '{0}' is not null here. + Здесь "{0}" имеет значение, отличное от NULL. '{0}' may be null here. - '{0}' may be null here. + Здесь "{0}" может иметь значение NULL. asynchronous foreach statement - asynchronous foreach statement + асинхронная инструкция foreach {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + асинхронное объявление using {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + объявление локальной переменной @@ -409,12 +409,12 @@ switch statement - switch statement + оператор switch {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + предложение case оператора switch {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + объявление using {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + оператор yield break {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + оператор yield return {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf index 99eae38e68c30..59903797a44aa 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf @@ -149,22 +149,22 @@ '{0}' is not null here. - '{0}' is not null here. + '{0}' burada null değil. '{0}' may be null here. - '{0}' may be null here. + '{0}' burada null olabilir. asynchronous foreach statement - asynchronous foreach statement + zaman uyumsuz foreach deyimi {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + zaman uyumsuz using bildirimi {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + yerel değişken bildirimi @@ -409,12 +409,12 @@ switch statement - switch statement + switch deyimi {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + switch deyimi case yan tümcesi {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + using bildirimi {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + yield break deyimi {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + yield return deyimi {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf index b1a0efa59faa2..536c2a50de895 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf @@ -149,22 +149,22 @@ '{0}' is not null here. - '{0}' is not null here. + “{0}”在此处不为 null。 '{0}' may be null here. - '{0}' may be null here. + “{0}”可能在此处为 null。 asynchronous foreach statement - asynchronous foreach statement + 异步 foreach 语句 {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + 异步 using 声明 {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + 局部变量声明 @@ -409,12 +409,12 @@ switch statement - switch statement + switch 语句 {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + switch 语句 case 子句 {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + using 声明 {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + yield break 语句 {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + yield return 语句 {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hant.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hant.xlf index ac76eff39d41c..1089d89e98131 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hant.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hant.xlf @@ -149,22 +149,22 @@ '{0}' is not null here. - '{0}' is not null here. + '{0}' 在此不是 null。 '{0}' may be null here. - '{0}' may be null here. + '{0}' 在此可能為 null。 asynchronous foreach statement - asynchronous foreach statement + 非同步 foreach 陳述式 {Locked="foreach"} "foreach" is a C# keyword and should not be localized. asynchronous using declaration - asynchronous using declaration + 非同步 using 宣告 {Locked="using"} "using" is a C# keyword and should not be localized. @@ -184,7 +184,7 @@ local variable declaration - local variable declaration + 區域變數宣告 @@ -409,12 +409,12 @@ switch statement - switch statement + switch 陳述式 {Locked="switch"} "switch" is a C# keyword and should not be localized. switch statement case clause - switch statement case clause + switch 陳述式 case 子句 {Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized. @@ -444,7 +444,7 @@ using declaration - using declaration + using 宣告 {Locked="using"} "using" is a C# keyword and should not be localized. @@ -829,12 +829,12 @@ yield break statement - yield break statement + yield break 陳述式 {Locked="yield break"} "yield break" is a C# keyword and should not be localized. yield return statement - yield return statement + yield return 陳述式 {Locked="yield return"} "yield return" is a C# keyword and should not be localized. diff --git a/src/Features/Core/Portable/CodeFixes/ICodeFixService.cs b/src/Features/Core/Portable/CodeFixes/ICodeFixService.cs index d96bb69f0290d..fc5c4e0e28dd0 100644 --- a/src/Features/Core/Portable/CodeFixes/ICodeFixService.cs +++ b/src/Features/Core/Portable/CodeFixes/ICodeFixService.cs @@ -11,6 +11,7 @@ namespace Microsoft.CodeAnalysis.CodeFixes { internal interface ICodeFixService { + Task> GetFixesAsync(Document document, TextSpan textSpan, bool includeSuppressionFixes, bool isBlocking, CancellationToken cancellationToken); Task> GetFixesAsync(Document document, TextSpan textSpan, bool includeSuppressionFixes, CancellationToken cancellationToken); Task GetDocumentFixAllForIdInSpanAsync(Document document, TextSpan textSpan, string diagnosticId, CancellationToken cancellationToken); Task ApplyCodeFixesForSpecificDiagnosticIdAsync(Document document, string diagnosticId, IProgressTracker progressTracker, CancellationToken cancellationToken); diff --git a/src/Features/Core/Portable/CodeRefactorings/CodeRefactoringService.cs b/src/Features/Core/Portable/CodeRefactorings/CodeRefactoringService.cs index 4f6a44a03949d..c957900848721 100644 --- a/src/Features/Core/Portable/CodeRefactorings/CodeRefactoringService.cs +++ b/src/Features/Core/Portable/CodeRefactorings/CodeRefactoringService.cs @@ -78,7 +78,7 @@ public async Task HasRefactoringsAsync( cancellationToken.ThrowIfCancellationRequested(); var refactoring = await GetRefactoringFromProviderAsync( - document, state, provider, extensionManager, cancellationToken).ConfigureAwait(false); + document, state, provider, extensionManager, isBlocking: false, cancellationToken).ConfigureAwait(false); if (refactoring != null) { @@ -89,10 +89,19 @@ public async Task HasRefactoringsAsync( return false; } - public async Task> GetRefactoringsAsync( + public Task> GetRefactoringsAsync( Document document, TextSpan state, CancellationToken cancellationToken) + { + return ((ICodeRefactoringService)this).GetRefactoringsAsync(document, state, isBlocking: false, cancellationToken); + } + + async Task> ICodeRefactoringService.GetRefactoringsAsync( + Document document, + TextSpan state, + bool isBlocking, + CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Refactoring_CodeRefactoringService_GetRefactoringsAsync, cancellationToken)) { @@ -102,7 +111,7 @@ public async Task> GetRefactoringsAsync( foreach (var provider in GetProviders(document)) { tasks.Add(Task.Run( - () => GetRefactoringFromProviderAsync(document, state, provider, extensionManager, cancellationToken), cancellationToken)); + () => GetRefactoringFromProviderAsync(document, state, provider, extensionManager, isBlocking, cancellationToken), cancellationToken)); } var results = await Task.WhenAll(tasks).ConfigureAwait(false); @@ -115,6 +124,7 @@ private async Task GetRefactoringFromProviderAsync( TextSpan state, CodeRefactoringProvider provider, IExtensionManager extensionManager, + bool isBlocking, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -137,6 +147,7 @@ private async Task GetRefactoringFromProviderAsync( actions.Add(a); } }, + isBlocking, cancellationToken); var task = provider.ComputeRefactoringsAsync(context) ?? Task.CompletedTask; diff --git a/src/Features/Core/Portable/CodeRefactorings/ICodeRefactoringService.cs b/src/Features/Core/Portable/CodeRefactorings/ICodeRefactoringService.cs index 3f8fb959e2415..39f52c6614ee4 100644 --- a/src/Features/Core/Portable/CodeRefactorings/ICodeRefactoringService.cs +++ b/src/Features/Core/Portable/CodeRefactorings/ICodeRefactoringService.cs @@ -12,5 +12,7 @@ internal interface ICodeRefactoringService Task HasRefactoringsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken); Task> GetRefactoringsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken); + + Task> GetRefactoringsAsync(Document document, TextSpan textSpan, bool isBlocking, CancellationToken cancellationToken); } } diff --git a/src/Features/Core/Portable/Completion/CommonCompletionService.cs b/src/Features/Core/Portable/Completion/CommonCompletionService.cs index fbbd902579182..e6bf264f15ed8 100644 --- a/src/Features/Core/Portable/Completion/CommonCompletionService.cs +++ b/src/Features/Core/Portable/Completion/CommonCompletionService.cs @@ -1,6 +1,9 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Tags; namespace Microsoft.CodeAnalysis.Completion @@ -32,6 +35,17 @@ protected override CompletionItem GetBetterItem(CompletionItem item, CompletionI return base.GetBetterItem(item, existingItem); } + internal override Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsInternalAsync( + Document document, + int caretPosition, + CompletionTrigger trigger, + ImmutableHashSet roles, + OptionSet options, + CancellationToken cancellationToken) + { + return GetCompletionsWithAvailabilityOfExpandedItemsAsync(document, caretPosition, trigger, roles, options, cancellationToken); + } + protected static bool IsKeywordItem(CompletionItem item) { return item.Tags.Contains(WellKnownTags.Keyword); diff --git a/src/Features/Core/Portable/Completion/CompletionContext.cs b/src/Features/Core/Portable/Completion/CompletionContext.cs index 9994e4596f8ad..053148064510a 100644 --- a/src/Features/Core/Portable/Completion/CompletionContext.cs +++ b/src/Features/Core/Portable/Completion/CompletionContext.cs @@ -70,6 +70,14 @@ public sealed class CompletionContext /// public bool IsExclusive { get; set; } + /// + /// Set to true if the corresponding provider can provide extended items with currect context, + /// regardless of whether those items are actually added. i.e. it might be disabled by default, + /// but we still want to show the expander so user can explicitly request them to be added to + /// completion list if we are in the aproperiate context. + /// + internal bool ExpandItemsAvailable { get; set; } + /// /// Creates a instance. /// diff --git a/src/Features/Core/Portable/Completion/CompletionHelper.cs b/src/Features/Core/Portable/Completion/CompletionHelper.cs index e85f205b9f31f..e948a4c331c5f 100644 --- a/src/Features/Core/Portable/Completion/CompletionHelper.cs +++ b/src/Features/Core/Portable/Completion/CompletionHelper.cs @@ -188,7 +188,16 @@ private static bool IsKeywordItem(CompletionItem item) private int CompareMatches(PatternMatch match1, PatternMatch match2, CompletionItem item1, CompletionItem item2) { - // First see how the two items compare in a case insensitive fashion. Matches that + // Always prefer non-expanded item regardless of the pattern matching result. + // This currently means unimported types will be treated as "2nd tier" results, + // which forces users to be more explicit about selecting them. + var expandedDiff = CompareExpandedItem(item1, item2); + if (expandedDiff != 0) + { + return expandedDiff; + } + + // Then see how the two items compare in a case insensitive fashion. Matches that // are strictly better (ignoring case) should prioritize the item. i.e. if we have // a prefix match, that should always be better than a substring match. // @@ -252,5 +261,19 @@ private int ComparePreselection(CompletionItem item1, CompletionItem item2) return 0; } + + private int CompareExpandedItem(CompletionItem item1, CompletionItem item2) + { + var isItem1Expanded = item1.Flags.IsExpanded(); + var isItem2Expanded = item2.Flags.IsExpanded(); + + if (isItem1Expanded == isItem2Expanded) + { + return 0; + } + + // Non-expanded item is better than expanded item + return isItem1Expanded ? 1 : -1; + } } } diff --git a/src/Features/Core/Portable/Completion/CompletionItem.cs b/src/Features/Core/Portable/Completion/CompletionItem.cs index 9a46a3d83d57c..75cfeecff7acb 100644 --- a/src/Features/Core/Portable/Completion/CompletionItem.cs +++ b/src/Features/Core/Portable/Completion/CompletionItem.cs @@ -90,15 +90,7 @@ public sealed class CompletionItem : IComparable /// internal string AutomationText { get; set; } - /// - /// Indicate whether this is cached and reused across completion sessions. - /// This might be used by completion system for things like deciding whether it can safaly cache and reuse - /// other data correspodning to this item. - /// - /// TODO: Revisit the approach we used for caching VS items. - /// https://github.com/dotnet/roslyn/issues/35160 - /// - internal bool IsCached { get; set; } + internal CompletionItemFlags Flags { get; set; } private CompletionItem( string displayText, @@ -259,7 +251,8 @@ private CompletionItem With( inlineDescription: newInlineDescription) { AutomationText = AutomationText, - ProviderName = ProviderName + ProviderName = ProviderName, + Flags = Flags, }; } diff --git a/src/Features/Core/Portable/Completion/CompletionItemFlags.cs b/src/Features/Core/Portable/Completion/CompletionItemFlags.cs new file mode 100644 index 0000000000000..013a3e5a1a74d --- /dev/null +++ b/src/Features/Core/Portable/Completion/CompletionItemFlags.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; + +namespace Microsoft.CodeAnalysis.Completion +{ + [Flags] + internal enum CompletionItemFlags + { + None = 0x0, + + /// + /// Indicates this is cached and reused across completion sessions. + /// This might be used by completion system for things like deciding whether it can safaly cache and reuse + /// other data correspodning to this item. + /// + /// TODO: Revisit the approach we used for caching VS items. + /// https://github.com/dotnet/roslyn/issues/35160 + /// + Cached = 0x1, + + /// + /// Indicates this should be shown only when expanded items is requested. + /// + Expanded = 0x2, + + CachedAndExpanded = Cached | Expanded, + } + + internal static class CompletionItemFlagsExtensions + { + public static bool IsCached(this CompletionItemFlags flags) + => (flags & CompletionItemFlags.Cached) != 0; + + public static bool IsExpanded(this CompletionItemFlags flags) + => (flags & CompletionItemFlags.Expanded) != 0; + } +} diff --git a/src/Features/Core/Portable/Completion/CompletionProvider.cs b/src/Features/Core/Portable/Completion/CompletionProvider.cs index 2ca7bbb8e3918..f41f98154b212 100644 --- a/src/Features/Core/Portable/Completion/CompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/CompletionProvider.cs @@ -64,5 +64,10 @@ internal virtual Task GetChangeAsync(Document document, Comple /// True if the provider produces snippet items. /// internal virtual bool IsSnippetProvider => false; + + /// + /// True if the provider produces items show be shown in expanded list only. + /// + internal virtual bool IsExpandItemProvider => false; } } diff --git a/src/Features/Core/Portable/Completion/CompletionService.cs b/src/Features/Core/Portable/Completion/CompletionService.cs index 417c91db0ede3..a2ef4b5774e3e 100644 --- a/src/Features/Core/Portable/Completion/CompletionService.cs +++ b/src/Features/Core/Portable/Completion/CompletionService.cs @@ -91,6 +91,25 @@ public abstract Task GetCompletionsAsync( OptionSet options = null, CancellationToken cancellationToken = default); + /// + /// Gets the completions available at the caret position, with additional info indicates + /// whether expander items are available. + /// + /// + /// expandItemsAvailable is true when expanded items are returned or can be provided upon request. + /// + internal virtual async Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsInternalAsync( + Document document, + int caretPosition, + CompletionTrigger trigger = default, + ImmutableHashSet roles = null, + OptionSet options = null, + CancellationToken cancellationToken = default) + { + var completionList = await GetCompletionsAsync(document, caretPosition, trigger, roles, options, cancellationToken).ConfigureAwait(false); + return (completionList, false); + } + /// /// Gets the description of the item. /// diff --git a/src/Features/Core/Portable/Completion/CompletionServiceOptions.cs b/src/Features/Core/Portable/Completion/CompletionServiceOptions.cs index 484fa599773d3..1c84faba154b8 100644 --- a/src/Features/Core/Portable/Completion/CompletionServiceOptions.cs +++ b/src/Features/Core/Portable/Completion/CompletionServiceOptions.cs @@ -6,6 +6,12 @@ namespace Microsoft.CodeAnalysis.Completion { internal static class CompletionServiceOptions { + /// + /// Indicates if the completion is trigger by toggle the expander. + /// + public static readonly Option IsExpandedCompletion + = new Option(nameof(CompletionServiceOptions), nameof(IsExpandedCompletion), defaultValue: false); + /// /// Timeout value used for time-boxing import completion. /// Telemetry shows that the average processing time with cache warmed up for 99th percentile is ~700ms, diff --git a/src/Features/Core/Portable/Completion/CompletionServiceWithProviders.cs b/src/Features/Core/Portable/Completion/CompletionServiceWithProviders.cs index 57aa3aa724079..f62b0c4de9216 100644 --- a/src/Features/Core/Portable/Completion/CompletionServiceWithProviders.cs +++ b/src/Features/Core/Portable/Completion/CompletionServiceWithProviders.cs @@ -152,6 +152,11 @@ private ImmutableArray FilterProviders( CompletionTrigger trigger, OptionSet options) { + if (options.GetOption(CompletionServiceOptions.IsExpandedCompletion)) + { + providers = providers.WhereAsArray(p => p.IsExpandItemProvider); + } + // If the caller passed along specific options that affect snippets, // then defer to those. Otherwise if the caller just wants the default // behavior, then get the snippets behavior from our own rules. @@ -212,6 +217,18 @@ public override async Task GetCompletionsAsync( ImmutableHashSet roles, OptionSet options, CancellationToken cancellationToken) + { + var (completionList, _) = await GetCompletionsWithAvailabilityOfExpandedItemsAsync(document, caretPosition, trigger, roles, options, cancellationToken).ConfigureAwait(false); + return completionList; + } + + private protected async Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsWithAvailabilityOfExpandedItemsAsync( + Document document, + int caretPosition, + CompletionTrigger trigger, + ImmutableHashSet roles, + OptionSet options, + CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var defaultItemSpan = GetDefaultCompletionListSpan(text, caretPosition); @@ -242,7 +259,7 @@ public override async Task GetCompletionsAsync( // Now, ask all the triggered providers, in parallel, to populate a completion context. // Note: we keep any context with items *or* with a suggested item. - var triggeredCompletionContexts = await ComputeNonEmptyCompletionContextsAsync( + var (triggeredCompletionContexts, expandItemsAvailableFromTriggeredProviders) = await ComputeNonEmptyCompletionContextsAsync( document, caretPosition, trigger, options, defaultItemSpan, triggeredProviders, cancellationToken).ConfigureAwait(false); @@ -252,7 +269,7 @@ public override async Task GetCompletionsAsync( // want to show any completion. if (!triggeredCompletionContexts.Any(cc => cc.Items.Count > 0)) { - return null; + return (null, expandItemsAvailableFromTriggeredProviders); } // All the contexts should be non-empty or have a suggestion item. @@ -264,10 +281,8 @@ public override async Task GetCompletionsAsync( if (exclusiveContexts.Any()) { - return MergeAndPruneCompletionLists( - exclusiveContexts, - defaultItemSpan, - isExclusive: true); + return (MergeAndPruneCompletionLists(exclusiveContexts, defaultItemSpan, isExclusive: true), + expandItemsAvailableFromTriggeredProviders); } // Shouldn't be any exclusive completion contexts at this point. @@ -279,7 +294,7 @@ public override async Task GetCompletionsAsync( // we'll want to augment the list with all the regular symbol completion items. var augmentingProviders = providers.Except(triggeredProviders).ToImmutableArray(); - var augmentingCompletionContexts = await ComputeNonEmptyCompletionContextsAsync( + var (augmentingCompletionContexts, expandItemsAvailableFromAugmentingProviders) = await ComputeNonEmptyCompletionContextsAsync( document, caretPosition, trigger, options, defaultItemSpan, augmentingProviders, cancellationToken).ConfigureAwait(false); @@ -290,7 +305,8 @@ public override async Task GetCompletionsAsync( // groups are properly ordered based on the original providers. allContexts = allContexts.Sort((p1, p2) => completionProviderToIndex[p1.Provider] - completionProviderToIndex[p2.Provider]); - return MergeAndPruneCompletionLists(allContexts, defaultItemSpan, isExclusive: false); + return (MergeAndPruneCompletionLists(allContexts, defaultItemSpan, isExclusive: false), + (expandItemsAvailableFromTriggeredProviders || expandItemsAvailableFromAugmentingProviders)); } private static bool HasAnyItems(CompletionContext cc) @@ -298,7 +314,7 @@ private static bool HasAnyItems(CompletionContext cc) return cc.Items.Count > 0 || cc.SuggestionModeItem != null; } - private async Task> ComputeNonEmptyCompletionContextsAsync( + private async Task<(ImmutableArray, bool)> ComputeNonEmptyCompletionContextsAsync( Document document, int caretPosition, CompletionTrigger trigger, OptionSet options, TextSpan defaultItemSpan, ImmutableArray providers, @@ -314,7 +330,8 @@ private async Task> ComputeNonEmptyCompletionC var completionContexts = await Task.WhenAll(completionContextTasks).ConfigureAwait(false); var nonEmptyContexts = completionContexts.Where(HasAnyItems).ToImmutableArray(); - return nonEmptyContexts; + var shouldShowExpander = completionContexts.Any(context => context.ExpandItemsAvailable); + return (nonEmptyContexts, shouldShowExpander); } private CompletionList MergeAndPruneCompletionLists( diff --git a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionProvider.cs b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionProvider.cs index 402c173a4c0cf..65f23e382b800 100644 --- a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionProvider.cs +++ b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionProvider.cs @@ -10,7 +10,7 @@ using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion; -using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Formatting; @@ -37,31 +37,42 @@ protected abstract ImmutableArray GetImportedNamespaces( protected abstract Task IsInImportsDirectiveAsync(Document document, int position, CancellationToken cancellationToken); + internal override bool IsExpandItemProvider => true; + public override async Task ProvideCompletionsAsync(CompletionContext completionContext) { var cancellationToken = completionContext.CancellationToken; var document = completionContext.Document; var workspace = document.Project.Solution.Workspace; - var importCompletionOptionValue = completionContext.Options.GetOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, document.Project.Language); - - // Don't trigger import completion if the option value is "default" and the experiment is disabled for the user. - if (importCompletionOptionValue == false || - (importCompletionOptionValue == null && !IsTypeImportCompletionExperimentEnabled(workspace))) + // We need to check for context before option values, so we can tell completion service that we are in a context to provide expanded items + // even though import completion might be disabled. This would show the expander in completion list which user can then use to explicitly ask for unimported items. + var syntaxContext = await CreateContextAsync(document, completionContext.Position, cancellationToken).ConfigureAwait(false); + if (!syntaxContext.IsTypeContext) { return; } - var syntaxContext = await CreateContextAsync(document, completionContext.Position, cancellationToken).ConfigureAwait(false); - if (!syntaxContext.IsTypeContext) + completionContext.ExpandItemsAvailable = true; + + // We will trigger import completion regardless of the option/experiment if extended items is being requested explicitly (via expander in completion list) + var isExpandedCompletion = completionContext.Options.GetOption(CompletionServiceOptions.IsExpandedCompletion); + if (!isExpandedCompletion) { - return; + var importCompletionOptionValue = completionContext.Options.GetOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, document.Project.Language); + + // Don't trigger import completion if the option value is "default" and the experiment is disabled for the user. + if (importCompletionOptionValue == false || + (importCompletionOptionValue == null && !IsTypeImportCompletionExperimentEnabled(workspace))) + { + return; + } } using (Logger.LogBlock(FunctionId.Completion_TypeImportCompletionProvider_GetCompletionItemsAsync, cancellationToken)) using (var telemetryCounter = new TelemetryCounter()) { - await AddCompletionItemsAsync(completionContext, syntaxContext, telemetryCounter, cancellationToken).ConfigureAwait(false); + await AddCompletionItemsAsync(completionContext, syntaxContext, isExpandedCompletion, telemetryCounter, cancellationToken).ConfigureAwait(false); } } @@ -76,7 +87,7 @@ private bool IsTypeImportCompletionExperimentEnabled(Workspace workspace) return _isTypeImportCompletionExperimentEnabled == true; } - private async Task AddCompletionItemsAsync(CompletionContext completionContext, SyntaxContext syntaxContext, TelemetryCounter telemetryCounter, CancellationToken cancellationToken) + private async Task AddCompletionItemsAsync(CompletionContext completionContext, SyntaxContext syntaxContext, bool isExpandedCompletion, TelemetryCounter telemetryCounter, CancellationToken cancellationToken) { var document = completionContext.Document; var project = document.Project; @@ -104,15 +115,17 @@ private async Task AddCompletionItemsAsync(CompletionContext completionContext, tasksToGetCompletionItems.AddRange( referencedAssemblySymbols.Select(symbol => Task.Run(() => HandleReferenceAsync(symbol)))); - // We want to timebox the operation that might need to traverse all the type symbols and populate the cache, - // the idea is not to block completion for too long (likely to happen the first time import completion is triggered). + // We want to timebox the operation that might need to traverse all the type symbols and populate the cache. + // The idea is not to block completion for too long (likely to happen the first time import completion is triggered). // The trade-off is we might not provide unimported types until the cache is warmed up. var timeoutInMilliseconds = completionContext.Options.GetOption(CompletionServiceOptions.TimeoutInMillisecondsForImportCompletion); var combinedTask = Task.WhenAll(tasksToGetCompletionItems.ToImmutableAndFree()); - if (timeoutInMilliseconds != 0 && await Task.WhenAny(combinedTask, Task.Delay(timeoutInMilliseconds, cancellationToken)).ConfigureAwait(false) == combinedTask) + if (isExpandedCompletion || + timeoutInMilliseconds != 0 && await Task.WhenAny(combinedTask, Task.Delay(timeoutInMilliseconds, cancellationToken)).ConfigureAwait(false) == combinedTask) { - // No timeout. We now have all completion items ready. + // Either there's no timeout, and we now have all completion items ready, + // or user asked for unimported type explicitly so we need to wait until they are calculated. var completionItemsToAdd = await combinedTask.ConfigureAwait(false); foreach (var completionItems in completionItemsToAdd) { @@ -272,8 +285,8 @@ async Task ShouldCompleteWithFullyQualifyTypeName() } // During an EnC session, adding import is not supported. - var encService = workspace.Services.GetService()?.EditAndContinueServiceOpt; - if (encService?.EditSession != null) + var encService = workspace.Services.GetService(); + if (encService?.IsDebuggingSessionInProgress == true) { return true; } diff --git a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.cs b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.cs index 4c4fde54b531a..10ca3c041a6e0 100644 --- a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.cs +++ b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractTypeImportCompletionService.cs @@ -271,10 +271,7 @@ public void AddItem(INamedTypeSymbol symbol, string containingNamespace, bool is var isAttribute = symbol.Name.HasAttributeSuffix(isCaseSensitive: false) && symbol.IsAttribute(); var item = TypeImportCompletionItem.Create(symbol, containingNamespace, _genericTypeSuffix); - item.IsCached = true; - _itemsBuilder.Add(new TypeImportCompletionItemInfo(item, isPublic, isGeneric, isAttribute)); - return; } } diff --git a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/TypeImportCompletionItem.cs b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/TypeImportCompletionItem.cs index 1a10e468280f7..785cd5ca5762d 100644 --- a/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/TypeImportCompletionItem.cs +++ b/src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/TypeImportCompletionItem.cs @@ -34,8 +34,8 @@ public static CompletionItem Create(INamedTypeSymbol typeSymbol, string containi // it also makes sure type with shorter name shows first, e.g. 'SomeType` before 'SomeTypeWithLongerName'. var sortTextBuilder = PooledStringBuilder.GetInstance(); sortTextBuilder.Builder.AppendFormat(SortTextFormat, typeSymbol.Name, containingNamespace); - - return CompletionItem.Create( + + var item = CompletionItem.Create( displayText: typeSymbol.Name, filterText: typeSymbol.Name, sortText: sortTextBuilder.ToStringAndFree(), @@ -45,6 +45,9 @@ public static CompletionItem Create(INamedTypeSymbol typeSymbol, string containi displayTextPrefix: null, displayTextSuffix: typeSymbol.Arity == 0 ? string.Empty : genericTypeSuffix, inlineDescription: containingNamespace); + + item.Flags = CompletionItemFlags.CachedAndExpanded; + return item; } public static CompletionItem CreateAttributeItemWithoutSuffix(CompletionItem attributeItem, string attributeNameWithoutSuffix) diff --git a/src/Features/Core/Portable/Debugging/DebuggingWorkspaceService.cs b/src/Features/Core/Portable/Debugging/DebuggingWorkspaceService.cs index 40f1c679f6871..f44e3dbb2c5a3 100644 --- a/src/Features/Core/Portable/Debugging/DebuggingWorkspaceService.cs +++ b/src/Features/Core/Portable/Debugging/DebuggingWorkspaceService.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using Microsoft.CodeAnalysis.EditAndContinue; namespace Microsoft.CodeAnalysis.Debugging { @@ -9,13 +8,6 @@ internal sealed class DebuggingWorkspaceService : IDebuggingWorkspaceService { public event EventHandler BeforeDebuggingStateChanged; - public IEditAndContinueService EditAndContinueServiceOpt { get; } - - internal DebuggingWorkspaceService(IEditAndContinueService editAndContinueServiceOpt) - { - EditAndContinueServiceOpt = editAndContinueServiceOpt; - } - public void OnBeforeDebuggingStateChanged(DebuggingState before, DebuggingState after) => BeforeDebuggingStateChanged?.Invoke(this, new DebuggingStateChangedEventArgs(before, after)); } diff --git a/src/Features/Core/Portable/Debugging/DebuggingWorkspaceServiceFactory.cs b/src/Features/Core/Portable/Debugging/DebuggingWorkspaceServiceFactory.cs index 095d8ea84dd64..5c1d3a9770778 100644 --- a/src/Features/Core/Portable/Debugging/DebuggingWorkspaceServiceFactory.cs +++ b/src/Features/Core/Portable/Debugging/DebuggingWorkspaceServiceFactory.cs @@ -1,5 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; using System.Composition; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; @@ -10,15 +11,13 @@ namespace Microsoft.CodeAnalysis.Debugging [ExportWorkspaceServiceFactory(typeof(IDebuggingWorkspaceService), ServiceLayer.Host), Shared] internal sealed class DebuggingWorkspaceServiceFactory : IWorkspaceServiceFactory { - private readonly IEditAndContinueService _editAndContinueServiceOpt; - [ImportingConstructor] - public DebuggingWorkspaceServiceFactory([Import(AllowDefault = true)]IEditAndContinueService editAndContinueServiceOpt) + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public DebuggingWorkspaceServiceFactory() { - _editAndContinueServiceOpt = editAndContinueServiceOpt; } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) - => new DebuggingWorkspaceService(_editAndContinueServiceOpt); + => new DebuggingWorkspaceService(); } } diff --git a/src/Features/Core/Portable/Debugging/IDebuggingWorkspaceService.cs b/src/Features/Core/Portable/Debugging/IDebuggingWorkspaceService.cs index 02fcc2d43a418..4a2583cc07032 100644 --- a/src/Features/Core/Portable/Debugging/IDebuggingWorkspaceService.cs +++ b/src/Features/Core/Portable/Debugging/IDebuggingWorkspaceService.cs @@ -8,8 +8,6 @@ namespace Microsoft.CodeAnalysis.Debugging { internal interface IDebuggingWorkspaceService : IWorkspaceService { - IEditAndContinueService EditAndContinueServiceOpt { get; } - event EventHandler BeforeDebuggingStateChanged; void OnBeforeDebuggingStateChanged(DebuggingState before, DebuggingState after); diff --git a/src/Features/Core/Portable/Diagnostics/Analyzers/EditAndContinueDiagnosticAnalyzer.cs b/src/Features/Core/Portable/Diagnostics/Analyzers/EditAndContinueDiagnosticAnalyzer.cs new file mode 100644 index 0000000000000..001b19bd590db --- /dev/null +++ b/src/Features/Core/Portable/Diagnostics/Analyzers/EditAndContinueDiagnosticAnalyzer.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Immutable; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Diagnostics; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.EditAndContinue +{ + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + internal sealed class EditAndContinueDiagnosticAnalyzer : DocumentDiagnosticAnalyzer, IBuiltInAnalyzer + { + private static readonly ImmutableArray s_supportedDiagnostics = EditAndContinueDiagnosticDescriptors.GetDescriptors(); + + // Return known descriptors. This will not include module diagnostics reported on behalf of the debugger. + public override ImmutableArray SupportedDiagnostics + => s_supportedDiagnostics; + + public DiagnosticAnalyzerCategory GetAnalyzerCategory() + => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; + + public bool OpenFileOnly(Workspace workspace) + => false; + + // No syntax diagnostics produced by the EnC engine. + public override Task> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) + => SpecializedTasks.EmptyImmutableArray(); + + public override Task> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken) + { + var encService = document.Project.Solution.Workspace.Services.GetService(); + return (encService != null) ? encService.GetDocumentDiagnosticsAsync(document, cancellationToken) : Task.FromResult(ImmutableArray.Empty); + } + } +} diff --git a/src/Features/Core/Portable/Diagnostics/Analyzers/RudeEditUserDiagnosticAnalyzer.cs b/src/Features/Core/Portable/Diagnostics/Analyzers/RudeEditUserDiagnosticAnalyzer.cs deleted file mode 100644 index 051df796e1a02..0000000000000 --- a/src/Features/Core/Portable/Diagnostics/Analyzers/RudeEditUserDiagnosticAnalyzer.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Immutable; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Debugging; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.ErrorReporting; -using Roslyn.Utilities; - -namespace Microsoft.CodeAnalysis.EditAndContinue -{ - [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] - internal class RudeEditDiagnosticAnalyzer : DocumentDiagnosticAnalyzer, IBuiltInAnalyzer - { - public override ImmutableArray SupportedDiagnostics => RudeEditDiagnosticDescriptors.AllDescriptors; - public bool OpenFileOnly(Workspace workspace) => false; - - public override Task> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) - { - // No syntax diagnostics produced by the EnC engine. - return SpecializedTasks.EmptyImmutableArray(); - } - - public override async Task> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken) - { - try - { - var encService = document.Project.Solution.Workspace.Services.GetService()?.EditAndContinueServiceOpt; - if (encService == null) - { - return ImmutableArray.Empty; - } - - var session = encService.EditSession; - if (session == null || - session.BaseSolution.WorkspaceVersion == document.Project.Solution.WorkspaceVersion || - !session.HasProject(document.Project.Id)) - { - return ImmutableArray.Empty; - } - - var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); - var analysis = await session.GetDocumentAnalysis(document).GetValueAsync(cancellationToken).ConfigureAwait(false); - if (analysis.RudeEditErrors.IsDefault) - { - return ImmutableArray.Empty; - } - - session.LogRudeEditErrors(analysis.RudeEditErrors); - return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); - } - catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) - { - throw ExceptionUtilities.Unreachable; - } - } - - public DiagnosticAnalyzerCategory GetAnalyzerCategory() - => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; - } -} diff --git a/src/Features/Core/Portable/Diagnostics/DiagnosticCategory.cs b/src/Features/Core/Portable/Diagnostics/DiagnosticCategory.cs index 07889d6b8c84c..1f8e324029216 100644 --- a/src/Features/Core/Portable/Diagnostics/DiagnosticCategory.cs +++ b/src/Features/Core/Portable/Diagnostics/DiagnosticCategory.cs @@ -6,7 +6,7 @@ internal static class DiagnosticCategory { public static readonly string Style = FeaturesResources.Style; public static readonly string CodeQuality = FeaturesResources.Code_Quality; - public static readonly string EditAndContinue = FeaturesResources.Edit_and_Continue2; + public static readonly string EditAndContinue = FeaturesResources.EditAndContinue; public static readonly string Compiler = FeaturesResources.Compiler1; } } diff --git a/src/Features/Core/Portable/Diagnostics/PredefinedBuildTools.cs b/src/Features/Core/Portable/Diagnostics/PredefinedBuildTools.cs index 91d0b523b4452..b333731fb4f62 100644 --- a/src/Features/Core/Portable/Diagnostics/PredefinedBuildTools.cs +++ b/src/Features/Core/Portable/Diagnostics/PredefinedBuildTools.cs @@ -5,7 +5,6 @@ namespace Microsoft.CodeAnalysis.Diagnostics internal static class PredefinedBuildTools { public static readonly string Build = FeaturesResources.Compiler2; - public static readonly string EnC = FeaturesResources.Edit_And_Continue; public static readonly string Live = FeaturesResources.Live; } } diff --git a/src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.cs b/src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.cs index 8600eb4906714..1b8516314e0f7 100644 --- a/src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.cs +++ b/src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.cs @@ -547,7 +547,7 @@ public async Task AnalyzeDocumentAsync( var location = firstDeclaratingErrorOpt.Location; DocumentAnalysisResults.Log.Write("Declaration errors, first: {0}", location.IsInSource ? location.SourceTree.FilePath : location.MetadataModule.Name); - return DocumentAnalysisResults.Errors(newActiveStatements.AsImmutable(), ImmutableArray.Create(), hasSemanticErrors: true); + return DocumentAnalysisResults.Errors(newActiveStatements.AsImmutable(), ImmutableArray.Empty, hasSemanticErrors: true); } if (diagnostics.Count > 0) diff --git a/src/Features/Core/Portable/EditAndContinue/DebuggeeModuleInfoCache.cs b/src/Features/Core/Portable/EditAndContinue/DebuggeeModuleInfoCache.cs index 71db3714e5a25..d596e236960ff 100644 --- a/src/Features/Core/Portable/EditAndContinue/DebuggeeModuleInfoCache.cs +++ b/src/Features/Core/Portable/EditAndContinue/DebuggeeModuleInfoCache.cs @@ -56,7 +56,7 @@ public DebuggeeModuleInfo GetOrAdd(Guid mvid, Func pro } /// - /// Removes metadata of specified module and process. + /// Removes metadata of specified module. /// public bool Remove(Guid mvid) { diff --git a/src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs b/src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs index 50a175a8260cb..85fda8f2e3a6d 100644 --- a/src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs +++ b/src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs @@ -1,20 +1,293 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; +using System.Collections.Generic; +using System.Collections.Immutable; using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using System.Reflection.PortableExecutable; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Emit; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// /// Represents a debugging session. /// - internal sealed class DebuggingSession + internal sealed class DebuggingSession : IDisposable { - public readonly Solution InitialSolution; + public readonly IActiveStatementProvider ActiveStatementProvider; + public readonly IDebuggeeModuleMetadataProvider DebugeeModuleMetadataProvider; + public readonly ICompilationOutputsProviderService CompilationOutputsProvider; - internal DebuggingSession(Solution initialSolution) + /// + /// MVIDs read from the assembly built for given project id. + /// + private readonly Dictionary _projectModuleIds; + private readonly object _projectModuleIdsGuard = new object(); + + /// + /// The current baseline for given project id. + /// The baseline is updated when changes are committed at the end of edit session. + /// The backing module readers of some baselines need to be kept alive -- store them in + /// and dispose them at the end of the debugging session + /// + private readonly Dictionary _projectEmitBaselines; + private List _lazyBaselineModuleReaders; + private readonly object _projectEmitBaselinesGuard = new object(); + + // Maps active statement instructions to their latest spans. + // Consumed by the next edit session and updated when changes are committed at the end of the edit session. + // + // Consider a function F containing a call to function G that is updated a couple of times + // before the thread returns from G and is remapped to the latest version of F. + // '>' indicates an active statement instruction. + // + // F v1: F v2: F v3: + // 0: nop 0: nop 0: nop + // 1> G() 1: nop 1: nop + // 2: nop 2: G() 2: nop + // 3: nop 3: nop 3> G() + // + // When entering a break state we query the debugger for current active statements. + // The returned statements reflect the current state of the threads in the runtime. + // When a change is successfully applied we remember changes in active statement spans. + // These changes are passed to the next edit session. + // We use them to map the spans for active statements returned by the debugger. + // + // In the above case the sequence of events is + // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date + // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 + // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 + // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements + // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 + // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 + // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date + // + internal ImmutableDictionary> NonRemappableRegions { get; private set; } + + private readonly HashSet _modulesPreparedForUpdate; + private readonly object _modulesPreparedForUpdateGuard = new object(); + + /// + /// The solution captured when the debugging session entered run mode (application debugging started), + /// or the solution which the last changes commited to the debuggee at the end of edit session were calculated from. + /// The solution reflecting the current state of the modules loaded in the debugee. + /// + internal Solution LastCommittedSolution { get; private set; } + + internal DebuggingSession( + Workspace workspace, + IDebuggeeModuleMetadataProvider debugeeModuleMetadataProvider, + IActiveStatementProvider activeStatementProvider, + ICompilationOutputsProviderService compilationOutputsProvider) + { + Debug.Assert(workspace != null); + Debug.Assert(debugeeModuleMetadataProvider != null); + + DebugeeModuleMetadataProvider = debugeeModuleMetadataProvider; + CompilationOutputsProvider = compilationOutputsProvider; + _projectModuleIds = new Dictionary(); + _projectEmitBaselines = new Dictionary(); + _modulesPreparedForUpdate = new HashSet(); + + ActiveStatementProvider = activeStatementProvider; + + LastCommittedSolution = workspace.CurrentSolution; + NonRemappableRegions = ImmutableDictionary>.Empty; + } + + // test only + internal void Test_SetNonRemappableRegions(ImmutableDictionary> nonRemappableRegions) + { + NonRemappableRegions = nonRemappableRegions; + } + + // test only + internal EmitBaseline Test_GetProjectEmitBaseline(ProjectId id) { - Debug.Assert(initialSolution != null); - InitialSolution = initialSolution; + lock (_projectEmitBaselinesGuard) + { + return _projectEmitBaselines[id]; + } + } + + // internal for testing + internal ImmutableArray GetBaselineModuleReaders() + { + lock (_projectEmitBaselinesGuard) + { + return _lazyBaselineModuleReaders.ToImmutableArrayOrEmpty(); + } + } + + public void Dispose() + { + foreach (var reader in GetBaselineModuleReaders()) + { + reader.Dispose(); + } + } + + internal void PrepareModuleForUpdate(Guid mvid) + { + lock (_modulesPreparedForUpdateGuard) + { + if (!_modulesPreparedForUpdate.Add(mvid)) + { + return; + } + } + + DebugeeModuleMetadataProvider.PrepareModuleForUpdate(mvid); + } + + public void CommitSolutionUpdate(PendingSolutionUpdate update) + { + // Save new non-remappable regions for the next edit session. + // If no edits were made the pending list will be empty and we need to keep the previous regions. + + var nonRemappableRegions = GroupToImmutableDictionary( + from delta in update.Deltas + from region in delta.NonRemappableRegions + group region.Region by region.Method); + + if (nonRemappableRegions.Count > 0) + { + NonRemappableRegions = nonRemappableRegions; + } + + // update baselines: + lock (_projectEmitBaselinesGuard) + { + foreach (var (projectId, baseline) in update.EmitBaselines) + { + _projectEmitBaselines[projectId] = baseline; + } + + if (!update.ModuleReaders.IsEmpty) + { + if (_lazyBaselineModuleReaders == null) + { + _lazyBaselineModuleReaders = new List(); + } + + _lazyBaselineModuleReaders.AddRange(update.ModuleReaders); + } + } + + LastCommittedSolution = update.Solution; + } + + /// + /// Reads the MVID of a compiled project. + /// + /// + /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. + /// The MVID is default if either project not built, or an it can't be read from the module binary. + /// + public async Task<(Guid Mvid, Diagnostic Error)> GetProjectModuleIdAsync(ProjectId projectId, CancellationToken cancellationToken) + { + lock (_projectModuleIdsGuard) + { + if (_projectModuleIds.TryGetValue(projectId, out var id)) + { + return id; + } + } + + (Guid Mvid, Diagnostic Error) ReadMvid() + { + var outputs = CompilationOutputsProvider.GetCompilationOutputs(projectId); + + try + { + return (outputs.ReadAssemblyModuleVersionId(), Error: null); + } + catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException) + { + return (Mvid: Guid.Empty, Error: null); + } + catch (Exception e) + { + var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); + return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); + } + } + + var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); + + lock (_projectModuleIdsGuard) + { + if (_projectModuleIds.TryGetValue(projectId, out var id)) + { + return id; + } + + return _projectModuleIds[projectId] = newId; + } + } + + /// + /// Get for given project. + /// Must be called on MTA thread. + /// + /// Null if the module corresponding to he project hasn't been loaded yet + /// Error reading project's binary. + public EmitBaseline GetOrCreateEmitBaseline(ProjectId projectId, Guid mvid) + { + Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA, "SymReader requires MTA"); + + EmitBaseline baseline; + lock (_projectEmitBaselinesGuard) + { + if (_projectEmitBaselines.TryGetValue(projectId, out baseline)) + { + return baseline; + } + } + + var moduleInfo = DebugeeModuleMetadataProvider.TryGetBaselineModuleInfo(mvid); + if (moduleInfo == null) + { + // Module not loaded. + // Do not cache this result as the module may be loaded in the next edit session. + return null; + } + + var infoReader = EditAndContinueMethodDebugInfoReader.Create(moduleInfo.SymReader, version: 1); + + var newBaseline = EmitBaseline.CreateInitialBaseline( + moduleInfo.Metadata, + infoReader.GetDebugInfo, + infoReader.GetLocalSignature, + infoReader.IsPortable); + + lock (_projectEmitBaselinesGuard) + { + if (_projectEmitBaselines.TryGetValue(projectId, out baseline)) + { + return baseline; + } + + return _projectEmitBaselines[projectId] = newBaseline; + } + } + + private static ImmutableDictionary> GroupToImmutableDictionary(IEnumerable> items) + { + var builder = ImmutableDictionary.CreateBuilder>(); + + foreach (var item in items) + { + builder.Add(item.Key, item.ToImmutableArray()); + } + + return builder.ToImmutable(); } } } diff --git a/src/Features/Core/Portable/EditAndContinue/DebuggingSessionTelemetry.cs b/src/Features/Core/Portable/EditAndContinue/DebuggingSessionTelemetry.cs new file mode 100644 index 0000000000000..961f793c1ab0e --- /dev/null +++ b/src/Features/Core/Portable/EditAndContinue/DebuggingSessionTelemetry.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.EditAndContinue +{ + internal sealed class DebuggingSessionTelemetry + { + internal readonly struct Data + { + public readonly ImmutableArray EditSessionData; + public readonly int EmptyEditSessionCount; + + public Data(DebuggingSessionTelemetry telemetry) + { + EditSessionData = telemetry._editSessionData.ToImmutableArray(); + EmptyEditSessionCount = telemetry._emptyEditSessionCount; + } + } + + private readonly object _guard = new object(); + + private readonly List _editSessionData; + private int _emptyEditSessionCount; + + public DebuggingSessionTelemetry() + { + _editSessionData = new List(); + } + + public Data GetDataAndClear() + { + lock (_guard) + { + var data = new Data(this); + _editSessionData.Clear(); + _emptyEditSessionCount = 0; + return data; + } + } + + public void LogEditSession(EditSessionTelemetry.Data editSessionTelemetryData) + { + lock (_guard) + { + if (editSessionTelemetryData.IsEmpty) + { + _emptyEditSessionCount++; + } + else + { + _editSessionData.Add(editSessionTelemetryData); + } + } + } + } +} diff --git a/src/Features/Core/Portable/EditAndContinue/Deltas.cs b/src/Features/Core/Portable/EditAndContinue/Deltas.cs index 31b322155865e..67cdb07d735c0 100644 --- a/src/Features/Core/Portable/EditAndContinue/Deltas.cs +++ b/src/Features/Core/Portable/EditAndContinue/Deltas.cs @@ -10,31 +10,31 @@ namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class Deltas { + public readonly Guid Mvid; public readonly ILDelta IL; public readonly MetadataDelta Metadata; - public readonly ImmutableArray<(DocumentId, ImmutableArray)> LineEdits; + public readonly ImmutableArray<(string SourceFilePath, ImmutableArray Deltas)> LineEdits; public readonly PdbDelta Pdb; - public readonly EmitDifferenceResult EmitResult; public readonly ImmutableArray<(ActiveMethodId Method, NonRemappableRegion Region)> NonRemappableRegions; public readonly ImmutableArray<(Guid ThreadId, ActiveInstructionId OldInstructionId, LinePositionSpan NewSpan)> ActiveStatementsInUpdatedMethods; public Deltas( - byte[] il, - byte[] metadata, - MemoryStream pdb, - int[] updatedMethods, - ImmutableArray<(DocumentId, ImmutableArray)> lineEdits, + Guid mvid, + ImmutableArray il, + ImmutableArray metadata, + ImmutableArray pdb, + ImmutableArray updatedMethods, + ImmutableArray<(string, ImmutableArray)> lineEdits, ImmutableArray<(ActiveMethodId, NonRemappableRegion)> nonRemappableRegions, - ImmutableArray<(Guid ThreadId, ActiveInstructionId OldInstructionId, LinePositionSpan NewSpan)> activeStatementsInUpdatedMethods, - EmitDifferenceResult emitResult) + ImmutableArray<(Guid ThreadId, ActiveInstructionId OldInstructionId, LinePositionSpan NewSpan)> activeStatementsInUpdatedMethods) { + Mvid = mvid; IL = new ILDelta(il); Metadata = new MetadataDelta(metadata); Pdb = new PdbDelta(pdb, updatedMethods); NonRemappableRegions = nonRemappableRegions; ActiveStatementsInUpdatedMethods = activeStatementsInUpdatedMethods; - EmitResult = emitResult; LineEdits = lineEdits; } } diff --git a/src/Features/Core/Portable/EditAndContinue/DocumentAnalysisResults.cs b/src/Features/Core/Portable/EditAndContinue/DocumentAnalysisResults.cs index 8489c5533a0b3..439efbba7dbfb 100644 --- a/src/Features/Core/Portable/EditAndContinue/DocumentAnalysisResults.cs +++ b/src/Features/Core/Portable/EditAndContinue/DocumentAnalysisResults.cs @@ -16,7 +16,7 @@ internal sealed class DocumentAnalysisResults public ImmutableArray ActiveStatements { get; } /// - /// Diagnostics for rude edits in the document, or null if the document is unchanged or has syntax errors. + /// Diagnostics for rude edits in the document, or empty if the document is unchanged or has syntax errors. /// If the compilation has semantic errors only syntactic rude edits are calculated. /// public ImmutableArray RudeEditErrors { get; } @@ -68,6 +68,7 @@ internal sealed class DocumentAnalysisResults private DocumentAnalysisResults(ImmutableArray rudeEdits) { + Debug.Assert(!rudeEdits.IsDefault); _hasCompilationErrors = rudeEdits.Length == 0; RudeEditErrors = rudeEdits; } @@ -80,12 +81,12 @@ public DocumentAnalysisResults( ImmutableArray lineEditsOpt, bool? hasSemanticErrors) { + Debug.Assert(!rudeEdits.IsDefault); Debug.Assert(!activeStatements.IsDefault); Debug.Assert(activeStatements.All(a => a != null)); if (hasSemanticErrors.HasValue) { - Debug.Assert(!rudeEdits.IsDefault); if (hasSemanticErrors.Value || rudeEdits.Length > 0) { @@ -124,7 +125,7 @@ public bool HasChangesAndErrors { get { - return HasChanges && (_hasCompilationErrors.Value || !RudeEditErrors.IsDefaultOrEmpty); + return HasChanges && (_hasCompilationErrors.Value || !RudeEditErrors.IsEmpty); } } @@ -136,7 +137,7 @@ public bool HasChangesAndCompilationErrors } } - public bool HasSignificantChanges + public bool HasSignificantValidChanges { get { @@ -155,7 +156,7 @@ public static DocumentAnalysisResults Unchanged( { return new DocumentAnalysisResults( activeStatements, - default, + ImmutableArray.Empty, ImmutableArray.Empty, exceptionRegionsOpt, ImmutableArray.Empty, diff --git a/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticDescriptors.cs b/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticDescriptors.cs new file mode 100644 index 0000000000000..2f6aa6d6a043d --- /dev/null +++ b/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticDescriptors.cs @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Microsoft.CodeAnalysis.EditAndContinue +{ + internal static class EditAndContinueDiagnosticDescriptors + { + private const int GeneralDiagnosticBaseId = 1000; + private const int ModuleDiagnosticBaseId = 2000; + private static readonly int s_diagnosticBaseIndex; + + private static readonly LocalizableResourceString s_rudeEditLocString; + private static readonly LocalizableResourceString s_encLocString; + private static readonly LocalizableResourceString s_encDisallowedByProjectLocString; + + private static readonly ImmutableArray s_descriptors; + + // descriptors for diagnostics reported by the debugger: + private static Dictionary s_lazyModuleDiagnosticDescriptors; + private static readonly object s_moduleDiagnosticDescriptorsGuard; + + static EditAndContinueDiagnosticDescriptors() + { + s_moduleDiagnosticDescriptorsGuard = new object(); + + s_rudeEditLocString = new LocalizableResourceString(nameof(FeaturesResources.RudeEdit), FeaturesResources.ResourceManager, typeof(FeaturesResources)); + s_encLocString = new LocalizableResourceString(nameof(FeaturesResources.EditAndContinue), FeaturesResources.ResourceManager, typeof(FeaturesResources)); + s_encDisallowedByProjectLocString = new LocalizableResourceString(nameof(FeaturesResources.EditAndContinueDisallowedByProject), FeaturesResources.ResourceManager, typeof(FeaturesResources)); + + var builder = ImmutableArray.CreateBuilder(); + + void add(int index, int id, string resourceName, LocalizableResourceString title, DiagnosticSeverity severity) + { + if (index >= builder.Count) + { + builder.Count = index + 1; + } + + builder[index] = new DiagnosticDescriptor( + $"ENC{id:D4}", + title, + messageFormat: new LocalizableResourceString(resourceName, FeaturesResources.ResourceManager, typeof(FeaturesResources)), + DiagnosticCategory.EditAndContinue, + severity, + isEnabledByDefault: true, + customTags: DiagnosticCustomTags.EditAndContinue); + } + + void AddRudeEdit(RudeEditKind kind, string resourceName) + => add(GetDescriptorIndex(kind), (int)kind, resourceName, s_rudeEditLocString, DiagnosticSeverity.Error); + + void AddGeneralDiagnostic(EditAndContinueErrorCode code, string resourceName, DiagnosticSeverity severity = DiagnosticSeverity.Error) + => add(GetDescriptorIndex(code), GeneralDiagnosticBaseId + (int)code, resourceName, s_encLocString, severity); + + // + // rude edits + // + + AddRudeEdit(RudeEditKind.InsertAroundActiveStatement, nameof(FeaturesResources.Adding_0_around_an_active_statement_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.DeleteAroundActiveStatement, nameof(FeaturesResources.Deleting_0_around_an_active_statement_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.DeleteActiveStatement, nameof(FeaturesResources.An_active_statement_has_been_removed_from_its_original_method_You_must_revert_your_changes_to_continue_or_restart_the_debugging_session)); + AddRudeEdit(RudeEditKind.UpdateAroundActiveStatement, nameof(FeaturesResources.Updating_a_0_around_an_active_statement_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.UpdateExceptionHandlerOfActiveTry, nameof(FeaturesResources.Modifying_a_catch_finally_handler_with_an_active_statement_in_the_try_block_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.UpdateTryOrCatchWithActiveFinally, nameof(FeaturesResources.Modifying_a_try_catch_finally_statement_when_the_finally_block_is_active_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.UpdateCatchHandlerAroundActiveStatement, nameof(FeaturesResources.Modifying_a_catch_handler_around_an_active_statement_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.Update, nameof(FeaturesResources.Updating_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ModifiersUpdate, nameof(FeaturesResources.Updating_the_modifiers_of_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.VarianceUpdate, nameof(FeaturesResources.Updating_the_variance_of_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.TypeUpdate, nameof(FeaturesResources.Updating_the_type_of_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InitializerUpdate, nameof(FeaturesResources.Updating_the_initializer_of_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.FixedSizeFieldUpdate, nameof(FeaturesResources.Updating_the_size_of_a_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.EnumUnderlyingTypeUpdate, nameof(FeaturesResources.Updating_the_underlying_type_of_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.BaseTypeOrInterfaceUpdate, nameof(FeaturesResources.Updating_the_base_class_and_or_base_interface_s_of_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.TypeKindUpdate, nameof(FeaturesResources.Updating_the_kind_of_a_type_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.AccessorKindUpdate, nameof(FeaturesResources.Updating_the_kind_of_an_property_event_accessor_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.MethodKindUpdate, nameof(FeaturesResources.Updating_the_kind_of_a_method_Sub_Function_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.DeclareAliasUpdate, nameof(FeaturesResources.Updating_the_alias_of_Declare_Statement_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.DeclareLibraryUpdate, nameof(FeaturesResources.Updating_the_library_name_of_Declare_Statement_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.FieldKindUpdate, nameof(FeaturesResources.Updating_a_field_to_an_event_or_vice_versa_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.Renamed, nameof(FeaturesResources.Renaming_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.Insert, nameof(FeaturesResources.Adding_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertVirtual, nameof(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertOverridable, nameof(FeaturesResources.Adding_a_MustOverride_0_or_overriding_an_inherited_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertExtern, nameof(FeaturesResources.Adding_an_extern_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertDllImport, nameof(FeaturesResources.Adding_an_imported_method_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertOperator, nameof(FeaturesResources.Adding_a_user_defined_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertIntoStruct, nameof(FeaturesResources.Adding_0_into_a_1_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertIntoClassWithLayout, nameof(FeaturesResources.Adding_0_into_a_class_with_explicit_or_sequential_layout_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertGenericMethod, nameof(FeaturesResources.Adding_a_generic_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.Move, nameof(FeaturesResources.Moving_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.Delete, nameof(FeaturesResources.Deleting_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.MethodBodyAdd, nameof(FeaturesResources.Adding_a_method_body_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.MethodBodyDelete, nameof(FeaturesResources.Deleting_a_method_body_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.GenericMethodUpdate, nameof(FeaturesResources.Modifying_a_generic_method_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.GenericMethodTriviaUpdate, nameof(FeaturesResources.Modifying_whitespace_or_comments_in_a_generic_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.GenericTypeUpdate, nameof(FeaturesResources.Modifying_a_method_inside_the_context_of_a_generic_type_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.GenericTypeTriviaUpdate, nameof(FeaturesResources.Modifying_whitespace_or_comments_in_0_inside_the_context_of_a_generic_type_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.GenericTypeInitializerUpdate, nameof(FeaturesResources.Modifying_the_initializer_of_0_in_a_generic_type_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.PartialTypeInitializerUpdate, nameof(FeaturesResources.Modifying_the_initializer_of_0_in_a_partial_type_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, nameof(FeaturesResources.Adding_a_constructor_to_a_type_with_a_field_or_property_initializer_that_contains_an_anonymous_function_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.RenamingCapturedVariable, nameof(FeaturesResources.Renaming_a_captured_variable_from_0_to_1_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.StackAllocUpdate, nameof(FeaturesResources.Modifying_0_which_contains_the_stackalloc_operator_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ExperimentalFeaturesEnabled, nameof(FeaturesResources.Modifying_source_with_experimental_language_features_enabled_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.AwaitStatementUpdate, nameof(FeaturesResources.Updating_a_complex_statement_containing_an_await_expression_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ChangingConstructorVisibility, nameof(FeaturesResources.Changing_visibility_of_a_constructor_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.CapturingVariable, nameof(FeaturesResources.Capturing_variable_0_that_hasn_t_been_captured_before_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.NotCapturingVariable, nameof(FeaturesResources.Ceasing_to_capture_variable_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.DeletingCapturedVariable, nameof(FeaturesResources.Deleting_captured_variable_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ChangingCapturedVariableType, nameof(FeaturesResources.Changing_the_type_of_a_captured_variable_0_previously_of_type_1_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ChangingCapturedVariableScope, nameof(FeaturesResources.Changing_the_declaration_scope_of_a_captured_variable_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ChangingLambdaParameters, nameof(FeaturesResources.Changing_the_parameters_of_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ChangingLambdaReturnType, nameof(FeaturesResources.Changing_the_return_type_of_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ChangingQueryLambdaType, nameof(FeaturesResources.Changing_the_type_of_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.AccessingCapturedVariableInLambda, nameof(FeaturesResources.Accessing_captured_variable_0_that_hasn_t_been_accessed_before_in_1_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.NotAccessingCapturedVariableInLambda, nameof(FeaturesResources.Ceasing_to_access_captured_variable_0_in_1_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertLambdaWithMultiScopeCapture, nameof(FeaturesResources.Adding_0_that_accesses_captured_variables_1_and_2_declared_in_different_scopes_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.DeleteLambdaWithMultiScopeCapture, nameof(FeaturesResources.Removing_0_that_accessed_captured_variables_1_and_2_declared_in_different_scopes_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ActiveStatementUpdate, nameof(FeaturesResources.Updating_an_active_statement_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ActiveStatementLambdaRemoved, nameof(FeaturesResources.Removing_0_that_contains_an_active_statement_will_prevent_the_debug_session_from_continuing)); + // TODO: change the error message to better explain what's going on + AddRudeEdit(RudeEditKind.PartiallyExecutedActiveStatementUpdate, nameof(FeaturesResources.Updating_an_active_statement_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.PartiallyExecutedActiveStatementDelete, nameof(FeaturesResources.An_active_statement_has_been_removed_from_its_original_method_You_must_revert_your_changes_to_continue_or_restart_the_debugging_session)); + AddRudeEdit(RudeEditKind.InsertFile, nameof(FeaturesResources.Adding_a_new_file_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, nameof(FeaturesResources.Updating_async_or_iterator_modifier_around_an_active_statement_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, nameof(FeaturesResources.Attribute_0_is_missing_Updating_an_async_method_or_an_iterator_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, nameof(FeaturesResources.Switching_between_lambda_and_local_function_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, nameof(FeaturesResources.Adding_method_with_explicit_interface_specifier_will_prevernt_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertIntoInterface, nameof(FeaturesResources.Adding_0_into_an_interface_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, nameof(FeaturesResources.Adding_0_into_an_interface_method_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InternalError, nameof(FeaturesResources.Modifying_source_file_will_prevent_the_debug_session_from_continuing_due_to_internal_error)); + AddRudeEdit(RudeEditKind.SwitchExpressionUpdate,nameof(FeaturesResources.Modifying_0_which_contains_a_switch_expression_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ChangingFromAsynchronousToSynchronous, nameof(FeaturesResources.Changing_0_from_asynchronous_to_synchronous_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ChangingStateMachineShape, nameof(FeaturesResources.Changing_0_to_1_will_prevent_the_debug_session_from_continuing_because_it_changes_the_shape_of_the_state_machine)); + AddRudeEdit(RudeEditKind.ComplexQueryExpression, nameof(FeaturesResources.Modifying_0_which_contains_an_Aggregate_Group_By_or_Join_query_clauses_will_prevent_the_debug_session_from_continuing)); + + // VB specific + AddRudeEdit(RudeEditKind.HandlesClauseUpdate, nameof(FeaturesResources.Updating_the_Handles_clause_of_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ImplementsClauseUpdate, nameof(FeaturesResources.Updating_the_Implements_clause_of_a_0_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.ConstraintKindUpdate, nameof(FeaturesResources.Changing_the_constraint_from_0_to_1_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.InsertHandlesClause, nameof(FeaturesResources.Adding_0_with_the_Handles_clause_will_prevent_the_debug_session_from_continuing)); + AddRudeEdit(RudeEditKind.UpdateStaticLocal, nameof(FeaturesResources.Modifying_0_which_contains_a_static_variable_will_prevent_the_debug_session_from_continuing)); + + // + // other Roslyn reported diagnostics: + // + + s_diagnosticBaseIndex = builder.Count; + + AddGeneralDiagnostic(EditAndContinueErrorCode.ErrorReadingFile, nameof(FeaturesResources.ErrorReadingFile)); + AddGeneralDiagnostic(EditAndContinueErrorCode.CannotApplyChangesUnexpectedError, nameof(FeaturesResources.CannotApplyChangesUnexpectedError)); + AddGeneralDiagnostic(EditAndContinueErrorCode.ChangesDisallowedWhileStoppedAtException, nameof(FeaturesResources.ChangesDisallowedWhileStoppedAtException)); + AddGeneralDiagnostic(EditAndContinueErrorCode.ChangesNotAppliedWhileRunning, nameof(FeaturesResources.ChangesNotAppliedWhileRunning), DiagnosticSeverity.Warning); + + s_descriptors = builder.ToImmutable(); + } + + internal static ImmutableArray GetDescriptors() + => s_descriptors.WhereAsArray(d => d != null); + + internal static DiagnosticDescriptor GetDescriptor(RudeEditKind kind) + => s_descriptors[GetDescriptorIndex(kind)]; + + internal static DiagnosticDescriptor GetDescriptor(EditAndContinueErrorCode errorCode) + => s_descriptors[GetDescriptorIndex(errorCode)]; + + internal static DiagnosticDescriptor GetModuleDiagnosticDescriptor(int errorCode) + { + lock (s_moduleDiagnosticDescriptorsGuard) + { + if (s_lazyModuleDiagnosticDescriptors == null) + { + s_lazyModuleDiagnosticDescriptors = new Dictionary(); + } + + if (!s_lazyModuleDiagnosticDescriptors.TryGetValue(errorCode, out var descriptor)) + { + s_lazyModuleDiagnosticDescriptors.Add(errorCode, descriptor = new DiagnosticDescriptor( + $"ENC{ModuleDiagnosticBaseId + errorCode:D4}", + s_encLocString, + s_encDisallowedByProjectLocString, + DiagnosticCategory.EditAndContinue, + DiagnosticSeverity.Error, + isEnabledByDefault: true, + customTags: DiagnosticCustomTags.EditAndContinue)); + } + + return descriptor; + } + } + + private static int GetDescriptorIndex(RudeEditKind kind) + => (int)kind; + + private static int GetDescriptorIndex(EditAndContinueErrorCode errorCode) + => s_diagnosticBaseIndex + (int)errorCode; + } +} diff --git a/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticUpdateSource.cs b/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticUpdateSource.cs new file mode 100644 index 0000000000000..caf3a778ccdb2 --- /dev/null +++ b/src/Features/Core/Portable/EditAndContinue/EditAndContinueDiagnosticUpdateSource.cs @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Composition; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.PooledObjects; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.EditAndContinue +{ + [Export(typeof(EditAndContinueDiagnosticUpdateSource))] + [Shared] + internal sealed class EditAndContinueDiagnosticUpdateSource : IDiagnosticUpdateSource + { + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public EditAndContinueDiagnosticUpdateSource(IDiagnosticUpdateSourceRegistrationService registrationService) + { + registrationService.Register(this); + } + + // for testing + internal EditAndContinueDiagnosticUpdateSource() + { + } + + public event EventHandler DiagnosticsUpdated; + public event EventHandler DiagnosticsCleared; + + /// + /// This implementation reports diagnostics via event. + /// + public bool SupportGetDiagnostics => false; + + public ImmutableArray GetDiagnostics(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default) + => ImmutableArray.Empty; + + /// + /// Clears all diagnostics reported thru this source. + /// We do not track the particular reported diagnostics here since we can just clear all of them at once. + /// + public void ClearDiagnostics() + => DiagnosticsCleared?.Invoke(this, EventArgs.Empty); + + /// + /// Reports given set of diagnostics. + /// Categorizes diagnostic into two groups - diagnostics associated with a document and diagnostics associated with a project or solution. + /// + public void ReportDiagnostics(Solution solution, ProjectId projectIdOpt, IEnumerable diagnostics) + { + Debug.Assert(solution != null); + + var updateEvent = DiagnosticsUpdated; + if (updateEvent == null) + { + return; + } + + var documentDiagnosticData = ArrayBuilder.GetInstance(); + var nonDocumentDiagnosticData = ArrayBuilder.GetInstance(); + var workspace = solution.Workspace; + var project = (projectIdOpt != null) ? solution.GetProject(projectIdOpt) : null; + + foreach (var diagnostic in diagnostics) + { + var documentOpt = solution.GetDocument(diagnostic.Location.SourceTree); + + if (documentOpt != null) + { + documentDiagnosticData.Add(DiagnosticData.Create(documentOpt, diagnostic)); + } + else + { + nonDocumentDiagnosticData.Add(DiagnosticData.Create(solution.Workspace, diagnostic, projectIdOpt)); + } + } + + if (documentDiagnosticData.Count > 0) + { + foreach (var (documentId, diagnosticData) in documentDiagnosticData.ToDictionary(data => data.DocumentId)) + { + var diagnosticGroupId = (this, documentId, projectIdOpt); + + updateEvent(this, DiagnosticsUpdatedArgs.DiagnosticsCreated( + diagnosticGroupId, + workspace, + solution, + projectIdOpt, + documentId: documentId, + diagnostics: diagnosticData)); + } + } + + if (nonDocumentDiagnosticData.Count > 0) + { + var diagnosticGroupId = (this, projectIdOpt); + + updateEvent(this, DiagnosticsUpdatedArgs.DiagnosticsCreated( + diagnosticGroupId, + workspace, + solution, + projectIdOpt, + documentId: null, + diagnostics: nonDocumentDiagnosticData.ToImmutable())); + } + + documentDiagnosticData.Free(); + nonDocumentDiagnosticData.Free(); + } + } +} diff --git a/src/Features/Core/Portable/EditAndContinue/EditAndContinueErrorCode.cs b/src/Features/Core/Portable/EditAndContinue/EditAndContinueErrorCode.cs new file mode 100644 index 0000000000000..6379531e67d42 --- /dev/null +++ b/src/Features/Core/Portable/EditAndContinue/EditAndContinueErrorCode.cs @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.CodeAnalysis.EditAndContinue +{ + internal enum EditAndContinueErrorCode + { + ErrorReadingFile = 1, + CannotApplyChangesUnexpectedError = 2, + ChangesNotAppliedWhileRunning = 3, + ChangesDisallowedWhileStoppedAtException = 4, + } +} diff --git a/src/Features/Core/Portable/EditAndContinue/EditAndContinueService.cs b/src/Features/Core/Portable/EditAndContinue/EditAndContinueService.cs deleted file mode 100644 index 400c1edd50d49..0000000000000 --- a/src/Features/Core/Portable/EditAndContinue/EditAndContinueService.cs +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Immutable; -using System.Diagnostics; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.ErrorReporting; -using Microsoft.CodeAnalysis.Text; -using Roslyn.Utilities; - -namespace Microsoft.CodeAnalysis.EditAndContinue -{ - /// - /// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services. - /// - /// - /// Although the service itself is host agnostic, some of the services it consumes are only available in particular hosts (like Visual Studio). - /// Therefore this service doesn't export on its own. Each host that supports EnC shall implement - /// a subclass that exports . - /// - internal class EditAndContinueService : IEditAndContinueService - { - private readonly IActiveStatementProvider _activeStatementProvider; - private readonly IDiagnosticAnalyzerService _diagnosticService; - private DebuggingSession _debuggingSession; - private EditSession _editSession; - - // TODO: - // Maps active statement instructions to their latest spans. - // - // Consider a function F containing a call to function G that is updated a couple of times - // before the thread returns from G and is remapped to the latest version of F. - // '>' indicates an active statement instruction. - // - // F v1: F v2: F v3: - // 0: nop 0: nop 0: nop - // 1> G() 1: nop 1: nop - // 2: nop 2: G() 2: nop - // 3: nop 3: nop 3> G() - // - // When entering a break state we query the debugger for current active statements. - // The returned statements reflect the current state of the threads in the runtime. - // When a change is successfully applied we remember changes in active statement spans. - // These changes are passed to the next edit session. - // We use them to map the spans for active statements returned by the debugger. - // - // In the above case the sequence of events is - // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date - // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 - // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 - // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements - // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 - // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 - // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date - // - private ImmutableDictionary> _nonRemappableRegions; - - internal EditAndContinueService(IDiagnosticAnalyzerService diagnosticService, IActiveStatementProvider activeStatementProvider) - { - Debug.Assert(diagnosticService != null); - Debug.Assert(activeStatementProvider != null); - - _diagnosticService = diagnosticService; - _activeStatementProvider = activeStatementProvider; - _nonRemappableRegions = ImmutableDictionary>.Empty; - } - - public DebuggingSession DebuggingSession => _debuggingSession; - - public EditSession EditSession => _editSession; - - public void StartDebuggingSession(Solution currentSolution) - { - Contract.ThrowIfNull(currentSolution); - - var previousSession = Interlocked.CompareExchange(ref _debuggingSession, new DebuggingSession(currentSolution), null); - Contract.ThrowIfFalse(previousSession == null, "New debugging session can't be started until the existing one has ended."); - - // TODO(tomat): allow changing documents - } - - public void StartEditSession( - Solution currentSolution, - ImmutableDictionary projects, - bool stoppedAtException) - { - Contract.ThrowIfNull(currentSolution); - - var newSession = new EditSession( - currentSolution, - _debuggingSession, - _activeStatementProvider, - projects, - _nonRemappableRegions, - stoppedAtException); - - var previousSession = Interlocked.CompareExchange(ref _editSession, newSession, null); - Contract.ThrowIfFalse(previousSession == null, "New edit session can't be started until the existing one has ended."); - - // TODO(tomat): allow changing documents - // TODO(tomat): document added - } - - public void EndEditSession(ImmutableDictionary> newRemappableRegionsOpt) - { - // first, publish null session: - var session = Interlocked.Exchange(ref _editSession, null); - Contract.ThrowIfNull(session, "Edit session has not started."); - - // then cancel all ongoing work bound to the session: - session.Cancellation.Cancel(); - - // then clear all reported rude edits: - _diagnosticService.Reanalyze(_debuggingSession.InitialSolution.Workspace, documentIds: session.GetDocumentsWithReportedRudeEdits()); - - // Save new non-remappable regions for the next edit session. - // If no edits were made keep the previous regions. - if (newRemappableRegionsOpt != null) - { - _nonRemappableRegions = newRemappableRegionsOpt; - } - - // TODO(tomat): allow changing documents - } - - public void EndDebuggingSession() - { - var session = Interlocked.Exchange(ref _debuggingSession, null); - Contract.ThrowIfNull(session, "Debugging session has not started."); - } - - public bool IsProjectReadOnly(ProjectId id, out SessionReadOnlyReason sessionReason, out ProjectReadOnlyReason projectReason) - { - if (_debuggingSession == null) - { - projectReason = ProjectReadOnlyReason.None; - sessionReason = SessionReadOnlyReason.None; - return false; - } - - // run mode - all documents that belong to the workspace shall be read-only: - var editSession = _editSession; - if (editSession == null) - { - projectReason = ProjectReadOnlyReason.None; - sessionReason = SessionReadOnlyReason.Running; - return true; - } - - // break mode and stopped at exception - all documents shall be read-only: - if (editSession.StoppedAtException) - { - projectReason = ProjectReadOnlyReason.None; - sessionReason = SessionReadOnlyReason.StoppedAtException; - return true; - } - - // normal break mode - if the document belongs to a project that hasn't entered the edit session it shall be read-only: - if (editSession.Projects.TryGetValue(id, out projectReason)) - { - sessionReason = SessionReadOnlyReason.None; - return projectReason != ProjectReadOnlyReason.None; - } - - sessionReason = SessionReadOnlyReason.None; - projectReason = ProjectReadOnlyReason.MetadataNotAvailable; - return true; - } - - public async Task GetCurrentActiveStatementPositionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken) - { - try - { - // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. - // We return null since there the concept of active statement only makes sense during break mode. - if (_editSession == null) - { - return null; - } - - Debug.Assert(_debuggingSession != null); - - // TODO: Avoid enumerating active statements for unchanged documents. - // We would need to add a document path parameter to be able to find the document we need to check for changes. - // https://github.com/dotnet/roslyn/issues/24324 - var baseActiveStatements = await _editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); - if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) - { - return null; - } - - var primaryDocument = _debuggingSession.InitialSolution.Workspace.CurrentSolution.GetDocument(baseActiveStatement.PrimaryDocumentId); - var documentAnalysis = await _editSession.GetDocumentAnalysis(primaryDocument).GetValueAsync(cancellationToken).ConfigureAwait(false); - var currentActiveStatements = documentAnalysis.ActiveStatements; - if (currentActiveStatements.IsDefault) - { - // The document has syntax errors. - return null; - } - - return currentActiveStatements[baseActiveStatement.PrimaryDocumentOrdinal].Span; - } - catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) - { - return null; - } - } - - public async Task IsActiveStatementInExceptionRegionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken) - { - try - { - if (_editSession == null) - { - return null; - } - - Debug.Assert(_debuggingSession != null); - - // TODO: Avoid enumerating active statements for unchanged documents. - // We would need to add a document path parameter to be able to find the document we need to check for changes. - // https://github.com/dotnet/roslyn/issues/24324 - var baseActiveStatements = await _editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); - if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) - { - return null; - } - - // TODO: avoid waiting for ERs of all active statements to be calculated and just calculate the one we are interested in at this moment: - // https://github.com/dotnet/roslyn/issues/24324 - var baseExceptionRegions = await _editSession.BaseActiveExceptionRegions.GetValueAsync(cancellationToken).ConfigureAwait(false); - return baseExceptionRegions[baseActiveStatement.Ordinal].IsActiveStatementCovered; - } - catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) - { - return null; - } - } - } -} diff --git a/src/Features/Core/Portable/EditAndContinue/EditAndContinueWorkspaceService.cs b/src/Features/Core/Portable/EditAndContinue/EditAndContinueWorkspaceService.cs new file mode 100644 index 0000000000000..76de6b9c4eca2 --- /dev/null +++ b/src/Features/Core/Portable/EditAndContinue/EditAndContinueWorkspaceService.cs @@ -0,0 +1,575 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.ErrorReporting; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Internal.Log; +using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.EditAndContinue +{ + /// + /// Implements core of Edit and Continue orchestration: management of edit sessions and connecting EnC related services. + /// + internal sealed class EditAndContinueWorkspaceService : IEditAndContinueWorkspaceService + { + internal static readonly TraceLog Log = new TraceLog(2048, "EnC"); + + private readonly Workspace _workspace; + private readonly IActiveStatementTrackingService _trackingService; + private readonly IActiveStatementProvider _activeStatementProvider; + private readonly IDiagnosticAnalyzerService _diagnosticService; + private readonly IDebuggeeModuleMetadataProvider _debugeeModuleMetadataProvider; + private readonly EditAndContinueDiagnosticUpdateSource _emitDiagnosticsUpdateSource; + private readonly EditSessionTelemetry _editSessionTelemetry; + private readonly DebuggingSessionTelemetry _debuggingSessionTelemetry; + private readonly ICompilationOutputsProviderService _compilationOutputsProvider; + private readonly Action _reportTelemetry; + + /// + /// A document id is added whenever a diagnostic is reported while in run mode. + /// These diagnostics are cleared as soon as we enter break mode or the debugging session terminates. + /// + private readonly HashSet _documentsWithReportedDiagnosticsDuringRunMode; + private readonly object _documentsWithReportedDiagnosticsDuringRunModeGuard = new object(); + + private DebuggingSession _debuggingSession; + private EditSession _editSession; + private PendingSolutionUpdate _pendingUpdate; + + internal EditAndContinueWorkspaceService( + Workspace workspace, + IActiveStatementTrackingService activeStatementTrackingService, + ICompilationOutputsProviderService compilationOutputsProvider, + IDiagnosticAnalyzerService diagnosticService, + EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, + IActiveStatementProvider activeStatementProvider, + IDebuggeeModuleMetadataProvider debugeeModuleMetadataProvider, + Action reportTelemetry = null) + { + Debug.Assert(workspace != null); + Debug.Assert(activeStatementTrackingService != null); + Debug.Assert(diagnosticService != null); + Debug.Assert(diagnosticUpdateSource != null); + Debug.Assert(activeStatementProvider != null); + Debug.Assert(debugeeModuleMetadataProvider != null); + Debug.Assert(compilationOutputsProvider != null); + + _workspace = workspace; + _diagnosticService = diagnosticService; + _emitDiagnosticsUpdateSource = diagnosticUpdateSource; + _activeStatementProvider = activeStatementProvider; + _debugeeModuleMetadataProvider = debugeeModuleMetadataProvider; + _trackingService = activeStatementTrackingService; + _debuggingSessionTelemetry = new DebuggingSessionTelemetry(); + _editSessionTelemetry = new EditSessionTelemetry(); + _documentsWithReportedDiagnosticsDuringRunMode = new HashSet(); + _compilationOutputsProvider = compilationOutputsProvider; + _reportTelemetry = reportTelemetry ?? ReportTelemetry; + } + + // test only: + internal EditSession Test_GetEditSession() => _editSession; + internal PendingSolutionUpdate Test_GetPendingSolutionUpdate() => _pendingUpdate; + + public bool IsDebuggingSessionInProgress + => _debuggingSession != null; + + /// + /// Invoked whenever a module instance is loaded to a process being debugged. + /// + public void OnManagedModuleInstanceLoaded(Guid mvid) + => _editSession?.ModuleInstanceLoadedOrUnloaded(mvid); + + /// + /// Invoked whenever a module instance is unloaded from a process being debugged. + /// + public void OnManagedModuleInstanceUnloaded(Guid mvid) + => _editSession?.ModuleInstanceLoadedOrUnloaded(mvid); + + public void StartDebuggingSession() + { + var previousSession = Interlocked.CompareExchange(ref _debuggingSession, new DebuggingSession(_workspace, _debugeeModuleMetadataProvider, _activeStatementProvider, _compilationOutputsProvider), null); + Contract.ThrowIfFalse(previousSession == null, "New debugging session can't be started until the existing one has ended."); + } + + public void StartEditSession() + { + var debuggingSession = _debuggingSession; + Contract.ThrowIfNull(debuggingSession, "Edit session can only be started during debugging session"); + + var newSession = new EditSession(debuggingSession, _editSessionTelemetry); + + var previousSession = Interlocked.CompareExchange(ref _editSession, newSession, null); + Contract.ThrowIfFalse(previousSession == null, "New edit session can't be started until the existing one has ended."); + + _trackingService.StartTracking(newSession); + + // clear diagnostics reported during run mode: + ClearReportedRunModeDiagnostics(); + } + + public void EndEditSession() + { + // first, publish null session: + var session = Interlocked.Exchange(ref _editSession, null); + Contract.ThrowIfNull(session, "Edit session has not started."); + + // then cancel all ongoing work bound to the session: + session.Cancel(); + + // then clear all reported rude edits: + _diagnosticService.Reanalyze(_workspace, documentIds: session.GetDocumentsWithReportedDiagnostics()); + + _trackingService.EndTracking(); + + _debuggingSessionTelemetry.LogEditSession(_editSessionTelemetry.GetDataAndClear()); + + session.Dispose(); + } + + public void EndDebuggingSession() + { + var debuggingSession = Interlocked.Exchange(ref _debuggingSession, null); + Contract.ThrowIfNull(debuggingSession, "Debugging session has not started."); + + _reportTelemetry(_debuggingSessionTelemetry.GetDataAndClear()); + + // clear emit/apply diagnostics reported previously: + _emitDiagnosticsUpdateSource.ClearDiagnostics(); + + // clear diagnostics reported during run mode: + ClearReportedRunModeDiagnostics(); + + debuggingSession.Dispose(); + } + + public async Task> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) + { + try + { + var debuggingSession = _debuggingSession; + if (debuggingSession == null) + { + return ImmutableArray.Empty; + } + + // The document has not changed while the application is running since the last changes were committed: + var oldDocument = debuggingSession.LastCommittedSolution.GetDocument(document.Id); + var editSession = _editSession; + if (editSession == null && document == oldDocument) + { + return ImmutableArray.Empty; + } + + // Not a C# or VB project: + var project = document.Project; + if (!EditSession.SupportsEditAndContinue(project)) + { + return ImmutableArray.Empty; + } + + // Do not analyze documents (and report diagnostics) of projects that have not been built. + // Allow user to make any changes in these documents, they won't be applied within the current debugging session. + // Do not report the file read error - it might be an intermittent issue. The error will be reported when the + // change is attempted to be applied. + var (mvid, _) = await debuggingSession.GetProjectModuleIdAsync(project.Id, cancellationToken).ConfigureAwait(false); + if (mvid == Guid.Empty) + { + return ImmutableArray.Empty; + } + + if (editSession == null) + { + // Any changes made in loaded, built projects outside of edit session are rude edits (the application is running): + var oldSyntaxTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); + var newSyntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); + var textChanges = await GetDocumentTextChangesAsync(oldSyntaxTree, newSyntaxTree, cancellationToken).ConfigureAwait(false); + return GetRunModeDocumentDiagnostics(document, newSyntaxTree, textChanges); + } + + // No changes made in the entire workspace since the edit session started: + if (editSession.BaseSolution.WorkspaceVersion == project.Solution.WorkspaceVersion) + { + return ImmutableArray.Empty; + } + + var analysis = await editSession.GetDocumentAnalysis(document).GetValueAsync(cancellationToken).ConfigureAwait(false); + if (analysis.HasChanges) + { + // Once we detected a change in a document let the debugger know that the corresponding loaded module + // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying + // the change blocks the UI when the user "continues". + debuggingSession.PrepareModuleForUpdate(mvid); + + // Check if EnC is allowed for all loaded modules corresponding to the project. + var moduleDiagnostics = editSession.GetModuleDiagnostics(mvid, project.Name); + + if (!moduleDiagnostics.IsEmpty) + { + // track the document, so that we can refresh or clean diagnostics at the end of edit session: + editSession.TrackDocumentWithReportedDiagnostics(document.Id); + + var oldSyntaxTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); + var newSyntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); + var textChanges = await GetDocumentTextChangesAsync(oldSyntaxTree, newSyntaxTree, cancellationToken).ConfigureAwait(false); + + var diagnosticsBuilder = ArrayBuilder.GetInstance(); + foreach (var span in GetSpansInNewDocument(textChanges)) + { + var location = Location.Create(newSyntaxTree, span); + + foreach (var diagnostic in moduleDiagnostics) + { + diagnosticsBuilder.Add(diagnostic.ToDiagnostic(location)); + } + } + + return diagnosticsBuilder.ToImmutableAndFree(); + } + } + + if (analysis.RudeEditErrors.IsEmpty) + { + return ImmutableArray.Empty; + } + + editSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); + + // track the document, so that we can refresh or clean diagnostics at the end of edit session: + editSession.TrackDocumentWithReportedDiagnostics(document.Id); + + var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); + return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); + } + catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) + { + return ImmutableArray.Empty; + } + } + + private ImmutableArray GetRunModeDocumentDiagnostics(Document newDocument, SyntaxTree newSyntaxTree, IEnumerable changes) + { + lock (_documentsWithReportedDiagnosticsDuringRunModeGuard) + { + _documentsWithReportedDiagnosticsDuringRunMode.Add(newDocument.Id); + } + + var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ChangesNotAppliedWhileRunning); + var args = new[] { newDocument.Project.Name }; + var result = GetSpansInNewDocument(changes).SelectAsArray(span => Diagnostic.Create(descriptor, Location.Create(newSyntaxTree, span), args)); + return result.IsEmpty ? ImmutableArray.Create(Diagnostic.Create(descriptor, Location.Create(newSyntaxTree, default), args)) : result; + } + + // internal for testing + internal static async Task> GetDocumentTextChangesAsync(SyntaxTree oldSyntaxTree, SyntaxTree newSyntaxTree, CancellationToken cancellationToken) + { + var list = newSyntaxTree.GetChanges(oldSyntaxTree); + if (list.Count != 0) + { + return list; + } + + var oldText = await oldSyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); + var newText = await newSyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); + if (oldText.ContentEquals(newText)) + { + return Array.Empty(); + } + + var roList = newText.GetTextChanges(oldText); + if (roList.Count != 0) + { + return roList.ToArray(); + } + + return Array.Empty(); + } + + // internal for testing + internal static IEnumerable GetSpansInNewDocument(IEnumerable changes) + { + int oldPosition = 0; + int newPosition = 0; + foreach (var change in changes) + { + if (change.Span.Start < oldPosition) + { + Debug.Fail("Text changes not ordered"); + yield break; + } + + if (change.Span.Length == 0 && change.NewText.Length == 0) + { + continue; + } + + // skip unchanged text: + newPosition += change.Span.Start - oldPosition; + + yield return new TextSpan(newPosition, change.NewText.Length); + + // apply change: + oldPosition = change.Span.End; + newPosition += change.NewText.Length; + } + } + + private void ClearReportedRunModeDiagnostics() + { + // clear diagnostics reported during run mode: + ImmutableArray documentsToReanalyze; + lock (_documentsWithReportedDiagnosticsDuringRunModeGuard) + { + documentsToReanalyze = _documentsWithReportedDiagnosticsDuringRunMode.ToImmutableArray(); + _documentsWithReportedDiagnosticsDuringRunMode.Clear(); + } + + // clear all reported run mode diagnostics: + _diagnosticService.Reanalyze(_workspace, documentIds: documentsToReanalyze); + } + + /// + /// Determine whether the updates made to projects containing the specified file (or all projects that are built, + /// if is null) are ready to be applied and the debugger should attempt to apply + /// them on "continue". + /// + /// + /// Returns if there are rude edits or other errors + /// that block the application of the updates. Might return even if there are + /// errors in the code that will block the application of the updates. E.g. emit diagnostics can't be determined until + /// emit is actually performed. Therefore, this method only serves as an optimization to avoid unnecessary emit attempts, + /// but does not provide a definitive answer. Only can definitively determine whether + /// the update is valid or not. + /// + public Task GetSolutionUpdateStatusAsync(string sourceFilePath, CancellationToken cancellationToken) + { + // GetStatusAsync is called outside of edit session when the debugger is determining + // whether a source file checksum matches the one in PDB. + // The debugger expects no changes in this case. + var editSession = _editSession; + if (editSession == null) + { + return Task.FromResult(SolutionUpdateStatus.None); + } + + return editSession.GetSolutionUpdateStatusAsync(_workspace.CurrentSolution, sourceFilePath, cancellationToken); + } + + public async Task<(SolutionUpdateStatus Summary, ImmutableArray Deltas)> EmitSolutionUpdateAsync(CancellationToken cancellationToken) + { + var editSession = _editSession; + if (editSession == null) + { + return (SolutionUpdateStatus.None, ImmutableArray.Empty); + } + + var solution = _workspace.CurrentSolution; + + var solutionUpdate = await editSession.EmitSolutionUpdateAsync(solution, cancellationToken).ConfigureAwait(false); + + if (solutionUpdate.Summary == SolutionUpdateStatus.Ready) + { + var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( + solution, + solutionUpdate.EmitBaselines, + solutionUpdate.Deltas, + solutionUpdate.ModuleReaders)); + + // commit/discard was not called: + Contract.ThrowIfFalse(previousPendingUpdate == null); + } + + // clear emit/apply diagnostics reported previously: + _emitDiagnosticsUpdateSource.ClearDiagnostics(); + + // report emit/apply diagnostics: + foreach (var (projectId, diagnostics) in solutionUpdate.Diagnostics) + { + _emitDiagnosticsUpdateSource.ReportDiagnostics(solution, projectId, diagnostics); + } + + // Note that we may return empty deltas if all updates have been deferred. + // The debugger will still call commit or discard on the update batch. + return (solutionUpdate.Summary, solutionUpdate.Deltas); + } + + public void CommitSolutionUpdate() + { + var editSession = _editSession; + + Contract.ThrowIfNull(editSession); + + var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); + Contract.ThrowIfNull(pendingUpdate); + + editSession.DebuggingSession.CommitSolutionUpdate(pendingUpdate); + editSession.ChangesApplied(); + } + + public void DiscardSolutionUpdate() + { + Contract.ThrowIfNull(_editSession); + + var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); + Contract.ThrowIfNull(pendingUpdate); + + foreach (var moduleReader in pendingUpdate.ModuleReaders) + { + moduleReader.Dispose(); + } + } + + public async Task GetCurrentActiveStatementPositionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken) + { + try + { + // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. + // We return null since there the concept of active statement only makes sense during break mode. + var editSession = _editSession; + if (editSession == null) + { + return null; + } + + // TODO: Avoid enumerating active statements for unchanged documents. + // We would need to add a document path parameter to be able to find the document we need to check for changes. + // https://github.com/dotnet/roslyn/issues/24324 + var baseActiveStatements = await editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); + if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) + { + return null; + } + + var primaryDocument = _workspace.CurrentSolution.GetDocument(baseActiveStatement.PrimaryDocumentId); + var documentAnalysis = await editSession.GetDocumentAnalysis(primaryDocument).GetValueAsync(cancellationToken).ConfigureAwait(false); + var currentActiveStatements = documentAnalysis.ActiveStatements; + if (currentActiveStatements.IsDefault) + { + // The document has syntax errors. + return null; + } + + return currentActiveStatements[baseActiveStatement.PrimaryDocumentOrdinal].Span; + } + catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) + { + return null; + } + } + + public async Task IsActiveStatementInExceptionRegionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken) + { + try + { + var editSession = _editSession; + if (editSession == null) + { + return null; + } + + // TODO: Avoid enumerating active statements for unchanged documents. + // We would need to add a document path parameter to be able to find the document we need to check for changes. + // https://github.com/dotnet/roslyn/issues/24324 + var baseActiveStatements = await editSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); + if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) + { + return null; + } + + // TODO: avoid waiting for ERs of all active statements to be calculated and just calculate the one we are interested in at this moment: + // https://github.com/dotnet/roslyn/issues/24324 + var baseExceptionRegions = await editSession.BaseActiveExceptionRegions.GetValueAsync(cancellationToken).ConfigureAwait(false); + return baseExceptionRegions[baseActiveStatement.Ordinal].IsActiveStatementCovered; + } + catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) + { + return null; + } + } + + public void ReportApplyChangesException(string message) + { + var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.CannotApplyChangesUnexpectedError); + + _emitDiagnosticsUpdateSource.ReportDiagnostics( + _workspace.CurrentSolution, + projectIdOpt: null, + new[] { Diagnostic.Create(descriptor, Location.None, new[] { message }) }); + } + + private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) + { + // report telemetry (fire and forget): + _ = Task.Run(() => LogDebuggingSessionTelemetry(data, Logger.Log, LogAggregator.GetNextId)); + } + + // internal for testing + internal static void LogDebuggingSessionTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action log, Func getNextId) + { + const string SessionId = nameof(SessionId); + const string EditSessionId = nameof(EditSessionId); + + var debugSessionId = getNextId(); + + log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => + { + map[SessionId] = debugSessionId; + map["SessionCount"] = debugSessionData.EditSessionData.Length; + map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; + })); + + foreach (var editSessionData in debugSessionData.EditSessionData) + { + var editSessionId = getNextId(); + + log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => + { + map[SessionId] = debugSessionId; + map[EditSessionId] = editSessionId; + + map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; + map["HadRudeEdits"] = editSessionData.HadRudeEdits; + map["HadValidChanges"] = editSessionData.HadValidChanges; + map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; + + map["RudeEditsCount"] = editSessionData.RudeEdits.Length; + map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; + })); + + foreach (var errorId in editSessionData.EmitErrorIds) + { + log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => + { + map[SessionId] = debugSessionId; + map[EditSessionId] = editSessionId; + map["ErrorId"] = errorId; + })); + } + + foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) + { + log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => + { + map[SessionId] = debugSessionId; + map[EditSessionId] = editSessionId; + + map["RudeEditKind"] = editKind; + map["RudeEditSyntaxKind"] = syntaxKind; + map["RudeEditBlocking"] = editSessionData.HadRudeEdits; + })); + } + } + } + } +} diff --git a/src/Features/Core/Portable/EditAndContinue/EditAndContinueWorkspaceServiceFactory.cs b/src/Features/Core/Portable/EditAndContinue/EditAndContinueWorkspaceServiceFactory.cs new file mode 100644 index 0000000000000..1c220e8b48dbb --- /dev/null +++ b/src/Features/Core/Portable/EditAndContinue/EditAndContinueWorkspaceServiceFactory.cs @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Composition; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Host.Mef; + +namespace Microsoft.CodeAnalysis.EditAndContinue +{ + [ExportWorkspaceServiceFactory(typeof(IEditAndContinueWorkspaceService), ServiceLayer.Default), Shared] + internal sealed class EditAndContinueWorkspaceServiceFactory : IWorkspaceServiceFactory + { + private readonly IDiagnosticAnalyzerService _diagnosticService; + private readonly IActiveStatementProvider _activeStatementProviderOpt; + private readonly IDebuggeeModuleMetadataProvider _debugeeModuleMetadataProviderOpt; + private readonly EditAndContinueDiagnosticUpdateSource _diagnosticUpdateSource; + + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public EditAndContinueWorkspaceServiceFactory( + IDiagnosticAnalyzerService diagnosticService, + EditAndContinueDiagnosticUpdateSource diagnosticUpdateSource, + [Import(AllowDefault = true)]IActiveStatementProvider activeStatementProvider, + [Import(AllowDefault = true)]IDebuggeeModuleMetadataProvider debugeeModuleMetadataProvider) + { + _diagnosticService = diagnosticService; + _diagnosticUpdateSource = diagnosticUpdateSource; + _activeStatementProviderOpt = activeStatementProvider; + _debugeeModuleMetadataProviderOpt = debugeeModuleMetadataProvider; + } + + [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] + public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) + { + if (_debugeeModuleMetadataProviderOpt == null || _activeStatementProviderOpt == null) + { + return null; + } + + return new EditAndContinueWorkspaceService( + workspaceServices.Workspace, + workspaceServices.Workspace.Services.GetRequiredService(), + workspaceServices.Workspace.Services.GetRequiredService(), + _diagnosticService, + _diagnosticUpdateSource, + _activeStatementProviderOpt, + _debugeeModuleMetadataProviderOpt); + } + } +} diff --git a/src/Features/Core/Portable/EditAndContinue/EditSession.cs b/src/Features/Core/Portable/EditAndContinue/EditSession.cs index 7cc7e336fb802..c29580651360f 100644 --- a/src/Features/Core/Portable/EditAndContinue/EditSession.cs +++ b/src/Features/Core/Portable/EditAndContinue/EditSession.cs @@ -10,34 +10,32 @@ using System.Reflection.Metadata.Ecma335; using System.Threading; using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; -using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { - internal sealed partial class EditSession + internal sealed class EditSession : IDisposable { - private readonly struct Analysis - { - public readonly Document Document; - public readonly AsyncLazy Results; + private readonly CancellationTokenSource _cancellationSource = new CancellationTokenSource(); - public Analysis(Document document, AsyncLazy results) - { - Document = document; - Results = results; - } - } + internal readonly DebuggingSession DebuggingSession; + internal readonly EditSessionTelemetry Telemetry; - private readonly Solution _baseSolution; + /// + /// The solution captured when entering the break state. + /// + internal readonly Solution BaseSolution; - // signaled when the session is terminated: - private readonly CancellationTokenSource _cancellation; + private readonly ImmutableDictionary> _nonRemappableRegions; + /// + /// Lazily calculated map of base active statements. + /// internal readonly AsyncLazy BaseActiveStatements; /// @@ -45,74 +43,107 @@ public Analysis(Document document, AsyncLazy results) /// internal readonly AsyncLazy> BaseActiveExceptionRegions; - private readonly DebuggingSession _debuggingSession; - private readonly IActiveStatementProvider _activeStatementProvider; - /// - /// Stopped at exception, an unwind is required before EnC is allowed. All edits are rude. + /// Results of changed documents analysis. + /// The work is triggered by an incremental analyzer on idle or explicitly when "continue" operation is executed. + /// Contains analyses of the latest observed document versions. /// - private readonly bool _stoppedAtException; - - // Results of changed documents analysis. - // The work is triggered by an incremental analyzer on idle or explicitly when "continue" operation is executed. - // Contains analyses of the latest observed document versions. + private readonly Dictionary Results)> _analyses + = new Dictionary)>(); private readonly object _analysesGuard = new object(); - private readonly Dictionary _analyses; - - // A document id is added whenever any analysis reports rude edits. - // We collect a set of document ids that contained a rude edit - // at some point in time during the lifespan of an edit session. - // At the end of the session we ask the diagnostic analyzer to reanalyze - // the documents to clean up the diagnostics. - // An id may be present in this set even if the document doesn't have a rude edit anymore. - private readonly object _documentsWithReportedRudeEditsGuard = new object(); - private readonly HashSet _documentsWithReportedRudeEdits; - private readonly ImmutableDictionary _projects; + /// + /// Errors to be reported when a project is updated but the corresponding module does not support EnC. + /// + /// The capability of a module to apply edits may change during edit session if the user attaches debugger to + /// an additional process that doesn't support EnC (or detaches from such process). The diagnostic reflects + /// the state of the module when queried for the first time. Before we actually apply an edit to the module + /// we need to query again instead of just reusing the diagnostic. + /// + private readonly Dictionary> _moduleDiagnostics + = new Dictionary>(); + private readonly object _moduleDiagnosticsGuard = new object(); - // EncEditSessionInfo is populated on a background thread and then read from the UI thread - private readonly object _encEditSessionInfoGuard = new object(); - private EncEditSessionInfo _encEditSessionInfo = new EncEditSessionInfo(); + /// + /// A is added whenever reports + /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze + /// the documents to clean up the diagnostics. + /// + private readonly HashSet _documentsWithReportedDiagnostics = new HashSet(); + private readonly object _documentsWithReportedDiagnosticsGuard = new object(); - private readonly ImmutableDictionary> _nonRemappableRegions; + private bool _changesApplied; - internal EditSession( - Solution baseSolution, - DebuggingSession debuggingSession, - IActiveStatementProvider activeStatementProvider, - ImmutableDictionary projects, - ImmutableDictionary> nonRemappableRegions, - bool stoppedAtException) + internal EditSession(DebuggingSession debuggingSession, EditSessionTelemetry telemetry) { - Debug.Assert(baseSolution != null); Debug.Assert(debuggingSession != null); - Debug.Assert(activeStatementProvider != null); - Debug.Assert(nonRemappableRegions != null); + Debug.Assert(telemetry != null); - _baseSolution = baseSolution; - _debuggingSession = debuggingSession; - _activeStatementProvider = activeStatementProvider; - _stoppedAtException = stoppedAtException; - _projects = projects; - _cancellation = new CancellationTokenSource(); + DebuggingSession = debuggingSession; - // TODO: small dict, pool? - _analyses = new Dictionary(); + _nonRemappableRegions = debuggingSession.NonRemappableRegions; - // TODO: small dict, pool? - _documentsWithReportedRudeEdits = new HashSet(); - - _nonRemappableRegions = nonRemappableRegions; + Telemetry = telemetry; + BaseSolution = debuggingSession.LastCommittedSolution; BaseActiveStatements = new AsyncLazy(GetBaseActiveStatementsAsync, cacheResult: true); BaseActiveExceptionRegions = new AsyncLazy>(GetBaseActiveExceptionRegionsAsync, cacheResult: true); } + internal CancellationToken CancellationToken => _cancellationSource.Token; + internal void Cancel() => _cancellationSource.Cancel(); + + public void Dispose() + { + _cancellationSource.Dispose(); + } + + internal void ModuleInstanceLoadedOrUnloaded(Guid mvid) + { + // invalidate diagnostic cache for the module: + lock (_moduleDiagnosticsGuard) + { + _moduleDiagnostics.Remove(mvid); + } + } + + public ImmutableArray GetModuleDiagnostics(Guid mvid, string projectDisplayName) + { + ImmutableArray result; + lock (_moduleDiagnosticsGuard) + { + if (_moduleDiagnostics.TryGetValue(mvid, out result)) + { + return result; + } + } + + var newResult = ImmutableArray.Empty; + if (!DebuggingSession.DebugeeModuleMetadataProvider.IsEditAndContinueAvailable(mvid, out var errorCode, out var localizedMessage)) + { + var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(errorCode); + newResult = ImmutableArray.Create(new LocationlessDiagnostic(descriptor, new[] { projectDisplayName, localizedMessage })); + } + + lock (_moduleDiagnosticsGuard) + { + if (!_moduleDiagnostics.TryGetValue(mvid, out result)) + { + _moduleDiagnostics.Add(mvid, result = newResult); + } + } + + return result; + } + + private Project GetBaseProject(ProjectId id) + => BaseSolution.GetProject(id); + private async Task GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { - return CreateActiveStatementsMap(_baseSolution, await _activeStatementProvider.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false)); + return CreateActiveStatementsMap(BaseSolution, await DebuggingSession.ActiveStatementProvider.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false)); } catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) { @@ -122,13 +153,16 @@ private async Task GetBaseActiveStatementsAsync(Cancellatio } } + internal static bool SupportsEditAndContinue(Project project) + => project.LanguageServices.GetService() != null; + private ActiveStatementsMap CreateActiveStatementsMap(Solution solution, ImmutableArray debugInfos) { var byDocument = PooledDictionary>.GetInstance(); var byInstruction = PooledDictionary.GetInstance(); - bool SupportsEditAndContinue(DocumentId documentId) - => solution.GetProject(documentId.ProjectId).LanguageServices.GetService() != null; + bool supportsEditAndContinue(DocumentId documentId) + => SupportsEditAndContinue(solution.GetProject(documentId.ProjectId)); foreach (var debugInfo in debugInfos) { @@ -140,7 +174,7 @@ bool SupportsEditAndContinue(DocumentId documentId) } var documentIds = solution.GetDocumentIdsWithFilePath(documentName); - var firstDocumentId = documentIds.FirstOrDefault(SupportsEditAndContinue); + var firstDocumentId = documentIds.FirstOrDefault(supportsEditAndContinue); if (firstDocumentId == null) { // Ignore active statements that don't belong to the solution or language that supports EnC service. @@ -168,7 +202,7 @@ bool SupportsEditAndContinue(DocumentId documentId) for (var i = 1; i < documentIds.Length; i++) { var documentId = documentIds[i]; - if (!SupportsEditAndContinue(documentId)) + if (!supportsEditAndContinue(documentId)) { continue; } @@ -188,7 +222,7 @@ bool SupportsEditAndContinue(DocumentId documentId) catch (ArgumentException) { throw new InvalidOperationException($"Multiple active statements with the same instruction id returned by " + - $"{_activeStatementProvider.GetType()}.{nameof(IActiveStatementProvider.GetActiveStatementsAsync)}"); + $"{DebuggingSession.ActiveStatementProvider.GetType()}.{nameof(IActiveStatementProvider.GetActiveStatementsAsync)}"); } } @@ -231,7 +265,8 @@ private async Task> GetBaseActiv foreach (var activeStatement in instructionMap.Values) { - var document = _baseSolution.GetDocument(activeStatement.PrimaryDocumentId); + var document = BaseSolution.GetDocument(activeStatement.PrimaryDocumentId); + var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); @@ -249,22 +284,7 @@ private async Task> GetBaseActiv } } - internal CancellationTokenSource Cancellation => _cancellation; - - internal Solution BaseSolution => _baseSolution; - - private Solution CurrentSolution => _baseSolution.Workspace.CurrentSolution; - - public bool StoppedAtException => _stoppedAtException; - - public IReadOnlyDictionary Projects => _projects; - - internal bool HasProject(ProjectId id) - { - return Projects.TryGetValue(id, out _); - } - - private List<(DocumentId, AsyncLazy)> GetChangedDocumentsAnalyses(Project baseProject, Project project) + private List<(DocumentId DocumentId, AsyncLazy Results)> GetChangedDocumentsAnalyses(Project baseProject, Project project) { var changes = project.GetChanges(baseProject); var changedDocuments = changes.GetChangedDocuments().Concat(changes.GetAddedDocuments()); @@ -285,19 +305,19 @@ private async Task> GetAllAddedSymbolsAsync(Project project, Ca { try { - Analysis[] analyses; + (Document Document, AsyncLazy Results)[] analyses; lock (_analysesGuard) { analyses = _analyses.Values.ToArray(); } HashSet addedSymbols = null; - foreach (var analysis in analyses) + foreach (var (document, lazyResults) in analyses) { // Only consider analyses for documents that belong the currently analyzed project. - if (analysis.Document.Project == project) + if (document.Project == project) { - var results = await analysis.Results.GetValueAsync(cancellationToken).ConfigureAwait(false); + var results = await lazyResults.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!results.HasChangesAndErrors) { foreach (var edit in results.SemanticEdits) @@ -352,19 +372,10 @@ private AsyncLazy GetDocumentAnalysisNoLock(Document do documentBaseActiveStatements = ImmutableArray.Empty; } - var trackingService = _baseSolution.Workspace.Services.GetService(); - var baseProject = _baseSolution.GetProject(document.Project.Id); - var result = await analyzer.AnalyzeDocumentAsync(baseProject, documentBaseActiveStatements, document, trackingService, cancellationToken).ConfigureAwait(false); + var trackingService = BaseSolution.Workspace.Services.GetService(); - if (!result.RudeEditErrors.IsDefault) - { - lock (_documentsWithReportedRudeEditsGuard) - { - _documentsWithReportedRudeEdits.Add(document.Id); - } - } - - return result; + var baseProject = GetBaseProject(document.Project.Id); + return await analyzer.AnalyzeDocumentAsync(baseProject, documentBaseActiveStatements, document, trackingService, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { @@ -373,100 +384,178 @@ private AsyncLazy GetDocumentAnalysisNoLock(Document do }, cacheResult: true); - _analyses[document.Id] = new Analysis(document, lazyResults); + _analyses[document.Id] = (document, lazyResults); return lazyResults; } - internal ImmutableArray GetDocumentsWithReportedRudeEdits() + internal ImmutableArray GetDocumentsWithReportedDiagnostics() { - lock (_documentsWithReportedRudeEditsGuard) + lock (_documentsWithReportedDiagnosticsGuard) { - return ImmutableArray.CreateRange(_documentsWithReportedRudeEdits); + return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } - public async Task GetProjectAnalysisSummaryAsync(Project project, CancellationToken cancellationToken) + internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { - try + lock (_documentsWithReportedDiagnosticsGuard) { - var baseProject = _baseSolution.GetProject(project.Id); + _documentsWithReportedDiagnostics.Add(documentId); + } + } - // TODO (https://github.com/dotnet/roslyn/issues/1204): - if (baseProject == null) + public async Task GetSolutionUpdateStatusAsync(Solution solution, string sourceFilePath, CancellationToken cancellationToken) + { + try + { + if (_changesApplied) { - return ProjectAnalysisSummary.NoChanges; + return SolutionUpdateStatus.None; } - var documentAnalyses = GetChangedDocumentsAnalyses(baseProject, project); - if (documentAnalyses.Count == 0) + var projects = (sourceFilePath == null) ? solution.Projects : + from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) + select solution.GetDocument(documentId).Project; + + bool anyChanges = false; + foreach (var project in projects) { - return ProjectAnalysisSummary.NoChanges; - } + if (!SupportsEditAndContinue(project)) + { + continue; + } - var hasChanges = false; - var hasSignificantChanges = false; + var baseProject = GetBaseProject(project.Id); - foreach (var analysis in documentAnalyses) - { - var result = await analysis.Item2.GetValueAsync(cancellationToken).ConfigureAwait(false); + // When debugging session is started some projects might not have been loaded to the workspace yet. + // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied + // and will result in source mismatch when the user steps into them. + // + // TODO (https://github.com/dotnet/roslyn/issues/1204): + // hook up the debugger reported error, check that the project has not been loaded and report a better error. + // Here, we assume these projects are not modified. + if (baseProject == null) + { + EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", project.Id.DebugName, project.Id); + continue; + } - // skip documents that actually were not changed: - if (!result.HasChanges) + var (mvid, _) = await DebuggingSession.GetProjectModuleIdAsync(baseProject.Id, cancellationToken).ConfigureAwait(false); + if (mvid == Guid.Empty) { + // project not built + EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } - // rude edit detection wasn't completed due to errors in compilation: - if (result.HasChangesAndCompilationErrors) + var changedDocumentAnalyses = GetChangedDocumentsAnalyses(baseProject, project); + var projectSummary = await GetProjectAnalysisSymmaryAsync(changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); + + if (projectSummary == ProjectAnalysisSummary.ValidChanges && + !GetModuleDiagnostics(mvid, project.Name).IsEmpty) { - return ProjectAnalysisSummary.CompilationErrors; + EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: module blocking EnC", project.Id.DebugName, project.Id); + return SolutionUpdateStatus.Blocked; } - // rude edits detected: - if (result.RudeEditErrors.Length != 0) + EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); + + switch (projectSummary) { - return ProjectAnalysisSummary.RudeEdits; + case ProjectAnalysisSummary.NoChanges: + continue; + + case ProjectAnalysisSummary.CompilationErrors: + case ProjectAnalysisSummary.RudeEdits: + return SolutionUpdateStatus.Blocked; + + case ProjectAnalysisSummary.ValidChanges: + case ProjectAnalysisSummary.ValidInsignificantChanges: + anyChanges = true; + continue; + + default: + throw ExceptionUtilities.UnexpectedValue(projectSummary); } + } + + return anyChanges ? SolutionUpdateStatus.Ready : SolutionUpdateStatus.None; + } + catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceledAndPropagate(e)) + { + throw ExceptionUtilities.Unreachable; + } + } - hasChanges = true; - hasSignificantChanges |= result.HasSignificantChanges; + private async Task GetProjectAnalysisSymmaryAsync( + List<(DocumentId DocumentId, AsyncLazy Results)> documentAnalyses, + CancellationToken cancellationToken) + { + if (documentAnalyses.Count == 0) + { + return ProjectAnalysisSummary.NoChanges; + } + + bool hasChanges = false; + bool hasSignificantValidChanges = false; + + foreach (var analysis in documentAnalyses) + { + var result = await analysis.Results.GetValueAsync(cancellationToken).ConfigureAwait(false); + + // skip documents that actually were not changed: + if (!result.HasChanges) + { + continue; } - if (!hasChanges) + // rude edit detection wasn't completed due to errors in compilation: + if (result.HasChangesAndCompilationErrors) { - // we get here if a document is closed and reopen without any actual change: - return ProjectAnalysisSummary.NoChanges; + return ProjectAnalysisSummary.CompilationErrors; } - if (_stoppedAtException) + // rude edits detected: + if (!result.RudeEditErrors.IsEmpty) { - // all edits are disallowed when stopped at exception: return ProjectAnalysisSummary.RudeEdits; } - return hasSignificantChanges ? - ProjectAnalysisSummary.ValidChanges : - ProjectAnalysisSummary.ValidInsignificantChanges; + hasChanges = true; + hasSignificantValidChanges |= result.HasSignificantValidChanges; } - catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) + + if (!hasChanges) { - throw ExceptionUtilities.Unreachable; + // we get here if a document is closed and reopen without any actual change: + return ProjectAnalysisSummary.NoChanges; } + + if (!hasSignificantValidChanges) + { + return ProjectAnalysisSummary.ValidInsignificantChanges; + } + + return ProjectAnalysisSummary.ValidChanges; } - private async Task GetProjectChangesAsync(Project project, CancellationToken cancellationToken) + private static async Task GetProjectChangesAsync(List<(DocumentId Document, AsyncLazy Results)> changedDocumentAnalyses, CancellationToken cancellationToken) { try { - var baseProject = _baseSolution.GetProject(project.Id); var allEdits = ArrayBuilder.GetInstance(); var allLineEdits = ArrayBuilder<(DocumentId, ImmutableArray)>.GetInstance(); - var allActiveStatements = ArrayBuilder<(DocumentId, ImmutableArray, ImmutableArray>)>.GetInstance(); + var activeStatementsInChangedDocuments = ArrayBuilder<(DocumentId, ImmutableArray, ImmutableArray>)>.GetInstance(); - foreach (var (documentId, asyncResult) in GetChangedDocumentsAnalyses(baseProject, project)) + foreach (var (documentId, asyncResult) in changedDocumentAnalyses) { var result = await asyncResult.GetValueAsync(cancellationToken).ConfigureAwait(false); + if (!result.HasSignificantValidChanges) + { + continue; + } + // we shouldn't be asking for deltas in presence of errors: Debug.Assert(!result.HasChangesAndErrors); @@ -478,16 +567,11 @@ private async Task GetProjectChangesAsync(Project project, Cance if (result.ActiveStatements.Length > 0) { - allActiveStatements.Add((documentId, result.ActiveStatements, result.ExceptionRegions)); + activeStatementsInChangedDocuments.Add((documentId, result.ActiveStatements, result.ExceptionRegions)); } } - // Ideally we shouldn't be asking for deltas in absence of significant changes. - // But in VS we have no way of telling the debugger that the changes made - // to the source are not significant. So we emit an empty delta. - // Debug.Assert(allEdits.Count > 0 || allLineEdits.Count > 0); - - return new ProjectChanges(allEdits.ToImmutableAndFree(), allLineEdits.ToImmutableAndFree(), allActiveStatements.ToImmutableAndFree()); + return new ProjectChanges(allEdits.ToImmutableAndFree(), allLineEdits.ToImmutableAndFree(), activeStatementsInChangedDocuments.ToImmutableAndFree()); } catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceledAndPropagate(e)) { @@ -495,70 +579,293 @@ private async Task GetProjectChangesAsync(Project project, Cance } } - public async Task EmitProjectDeltaAsync(Project project, EmitBaseline baseline, CancellationToken cancellationToken) + internal ImmutableArray GetDebugeeStateDiagnostics() + { + return ImmutableArray.Empty; + } + + public async Task EmitSolutionUpdateAsync(Solution solution, CancellationToken cancellationToken) { + var deltas = ArrayBuilder.GetInstance(); + var emitBaselines = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(); + var readers = ArrayBuilder.GetInstance(); + var diagnostics = ArrayBuilder<(ProjectId, ImmutableArray)>.GetInstance(); + try { - Debug.Assert(!_stoppedAtException); + bool isBlocked = false; - var projectChanges = await GetProjectChangesAsync(project, cancellationToken).ConfigureAwait(false); - var currentCompilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); - var allAddedSymbols = await GetAllAddedSymbolsAsync(project, cancellationToken).ConfigureAwait(false); - var baseActiveStatements = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); - var baseActiveExceptionRegions = await BaseActiveExceptionRegions.GetValueAsync(cancellationToken).ConfigureAwait(false); + foreach (var project in solution.Projects) + { + if (!SupportsEditAndContinue(project)) + { + continue; + } - var pdbStream = new MemoryStream(); - var updatedMethods = new List(); + var baseProject = GetBaseProject(project.Id); - using (var metadataStream = SerializableBytes.CreateWritableStream()) - using (var ilStream = SerializableBytes.CreateWritableStream()) + // TODO (https://github.com/dotnet/roslyn/issues/1204): + // When debugging session is started some projects might not have been loaded to the workspace yet. + // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied + // and will result in source mismatch when the user steps into them. + // TODO: hook up the debugger reported error, check that the project has not been loaded and report a better error. + // Here, we assume these projects are not modified. + if (baseProject == null) + { + EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not loaded", project.Id.DebugName, project.Id); + continue; + } + + var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project.Id, cancellationToken).ConfigureAwait(false); + if (mvid == Guid.Empty && mvidReadError == null) + { + EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", project.Id.DebugName, project.Id); + continue; + } + + var changedDocumentAnalyses = GetChangedDocumentsAnalyses(baseProject, project); + var projectSummary = await GetProjectAnalysisSymmaryAsync(changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); + + if (projectSummary != ProjectAnalysisSummary.ValidChanges) + { + Telemetry.LogProjectAnalysisSummary(projectSummary, ImmutableArray.Empty); + + if (projectSummary == ProjectAnalysisSummary.CompilationErrors || projectSummary == ProjectAnalysisSummary.RudeEdits) + { + isBlocked = true; + } + + continue; + } + + if (mvidReadError != null) + { + // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. + // The MVID is required for emit so we consider the error permanent and report it here. + diagnostics.Add((project.Id, ImmutableArray.Create(mvidReadError))); + + Telemetry.LogProjectAnalysisSummary(projectSummary, ImmutableArray.Create(mvidReadError.Descriptor.Id)); + isBlocked = true; + continue; + } + + var moduleDiagnostics = GetModuleDiagnostics(mvid, project.Name); + if (!moduleDiagnostics.IsEmpty) + { + Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.SelectAsArray(d => d.Descriptor.Id)); + isBlocked = true; + continue; + } + + var projectChanges = await GetProjectChangesAsync(changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); + var currentCompilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); + var allAddedSymbols = await GetAllAddedSymbolsAsync(project, cancellationToken).ConfigureAwait(false); + var baseActiveStatements = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); + var baseActiveExceptionRegions = await BaseActiveExceptionRegions.GetValueAsync(cancellationToken).ConfigureAwait(false); + var lineEdits = projectChanges.LineChanges.SelectAsArray((lineChange, p) => (p.GetDocument(lineChange.DocumentId).FilePath, lineChange.Changes), project); + + // Dispatch to a background thread - the compiler reads symbols and ISymUnmanagedReader requires MTA thread. + // We also don't want to block the UI thread - emit might perform IO. + if (Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA) + { + await Task.Factory.SafeStartNew(Emit, cancellationToken, TaskScheduler.Default).ConfigureAwait(false); + } + else + { + Emit(); + } + + void Emit() + { + Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA, "SymReader requires MTA"); + + var baseline = DebuggingSession.GetOrCreateEmitBaseline(project.Id, mvid); + + // The metadata blob is guaranteed to not be disposed while "continue" operation is being executed. + // If it is disposed it means it had been disposed when "continue" operation started. + if (baseline == null || baseline.OriginalMetadata.IsDisposed) + { + // If we have no baseline the module has not been loaded yet. + // We need to create the baseline from compiler outputs. + var outputs = DebuggingSession.CompilationOutputsProvider.GetCompilationOutputs(project.Id); + if (CreateInitialBaselineForDeferredModuleUpdate(outputs, out var createBaselineDiagnostics, out baseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) + { + readers.Add(metadataReaderProvider); + readers.Add(debugInfoReaderProvider); + } + else + { + diagnostics.Add((project.Id, createBaselineDiagnostics)); + Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics); + isBlocked = true; + return; + } + } + + EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", project.Id.DebugName, project.Id); + + using var pdbStream = SerializableBytes.CreateWritableStream(); + using var metadataStream = SerializableBytes.CreateWritableStream(); + using var ilStream = SerializableBytes.CreateWritableStream(); + + var updatedMethods = ImmutableArray.CreateBuilder(); + + var emitResult = currentCompilation.EmitDifference( + baseline, + projectChanges.SemanticEdits, + s => allAddedSymbols?.Contains(s) ?? false, + metadataStream, + ilStream, + pdbStream, + updatedMethods, + cancellationToken); + + if (emitResult.Success) + { + var updatedMethodTokens = updatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); + + // Determine all active statements whose span changed and exception region span deltas. + GetActiveStatementAndExceptionRegionSpans( + mvid, + baseActiveStatements, + baseActiveExceptionRegions, + updatedMethodTokens, + _nonRemappableRegions, + projectChanges.NewActiveStatements, + out var activeStatementsInUpdatedMethods, + out var nonRemappableRegions); + + deltas.Add(new Deltas( + mvid, + ilStream.ToImmutableArray(), + metadataStream.ToImmutableArray(), + pdbStream.ToImmutableArray(), + updatedMethodTokens, + lineEdits, + nonRemappableRegions, + activeStatementsInUpdatedMethods)); + + emitBaselines.Add((project.Id, emitResult.Baseline)); + } + else + { + // error + isBlocked = true; + } + + // TODO: https://github.com/dotnet/roslyn/issues/36061 + // We should only report diagnostics from emit phase. + // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. + // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. + // Querying diagnostics of the entire compilation or just the updated files migth be slow. + // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched + // method bodies to have errors. + diagnostics.Add((project.Id, emitResult.Diagnostics)); + Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics); + } + } + + if (isBlocked) { - var result = currentCompilation.EmitDifference( - baseline, - projectChanges.SemanticEdits, - s => allAddedSymbols?.Contains(s) ?? false, - metadataStream, - ilStream, - pdbStream, - updatedMethods, - cancellationToken); - - var updatedMethodTokens = updatedMethods.Select(h => MetadataTokens.GetToken(h)).ToArray(); - - // Determine all active statements whose span changed and exception region span deltas. - - GetActiveStatementAndExceptionRegionSpans( - baseline.OriginalMetadata.GetModuleVersionId(), - baseActiveStatements, - baseActiveExceptionRegions, - updatedMethodTokens, - _nonRemappableRegions, - projectChanges.NewActiveStatements, - out var activeStatementsInUpdatedMethods, - out var nonRemappableRegions); - - return new Deltas( - ilStream.ToArray(), - metadataStream.ToArray(), - pdbStream, - updatedMethodTokens, - projectChanges.LineChanges, - nonRemappableRegions, - activeStatementsInUpdatedMethods, - result); + deltas.Free(); + emitBaselines.Free(); + + foreach (var reader in readers) + { + reader.Dispose(); + } + + readers.Free(); + + return SolutionUpdate.Blocked(diagnostics.ToImmutableAndFree()); } + + return new SolutionUpdate( + (deltas.Count > 0) ? SolutionUpdateStatus.Ready : SolutionUpdateStatus.None, + deltas.ToImmutableAndFree(), + readers.ToImmutableAndFree(), + emitBaselines.ToImmutableAndFree(), + diagnostics.ToImmutableAndFree()); } - catch (Exception e) when (FatalError.ReportWithoutCrashAndPropagate(e)) + catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceledAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } } - private static void GetActiveStatementAndExceptionRegionSpans( + private static unsafe bool CreateInitialBaselineForDeferredModuleUpdate( + CompilationOutputs compilationOutputs, + out ImmutableArray diagnostics, + out EmitBaseline baseline, + out DebugInformationReaderProvider debugInfoReaderProvider, + out MetadataReaderProvider metadataReaderProvider) + { + // Since the module has not been loaded to the debuggee the debugger does not have its metadata or symbols available yet. + // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize + // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent + // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. + // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again + // when we need it next time and the module is loaded. + + diagnostics = default; + baseline = null; + debugInfoReaderProvider = null; + metadataReaderProvider = null; + + bool success = false; + string fileBeingRead = compilationOutputs.PdbDisplayPath; + try + { + debugInfoReaderProvider = compilationOutputs.OpenPdb(); + if (debugInfoReaderProvider == null) + { + throw new FileNotFoundException(); + } + + var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); + + fileBeingRead = compilationOutputs.AssemblyDisplayPath; + + metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); + if (metadataReaderProvider == null) + { + throw new FileNotFoundException(); + } + + var metadataReader = metadataReaderProvider.GetMetadataReader(); + var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); + + baseline = EmitBaseline.CreateInitialBaseline( + moduleMetadata, + debugInfoReader.GetDebugInfo, + debugInfoReader.GetLocalSignature, + debugInfoReader.IsPortable); + + success = true; + } + catch (Exception e) + { + var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); + diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); + } + finally + { + if (!success) + { + debugInfoReaderProvider?.Dispose(); + metadataReaderProvider?.Dispose(); + } + } + + return success; + } + + // internal for testing + internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap baseActiveStatements, ImmutableArray baseActiveExceptionRegions, - int[] updatedMethodTokens, + ImmutableArray updatedMethodTokens, ImmutableDictionary> previousNonRemappableRegions, ImmutableArray<(DocumentId DocumentId, ImmutableArray ActiveStatements, ImmutableArray> ExceptionRegions)> newActiveStatementsInChangedDocuments, out ImmutableArray<(Guid ThreadId, ActiveInstructionId OldInstructionId, LinePositionSpan NewSpan)> activeStatementsInUpdatedMethods, @@ -678,83 +985,10 @@ void AddNonRemappableRegion(LinePositionSpan oldSpan, LinePositionSpan newSpan, unremappedActiveMethods.Free(); } - internal void LogRudeEditErrors(ImmutableArray rudeEditErrors) - { - lock (_encEditSessionInfoGuard) - { - if (_encEditSessionInfo != null) - { - foreach (var item in rudeEditErrors) - { - _encEditSessionInfo.LogRudeEdit((ushort)item.Kind, item.SyntaxKind); - } - } - } - } - - internal void LogEmitProjectDeltaErrors(IEnumerable errorIds) + internal void ChangesApplied() { - lock (_encEditSessionInfoGuard) - { - Debug.Assert(_encEditSessionInfo != null); - _encEditSessionInfo.EmitDeltaErrorIds = errorIds; - } - } - - internal void LogBuildState(ProjectAnalysisSummary lastEditSessionSummary) - { - lock (_encEditSessionInfoGuard) - { - Debug.Assert(_encEditSessionInfo != null); - _encEditSessionInfo.HadCompilationErrors |= lastEditSessionSummary == ProjectAnalysisSummary.CompilationErrors; - _encEditSessionInfo.HadRudeEdits |= lastEditSessionSummary == ProjectAnalysisSummary.RudeEdits; - _encEditSessionInfo.HadValidChanges |= lastEditSessionSummary == ProjectAnalysisSummary.ValidChanges; - _encEditSessionInfo.HadValidInsignificantChanges |= lastEditSessionSummary == ProjectAnalysisSummary.ValidInsignificantChanges; - } - } - - internal void LogEditSession(EncDebuggingSessionInfo encDebuggingSessionInfo) - { - lock (_encEditSessionInfoGuard) - { - Debug.Assert(_encEditSessionInfo != null); - encDebuggingSessionInfo.EndEditSession(_encEditSessionInfo); - _encEditSessionInfo = null; - } - } - - internal TestAccessor GetTestAccessor() - => new TestAccessor(this); - - internal readonly struct TestAccessor - { - private readonly EditSession _editSession; - - public TestAccessor(EditSession editSession) - { - _editSession = editSession; - } - - internal static void GetActiveStatementAndExceptionRegionSpans( - Guid moduleId, - ActiveStatementsMap baseActiveStatements, - ImmutableArray baseActiveExceptionRegions, - int[] updatedMethodTokens, - ImmutableDictionary> previousNonRemappableRegions, - ImmutableArray<(DocumentId DocumentId, ImmutableArray ActiveStatements, ImmutableArray> ExceptionRegions)> newActiveStatementsInChangedDocuments, - out ImmutableArray<(Guid ThreadId, ActiveInstructionId OldInstructionId, LinePositionSpan NewSpan)> activeStatementsInUpdatedMethods, - out ImmutableArray<(ActiveMethodId Method, NonRemappableRegion Region)> nonRemappableRegions) - { - EditSession.GetActiveStatementAndExceptionRegionSpans( - moduleId, - baseActiveStatements, - baseActiveExceptionRegions, - updatedMethodTokens, - previousNonRemappableRegions, - newActiveStatementsInChangedDocuments, - out activeStatementsInUpdatedMethods, - out nonRemappableRegions); - } + Debug.Assert(!_changesApplied); + _changesApplied = true; } } } diff --git a/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs b/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs new file mode 100644 index 0000000000000..738ba8b50bd76 --- /dev/null +++ b/src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; +using System.Collections.Immutable; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.EditAndContinue +{ + // EncEditSessionInfo is populated on a background thread and then read from the UI thread + internal sealed class EditSessionTelemetry + { + internal readonly struct Data + { + public readonly ImmutableArray<(ushort EditKind, ushort SyntaxKind)> RudeEdits; + public readonly ImmutableArray EmitErrorIds; + public readonly bool HadCompilationErrors; + public readonly bool HadRudeEdits; + public readonly bool HadValidChanges; + public readonly bool HadValidInsignificantChanges; + + public Data(EditSessionTelemetry telemetry) + { + RudeEdits = telemetry._rudeEdits.AsImmutable(); + EmitErrorIds = telemetry._emitErrorIds.AsImmutable(); + HadCompilationErrors = telemetry._hadCompilationErrors; + HadRudeEdits = telemetry._hadRudeEdits; + HadValidChanges = telemetry._hadValidChanges; + HadValidInsignificantChanges = telemetry._hadValidInsignificantChanges; + } + + public bool IsEmpty => !(HadCompilationErrors || HadRudeEdits || HadValidChanges || HadValidInsignificantChanges); + } + + private readonly object _guard = new object(); + + private readonly HashSet<(ushort, ushort)> _rudeEdits; + private readonly HashSet _emitErrorIds; + + private bool _hadCompilationErrors; + private bool _hadRudeEdits; + private bool _hadValidChanges; + private bool _hadValidInsignificantChanges; + + public EditSessionTelemetry() + { + _rudeEdits = new HashSet<(ushort, ushort)>(); + _emitErrorIds = new HashSet(); + _hadCompilationErrors = false; + _hadRudeEdits = false; + _hadValidChanges = false; + _hadValidInsignificantChanges = false; + } + + public Data GetDataAndClear() + { + lock (_guard) + { + var data = new Data(this); + _rudeEdits.Clear(); + _emitErrorIds.Clear(); + _hadCompilationErrors = false; + _hadRudeEdits = false; + _hadValidChanges = false; + _hadValidInsignificantChanges = false; + return data; + } + } + + public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, ImmutableArray errorsIds) + { + lock (_guard) + { + _emitErrorIds.AddRange(errorsIds); + + switch (summary) + { + case ProjectAnalysisSummary.NoChanges: + break; + + case ProjectAnalysisSummary.CompilationErrors: + _hadCompilationErrors = true; + break; + + case ProjectAnalysisSummary.RudeEdits: + _hadRudeEdits = true; + break; + + case ProjectAnalysisSummary.ValidChanges: + _hadValidChanges = true; + break; + + case ProjectAnalysisSummary.ValidInsignificantChanges: + _hadValidInsignificantChanges = true; + break; + + default: + throw ExceptionUtilities.UnexpectedValue(summary); + } + } + } + + public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, ImmutableArray emitDiagnostics) + => LogProjectAnalysisSummary(summary, emitDiagnostics.SelectAsArray(d => d.Severity == DiagnosticSeverity.Error, d => d.Id)); + + public void LogRudeEditDiagnostics(ImmutableArray diagnostics) + { + lock (_guard) + { + foreach (var diagnostic in diagnostics) + { + _rudeEdits.Add(((ushort)diagnostic.Kind, diagnostic.SyntaxKind)); + } + } + } + } +} diff --git a/src/Features/Core/Portable/EditAndContinue/EncDebuggingSessionInfo.cs b/src/Features/Core/Portable/EditAndContinue/EncDebuggingSessionInfo.cs deleted file mode 100644 index bb18981229a6f..0000000000000 --- a/src/Features/Core/Portable/EditAndContinue/EncDebuggingSessionInfo.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; - -namespace Microsoft.CodeAnalysis.EditAndContinue -{ - internal sealed class EncDebuggingSessionInfo - { - public readonly List EditSessions = new List(); - public int EmptyEditSessions { get; private set; } - - internal void EndEditSession(EncEditSessionInfo encEditSessionInfo) - { - if (encEditSessionInfo.IsEmpty()) - { - EmptyEditSessions++; - } - else - { - EditSessions.Add(encEditSessionInfo); - } - } - } -} diff --git a/src/Features/Core/Portable/EditAndContinue/EncEditSessionInfo.cs b/src/Features/Core/Portable/EditAndContinue/EncEditSessionInfo.cs deleted file mode 100644 index 83e850a1d6299..0000000000000 --- a/src/Features/Core/Portable/EditAndContinue/EncEditSessionInfo.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; - -namespace Microsoft.CodeAnalysis.EditAndContinue -{ - internal class EncEditSessionInfo - { - public readonly HashSet> RudeEdits = new HashSet>(); - - public IEnumerable EmitDeltaErrorIds; - public bool HadCompilationErrors; - public bool HadRudeEdits; - public bool HadValidChanges; - public bool HadValidInsignificantChanges; - - public void LogRudeEdit(ushort kind, ushort syntaxKind) - { - RudeEdits.Add(ValueTuple.Create(kind, syntaxKind)); - } - - public bool IsEmpty() - { - return !(HadCompilationErrors || HadRudeEdits || HadValidChanges || HadValidInsignificantChanges); - } - } -} diff --git a/src/Features/Core/Portable/EditAndContinue/IDebuggeeModuleMetadataProvider.cs b/src/Features/Core/Portable/EditAndContinue/IDebuggeeModuleMetadataProvider.cs index 978a757b66d29..535156fa2cba5 100644 --- a/src/Features/Core/Portable/EditAndContinue/IDebuggeeModuleMetadataProvider.cs +++ b/src/Features/Core/Portable/EditAndContinue/IDebuggeeModuleMetadataProvider.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.EditAndContinue { @@ -12,7 +13,18 @@ internal interface IDebuggeeModuleMetadataProvider /// /// Finds a module of given MVID in one of the processes being debugged and returns its baseline metadata and symbols. /// Shall only be called while in debug mode. + /// Shall only be called on MTA thread. /// DebuggeeModuleInfo TryGetBaselineModuleInfo(Guid mvid); + + /// + /// Returns an error message when any instance of a module with given disallows EnC. + /// + bool IsEditAndContinueAvailable(Guid mvid, out int errorCode, out string localizedMessage); + + /// + /// Notifies the debugger that a document changed that may affect the given module when the change is applied. + /// + void PrepareModuleForUpdate(Guid mvid); } } diff --git a/src/Features/Core/Portable/EditAndContinue/IEditAndContinueService.cs b/src/Features/Core/Portable/EditAndContinue/IEditAndContinueService.cs deleted file mode 100644 index ef36271812b85..0000000000000 --- a/src/Features/Core/Portable/EditAndContinue/IEditAndContinueService.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Immutable; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis.Text; - -namespace Microsoft.CodeAnalysis.EditAndContinue -{ - internal interface IEditAndContinueService - { - EditSession EditSession { get; } - DebuggingSession DebuggingSession { get; } - - void StartDebuggingSession(Solution currentSolution); - - void StartEditSession( - Solution currentSolution, - ImmutableDictionary projects, - bool stoppedAtException); - - void EndEditSession(ImmutableDictionary> newNonRemappableRegionsOpt); - - void EndDebuggingSession(); - - bool IsProjectReadOnly(ProjectId id, out SessionReadOnlyReason sessionReason, out ProjectReadOnlyReason projectReason); - - Task IsActiveStatementInExceptionRegionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken); - Task GetCurrentActiveStatementPositionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken); - } -} diff --git a/src/Features/Core/Portable/EditAndContinue/IEditAndContinueWorkspaceService.cs b/src/Features/Core/Portable/EditAndContinue/IEditAndContinueWorkspaceService.cs new file mode 100644 index 0000000000000..c83381e6aa5cb --- /dev/null +++ b/src/Features/Core/Portable/EditAndContinue/IEditAndContinueWorkspaceService.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Immutable; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.EditAndContinue +{ + internal interface IEditAndContinueWorkspaceService : IWorkspaceService + { + Task> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken); + Task GetSolutionUpdateStatusAsync(string sourceFilePath, CancellationToken cancellationToken); + Task<(SolutionUpdateStatus Summary, ImmutableArray Deltas)> EmitSolutionUpdateAsync(CancellationToken cancellationToken); + + void CommitSolutionUpdate(); + void DiscardSolutionUpdate(); + + void OnManagedModuleInstanceLoaded(Guid mvid); + void OnManagedModuleInstanceUnloaded(Guid mvid); + + bool IsDebuggingSessionInProgress { get; } + + void StartDebuggingSession(); + void StartEditSession(); + void EndEditSession(); + void EndDebuggingSession(); + + Task IsActiveStatementInExceptionRegionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken); + Task GetCurrentActiveStatementPositionAsync(ActiveInstructionId instructionId, CancellationToken cancellationToken); + + void ReportApplyChangesException(string message); + } +} diff --git a/src/Features/Core/Portable/EditAndContinue/ILDelta.cs b/src/Features/Core/Portable/EditAndContinue/ILDelta.cs index 4ff5122f972a3..86f4760d61b5c 100644 --- a/src/Features/Core/Portable/EditAndContinue/ILDelta.cs +++ b/src/Features/Core/Portable/EditAndContinue/ILDelta.cs @@ -1,12 +1,14 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Collections.Immutable; + namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct ILDelta { - public readonly byte[] Value; + public readonly ImmutableArray Value; - public ILDelta(byte[] value) + public ILDelta(ImmutableArray value) { Value = value; } diff --git a/src/Features/Core/Portable/EditAndContinue/LineChange.cs b/src/Features/Core/Portable/EditAndContinue/LineChange.cs index 5dd1c89f93943..4e7c4318b2dd8 100644 --- a/src/Features/Core/Portable/EditAndContinue/LineChange.cs +++ b/src/Features/Core/Portable/EditAndContinue/LineChange.cs @@ -8,7 +8,14 @@ namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct LineChange : IEquatable { + /// + /// Zero-based line number. + /// public readonly int OldLine; + + /// + /// Zero-based line number. + /// public readonly int NewLine; internal LineChange(int oldLine, int newLine) @@ -22,24 +29,15 @@ internal LineChange(int oldLine, int newLine) } public override bool Equals(object obj) - { - return obj is LineChange && Equals((LineChange)obj); - } + => obj is LineChange && Equals((LineChange)obj); public bool Equals(LineChange other) - { - return OldLine == other.OldLine - && NewLine == other.NewLine; - } + => OldLine == other.OldLine && NewLine == other.NewLine; public override int GetHashCode() - { - return Hash.Combine(OldLine, NewLine); - } + => Hash.Combine(OldLine, NewLine); public override string ToString() - { - return OldLine.ToString() + " -> " + NewLine.ToString(); - } + => $"{OldLine} -> {NewLine}"; } } diff --git a/src/Features/Core/Portable/EditAndContinue/LocationlessDiagnostic.cs b/src/Features/Core/Portable/EditAndContinue/LocationlessDiagnostic.cs new file mode 100644 index 0000000000000..8af21210231b6 --- /dev/null +++ b/src/Features/Core/Portable/EditAndContinue/LocationlessDiagnostic.cs @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Immutable; + +namespace Microsoft.CodeAnalysis.EditAndContinue +{ + internal readonly struct LocationlessDiagnostic + { + public readonly DiagnosticDescriptor Descriptor; + public readonly object[] MessageArgs; + + public LocationlessDiagnostic(DiagnosticDescriptor descriptor, object[] messageArgs) + { + Descriptor = descriptor; + MessageArgs = messageArgs; + } + + public Diagnostic ToDiagnostic(Location location) + => Diagnostic.Create(Descriptor, location, MessageArgs); + } +} diff --git a/src/Features/Core/Portable/EditAndContinue/MetadataDelta.cs b/src/Features/Core/Portable/EditAndContinue/MetadataDelta.cs index 35d2b0056351c..fff55f3d7b445 100644 --- a/src/Features/Core/Portable/EditAndContinue/MetadataDelta.cs +++ b/src/Features/Core/Portable/EditAndContinue/MetadataDelta.cs @@ -1,12 +1,14 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Collections.Immutable; + namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct MetadataDelta { - public readonly byte[] Bytes; + public readonly ImmutableArray Bytes; - public MetadataDelta(byte[] bytes) + public MetadataDelta(ImmutableArray bytes) { Bytes = bytes; } diff --git a/src/Features/Core/Portable/EditAndContinue/PdbDelta.cs b/src/Features/Core/Portable/EditAndContinue/PdbDelta.cs index 227fb827de41c..12fb34dee8386 100644 --- a/src/Features/Core/Portable/EditAndContinue/PdbDelta.cs +++ b/src/Features/Core/Portable/EditAndContinue/PdbDelta.cs @@ -1,5 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Collections.Immutable; using System.IO; namespace Microsoft.CodeAnalysis.EditAndContinue @@ -8,11 +9,11 @@ internal readonly struct PdbDelta { // Tokens of updated methods. The debugger enumerates this list // updated methods containing active statements. - public readonly int[] UpdatedMethods; + public readonly ImmutableArray UpdatedMethods; - public readonly MemoryStream Stream; + public readonly ImmutableArray Stream; - public PdbDelta(MemoryStream stream, int[] updatedMethods) + public PdbDelta(ImmutableArray stream, ImmutableArray updatedMethods) { Stream = stream; UpdatedMethods = updatedMethods; diff --git a/src/Features/Core/Portable/EditAndContinue/PendingSolutionUpdate.cs b/src/Features/Core/Portable/EditAndContinue/PendingSolutionUpdate.cs new file mode 100644 index 0000000000000..153d2ba4c3948 --- /dev/null +++ b/src/Features/Core/Portable/EditAndContinue/PendingSolutionUpdate.cs @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.EditAndContinue +{ + internal sealed class PendingSolutionUpdate + { + public readonly Solution Solution; + public readonly ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> EmitBaselines; + public readonly ImmutableArray Deltas; + public readonly ImmutableArray ModuleReaders; + + public PendingSolutionUpdate( + Solution solution, + ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> emitBaselines, + ImmutableArray deltas, + ImmutableArray moduleReaders) + { + Solution = solution; + EmitBaselines = emitBaselines; + Deltas = deltas; + ModuleReaders = moduleReaders; + } + } +} diff --git a/src/Features/Core/Portable/EditAndContinue/ProjectChanges.cs b/src/Features/Core/Portable/EditAndContinue/ProjectChanges.cs index bd0724f42b76b..ad36d6a74fc1c 100644 --- a/src/Features/Core/Portable/EditAndContinue/ProjectChanges.cs +++ b/src/Features/Core/Portable/EditAndContinue/ProjectChanges.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; +using System.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; @@ -16,7 +17,7 @@ internal readonly struct ProjectChanges /// /// All line changes made in changed documents. /// - public readonly ImmutableArray<(DocumentId, ImmutableArray)> LineChanges; + public readonly ImmutableArray<(DocumentId DocumentId, ImmutableArray Changes)> LineChanges; /// /// All active statements and the corresponding exception regions in changed documents. @@ -28,6 +29,10 @@ public ProjectChanges( ImmutableArray<(DocumentId, ImmutableArray)> lineChanges, ImmutableArray<(DocumentId, ImmutableArray, ImmutableArray>)> newActiveStatements) { + Debug.Assert(!semanticEdits.IsDefault); + Debug.Assert(!lineChanges.IsDefault); + Debug.Assert(!newActiveStatements.IsDefault); + SemanticEdits = semanticEdits; LineChanges = lineChanges; NewActiveStatements = newActiveStatements; diff --git a/src/Features/Core/Portable/EditAndContinue/ProjectReadOnlyReason.cs b/src/Features/Core/Portable/EditAndContinue/ProjectReadOnlyReason.cs deleted file mode 100644 index ac75739fe4967..0000000000000 --- a/src/Features/Core/Portable/EditAndContinue/ProjectReadOnlyReason.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.CodeAnalysis.EditAndContinue -{ - internal enum ProjectReadOnlyReason - { - /// - /// Project module was successfully loaded into the debuggee process when edit session started and is editable. - /// - None, - - /// - /// Project hasn't been built at the time debugging session started (or the binary is unreadable). - /// - MetadataNotAvailable, - - /// - /// One of the following reasons - /// - Module wasn't loaded into the debuggee process when edit session started. - /// - The debugger has been attached to an already running process. - /// - The code being debugged was optimized at build or runtime. - /// - The assembly being debugged is loaded as domain-neutral. - /// - The assembly being debugged is runtime-generated (Reflection.Emit). - /// - IntelliTrace is enabled. - /// - NotLoaded, - } -} diff --git a/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnostic.cs b/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnostic.cs index 46a801481e1f5..50b98b1b81c57 100644 --- a/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnostic.cs +++ b/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnostic.cs @@ -21,7 +21,7 @@ internal RudeEditDiagnostic(RudeEditKind kind, TextSpan span, SyntaxNode node = internal Diagnostic ToDiagnostic(SyntaxTree tree) { - var descriptor = RudeEditDiagnosticDescriptors.GetDescriptor(Kind); + var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(Kind); return Diagnostic.Create(descriptor, tree.GetLocation(Span), Arguments); } } diff --git a/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnosticDescriptors.cs b/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnosticDescriptors.cs deleted file mode 100644 index c2b3cf89cb0a5..0000000000000 --- a/src/Features/Core/Portable/EditAndContinue/RudeEditDiagnosticDescriptors.cs +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Collections.Immutable; -using Microsoft.CodeAnalysis.Diagnostics; - -namespace Microsoft.CodeAnalysis.EditAndContinue -{ - // TODO (tomat): cleanup and localize - - internal static class RudeEditDiagnosticDescriptors - { - private static readonly ImmutableDictionary s_descriptors = new List> - { - { GetDescriptorPair(RudeEditKind.InsertAroundActiveStatement, FeaturesResources.Adding_0_around_an_active_statement_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.DeleteAroundActiveStatement, FeaturesResources.Deleting_0_around_an_active_statement_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.DeleteActiveStatement, FeaturesResources.An_active_statement_has_been_removed_from_its_original_method_You_must_revert_your_changes_to_continue_or_restart_the_debugging_session) }, - { GetDescriptorPair(RudeEditKind.UpdateAroundActiveStatement, FeaturesResources.Updating_a_0_around_an_active_statement_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.UpdateExceptionHandlerOfActiveTry, FeaturesResources.Modifying_a_catch_finally_handler_with_an_active_statement_in_the_try_block_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.UpdateTryOrCatchWithActiveFinally, FeaturesResources.Modifying_a_try_catch_finally_statement_when_the_finally_block_is_active_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.UpdateCatchHandlerAroundActiveStatement, FeaturesResources.Modifying_a_catch_handler_around_an_active_statement_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.Update, FeaturesResources.Updating_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ModifiersUpdate, FeaturesResources.Updating_the_modifiers_of_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.VarianceUpdate, FeaturesResources.Updating_the_variance_of_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.TypeUpdate, FeaturesResources.Updating_the_type_of_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InitializerUpdate, FeaturesResources.Updating_the_initializer_of_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.FixedSizeFieldUpdate, FeaturesResources.Updating_the_size_of_a_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.EnumUnderlyingTypeUpdate, FeaturesResources.Updating_the_underlying_type_of_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.BaseTypeOrInterfaceUpdate, FeaturesResources.Updating_the_base_class_and_or_base_interface_s_of_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.TypeKindUpdate, FeaturesResources.Updating_the_kind_of_a_type_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.AccessorKindUpdate, FeaturesResources.Updating_the_kind_of_an_property_event_accessor_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.MethodKindUpdate, FeaturesResources.Updating_the_kind_of_a_method_Sub_Function_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.DeclareAliasUpdate, FeaturesResources.Updating_the_alias_of_Declare_Statement_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.DeclareLibraryUpdate, FeaturesResources.Updating_the_library_name_of_Declare_Statement_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.FieldKindUpdate, FeaturesResources.Updating_a_field_to_an_event_or_vice_versa_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.Renamed, FeaturesResources.Renaming_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.Insert, FeaturesResources.Adding_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertVirtual, FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertOverridable, FeaturesResources.Adding_a_MustOverride_0_or_overriding_an_inherited_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertExtern, FeaturesResources.Adding_an_extern_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertDllImport, FeaturesResources.Adding_an_imported_method_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertOperator, FeaturesResources.Adding_a_user_defined_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertIntoStruct, FeaturesResources.Adding_0_into_a_1_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertIntoClassWithLayout, FeaturesResources.Adding_0_into_a_class_with_explicit_or_sequential_layout_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertGenericMethod, FeaturesResources.Adding_a_generic_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.Move, FeaturesResources.Moving_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.Delete, FeaturesResources.Deleting_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.MethodBodyAdd, FeaturesResources.Adding_a_method_body_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.MethodBodyDelete, FeaturesResources.Deleting_a_method_body_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.GenericMethodUpdate, FeaturesResources.Modifying_a_generic_method_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.GenericMethodTriviaUpdate, FeaturesResources.Modifying_whitespace_or_comments_in_a_generic_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.GenericTypeUpdate, FeaturesResources.Modifying_a_method_inside_the_context_of_a_generic_type_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.GenericTypeTriviaUpdate, FeaturesResources.Modifying_whitespace_or_comments_in_0_inside_the_context_of_a_generic_type_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.GenericTypeInitializerUpdate, FeaturesResources.Modifying_the_initializer_of_0_in_a_generic_type_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.PartialTypeInitializerUpdate, FeaturesResources.Modifying_the_initializer_of_0_in_a_partial_type_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, FeaturesResources.Adding_a_constructor_to_a_type_with_a_field_or_property_initializer_that_contains_an_anonymous_function_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.RenamingCapturedVariable, FeaturesResources.Renaming_a_captured_variable_from_0_to_1_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.StackAllocUpdate, FeaturesResources.Modifying_0_which_contains_the_stackalloc_operator_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ExperimentalFeaturesEnabled, FeaturesResources.Modifying_source_with_experimental_language_features_enabled_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.AwaitStatementUpdate, FeaturesResources.Updating_a_complex_statement_containing_an_await_expression_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ChangingConstructorVisibility, FeaturesResources.Changing_visibility_of_a_constructor_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.CapturingVariable, FeaturesResources.Capturing_variable_0_that_hasn_t_been_captured_before_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.NotCapturingVariable, FeaturesResources.Ceasing_to_capture_variable_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.DeletingCapturedVariable, FeaturesResources.Deleting_captured_variable_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ChangingCapturedVariableType, FeaturesResources.Changing_the_type_of_a_captured_variable_0_previously_of_type_1_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ChangingCapturedVariableScope, FeaturesResources.Changing_the_declaration_scope_of_a_captured_variable_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ChangingLambdaParameters, FeaturesResources.Changing_the_parameters_of_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ChangingLambdaReturnType, FeaturesResources.Changing_the_return_type_of_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ChangingQueryLambdaType, FeaturesResources.Changing_the_type_of_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.AccessingCapturedVariableInLambda, FeaturesResources.Accessing_captured_variable_0_that_hasn_t_been_accessed_before_in_1_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.NotAccessingCapturedVariableInLambda, FeaturesResources.Ceasing_to_access_captured_variable_0_in_1_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertLambdaWithMultiScopeCapture, FeaturesResources.Adding_0_that_accesses_captured_variables_1_and_2_declared_in_different_scopes_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.DeleteLambdaWithMultiScopeCapture, FeaturesResources.Removing_0_that_accessed_captured_variables_1_and_2_declared_in_different_scopes_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ActiveStatementUpdate, FeaturesResources.Updating_an_active_statement_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ActiveStatementLambdaRemoved, FeaturesResources.Removing_0_that_contains_an_active_statement_will_prevent_the_debug_session_from_continuing) }, - // TODO: change the error message to better explain what's going on - { GetDescriptorPair(RudeEditKind.PartiallyExecutedActiveStatementUpdate, FeaturesResources.Updating_an_active_statement_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.PartiallyExecutedActiveStatementDelete, FeaturesResources.An_active_statement_has_been_removed_from_its_original_method_You_must_revert_your_changes_to_continue_or_restart_the_debugging_session) }, - { GetDescriptorPair(RudeEditKind.InsertFile, FeaturesResources.Adding_a_new_file_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, FeaturesResources.Updating_async_or_iterator_modifier_around_an_active_statement_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, FeaturesResources.Attribute_0_is_missing_Updating_an_async_method_or_an_iterator_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, FeaturesResources.Switching_between_lambda_and_local_function_will_prevent_the_debug_session_from_continuing ) }, - { GetDescriptorPair(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, FeaturesResources.Adding_method_with_explicit_interface_specifier_will_prevernt_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertIntoInterface, FeaturesResources.Adding_0_into_an_interface_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, FeaturesResources.Adding_0_into_an_interface_method_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InternalError, FeaturesResources.Modifying_source_file_will_prevent_the_debug_session_from_continuing_due_to_internal_error) }, - { GetDescriptorPair(RudeEditKind.SwitchExpressionUpdate, FeaturesResources.Modifying_0_which_contains_a_switch_expression_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ChangingFromAsynchronousToSynchronous, FeaturesResources.Changing_0_from_asynchronous_to_synchronous_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ChangingStateMachineShape, FeaturesResources.Changing_0_to_1_will_prevent_the_debug_session_from_continuing_because_it_changes_the_shape_of_the_state_machine) }, - { GetDescriptorPair(RudeEditKind.RUDE_EDIT_COMPLEX_QUERY_EXPRESSION, FeaturesResources.Modifying_0_which_contains_an_Aggregate_Group_By_or_Join_query_clauses_will_prevent_the_debug_session_from_continuing) }, - - // VB specific, - { GetDescriptorPair(RudeEditKind.HandlesClauseUpdate, FeaturesResources.Updating_the_Handles_clause_of_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ImplementsClauseUpdate, FeaturesResources.Updating_the_Implements_clause_of_a_0_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.ConstraintKindUpdate, FeaturesResources.Changing_the_constraint_from_0_to_1_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.InsertHandlesClause, FeaturesResources.Adding_0_with_the_Handles_clause_will_prevent_the_debug_session_from_continuing) }, - { GetDescriptorPair(RudeEditKind.UpdateStaticLocal, FeaturesResources.Modifying_0_which_contains_a_static_variable_will_prevent_the_debug_session_from_continuing) }, - }.ToImmutableDictionary(); - - private static KeyValuePair GetDescriptorPair(RudeEditKind kind, string message) - { - return new KeyValuePair(kind, - new DiagnosticDescriptor(id: "ENC" + ((int)kind).ToString("0000"), - title: message, // TODO: come up with real titles. - messageFormat: message, - category: DiagnosticCategory.EditAndContinue, - defaultSeverity: DiagnosticSeverity.Error, - isEnabledByDefault: true, - customTags: DiagnosticCustomTags.EditAndContinue)); - } - - internal static ImmutableArray AllDescriptors - { - get - { - return s_descriptors.Values.ToImmutableArray(); - } - } - - internal static DiagnosticDescriptor GetDescriptor(RudeEditKind kind) - { - return s_descriptors[kind]; - } - } -} diff --git a/src/Features/Core/Portable/EditAndContinue/RudeEditKind.cs b/src/Features/Core/Portable/EditAndContinue/RudeEditKind.cs index 5e3ad726a19d4..f603d047c39a9 100644 --- a/src/Features/Core/Portable/EditAndContinue/RudeEditKind.cs +++ b/src/Features/Core/Portable/EditAndContinue/RudeEditKind.cs @@ -31,12 +31,12 @@ internal enum RudeEditKind : ushort DeclareAliasUpdate = 19, Renamed = 20, Insert = 21, - //// InsertNonPrivate = 22, + // InsertNonPrivate = 22, InsertVirtual = 23, InsertOverridable = 24, InsertExtern = 25, InsertOperator = 26, - //// InsertNonPublicConstructor = 27, + // InsertNonPublicConstructor = 27, InsertGenericMethod = 28, InsertDllImport = 29, InsertIntoStruct = 30, @@ -51,8 +51,8 @@ internal enum RudeEditKind : ushort GenericTypeTriviaUpdate = 39, GenericTypeInitializerUpdate = 40, PartialTypeInitializerUpdate = 41, - //// AsyncMethodUpdate = 42, - //// AsyncMethodTriviaUpdate = 43, + // AsyncMethodUpdate = 42, + // AsyncMethodTriviaUpdate = 43, StackAllocUpdate = 44, ExperimentalFeaturesEnabled = 45, @@ -106,7 +106,7 @@ internal enum RudeEditKind : ushort ChangingFromAsynchronousToSynchronous = 85, ChangingStateMachineShape = 86, - // TODO: remove values below - RUDE_EDIT_COMPLEX_QUERY_EXPRESSION = 0x103, + // Chagned from 0x103 in 16.1 + ComplexQueryExpression = 82, } } diff --git a/src/Features/Core/Portable/EditAndContinue/SolutionUpdate.cs b/src/Features/Core/Portable/EditAndContinue/SolutionUpdate.cs new file mode 100644 index 0000000000000..033ced9df8bc3 --- /dev/null +++ b/src/Features/Core/Portable/EditAndContinue/SolutionUpdate.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.Emit; + +namespace Microsoft.CodeAnalysis.EditAndContinue +{ + internal readonly struct SolutionUpdate + { + public readonly SolutionUpdateStatus Summary; + public readonly ImmutableArray Deltas; + public readonly ImmutableArray ModuleReaders; + public readonly ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> EmitBaselines; + public readonly ImmutableArray<(ProjectId ProjectId, ImmutableArray Diagnostic)> Diagnostics; + + public SolutionUpdate( + SolutionUpdateStatus summary, + ImmutableArray deltas, + ImmutableArray moduleReaders, + ImmutableArray<(ProjectId, EmitBaseline)> emitBaselines, + ImmutableArray<(ProjectId ProjectId, ImmutableArray Diagnostics)> diagnostics) + { + Summary = summary; + Deltas = deltas; + EmitBaselines = emitBaselines; + ModuleReaders = moduleReaders; + Diagnostics = diagnostics; + } + + public static SolutionUpdate Blocked() + => Blocked(ImmutableArray<(ProjectId ProjectId, ImmutableArray Diagnostics)>.Empty); + + public static SolutionUpdate Blocked(ImmutableArray<(ProjectId ProjectId, ImmutableArray Diagnostics)> diagnostics) => new SolutionUpdate( + SolutionUpdateStatus.Blocked, + ImmutableArray.Empty, + ImmutableArray.Empty, + ImmutableArray<(ProjectId, EmitBaseline)>.Empty, + diagnostics); + } +} diff --git a/src/Features/Core/Portable/EditAndContinue/SessionReadOnlyReason.cs b/src/Features/Core/Portable/EditAndContinue/SolutionUpdateStatus.cs similarity index 54% rename from src/Features/Core/Portable/EditAndContinue/SessionReadOnlyReason.cs rename to src/Features/Core/Portable/EditAndContinue/SolutionUpdateStatus.cs index 01a700633358a..03502be055a4c 100644 --- a/src/Features/Core/Portable/EditAndContinue/SessionReadOnlyReason.cs +++ b/src/Features/Core/Portable/EditAndContinue/SolutionUpdateStatus.cs @@ -2,21 +2,21 @@ namespace Microsoft.CodeAnalysis.EditAndContinue { - internal enum SessionReadOnlyReason + internal enum SolutionUpdateStatus { /// - /// The project is editable. + /// No updates have been made to the solution. /// - None, + None = 0, /// - /// The program is running. No edits allowed. + /// Solution udpate is ready to be applied. /// - Running, + Ready = 1, /// - /// The program is stopped at exception. No edits allowed. + /// Solution update is blocked. Edit can't be applied due to compiler errors or rude edits. /// - StoppedAtException, + Blocked = 2, } } diff --git a/src/Features/Core/Portable/EditAndContinue/TraceLog.cs b/src/Features/Core/Portable/EditAndContinue/TraceLog.cs index 97d602f2a2e02..76588bce1a3ef 100644 --- a/src/Features/Core/Portable/EditAndContinue/TraceLog.cs +++ b/src/Features/Core/Portable/EditAndContinue/TraceLog.cs @@ -38,6 +38,21 @@ public Arg(int value) public static implicit operator Arg(string value) => new Arg(value); public static implicit operator Arg(int value) => new Arg(value); + public static implicit operator Arg(ProjectId value) => new Arg(value.Id.GetHashCode()); + public static implicit operator Arg(ProjectAnalysisSummary value) => new Arg(ToString(value)); + + private static string ToString(ProjectAnalysisSummary summary) + { + switch (summary) + { + case ProjectAnalysisSummary.CompilationErrors: return nameof(ProjectAnalysisSummary.CompilationErrors); + case ProjectAnalysisSummary.NoChanges: return nameof(ProjectAnalysisSummary.NoChanges); + case ProjectAnalysisSummary.RudeEdits: return nameof(ProjectAnalysisSummary.RudeEdits); + case ProjectAnalysisSummary.ValidChanges: return nameof(ProjectAnalysisSummary.ValidChanges); + case ProjectAnalysisSummary.ValidInsignificantChanges: return nameof(ProjectAnalysisSummary.ValidInsignificantChanges); + default: return null; + } + } } internal readonly struct Entry diff --git a/src/Features/Core/Portable/Emit/CompilationOutputs.cs b/src/Features/Core/Portable/Emit/CompilationOutputs.cs index 7af2a6c86a46b..d9fd3c70d9dd3 100644 --- a/src/Features/Core/Portable/Emit/CompilationOutputs.cs +++ b/src/Features/Core/Portable/Emit/CompilationOutputs.cs @@ -41,22 +41,39 @@ internal abstract class CompilationOutputs public virtual MetadataReaderProvider OpenAssemblyMetadata(bool prefetch) { var peStream = OpenAssemblyStreamChecked(); - if (peStream != null) + if (peStream == null) { - PEHeaders peHeaders; - using (var peReader = new PEReader(peStream, PEStreamOptions.LeaveOpen)) - { - peHeaders = peReader.PEHeaders; - } + return null; + } - peStream.Position = peHeaders.MetadataStartOffset; - return MetadataReaderProvider.FromMetadataStream( - peStream, - prefetch ? MetadataStreamOptions.PrefetchMetadata : MetadataStreamOptions.Default, - size: peHeaders.MetadataSize); + PEHeaders peHeaders; + using (var peReader = new PEReader(peStream, PEStreamOptions.LeaveOpen)) + { + peHeaders = peReader.PEHeaders; } - return null; + peStream.Position = peHeaders.MetadataStartOffset; + return MetadataReaderProvider.FromMetadataStream( + peStream, + prefetch ? MetadataStreamOptions.PrefetchMetadata : MetadataStreamOptions.Default, + size: peHeaders.MetadataSize); + } + + /// + /// Reads MVID of the output assembly. Overridable for test mocking. + /// Returns if the assembly is not available. + /// + internal virtual Guid ReadAssemblyModuleVersionId() + { + using var metadataProvider = OpenAssemblyMetadata(prefetch: false); + if (metadataProvider == null) + { + return Guid.Empty; + } + + var metadataReader = metadataProvider.GetMetadataReader(); + var mvidHandle = metadataReader.GetModuleDefinition().Mvid; + return metadataReader.GetGuid(mvidHandle); } /// @@ -75,15 +92,17 @@ public virtual MetadataReaderProvider OpenAssemblyMetadata(bool prefetch) /// public virtual DebugInformationReaderProvider OpenPdb() { - var stream = OpenPdbStreamChecked(); - if (stream != null) + var pdbStream = OpenPdbStreamChecked(); + if (pdbStream != null) { - return DebugInformationReaderProvider.CreateFromStream(stream); + return DebugInformationReaderProvider.CreateFromStream(pdbStream); } // check for embedded PDB - using (var peReader = new PEReader(OpenAssemblyStreamChecked())) + var peStream = OpenAssemblyStreamChecked(); + if (peStream != null) { + using var peReader = new PEReader(peStream); var embeddedPdbEntry = peReader.ReadDebugDirectory().FirstOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); if (embeddedPdbEntry.DataSize != 0) { diff --git a/src/Features/Core/Portable/FeaturesResources.Designer.cs b/src/Features/Core/Portable/FeaturesResources.Designer.cs index d9aec65fc9b83..f36a3cdf4f30f 100644 --- a/src/Features/Core/Portable/FeaturesResources.Designer.cs +++ b/src/Features/Core/Portable/FeaturesResources.Designer.cs @@ -750,6 +750,15 @@ internal static string can_t_not_construct_final_tree { } } + /// + /// Looks up a localized string similar to Cannot apply changes -- unexpected error: '{0}'. + /// + internal static string CannotApplyChangesUnexpectedError { + get { + return ResourceManager.GetString("CannotApplyChangesUnexpectedError", resourceCulture); + } + } + /// /// Looks up a localized string similar to Capturing variable '{0}' that hasn't been captured before will prevent the debug session from continuing.. /// @@ -824,6 +833,24 @@ internal static string Changes_to_expression_trees_may_result_in_behavior_change } } + /// + /// Looks up a localized string similar to Changes are not allowed while stopped at exception. + /// + internal static string ChangesDisallowedWhileStoppedAtException { + get { + return ResourceManager.GetString("ChangesDisallowedWhileStoppedAtException", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changes made in project '{0}' will not be applied while the application is running. + /// + internal static string ChangesNotAppliedWhileRunning { + get { + return ResourceManager.GetString("ChangesNotAppliedWhileRunning", resourceCulture); + } + } + /// /// Looks up a localized string similar to Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing.. /// @@ -1293,29 +1320,29 @@ internal static string Document { } /// - /// Looks up a localized string similar to Edit And Continue. + /// Looks up a localized string similar to Edit and Continue. /// - internal static string Edit_And_Continue { + internal static string EditAndContinue { get { - return ResourceManager.GetString("Edit_And_Continue", resourceCulture); + return ResourceManager.GetString("EditAndContinue", resourceCulture); } } /// - /// Looks up a localized string similar to Edit and Continue. + /// Looks up a localized string similar to Edit and Continue disallowed by module. /// - internal static string Edit_and_Continue1 { + internal static string EditAndContinueDisallowedByModule { get { - return ResourceManager.GetString("Edit_and_Continue1", resourceCulture); + return ResourceManager.GetString("EditAndContinueDisallowedByModule", resourceCulture); } } /// - /// Looks up a localized string similar to Edit and Continue. + /// Looks up a localized string similar to Changes made in project '{0}' will prevent the debug session from continuing: {1}. /// - internal static string Edit_and_Continue2 { + internal static string EditAndContinueDisallowedByProject { get { - return ResourceManager.GetString("Edit_and_Continue2", resourceCulture); + return ResourceManager.GetString("EditAndContinueDisallowedByProject", resourceCulture); } } @@ -1382,6 +1409,15 @@ internal static string Enums { } } + /// + /// Looks up a localized string similar to Error while reading file '{0}': {1}. + /// + internal static string ErrorReadingFile { + get { + return ResourceManager.GetString("ErrorReadingFile", resourceCulture); + } + } + /// /// Looks up a localized string similar to event. /// @@ -3521,6 +3557,15 @@ internal static string Roslyn_HostError { } } + /// + /// Looks up a localized string similar to Rude edit. + /// + internal static string RudeEdit { + get { + return ResourceManager.GetString("RudeEdit", resourceCulture); + } + } + /// /// Looks up a localized string similar to Separate nibbles. /// diff --git a/src/Features/Core/Portable/FeaturesResources.resx b/src/Features/Core/Portable/FeaturesResources.resx index 0ff88bc7a653c..fa4dea74e2323 100644 --- a/src/Features/Core/Portable/FeaturesResources.resx +++ b/src/Features/Core/Portable/FeaturesResources.resx @@ -646,9 +646,6 @@ Do you want to continue? Remove qualification - - Edit and Continue - This signature does not contain parameters that can be changed. @@ -706,9 +703,6 @@ Do you want to continue? Compiler - - Edit and Continue - Style @@ -757,8 +751,8 @@ Do you want to continue? Compiler - - Edit And Continue + + Edit and Continue Live @@ -1659,6 +1653,27 @@ This version used in: {2} {0} must return a stream that supports read and seek operations. + + Rude edit + + + Edit and Continue disallowed by module + + + Cannot apply changes -- unexpected error: '{0}' + + + Error while reading file '{0}': {1} + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + + + Changes made in project '{0}' will not be applied while the application is running + + + Changes are not allowed while stopped at exception + Dispose objects before losing scope diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf index 3375e3980ca6e..329df0c54b119 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.cs.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + Přidání prvku {0} do metody rozhraní zabrání v pokračování relace ladění. Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + Přidání prvku {0} do rozhraní zabrání v pokračování relace ladění. @@ -77,6 +77,11 @@ Vyhněte se v kódu nepoužitým parametrům. Pokud parametr nelze odebrat, změňte jeho název tak, aby začínal podtržítkem, za kterým volitelně následuje celé číslo, například _, _1, _2 atd. Tyto řetězce se považují za názvy speciálních symbolů pro vyřazení. + + Cannot apply changes -- unexpected error: '{0}' + Změny se nedají použít – neočekávaná chyba: {0} + + Change namespace to '{0}' Změnit obor názvů na {0} @@ -87,14 +92,24 @@ Změnit na globální obor názvů + + Changes are not allowed while stopped at exception + Když se běh zastaví na výjimce, změny se nepovolují. + + + + Changes made in project '{0}' will not be applied while the application is running + Změny provedené v projektu {0} se nepoužijí, dokud je aplikace spuštěná. + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + Pokud se změní {0} z asynchronního na synchronní, relace ladění nebude moct pokračovat. Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + Pokud se změní {0} na {1}, relace ladění nebude moct pokračovat, protože dojde ke změně tvaru stavového počítače. @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + Nakonfigurovat styl kódu {0} Configure {0} severity - Configure {0} severity + Nakonfigurovat závažnost {0} @@ -167,6 +182,26 @@ Uvolňujte objekty před ztrátou oboru + + Edit and Continue + Upravit a pokračovat + + + + Edit and Continue disallowed by module + Modul zakázal funkci Upravit a pokračovat. + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + Změny provedené v projektu {0} znemožní relaci ladění pokračovat dále: {1} + + + + Error while reading file '{0}': {1} + Při čtení souboru {0} došlo k chybě: {1} + + Expression value is never used Hodnota výrazu se nikdy nepoužívá. @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + Pokud se změní {0} obsahující výraz switch, relace ladění nebude moct pokračovat. @@ -412,6 +447,11 @@ Místo {0} použijte {1} + + Rude edit + Hrubá úprava + + Split into consecutive '{0}' statements Rozdělit do následných příkazů {0} @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + Potlačit {0} @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + Nezalamovat posloupnost volání @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + Pokud se aktualizuje {0} v okolí aktivního příkazu, relace ladění nebude moct pokračovat. @@ -567,14 +607,14 @@ Upozornění: Změna oboru názvů může vést k vytvoření neplatného kódu a změnit význam kódu. - - Wrap and align call chain - Wrap and align call chain - - Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + Upozornění: Při převodu příkazu se může změnit sémantika. + + + + Wrap and align call chain + Zalomit a zarovnat posloupnost volání @@ -584,12 +624,12 @@ Wrap and align long call chain - Wrap and align long call chain + Zalomit a zarovnat dlouhou posloupnost volání Wrap call chain - Wrap call chain + Zalomit posloupnost volání @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + Zalomit dlouhou posloupnost volání @@ -1473,11 +1513,6 @@ Chcete pokračovat? Odebrat kvalifikaci - - Edit and Continue - Upravit a pokračovat - - This signature does not contain parameters that can be changed. Tento podpis neobsahuje parametry, které by se daly změnit. @@ -1563,11 +1598,6 @@ Chcete pokračovat? Kompilátor - - Edit and Continue - Upravit a pokračovat - - Style Styl @@ -1643,11 +1673,6 @@ Chcete pokračovat? Kompilátor - - Edit And Continue - Upravit a pokračovat - - Live Živě diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf index 7c4946319cdf1..584852878ab72 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.de.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + Das Hinzufügen von "{0}" zu einer Schnittstellenmethode verhindert das Fortsetzen der Debugsitzung. Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + Das Hinzufügen von "{0}" zu einer Schnittstelle verhindert das Fortsetzen der Debugsitzung. @@ -77,6 +77,11 @@ Vermeiden Sie nicht verwendete Parameter in Ihrem Code. Wenn der Parameter nicht entfernt werden kann, ändern Sie dessen Namen so, dass er mit einem Unterstrich beginnt, dem optional eine Zahl angefügt wird. Beispiel: "_", "_1", "_2" usw. Diese werden als spezielle Symbolnamen für Ausschussparameter behandelt. + + Cannot apply changes -- unexpected error: '{0}' + Änderungen können nicht angewendet werden -- unerwarteter Fehler: "{0}" + + Change namespace to '{0}' Namespace in "{0}" ändern @@ -87,14 +92,24 @@ In globalen Namespace ändern + + Changes are not allowed while stopped at exception + Änderungen sind nicht zulässig, solange der Vorgang bei einer Ausnahme angehalten ist. + + + + Changes made in project '{0}' will not be applied while the application is running + Im Projekt "{0}" vorgenommene Änderungen werden nicht angewendet, während die Anwendung ausgeführt wird. + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + Die Änderung von "{0}" von asynchron in synchron verhindert, dass die Debugsitzung fortgesetzt wird. Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + Die Änderung von "{0}" in "{1}" verhindert, dass die Debugsitzung fortgesetzt wird, weil sich dadurch die Form des Zustandsautomaten verändert. @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + Codeformat "{0}" konfigurieren Configure {0} severity - Configure {0} severity + Schweregrad "{0}" konfigurieren @@ -167,6 +182,26 @@ Objekte verwerfen, bevor Bereich verloren geht + + Edit and Continue + Bearbeiten und Fortfahren + + + + Edit and Continue disallowed by module + Bearbeiten und Fortfahren durch Modul untersagt + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + Die im Projekt "{0}" vorgenommenen Änderungen verhindern, dass die Debugsitzung fortgesetzt wird: {1} + + + + Error while reading file '{0}': {1} + Fehler beim Lesen der Datei "{0}": {1} + + Expression value is never used Der Ausdruckswert wird niemals verwendet. @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + Nach dem Ändern von "{0}" mit Schalterausdruck kann die Debugsitzung nicht mehr fortgesetzt werden. @@ -412,6 +447,11 @@ "{0}" durch "{1}" ersetzen + + Rude edit + Grobe Bearbeitung + + Split into consecutive '{0}' statements In aufeinanderfolgende {0}-Anweisungen teilen @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + {0} unterdrücken @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + Zeilenumbruch für Aufrufkette aufheben @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + Durch Aktualisieren von "{0}" im Kontext einer aktiven Anweisung wird verhindert, dass die Debugsitzung fortgesetzt wird. @@ -569,12 +609,12 @@ Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + Warnung: Die Semantik kann sich beim Konvertieren der Anweisung ändern. Wrap and align call chain - Wrap and align call chain + Aufrufkette umbrechen und ausrichten @@ -584,12 +624,12 @@ Wrap and align long call chain - Wrap and align long call chain + Lange Aufrufkette umbrechen und ausrichten Wrap call chain - Wrap call chain + Aufrufkette umbrechen @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + Lange Aufrufkette umbrechen @@ -1473,11 +1513,6 @@ Möchten Sie fortfahren? Qualifizierung entfernen - - Edit and Continue - Bearbeiten und Fortfahren - - This signature does not contain parameters that can be changed. Diese Signatur enthält keine Parameter, die geändert werden können. @@ -1563,11 +1598,6 @@ Möchten Sie fortfahren? Compiler - - Edit and Continue - Bearbeiten und Fortfahren - - Style Stil @@ -1643,11 +1673,6 @@ Möchten Sie fortfahren? Compiler - - Edit And Continue - Bearbeiten und fortfahren - - Live Live diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf index 4d9d9ef2aded4..cdacd0fd3bbbe 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.es.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + Agregar "{0}" a un método importado impedirá que continúe la sesión de depuración. Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + Agregar '{0}' en una interfaz impedirá que continúe la sesión de depuración. @@ -77,6 +77,11 @@ Evite los parámetros sin usar en el código. Si el parámetro no se puede quitar, cámbielo de nombre para que empiece por un carácter de subrayado, seguido opcionalmente por un entero, como "_", "_1", "_2", etc. Estos se tratan como nombres de símbolos de descarte especiales. + + Cannot apply changes -- unexpected error: '{0}' + No se pueden aplicar los cambios. Error inesperado: "{0}" + + Change namespace to '{0}' Cambiar el espacio de nombres "{0}" @@ -87,14 +92,24 @@ Cambiar al espacio de nombres global + + Changes are not allowed while stopped at exception + No se permiten cambios durante una parada por una excepción + + + + Changes made in project '{0}' will not be applied while the application is running + Los cambios realizados en el proyecto "{0}" no se aplicarán mientras se esté ejecutando la aplicación + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + Si se cambia "{0}" del modo asincrónico al modo sincrónico, la sesión de depuración no podrá continuar. Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + Si se cambia "{0}" a "{1}", la sesión de depuración no podrá continuar porque cambia la forma de la máquina de estados. @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + Configurar el estilo de código de {0} Configure {0} severity - Configure {0} severity + Configurar la gravedad de {0} @@ -167,6 +182,26 @@ Desechar (Dispose) objetos antes de perder el ámbito + + Edit and Continue + Editar y continuar + + + + Edit and Continue disallowed by module + El módulo no permite editar y continuar + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + Los cambios realizados en el proyecto "{0}" impedirán que continúe la sesión de depuración: {1} + + + + Error while reading file '{0}': {1} + Error al leer el archivo "{0}": {1} + + Expression value is never used El valor de la expresión no se utiliza nunca. @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + Si se modifica "{0}", que contiene una expresión switch, la sesión de depuración no podrá continuar. @@ -412,6 +447,11 @@ Reemplazar "{0}" por "{1}" + + Rude edit + Edición superficial + + Split into consecutive '{0}' statements Dividir en instrucciones "{0}" consecutivas @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + Suprimir {0} @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + Desencapsular la cadena de llamada @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + Si se actualiza un "{0}" en torno a una instrucción activa, la sesión de depuración no podrá continuar. @@ -567,14 +607,14 @@ Advertencia: si cambia Cambiar el espacio de nombres puede producir código inválido y cambiar el significado del código. - - Wrap and align call chain - Wrap and align call chain - - Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + Advertencia: La semántica puede cambiar al convertir la instrucción. + + + + Wrap and align call chain + Encapsular y alinear la cadena de llamada @@ -584,12 +624,12 @@ Wrap and align long call chain - Wrap and align long call chain + Encapsular y alinear la cadena de llamada larga Wrap call chain - Wrap call chain + Encapsular la cadena de llamada @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + Encapsular la cadena de llamada larga @@ -1473,11 +1513,6 @@ Do you want to continue? Quitar cualificación - - Edit and Continue - Editar y continuar - - This signature does not contain parameters that can be changed. Esta firma no contiene parámetros que se puedan cambiar. @@ -1563,11 +1598,6 @@ Do you want to continue? Compilador - - Edit and Continue - Editar y continuar - - Style Estilo @@ -1643,11 +1673,6 @@ Do you want to continue? Compilador - - Edit And Continue - Editar y continuar - - Live Activo diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf index 41d8dfb79e81c..0d715967cc2c9 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.fr.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + L'ajout de '{0}' à une méthode d'interface empêche la session de débogage de se poursuivre. Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + L'ajout de '{0}' à une interface empêche la session de débogage de se poursuivre. @@ -77,6 +77,11 @@ Évitez les paramètres inutilisés dans votre code. Évitez les paramètres inutilisés dans votre code. Si vous ne pouvez pas supprimer un paramètre, changez son nom en le faisant commencer par un trait de soulignement éventuellement suivi d'un entier, par exemple '_', '_1', '_2', etc. Ces types d'élément sont traités en tant que noms de symboles discard spéciaux. + + Cannot apply changes -- unexpected error: '{0}' + Impossible d'appliquer les changements -- Erreur inattendue : '{0}' + + Change namespace to '{0}' Remplacer l’espace de noms par '{0}' @@ -87,14 +92,24 @@ Remplacer par l'espace de noms général + + Changes are not allowed while stopped at exception + Aucun changement n'est autorisé en cas d'arrêt à la suite d'une exception + + + + Changes made in project '{0}' will not be applied while the application is running + Les changements apportés au projet '{0}' ne sont pas appliqués tant que l'application est en cours d'exécution + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + Si vous changez '{0}' en le faisant passer d'asynchrone à synchrone, vous allez empêcher la session de débogage de se poursuivre. Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + Le remplacement de '{0}' par '{1}' va empêcher la session de débogage de se poursuivre, car cela change la forme de la machine à états. @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + Configurer le style de code {0} Configure {0} severity - Configure {0} severity + Configurer la gravité {0} @@ -167,6 +182,26 @@ Supprimer les objets avant la mise hors de portée + + Edit and Continue + Modifier et continuer + + + + Edit and Continue disallowed by module + Fonctionnalité Modifier et Continuer interdite par le module + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + Les changements apportés au projet '{0}' empêchent la session de débogage de se poursuivre : {1} + + + + Error while reading file '{0}': {1} + Erreur durant la lecture du fichier '{0}' : {1} + + Expression value is never used La valeur d'expression n'est jamais utilisée @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + La modification de '{0}', qui contient une expression de switch, va empêcher la session de débogage de se poursuivre. @@ -412,6 +447,11 @@ Remplacer '{0}' par '{1}' + + Rude edit + Modification non applicable + + Split into consecutive '{0}' statements Diviser en instructions '{0}' consécutives @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + Supprimer {0} @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + Ne pas effectuer le retour à la ligne d'une chaîne d'appels @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + La mise à jour de '{0}' autour d'une instruction active va empêcher la session de débogage de se poursuivre. @@ -567,14 +607,14 @@ Avertissement : Le changement d’espace de noms peut produire du code non valide et changer la signification du code. - - Wrap and align call chain - Wrap and align call chain - - Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + Avertissement : La sémantique peut changer durant la conversion d'une instruction. + + + + Wrap and align call chain + Effectuer le retour à la ligne et l'alignement d'une chaîne d'appels @@ -584,12 +624,12 @@ Wrap and align long call chain - Wrap and align long call chain + Effectuer le retour à la ligne et l'alignement d'une longue chaîne d'appels Wrap call chain - Wrap call chain + Effectuer le retour à la ligne d'une chaîne d'appels @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + Effectuer le retour à la ligne d'une longue chaîne d'appels @@ -1473,11 +1513,6 @@ Voulez-vous continuer ? Supprimer une qualification - - Edit and Continue - Modifier et continuer - - This signature does not contain parameters that can be changed. Cette signature ne contient pas de paramètres susceptibles d'être modifiés. @@ -1563,11 +1598,6 @@ Voulez-vous continuer ? Compilateur - - Edit and Continue - Modifier et continuer - - Style Style @@ -1643,11 +1673,6 @@ Voulez-vous continuer ? Compilateur - - Edit And Continue - Modifier & Continuer - - Live En direct diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf index 7d778d72afba4..5c296f3e52151 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.it.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + Se si aggiunge '{0}' in metodo di interfaccia, la sessione di debug non potrà continuare. Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + Se si aggiunge '{0}' in un'interfaccia, la sessione di debug non potrà continuare. @@ -77,6 +77,11 @@ Evitare parametri inutilizzati nel codice. Se non è possibile rimuovere il parametro, modificarne il nome in modo che inizi con un carattere di sottolineatura e, facoltativamente, sia seguito da un numero intero, seguito da un numero intero, ad esempio '_', '_1', '_1', '_2' e così via. Questi vengono considerati come nomi di simboli speciali di rimozione. + + Cannot apply changes -- unexpected error: '{0}' + Non è possibile applicare le modifiche. Errore imprevisto: '{0}' + + Change namespace to '{0}' Modifica lo spazio dei nomi in '{0}' @@ -87,14 +92,24 @@ Passa allo spazio dei nomi globale + + Changes are not allowed while stopped at exception + Le modifiche non sono consentite in caso di arresto in corrispondenza dell'eccezione + + + + Changes made in project '{0}' will not be applied while the application is running + Le modifiche apportate al progetto '{0}' non verranno applicate mentre l'applicazione è in esecuzione + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + Se si modifica '{0}' da asincrono a sincrono, la sessione di debug non potrà continuare. Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + Se si modifica '{0}' in '{1}', la sessione di debug non potrà continuare perché modifica la forma della macchina a stati. @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + Configura lo stile del codice di {0} Configure {0} severity - Configure {0} severity + Configura la gravità di {0} @@ -167,6 +182,26 @@ Elimina gli oggetti prima che siano esterni all'ambito + + Edit and Continue + Modifica e continuazione + + + + Edit and Continue disallowed by module + Modifica e continuazione non consentito dal modulo + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + Le modifiche apportate al progetto '{0}' impediranno la continuazione della sessione di debug: {1} + + + + Error while reading file '{0}': {1} + Si è verificato un errore durante la lettura del file '{0}': {1} + + Expression value is never used Il valore dell'espressione non viene mai usato @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + Se si modifica '{0}' che contiene un'espressione switch, la sessione di debug non potrà continuare. @@ -412,6 +447,11 @@ Sostituisci '{0}' con '{1}' + + Rude edit + Modifica non applicabile + + Split into consecutive '{0}' statements Dividi in istruzioni '{0}' consecutive @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + Elimina {0} @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + Annulla ritorno a capo per la catena di chiamate @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + Se si aggiorna '{0}' in prossimità di un'istruzione attiva, la sessione di debug non potrà continuare. @@ -567,29 +607,29 @@ Avviso: la modifica dello spazio dei nomi può comportare la creazione di codice non valido e modificare il significato del codice. - - Wrap and align call chain - Wrap and align call chain - - Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + Avviso: durante la conversione dell'istruzione la semantica può cambiare. + + + + Wrap and align call chain + Applica ritorno a capo e allinea la catena di chiamate Wrap and align expression - Esegui il wrapping e allinea l'espressione + Applica ritorno a capo e allinea l'espressione Wrap and align long call chain - Wrap and align long call chain + Applica ritorno a capo e allinea la catena di chiamate lunga Wrap call chain - Wrap call chain + Applica ritorno a capo alla catena di chiamate @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + Applica ritorno a capo alla catena di chiamate lunga @@ -1473,11 +1513,6 @@ Continuare? Rimuovi qualificazione - - Edit and Continue - Modifica e continuazione - - This signature does not contain parameters that can be changed. Questa firma non contiene parametri modificabili. @@ -1563,11 +1598,6 @@ Continuare? Compilatore - - Edit and Continue - Modifica e continuazione - - Style Stile @@ -1643,11 +1673,6 @@ Continuare? Compilatore - - Edit And Continue - Modifica e continuazione - - Live In tempo reale diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf index f4b7830143f2e..af81ec8d4a397 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.ja.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + '{0}' をインターフェイス メソッドに追加すると、デバッグ セッションは続行されません。 Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + {0}' をインターフェイスに追加すると、デバッグ セッションは続行されません。 @@ -77,6 +77,11 @@ コード内に使用されないパラメーターを指定しないでください。パラメーターを削除できない場合は、パラメーターの名前をアンダースコアの後にオプションで整数が続く名前 ('_'、'_1'、'_2' など) に変更してください。これらは、特別なディスカード シンボル名として扱われます。 + + Cannot apply changes -- unexpected error: '{0}' + 変更を適用できません。予期しないエラー: '{0}' + + Change namespace to '{0}' 名前空間を '{0}' に変更します @@ -87,14 +92,24 @@ グローバル名前空間に変更します + + Changes are not allowed while stopped at exception + 例外で停止している場合、変更は許可されていません + + + + Changes made in project '{0}' will not be applied while the application is running + プロジェクト '{0}' で行った変更は、アプリケーションの実行中には適用されません + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + '{0}' を非同期から同期に変更すると、デバッグ セッションは続行されません。 Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + '{0}' から '{1}' に変更すると、ステート マシンの形状が変わるため、デバッグ セッションは続行されません。 @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + {0} コード スタイルの構成 Configure {0} severity - Configure {0} severity + {0} の重要度の構成 @@ -167,6 +182,26 @@ スコープを失う前にオブジェクトを破棄 + + Edit and Continue + エディット コンティニュ + + + + Edit and Continue disallowed by module + エディット コンティニュはモジュールで許可されませんでした + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + プロジェクト '{0}' で変更を行うと、デバッグ セッションは続行されません。{1} + + + + Error while reading file '{0}': {1} + ファイル {0}' の読み取り中にエラーが発生しました: {1} + + Expression value is never used 式の値が使用されていません @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + switch 式を含む '{0}' を変更すると、デバッグ セッションは続行されません。 @@ -412,6 +447,11 @@ '{0}' を '{1}' に置き換える + + Rude edit + Rude 編集 + + Split into consecutive '{0}' statements 連続する '{0}' ステートメントに分割 @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + {0} の非表示 @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + 呼び出しチェーンのラップ解除 @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + アクティブ ステートメントの前後の '{0}' を更新すると、デバッグ セッションは続行されません。 @@ -567,14 +607,14 @@ 警告: 名前空間を変更すると無効なコードが生成され、コードの意味が変更される可能性があります。 - - Wrap and align call chain - Wrap and align call chain - - Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + 警告: ステートメントの変換時にセマンティクスが変更される可能性があります。 + + + + Wrap and align call chain + 呼び出しチェーンのラップと配置 @@ -584,12 +624,12 @@ Wrap and align long call chain - Wrap and align long call chain + 長い呼び出しチェーンのラップと配置 Wrap call chain - Wrap call chain + 呼び出しチェーンのラップ @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + 長い呼び出しチェーンのラップ @@ -1473,11 +1513,6 @@ Do you want to continue? 修飾子を削除 - - Edit and Continue - エディット コンティニュ - - This signature does not contain parameters that can be changed. この署名には、変更できるパラメーターが含まれていません。 @@ -1563,11 +1598,6 @@ Do you want to continue? コンパイラ - - Edit and Continue - エディット コンティニュ - - Style スタイル @@ -1643,11 +1673,6 @@ Do you want to continue? コンパイラ - - Edit And Continue - エディット コンティニュ - - Live ライブ diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf index 15352042046f3..8f920c81c0df3 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.ko.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + 인터페이스 메서드에 '{0}'을(를) 추가하면 디버그 세션을 계속할 수 없습니다. Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + 인터페이스에 '{0}'을(를) 추가하면 디버그 세션을 계속할 수 없습니다. @@ -77,6 +77,11 @@ 코드에 사용되지 않는 매개 변수를 사용하지 않도록 합니다. 매개 변수를 제거할 수 없는 경우 이름을 변경하여 밑줄로 시작하고 필요에 따라 뒤에 정수가 있도록 합니다(예: '_', '_1', '_2' 등). 해당 이름은 특수 무시 기호 이름으로 처리됩니다. + + Cannot apply changes -- unexpected error: '{0}' + 변경 내용을 적용할 수 없음 -- 예기치 않은 오류: '{0}' + + Change namespace to '{0}' 네임스페이스를 '{0}'(으)로 변경 @@ -87,14 +92,24 @@ 전역 네임스페이스로 변경 + + Changes are not allowed while stopped at exception + 예외에서 중지된 동안에는 변경할 수 없습니다. + + + + Changes made in project '{0}' will not be applied while the application is running + 애플리케이션이 실행되는 동안에는 '{0}' 프로젝트의 변경 내용이 적용되지 않습니다. + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + '{0}'을(를) 비동기에서 동기로 변경하면 디버그 세션을 계속할 수 없습니다. Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + '{0}'을(를) '{1}'(으)로 변경하면 상태 시스템의 셰이프가 변경되므로 디버그 세션을 계속할 수 없습니다. @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + {0} 코드 스타일 구성 Configure {0} severity - Configure {0} severity + {0} 심각도 구성 @@ -167,6 +182,26 @@ 범위를 벗어나기 전에 개체를 삭제하십시오. + + Edit and Continue + 편집하며 계속하기 + + + + Edit and Continue disallowed by module + 모듈에서 편집하며 계속하기를 허용하지 않음 + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + '{0}' 프로젝트에서 수행한 변경으로 디버그 세션을 계속할 수 없습니다. {1} + + + + Error while reading file '{0}': {1} + '{0}' 파일을 읽는 동안 오류가 발생했습니다. {1} + + Expression value is never used 식 값은 절대 사용되지 않습니다. @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + switch 식을 포함하는 '{0}'을(를) 수정하면 디버그 세션을 계속할 수 없습니다. @@ -412,6 +447,11 @@ '{0}'을(를) '{1}'(으)로 바꾸기 + + Rude edit + 편집 다시 실행 + + Split into consecutive '{0}' statements 연속 '{0}' 문으로 분할 @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + {0}을(를) 표시하지 않음 @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + 호출 체인 래핑 해제 @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + 활성 문 주위에서 '{0}'을(를) 업데이트하면 디버그 세션을 계속할 수 없습니다. @@ -567,14 +607,14 @@ 경고: 네임스페이스를 변경하면 잘못된 코드가 발생하고 코드 의미가 변경될 수 있습니다. - - Wrap and align call chain - Wrap and align call chain - - Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + 경고: 문을 변환할 때 의미 체계가 변경될 수 있습니다. + + + + Wrap and align call chain + 호출 체인 래핑 및 맞춤 @@ -584,12 +624,12 @@ Wrap and align long call chain - Wrap and align long call chain + 긴 호출 체인 래핑 및 맞춤 Wrap call chain - Wrap call chain + 호출 체인 래핑 @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + 긴 호출 체인 래핑 @@ -1473,11 +1513,6 @@ Do you want to continue? 한정자 제거 - - Edit and Continue - 편집하며 계속하기 - - This signature does not contain parameters that can be changed. 이 시그니처에는 변경할 수 있는 매개 변수가 포함되어 있지 않습니다. @@ -1563,11 +1598,6 @@ Do you want to continue? 컴파일러 - - Edit and Continue - 편집하며 계속하기 - - Style 스타일 @@ -1643,11 +1673,6 @@ Do you want to continue? 컴파일러 - - Edit And Continue - 편집하며 계속하기 - - Live 라이브 diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf index 06a5791093063..08d2ebd37124f 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.pl.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + Dodanie elementu „{0}” do metody interfejsu uniemożliwi kontynuowanie sesji debugowania. Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + Dodanie elementu „{0}” do interfejsu uniemożliwi kontynuowanie sesji debugowania. @@ -77,6 +77,11 @@ Unikaj nieużywanych parametrów w kodzie. Jeśli nie można usunąć parametru, zmień jego nazwę, tak aby rozpoczynała się od znaku podkreślenia, a opcjonalnie następowała po niej liczba całkowita, taka jak „_”, „_1”, „_2” itp. Są one traktowane jako specjalne nazwy symboli odrzucenia. + + Cannot apply changes -- unexpected error: '{0}' + Nie można zastosować zmian — nieoczekiwany błąd: „{0}” + + Change namespace to '{0}' Zmień przestrzeń nazw na „{0}” @@ -87,14 +92,24 @@ Zmień na globalną przestrzeń nazw + + Changes are not allowed while stopped at exception + Zmiany nie są dozwolone, gdy wyjątek został zatrzymany + + + + Changes made in project '{0}' will not be applied while the application is running + Zmiany wprowadzone w projekcie „{0}” nie zostaną zastosowane, gdy aplikacja jest uruchomiona + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + Zmiana elementu „{0}” z asynchronicznego na synchroniczny uniemożliwi kontynuowanie sesji debugowania. Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + Zmiana elementu „{0}” na „{1}” uniemożliwi kontynuowanie sesji debugowania, ponieważ powoduje zmianę kształtu automatu stanów. @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + Konfiguruj styl kodu {0} Configure {0} severity - Configure {0} severity + Konfiguruj ważność {0} @@ -167,6 +182,26 @@ Likwiduj obiekty przed utratą zakresu + + Edit and Continue + Edytuj i kontynuuj + + + + Edit and Continue disallowed by module + Edycja i kontynuowanie niedozwolone przez moduł + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + Zmiany wprowadzone w projekcie „{0}” uniemożliwią kontynuowanie sesji debugowania: {1} + + + + Error while reading file '{0}': {1} + Błąd podczas odczytywania pliku „{0}”: {1} + + Expression value is never used Wartość wyrażenia nie jest nigdy używana. @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + Zmodyfikowanie elementu „{0}”, który zawiera wyrażenie switch, uniemożliwi kontynuowanie sesji debugowania. @@ -412,6 +447,11 @@ Zamień element „{0}” na element „{1}” + + Rude edit + Edycja reguły + + Split into consecutive '{0}' statements Podziel na kolejne instrukcje „{0}” @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + Pomiń element {0} @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + Cofnij zawijanie łańcucha wywołań @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + Aktualizacja elementu „{0}” w pobliżu aktywnej instrukcji uniemożliwi kontynuowanie sesji debugowania. @@ -567,14 +607,14 @@ Ostrzeżenie: Zmiana przestrzeni nazw może skutkować nieprawidłowym kodem i zmianą jego znaczenia. - - Wrap and align call chain - Wrap and align call chain - - Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + Ostrzeżenie: semantyka może ulec zmianie podczas konwertowania instrukcji. + + + + Wrap and align call chain + Zawijaj i dopasowuj łańcuch wywołań @@ -584,12 +624,12 @@ Wrap and align long call chain - Wrap and align long call chain + Zawijaj i dopasowuj długi łańcuch wywołań Wrap call chain - Wrap call chain + Zawijaj łańcuch wywołań @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + Zawijaj długi łańcuch wywołań @@ -1473,11 +1513,6 @@ Czy chcesz kontynuować? Usuń kwalifikacje - - Edit and Continue - Edytuj i kontynuuj - - This signature does not contain parameters that can be changed. Ta sygnatura nie zawiera parametrów, które można zmienić. @@ -1563,11 +1598,6 @@ Czy chcesz kontynuować? Kompilator - - Edit and Continue - Edytuj i kontynuuj - - Style Styl @@ -1643,11 +1673,6 @@ Czy chcesz kontynuować? Kompilator - - Edit And Continue - Edytuj i kontynuuj - - Live Na żywo diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf index 9d22c0240bae1..36b31ff20733f 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.pt-BR.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + Adicionar '{0}' a um método de interface impedirá que a sessão de depuração continue. Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + Adicionar '{0}' a uma interface impedirá que a sessão de depuração continue. @@ -77,6 +77,11 @@ Evite parâmetros não usados no código. Se o parâmetro não puder ser removido, altere seu nome para que ele comece com um sublinhado e seja seguido opcionalmente por um inteiro, como '_', '_1', '_2' etc. Esses nomes são tratados como nomes de símbolo de descarte especiais. + + Cannot apply changes -- unexpected error: '{0}' + Não é possível aplicar as alterações – erro inesperado: '{0}' + + Change namespace to '{0}' Alterar o namespace para '{0}' @@ -87,14 +92,24 @@ Alterar para o namespace global + + Changes are not allowed while stopped at exception + Não são permitidas alterações durante uma interrupção em exceção + + + + Changes made in project '{0}' will not be applied while the application is running + As alterações feitas no projeto '{0}' não serão aplicadas enquanto o aplicativo estiver em execução + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + Alterar '{0}' de assíncrono para síncrono impedirá a continuação da sessão de depuração. Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + Alterar '{0}' para '{1}' impedirá a continuação da sessão de depuração porque altera a forma da máquina de estado. @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + Configurar estilo de código de {0} Configure {0} severity - Configure {0} severity + Configurar severidade de {0} @@ -167,6 +182,26 @@ Descartar objetos antes de perder o escopo + + Edit and Continue + Editar e Continuar + + + + Edit and Continue disallowed by module + Pelo módulo, não é permitido Editar e Continuar + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + As alterações feitas no projeto '{0}' impedirão que a sessão de depuração continue: {1} + + + + Error while reading file '{0}': {1} + Erro ao ler o arquivo '{0}': {1} + + Expression value is never used O valor da expressão nunca é usado @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + A modificação de '{0}' contendo uma expressão de switch impedirá a continuação da sessão de depuração. @@ -412,6 +447,11 @@ Substituir '{0}' por '{1}' + + Rude edit + Edição rudimentar + + Split into consecutive '{0}' statements Dividir em instruções '{0}' consecutivas @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + Suprimir {0} @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + Desencapsular cadeia de chamadas @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + Atualizar um '{0}' ao redor de uma instrução ativa impedirá a continuação da sessão de depuração. @@ -567,29 +607,29 @@ Aviso: a alteração do namespace pode produzir código inválido e mudar o significado do código. - - Wrap and align call chain - Wrap and align call chain - - Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + Aviso: a semântica pode ser alterada ao converter a instrução. + + + + Wrap and align call chain + Encapsular e alinhar cadeia de chamadas Wrap and align expression - Encapsular e alinhar expressão + Quebrar e alinhar expressão Wrap and align long call chain - Wrap and align long call chain + Encapsular e alinhar cadeia longa de chamadas Wrap call chain - Wrap call chain + Encapsular cadeia de chamadas @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + Encapsular cadeia longa de chamadas @@ -1473,11 +1513,6 @@ Deseja continuar? Remover qualificação - - Edit and Continue - Editar e Continuar - - This signature does not contain parameters that can be changed. Esta assinatura não contêm parâmetros que podem ser alterados. @@ -1563,11 +1598,6 @@ Deseja continuar? Compilador - - Edit and Continue - Editar e Continuar - - Style Estilo @@ -1643,11 +1673,6 @@ Deseja continuar? Compilador - - Edit And Continue - Editar e Continuar - - Live Ao Vivo diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf index 837b9c4d18130..3408787567623 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.ru.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + Добавление "{0}" в метод интерфейса сделает продолжение сеанса отладки невозможным. Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + Добавление "{0}" в интерфейс сделает продолжение сеанса отладки невозможным. @@ -77,6 +77,11 @@ Избегайте неиспользуемых параметров в коде. Если параметр не может быть удален, измените его имя так, чтобы оно начиналось с символа подчеркивания, за которым при необходимости следует целое число, например, "_", "_1", "_2" и т. д. Эти имена рассматриваются как специальные имена для освобождаемых параметров. + + Cannot apply changes -- unexpected error: '{0}' + Не удается применить изменения, так как возникла непредвиденная ошибка: "{0}" + + Change namespace to '{0}' Изменить пространство имен на "{0}" @@ -87,14 +92,24 @@ Изменить на глобальное пространство имен + + Changes are not allowed while stopped at exception + Изменения запрещены, когда выполнение остановлено при исключении + + + + Changes made in project '{0}' will not be applied while the application is running + Изменения, внесенные в проект "{0}", не будут применены во время выполнения приложения. + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + Изменение "{0}" с асинхронного на синхронное сделает продолжение сеанса отладки невозможным. Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + Изменение "{0}" на "{1}" сделает продолжение сеанса отладки невозможным, так как меняет форму конечной машины. @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + Настройка стиля кода {0} Configure {0} severity - Configure {0} severity + Настройка серьезности {0} @@ -167,6 +182,26 @@ Ликвидировать объекты перед потерей области + + Edit and Continue + Операция "Изменить и продолжить" + + + + Edit and Continue disallowed by module + Операция "Изменить и продолжить" запрещена модулем + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + Изменения, внесенные в проект "{0}", препятствуют продолжению сеанса отладки: {1} + + + + Error while reading file '{0}': {1} + Ошибка при чтении файла "{0}": {1} + + Expression value is never used Значение выражения никогда не используется @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + Изменение "{0}", которое содержит выражение switch, сделает продолжение сеанса отладки невозможным. @@ -412,6 +447,11 @@ Замените '{0}' на '{1}' + + Rude edit + Грубая редакция + + Split into consecutive '{0}' statements Разделить на последовательные операторы "{0}" @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + Скрыть {0} @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + Развернуть цепочку вызовов @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + Обновление "{0}" рядом с активной инструкцией сделает продолжение сеанса отладки невозможным. @@ -567,14 +607,14 @@ Предупреждение: изменение пространства имен может привести к появлению недопустимого кода и к изменению значения кода. - - Wrap and align call chain - Wrap and align call chain - - Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + Внимание! При преобразовании инструкции семантика может измениться. + + + + Wrap and align call chain + Свернуть и выровнять цепочку вызовов @@ -584,12 +624,12 @@ Wrap and align long call chain - Wrap and align long call chain + Свернуть и выровнять длинную цепочку вызовов Wrap call chain - Wrap call chain + Свернуть цепочку вызовов @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + Свернуть длинную цепочку вызовов @@ -1473,11 +1513,6 @@ Do you want to continue? Удалить квалификацию - - Edit and Continue - Операция "Изменить и продолжить" - - This signature does not contain parameters that can be changed. Эта подпись не содержит параметры, которые можно изменить. @@ -1563,11 +1598,6 @@ Do you want to continue? Компилятор - - Edit and Continue - Операция "Изменить и продолжить" - - Style Стиль @@ -1643,11 +1673,6 @@ Do you want to continue? Компилятор - - Edit And Continue - Изменить и продолжить - - Live В реальном времени diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf index ab3213d46c0e6..d109188783e3b 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.tr.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + Arabirim yöntemine '{0}' eklenmesi, hata ayıklama oturumunun devam etmesini engeller. Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + Arabirime '{0}' eklenmesi, hata ayıklama oturumunun devam etmesini engeller. @@ -77,6 +77,11 @@ Kodunuzda, kullanılmayan parametrelerden kaçının. Parametre kaldırılamıyorsa adını, bir alt çizgiyle başlayan ve isteğe bağlı olarak ardından tamsayı gelen ('_', '_1', '_2' gibi) bir değerle değiştirin. Bu değerler özel atılabilir değişken sembolü olarak işlenir. + + Cannot apply changes -- unexpected error: '{0}' + Değişiklikler uygulanamıyor - beklenmeyen hata: '{0}' + + Change namespace to '{0}' Ad alanını '{0}' olarak değiştir @@ -87,14 +92,24 @@ Genel ad alanı olarak değiştir + + Changes are not allowed while stopped at exception + Özel durum sırasında durdurulduğunda değişikliklere izin verilmez + + + + Changes made in project '{0}' will not be applied while the application is running + '{0}' projesinde yapılan değişiklikler, uygulama çalışırken uygulanmayacak + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + '{0}' öğesini zaman uyumsuzdan zaman uyumluya değiştirmek hata ayıklama oturumunun devam etmesini engeller. Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + '{0}' öğesini '{1}' olarak değiştirmek, durum makinesinin şeklini değiştirdiğinden hata ayıklama oturumunun devam etmesini engeller. @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + {0} kod stilini yapılandır Configure {0} severity - Configure {0} severity + {0} önem derecesini yapılandır @@ -167,6 +182,26 @@ Kapsamı kaybetmeden çnce nesneleri bırakın + + Edit and Continue + Düzenle ve Devam Et + + + + Edit and Continue disallowed by module + Düzenle ve Devam Et'e modül tarafından izin verilmiyor + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + '{0}' projesinde yapılan değişiklikler hata ayıklama oturumunun devam etmesini engelleyecek: {1} + + + + Error while reading file '{0}': {1} + '{0}' dosyası okunurken hata: {1} + + Expression value is never used İfade değeri asla kullanılmaz @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + Switch ifadesi içeren '{0}' öğesinin değiştirilmesi hata ayıklama oturumunun devam etmesini engeller. @@ -412,6 +447,11 @@ '{0}' öğesini '{1}' ile değiştir + + Rude edit + İşlenmemiş düzenleme + + Split into consecutive '{0}' statements Ardışık '{0}' deyimlerine ayır @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + {0} eylemini bastır @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + Çağrı zincirinin sarmalamasını kaldır @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + Etkin bir deyim etrafındaki '{0}' öğesini güncelleştirmek, hata ayıklama oturumunun devam etmesini engeller. @@ -567,14 +607,14 @@ Uyarı: Ad alanının değiştirilmesi geçersiz kod oluşturabilir ve kodun anlamını değiştirebilir. - - Wrap and align call chain - Wrap and align call chain - - Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + Uyarı: İfade dönüştürülürken semantikleri değişebilir. + + + + Wrap and align call chain + Çağrı zincirini sarmala ve hizala @@ -584,12 +624,12 @@ Wrap and align long call chain - Wrap and align long call chain + Uzun çağrı zincirini sarmala ve hizala Wrap call chain - Wrap call chain + Çağrı zincirini sarmala @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + Uzun çağrı zincirini sarmala @@ -1473,11 +1513,6 @@ Devam etmek istiyor musunuz? Nitelemeyi kaldır - - Edit and Continue - Düzenle ve Devam Et - - This signature does not contain parameters that can be changed. Bu imza değiştirilebilen parametreleri içermiyor. @@ -1563,11 +1598,6 @@ Devam etmek istiyor musunuz? Derleyici - - Edit and Continue - Düzenle ve Devam Et - - Style Stil @@ -1643,11 +1673,6 @@ Devam etmek istiyor musunuz? Derleyici - - Edit And Continue - Düzenle ve Devam Et - - Live Canlı diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf index 14f6fe294b9af..1f60ff790a985 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hans.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + 将 "{0}" 添加进接口方法将阻止调试会话继续。 Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + 将 "{0}" 添加进接口将阻止调试会话继续。 @@ -77,6 +77,11 @@ 请避免在代码中使用未使用的参数。如果无法删除该参数,请更改其名称,使其以下划线开头,也可在下划线后面跟一个整数(如 "_"、"_1"、"_2" 等)。这些被视为特殊丢弃符号名。 + + Cannot apply changes -- unexpected error: '{0}' + 无法应用更改 - 意外错误:“{0}” + + Change namespace to '{0}' 将名称空间更改为“{0}” @@ -87,14 +92,24 @@ 更改为全局命名空间 + + Changes are not allowed while stopped at exception + 在出现异常而停止时禁止更改 + + + + Changes made in project '{0}' will not be applied while the application is running + 在应用程序运行时,将不应用在项目“{0}”中所作的更改 + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + 将“{0}”从异步更改为同步会阻止调试会话继续执行。 Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + 将“{0}”更改为“{1}”会阻止调试会话继续执行,因为它会更改状态机的形状。 @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + 配置 {0} 代码样式 Configure {0} severity - Configure {0} severity + 配置 {0} 严重性 @@ -167,6 +182,26 @@ 丢失范围之前释放对象 + + Edit and Continue + 编辑并继续 + + + + Edit and Continue disallowed by module + 模块已禁用“编辑并继续” + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + 在项目“{0}”中所作的更改将阻止调试会话继续: {1} + + + + Error while reading file '{0}': {1} + 读取文件“{0}”时出错: {1} + + Expression value is never used 永远不会使用表达式值 @@ -179,7 +214,7 @@ Fix formatting - 解决格式问题 + 修正格式 @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + 修改包含 switch 表达式的“{0}”将阻止调试会话继续执行。 @@ -412,6 +447,11 @@ 将 "{0}" 替换为 "{1}" + + Rude edit + 原始编辑 + + Split into consecutive '{0}' statements 拆分为连续的 "{0}" 语句 @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + 取消 {0} @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + 对调用链解包 @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + 更新活动语句周围的“{0}”将阻止调试会话继续执行。 @@ -567,14 +607,14 @@ 警告: 更改命名空间可能会产生无效的代码并更改代码的含义。 - - Wrap and align call chain - Wrap and align call chain - - Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + 警告: 转换语句时,语义可能出现变化。 + + + + Wrap and align call chain + 包装并对齐调用链 @@ -584,12 +624,12 @@ Wrap and align long call chain - Wrap and align long call chain + 包装并对齐长调用链 Wrap call chain - Wrap call chain + 包装调用链 @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + 包装长调用链 @@ -1473,11 +1513,6 @@ Do you want to continue? 删除限定 - - Edit and Continue - 编辑并继续 - - This signature does not contain parameters that can be changed. 此签名不含可更改的参数。 @@ -1563,11 +1598,6 @@ Do you want to continue? 编译器 - - Edit and Continue - 编辑并继续 - - Style 样式 @@ -1643,11 +1673,6 @@ Do you want to continue? 编译器 - - Edit And Continue - 编辑并继续 - - Live 活动 diff --git a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf index dcfa693841d6e..6322ed5a5b5f6 100644 --- a/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf +++ b/src/Features/Core/Portable/xlf/FeaturesResources.zh-Hant.xlf @@ -44,12 +44,12 @@ Adding '{0}' into an interface method will prevent the debug session from continuing. - Adding '{0}' into an interface method will prevent the debug session from continuing. + 將 '{0}' 新增至介面方法,會造成偵錯工作階段無法繼續。 Adding '{0}' into an interface will prevent the debug session from continuing. - Adding '{0}' into an interface will prevent the debug session from continuing. + 將 '{0}' 新增至介面,會造成偵錯工作階段無法繼續。 @@ -77,6 +77,11 @@ 請避免在您的程式碼中使用參數。如果無法移除參數,請變更其名稱,使其以底線開頭,並可選擇在後面接著整數,例如 '_'、'_1'、'_2' 等。這些會視為特殊的捨棄符號名稱。 + + Cannot apply changes -- unexpected error: '{0}' + 無法套用變更 -- 未預期的錯誤: '{0}' + + Change namespace to '{0}' 將命名空間變更為 ‘{0}' @@ -87,14 +92,24 @@ 變更為全域命名空間 + + Changes are not allowed while stopped at exception + 於例外狀況停止時不允許變更 + + + + Changes made in project '{0}' will not be applied while the application is running + 將不會在應用程式執行時套用在專案 '{0}' 中所做的變更 + + Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. - Changing '{0}' from asynchronous to synchronous will prevent the debug session from continuing. + 將 '{0}' 從非同步變更為同步,會造成偵錯工作階段無法繼續。 Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. - Changing '{0}' to '{1}' will prevent the debug session from continuing because it changes the shape of the state machine. + 將 '{0}' 變更為 '{1}' 會變更狀態機器的圖形,進而使偵錯工作階段無法繼續。 @@ -104,12 +119,12 @@ Configure {0} code style - Configure {0} code style + 設定 {0} 程式碼樣式 Configure {0} severity - Configure {0} severity + 設定 {0} 嚴重性 @@ -167,6 +182,26 @@ 必須在超出範圍前處置物件 + + Edit and Continue + 編輯並繼續 + + + + Edit and Continue disallowed by module + 模組不允許編輯和繼續 + + + + Changes made in project '{0}' will prevent the debug session from continuing: {1} + 在專案 '{0}' 中所做的變更將使偵錯工作階段無法繼續: {1} + + + + Error while reading file '{0}': {1} + 讀取檔案 '{0}' 時發生錯誤: {1} + + Expression value is never used 永遠不會使用運算式值 @@ -294,7 +329,7 @@ Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. - Modifying '{0}' which contains a switch expression will prevent the debug session from continuing. + 修改包含參數運算式的 '{0}' 會讓偵錯工作階段無法繼續。 @@ -412,6 +447,11 @@ 將 ‘{0}’ 取代為 ‘{1}' + + Rude edit + 粗略編輯 + + Split into consecutive '{0}' statements 分割成連續的 '{0}' 陳述式 @@ -429,7 +469,7 @@ Suppress {0} - Suppress {0} + 隱藏 {0} @@ -474,7 +514,7 @@ Unwrap call chain - Unwrap call chain + 將呼叫鏈結取消包裝 @@ -489,7 +529,7 @@ Updating a '{0}' around an active statement will prevent the debug session from continuing. - Updating a '{0}' around an active statement will prevent the debug session from continuing. + 更新使用中陳述式前後的 '{0}',會造成偵錯工作階段無法繼續。 @@ -567,14 +607,14 @@ 警告: 變更命名空間可能會產生無效的程式碼及變更程式碼意義。 - - Wrap and align call chain - Wrap and align call chain - - Warning: Semantics may change when converting statement. - Warning: Semantics may change when converting statement. + 警告: 轉換陳述式時,語意可能會變更。 + + + + Wrap and align call chain + 包裝並對齊呼叫鏈結 @@ -584,12 +624,12 @@ Wrap and align long call chain - Wrap and align long call chain + 包裝並對齊長呼叫鏈結 Wrap call chain - Wrap call chain + 包裝呼叫鏈結 @@ -614,7 +654,7 @@ Wrap long call chain - Wrap long call chain + 包裝長呼叫鏈結 @@ -1473,11 +1513,6 @@ Do you want to continue? 移除限定性條件 - - Edit and Continue - 編輯並繼續 - - This signature does not contain parameters that can be changed. 此簽章不包含可以變更的參數。 @@ -1563,11 +1598,6 @@ Do you want to continue? 編譯器 - - Edit and Continue - 編輯並繼續 - - Style 樣式 @@ -1643,11 +1673,6 @@ Do you want to continue? 編譯器 - - Edit And Continue - 編輯後繼續 - - Live 即時 diff --git a/src/Features/LanguageServer/Protocol/Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj b/src/Features/LanguageServer/Protocol/Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj index 5401a5c9d99ae..a716c03312788 100644 --- a/src/Features/LanguageServer/Protocol/Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj +++ b/src/Features/LanguageServer/Protocol/Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj @@ -5,7 +5,7 @@ Library Microsoft.CodeAnalysis.LanguageServer net472 - + true .NET Compiler Platform ("Roslyn") support for Language Server Protocol. @@ -16,11 +16,14 @@ - + + + + @@ -28,9 +31,10 @@ + - + diff --git a/src/Features/VisualBasic/Portable/EditAndContinue/VisualBasicEditAndContinueAnalyzer.vb b/src/Features/VisualBasic/Portable/EditAndContinue/VisualBasicEditAndContinueAnalyzer.vb index 959d8e5569d8c..97018d1ef6586 100644 --- a/src/Features/VisualBasic/Portable/EditAndContinue/VisualBasicEditAndContinueAnalyzer.vb +++ b/src/Features/VisualBasic/Portable/EditAndContinue/VisualBasicEditAndContinueAnalyzer.vb @@ -2812,7 +2812,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue SyntaxKind.GroupByClause, SyntaxKind.SimpleJoinClause, SyntaxKind.GroupJoinClause - ReportError(RudeEditKind.RUDE_EDIT_COMPLEX_QUERY_EXPRESSION, node, Me._newNode) + ReportError(RudeEditKind.ComplexQueryExpression, node, Me._newNode) Return Case SyntaxKind.LocalDeclarationStatement diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.it.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.it.xlf index 4cea6088815cf..7a5c681531c64 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.it.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.it.xlf @@ -64,7 +64,7 @@ Conflict(s) detected. - Sono stati rilevati conflitti + Sono stati rilevati conflitti. diff --git a/src/Setup/DevDivInsertionFiles/DevDivInsertionFiles.csproj b/src/Setup/DevDivInsertionFiles/DevDivInsertionFiles.csproj index 487fae906dd5e..b16ea0fa66fdc 100644 --- a/src/Setup/DevDivInsertionFiles/DevDivInsertionFiles.csproj +++ b/src/Setup/DevDivInsertionFiles/DevDivInsertionFiles.csproj @@ -118,6 +118,9 @@ <_Dependency Remove="VSLangProj"/> <_Dependency Remove="VSLangProj2"/> <_Dependency Remove="VSLangProj80"/> + <_Dependency Remove="Microsoft.Win32.Registry"/> + <_Dependency Remove="System.Security.AccessControl"/> + <_Dependency Remove="System.Security.Principal.Windows"/> diff --git a/src/Test/Diagnostics/RemoteHost/RemoteHostPanel.xaml.cs b/src/Test/Diagnostics/RemoteHost/RemoteHostPanel.xaml.cs index 1319b15fa9164..6533b95c723d0 100644 --- a/src/Test/Diagnostics/RemoteHost/RemoteHostPanel.xaml.cs +++ b/src/Test/Diagnostics/RemoteHost/RemoteHostPanel.xaml.cs @@ -27,7 +27,9 @@ public RemoteHostPanel(Workspace workspace) : this() _workspace = workspace; } +#pragma warning disable VSTHRD100 // Avoid async void methods private async void OnSolutionSave(object sender, RoutedEventArgs e) +#pragma warning restore VSTHRD100 // Avoid async void methods { using (Disable(SolutionSaveButton)) { @@ -66,7 +68,9 @@ private void OnFileToSave(object sender, RoutedEventArgs e) } } +#pragma warning disable VSTHRD100 // Avoid async void methods private async void OnSolutionOpen(object sender, RoutedEventArgs e) +#pragma warning restore VSTHRD100 // Avoid async void methods { using (Disable(SolutionOpenButton)) { diff --git a/src/Test/Diagnostics/Roslyn.Hosting.Diagnostics.csproj b/src/Test/Diagnostics/Roslyn.Hosting.Diagnostics.csproj index 00065b735e377..d89d9f163f99d 100644 --- a/src/Test/Diagnostics/Roslyn.Hosting.Diagnostics.csproj +++ b/src/Test/Diagnostics/Roslyn.Hosting.Diagnostics.csproj @@ -25,6 +25,7 @@ + diff --git a/src/Test/Utilities/Portable/FX/Delegates.cs b/src/Test/Utilities/Portable/FX/Delegates.cs new file mode 100644 index 0000000000000..29802a3a61186 --- /dev/null +++ b/src/Test/Utilities/Portable/FX/Delegates.cs @@ -0,0 +1,6 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests +{ + internal delegate TRet FuncInOutOut(T1 guid, out T2 errorCode, out T3 localizedMessage); +} diff --git a/src/Test/Utilities/Portable/Mocks/MoqExtensions.cs b/src/Test/Utilities/Portable/Mocks/MoqExtensions.cs new file mode 100644 index 0000000000000..106832d245ebc --- /dev/null +++ b/src/Test/Utilities/Portable/Mocks/MoqExtensions.cs @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using Moq; +using System.Linq; + +namespace Roslyn.Test.Utilities +{ + public static class MoqExtensions + { + public static void VerifyAndClear(this IInvocationList invocations, params (string Name, object[] Args)[] expectedInvocations) + { + AssertEx.Equal( + expectedInvocations.Select(i => $"{i.Name}: {string.Join(",", i.Args)}"), + invocations.Select(i => $"{i.Method.Name}: {string.Join(",", i.Arguments)}")); + + for (int i = 0; i < expectedInvocations.Length; i++) + { + AssertEx.Equal(expectedInvocations[i].Args, invocations[i].Arguments); + } + + invocations.Clear(); + } + } +} diff --git a/src/Test/Utilities/Portable/Roslyn.Test.Utilities.csproj b/src/Test/Utilities/Portable/Roslyn.Test.Utilities.csproj index f58c419f9e764..0f020752555d4 100644 --- a/src/Test/Utilities/Portable/Roslyn.Test.Utilities.csproj +++ b/src/Test/Utilities/Portable/Roslyn.Test.Utilities.csproj @@ -87,6 +87,7 @@ + diff --git a/src/Test/Utilities/Portable/Traits/Traits.cs b/src/Test/Utilities/Portable/Traits/Traits.cs index f9b441fc81d65..a45647ec3c53b 100644 --- a/src/Test/Utilities/Portable/Traits/Traits.cs +++ b/src/Test/Utilities/Portable/Traits/Traits.cs @@ -264,6 +264,7 @@ public static class Features public const string Venus = nameof(Venus); public const string VsLanguageBlock = nameof(VsLanguageBlock); public const string VsNavInfo = nameof(VsNavInfo); + public const string VsSearch = nameof(VsSearch); public const string WinForms = nameof(WinForms); public const string Workspace = nameof(Workspace); public const string XmlTagCompletion = nameof(XmlTagCompletion); diff --git a/src/Tools/ExternalAccess/FSharp/Microsoft.CodeAnalysis.ExternalAccess.FSharp.csproj b/src/Tools/ExternalAccess/FSharp/Microsoft.CodeAnalysis.ExternalAccess.FSharp.csproj index 845061519e952..0ac3c5beb5033 100644 --- a/src/Tools/ExternalAccess/FSharp/Microsoft.CodeAnalysis.ExternalAccess.FSharp.csproj +++ b/src/Tools/ExternalAccess/FSharp/Microsoft.CodeAnalysis.ExternalAccess.FSharp.csproj @@ -79,7 +79,9 @@ + + diff --git a/src/Tools/ExternalAccess/FSharpTest/Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests.csproj b/src/Tools/ExternalAccess/FSharpTest/Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests.csproj index 802645b238373..97d23893344cc 100644 --- a/src/Tools/ExternalAccess/FSharpTest/Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests.csproj +++ b/src/Tools/ExternalAccess/FSharpTest/Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests.csproj @@ -49,8 +49,10 @@ + + \ No newline at end of file diff --git a/src/Tools/ExternalAccess/LiveShare/Microsoft.CodeAnalysis.ExternalAccess.LiveShare.csproj b/src/Tools/ExternalAccess/LiveShare/Microsoft.CodeAnalysis.ExternalAccess.LiveShare.csproj index 25e39d97ccbeb..4e9faca02bd91 100644 --- a/src/Tools/ExternalAccess/LiveShare/Microsoft.CodeAnalysis.ExternalAccess.LiveShare.csproj +++ b/src/Tools/ExternalAccess/LiveShare/Microsoft.CodeAnalysis.ExternalAccess.LiveShare.csproj @@ -41,12 +41,16 @@ + + + + diff --git a/src/Tools/ExternalAccess/Xamarin.Remote/Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote.csproj b/src/Tools/ExternalAccess/Xamarin.Remote/Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote.csproj index 9c9d58200a986..64ab7a07a2702 100644 --- a/src/Tools/ExternalAccess/Xamarin.Remote/Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote.csproj +++ b/src/Tools/ExternalAccess/Xamarin.Remote/Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote.csproj @@ -28,7 +28,9 @@ + + diff --git a/src/VisualStudio/CSharp/Impl/CSharpVSResources.Designer.cs b/src/VisualStudio/CSharp/Impl/CSharpVSResources.Designer.cs index d7fa22047b418..ad9d2171b1e35 100644 --- a/src/VisualStudio/CSharp/Impl/CSharpVSResources.Designer.cs +++ b/src/VisualStudio/CSharp/Impl/CSharpVSResources.Designer.cs @@ -168,6 +168,15 @@ internal static string CSharp_Formatting_Rules { } } + /// + /// Looks up a localized string similar to C# Language Server Client. + /// + internal static string CSharp_language_server_client { + get { + return ResourceManager.GetString("CSharp_language_server_client", resourceCulture); + } + } + /// /// Looks up a localized string similar to Discard. /// diff --git a/src/VisualStudio/CSharp/Impl/CSharpVSResources.resx b/src/VisualStudio/CSharp/Impl/CSharpVSResources.resx index 3241eba368041..285a434cfd55f 100644 --- a/src/VisualStudio/CSharp/Impl/CSharpVSResources.resx +++ b/src/VisualStudio/CSharp/Impl/CSharpVSResources.resx @@ -600,4 +600,7 @@ Prefer switch expression + + C# Language Server Client + \ No newline at end of file diff --git a/src/VisualStudio/CSharp/Impl/LanguageClient/CSharpLanguageServerClient.cs b/src/VisualStudio/CSharp/Impl/LanguageClient/CSharpLanguageServerClient.cs new file mode 100644 index 0000000000000..d87843654b167 --- /dev/null +++ b/src/VisualStudio/CSharp/Impl/LanguageClient/CSharpLanguageServerClient.cs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel.Composition; +using Microsoft.CodeAnalysis.Editor; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Options; +using Microsoft.CodeAnalysis.Remote; +using Microsoft.CodeAnalysis.Shared.TestHooks; +using Microsoft.VisualStudio.Composition; +using Microsoft.VisualStudio.LanguageServer.Client; +using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; +using Microsoft.VisualStudio.Utilities; + +namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageClient +{ + // currently, platform doesn't allow multiple content types + // to be associated with 1 ILanguageClient forcing us to + // create multiple ILanguageClients for each content type + // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/952373 + [ContentType(ContentTypeNames.CSharpContentType)] + [Export(typeof(ILanguageClient))] + [ExportMetadata("Capabilities", "WorkspaceStreamingSymbolProvider")] + internal class CSharpLanguageServerClient : AbstractLanguageServerClient + { + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public CSharpLanguageServerClient( + IThreadingContext threadingContext, + VisualStudioWorkspace workspace, + [ImportMany]IEnumerable> lazyOptions, + LanguageServerClientEventListener eventListener, + IAsynchronousOperationListenerProvider listenerProvider) + : base( + threadingContext, + workspace, + lazyOptions, + eventListener, + listenerProvider, + languageServerName: WellKnownServiceHubServices.CSharpLanguageServer, + serviceHubClientName: "ManagedLanguage.IDE.CSharpLanguageServer") + { + } + + public override string Name => CSharpVSResources.CSharp_language_server_client; + } +} diff --git a/src/VisualStudio/CSharp/Impl/Microsoft.VisualStudio.LanguageServices.CSharp.csproj b/src/VisualStudio/CSharp/Impl/Microsoft.VisualStudio.LanguageServices.CSharp.csproj index 465cfc4f07f9d..7393900e4f352 100644 --- a/src/VisualStudio/CSharp/Impl/Microsoft.VisualStudio.LanguageServices.CSharp.csproj +++ b/src/VisualStudio/CSharp/Impl/Microsoft.VisualStudio.LanguageServices.CSharp.csproj @@ -44,6 +44,7 @@ + @@ -52,6 +53,7 @@ + diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.cs.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.cs.xlf index 8c90066dbb66e..cb5ae7383da53 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.cs.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.cs.xlf @@ -22,6 +22,11 @@ Pravidla formátování jazyka C# + + C# Language Server Client + Klient serveru pro jazyk C# + + Discard Zahodit diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.de.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.de.xlf index 5f53a001ebc32..bb2049f3ea696 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.de.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.de.xlf @@ -22,6 +22,11 @@ C#-Formatierungsregeln + + C# Language Server Client + Client des C#-Sprachservers + + Discard Verwerfen diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.es.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.es.xlf index d6802387f545d..4b5cca0c29f7d 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.es.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.es.xlf @@ -22,6 +22,11 @@ Reglas de formato de C# + + C# Language Server Client + Cliente de servidor del lenguaje C# + + Discard Descartar diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.fr.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.fr.xlf index 543f6ac52549a..82df1039d3d3b 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.fr.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.fr.xlf @@ -22,6 +22,11 @@ Règles de formatage C# + + C# Language Server Client + Client du serveur de langage C# + + Discard Annuler diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.it.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.it.xlf index 38b529e73d0de..2d81e0f43f5f9 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.it.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.it.xlf @@ -22,6 +22,11 @@ Regole di formattazione C# + + C# Language Server Client + Client del server di linguaggio C# + + Discard Scarta diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ja.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ja.xlf index bb4855b669333..5132e1beb4eae 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ja.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ja.xlf @@ -22,6 +22,11 @@ C# 書式ルール + + C# Language Server Client + C# 言語サーバー クライアント + + Discard 破棄 diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ko.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ko.xlf index b7c929b3246bb..eaa324016e162 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ko.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ko.xlf @@ -22,6 +22,11 @@ C# 서식 설정 규칙 + + C# Language Server Client + C# 언어 서버 클라이언트 + + Discard 폐기 diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pl.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pl.xlf index 289f9d9673767..ae1eea2811661 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pl.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pl.xlf @@ -22,6 +22,11 @@ Reguły formatowania kodu C# + + C# Language Server Client + Klient serwera języka C# + + Discard Odrzuć diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pt-BR.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pt-BR.xlf index 56b951eeff849..141a9ff02bb57 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pt-BR.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.pt-BR.xlf @@ -22,6 +22,11 @@ Regras de Formatação de C# + + C# Language Server Client + Cliente do Servidor de Linguagem C# + + Discard Descarte diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ru.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ru.xlf index 8dcb9824049df..435fd1ba0b8b1 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ru.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.ru.xlf @@ -22,6 +22,11 @@ Правила форматирования C# + + C# Language Server Client + Клиент языкового сервера C# + + Discard Отменить diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.tr.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.tr.xlf index e7dac25aedc02..accdfbe70229f 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.tr.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.tr.xlf @@ -22,6 +22,11 @@ C# biçimlendirme kuralları + + C# Language Server Client + C# Dil Sunucusu İstemcisi + + Discard At diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hans.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hans.xlf index f7b153bac677c..7cc2b6776674d 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hans.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hans.xlf @@ -22,6 +22,11 @@ C# 格式规则 + + C# Language Server Client + C# 语言服务器客户端 + + Discard 放弃 diff --git a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hant.xlf b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hant.xlf index bce79266dd88c..861168f9be421 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hant.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/CSharpVSResources.zh-Hant.xlf @@ -22,6 +22,11 @@ C# 格式化規則 + + C# Language Server Client + C# 語言伺服器用戶端 + + Discard 捨棄 diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.cs.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.cs.xlf index 022f7f9a6cb14..49e54408be1e0 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.cs.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.cs.xlf @@ -331,12 +331,12 @@ Zobrazovat návrhy názvů; C# Editor - Editor CSharp + Editor C# C# Editor with Encoding - Editor CSharp s kódováním + Editor C# s kódováním diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.de.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.de.xlf index c372d4d9b0720..63e85f480a05e 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.de.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.de.xlf @@ -331,12 +331,12 @@ Namensvorschläge anzeigen; C# Editor - CSharp-Editor + C#-Editor C# Editor with Encoding - CSharp-Editor mit Codierung + C#-Editor mit Codierung diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.es.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.es.xlf index 810fc4b10dc9b..39aac13fc3b2b 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.es.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.es.xlf @@ -331,12 +331,12 @@ Mostrar sugerencias de nombre; C# Editor - Editor de CSharp + Editor de C# C# Editor with Encoding - Editor de CSharp con Encoding + Editor de C# con Encoding diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.fr.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.fr.xlf index a04b1efc63d0e..7bf4e933c2731 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.fr.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.fr.xlf @@ -331,12 +331,12 @@ Afficher les suggestions de nom ; C# Editor - Éditeur CSharp + C# - Éditeur C# Editor with Encoding - Éditeur CSharp avec encodage + Éditeur C# avec encodage diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.it.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.it.xlf index 3eb75b6851fa3..61e9cbf8ee343 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.it.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.it.xlf @@ -265,7 +265,7 @@ Inserisci spazio prima e dopo gli operatori binari; Change formatting options for wrapping;leave block on single line;leave statements and member declarations on the same line - Modifica opzioni di formattazione per wrapping;Lascia blocco su una sola riga;Lascia istruzioni e dichiarazioni di membri sulla stessa riga + Modifica opzioni di formattazione per ritorno a capo;Lascia blocco su una sola riga;Lascia istruzioni e dichiarazioni di membri sulla stessa riga C# Formatting > Wrapping options page keywords @@ -331,12 +331,12 @@ Mostra suggerimenti per nomi; C# Editor - Editor CSharp + Editor C# C# Editor with Encoding - Editor CSharp con codifica + Editor C# con codifica diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ja.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ja.xlf index db7e84caff3b1..9de56661df06a 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ja.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ja.xlf @@ -331,12 +331,12 @@ Enter キーで常に新しい行を追加する; C# Editor - CSharp エディター + C# エディター C# Editor with Encoding - Encoding 付き CSharp エディター + エンコード付き C# エディター diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ko.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ko.xlf index cd3a0e5a6fd37..d39d7f64d2337 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ko.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ko.xlf @@ -331,12 +331,12 @@ Show name suggestions; C# Editor - CSharp 편집기 + C# 편집기 C# Editor with Encoding - CSharp 편집기(인코딩 사용) + C# 편집기(인코딩 사용) diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pl.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pl.xlf index 2514bbcdddaf1..59137892fcf52 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pl.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pl.xlf @@ -331,12 +331,12 @@ Pokaż sugestie dotyczące nazwy; C# Editor - Edytor CSharp + Edytor C# C# Editor with Encoding - Edytor CSharp z kodowaniem + Edytor C# z kodowaniem diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pt-BR.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pt-BR.xlf index d7550f15e20d4..31b27ef27e959 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pt-BR.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.pt-BR.xlf @@ -331,12 +331,12 @@ Mostrar sugestões de nomes; C# Editor - Editor CSharp + Editor C# C# Editor with Encoding - Editor CSharp com Codificação + Editor C# com Codificação diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ru.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ru.xlf index b98dc2ed953e2..67047e17777e5 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ru.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.ru.xlf @@ -331,12 +331,12 @@ Show name suggestions; C# Editor - Редактор CSharp + Редактор C# C# Editor with Encoding - Редактор CSharp с кодировкой + Редактор C# с кодировкой diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.tr.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.tr.xlf index 321aeac9984fd..7eea7f3799802 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.tr.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.tr.xlf @@ -331,12 +331,12 @@ Ad önerilerini göster; C# Editor - CSharp Düzenleyici + C# Düzenleyicisi C# Editor with Encoding - Encoding ile CSharp Düzenleyici + Kodlamalı C# Düzenleyicisi diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hans.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hans.xlf index eb8fe2fa3f981..9e411a335a8e7 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hans.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hans.xlf @@ -331,12 +331,12 @@ Show name suggestions; C# Editor - CSharp 编辑器 + C# 编辑器 C# Editor with Encoding - 带编码功能的 CSharp 编辑器 + 带编码功能的 C# 编辑器 diff --git a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hant.xlf b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hant.xlf index 42614f75e7054..c21e73ad9dcc0 100644 --- a/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hant.xlf +++ b/src/VisualStudio/CSharp/Impl/xlf/VSPackage.zh-Hant.xlf @@ -331,12 +331,12 @@ Show name suggestions; C# Editor - CSharp 編輯器 + C# 編輯器 C# Editor with Encoding - 具備編碼功能的 CSharp 編輯器 + 具備編碼功能的 C# 編輯器 diff --git a/src/VisualStudio/CSharp/Test/Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.csproj b/src/VisualStudio/CSharp/Test/Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.csproj index 07059ab2e18dc..88e94c6d9f616 100644 --- a/src/VisualStudio/CSharp/Test/Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.csproj +++ b/src/VisualStudio/CSharp/Test/Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.csproj @@ -62,6 +62,7 @@ + diff --git a/src/VisualStudio/CodeLens/Microsoft.VisualStudio.LanguageServices.CodeLens.csproj b/src/VisualStudio/CodeLens/Microsoft.VisualStudio.LanguageServices.CodeLens.csproj index 97d6fccc60f15..d64a8fb554631 100644 --- a/src/VisualStudio/CodeLens/Microsoft.VisualStudio.LanguageServices.CodeLens.csproj +++ b/src/VisualStudio/CodeLens/Microsoft.VisualStudio.LanguageServices.CodeLens.csproj @@ -34,6 +34,8 @@ + + diff --git a/src/VisualStudio/Core/Def/Implementation/AbstractVsTextViewFilter`2.cs b/src/VisualStudio/Core/Def/Implementation/AbstractVsTextViewFilter`2.cs index b2a0ddb64b1e0..ba52de281caf6 100644 --- a/src/VisualStudio/Core/Def/Implementation/AbstractVsTextViewFilter`2.cs +++ b/src/VisualStudio/Core/Def/Implementation/AbstractVsTextViewFilter`2.cs @@ -20,7 +20,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation { - internal abstract class AbstractVsTextViewFilter : AbstractVsTextViewFilter, IVsTextViewFilter, IVsReadOnlyViewNotification + internal abstract class AbstractVsTextViewFilter : AbstractVsTextViewFilter, IVsTextViewFilter where TPackage : AbstractPackage where TLanguageService : AbstractLanguageService { @@ -122,39 +122,5 @@ private int GetPairExtentsWorker(int iLine, int iIndex, TextSpan[] pSpan, Cancel int IVsTextViewFilter.GetWordExtent(int iLine, int iIndex, uint dwFlags, TextSpan[] pSpan) => VSConstants.E_NOTIMPL; - - #region Edit and Continue - - int IVsReadOnlyViewNotification.OnDisabledEditingCommand(ref Guid pguidCmdGuid, uint dwCmdId) - { - var container = GetSubjectBufferContainingCaret().AsTextContainer(); - if (!CodeAnalysis.Workspace.TryGetWorkspace(container, out var workspace)) - { - return VSConstants.S_OK; - } - - var vsWorkspace = workspace as VisualStudioWorkspaceImpl; - if (vsWorkspace == null) - { - return VSConstants.S_OK; - } - - foreach (var documentId in vsWorkspace.GetRelatedDocumentIds(container)) - { - var project = VsENCRebuildableProjectImpl.TryGetRebuildableProject(documentId.ProjectId); - - if (project != null) - { - if (project.OnEdit(documentId)) - { - break; - } - } - } - - return VSConstants.S_OK; - } - - #endregion } } diff --git a/src/VisualStudio/Core/Def/Implementation/CallHierarchy/CallHierarchyCommandHandler.cs b/src/VisualStudio/Core/Def/Implementation/CallHierarchy/CallHierarchyCommandHandler.cs index a20e6f55e69a1..534dbb332dab8 100644 --- a/src/VisualStudio/Core/Def/Implementation/CallHierarchy/CallHierarchyCommandHandler.cs +++ b/src/VisualStudio/Core/Def/Implementation/CallHierarchy/CallHierarchyCommandHandler.cs @@ -5,6 +5,7 @@ using System.Linq; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.SymbolMapping; @@ -23,14 +24,19 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy [Order(After = PredefinedCommandHandlerNames.DocumentationComments)] internal class CallHierarchyCommandHandler : VSCommanding.ICommandHandler { + private readonly IThreadingContext _threadingContext; private readonly ICallHierarchyPresenter _presenter; private readonly CallHierarchyProvider _provider; public string DisplayName => EditorFeaturesResources.Call_Hierarchy; [ImportingConstructor] - public CallHierarchyCommandHandler([ImportMany] IEnumerable presenters, CallHierarchyProvider provider) + public CallHierarchyCommandHandler( + IThreadingContext threadingContext, + [ImportMany] IEnumerable presenters, + CallHierarchyProvider provider) { + _threadingContext = threadingContext; _presenter = presenters.FirstOrDefault(); _provider = provider; } @@ -40,8 +46,8 @@ public bool ExecuteCommand(ViewCallHierarchyCommandArgs args, CommandExecutionCo using (var waitScope = context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesResources.Computing_Call_Hierarchy_Information)) { var cancellationToken = context.OperationContext.UserCancellationToken; - var document = args.SubjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync( - context.OperationContext).WaitAndGetResult(cancellationToken); + var document = args.SubjectBuffer.CurrentSnapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( + context.OperationContext, _threadingContext); if (document == null) { return true; diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/DebugLogMessage.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/DebugLogMessage.cs deleted file mode 100644 index 8646915398a48..0000000000000 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/DebugLogMessage.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using Microsoft.CodeAnalysis.EditAndContinue; -using Microsoft.CodeAnalysis.Internal.Log; -using Roslyn.Utilities; - -namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue -{ - internal static class DebugLogMessage - { - private const string SessionId = nameof(SessionId); - private const string EditSessionId = nameof(EditSessionId); - - private const string SessionCount = nameof(SessionCount); - private const string EmptySessionCount = nameof(EmptySessionCount); - private const string ReadOnlyEditAttemptedProjectNotBuiltOrLoaded = nameof(ReadOnlyEditAttemptedProjectNotBuiltOrLoaded); - - private const string HadCompilationErrors = nameof(HadCompilationErrors); - private const string HadRudeEdits = nameof(HadRudeEdits); - private const string HadValidChanges = nameof(HadValidChanges); - private const string HadValidInsignificantChanges = nameof(HadValidInsignificantChanges); - private const string RudeEditsCount = nameof(RudeEditsCount); - private const string EmitDeltaErrorIdCount = nameof(EmitDeltaErrorIdCount); - - private const string ErrorId = nameof(ErrorId); - - private const string RudeEditKind = nameof(RudeEditKind); - private const string RudeEditSyntaxKind = nameof(RudeEditSyntaxKind); - private const string RudeEditBlocking = nameof(RudeEditBlocking); - - public static KeyValueLogMessage Create(int sessionId, EncDebuggingSessionInfo session) - { - return KeyValueLogMessage.Create(m => CreateSessionKeyValue(m, sessionId, session)); - } - - public static KeyValueLogMessage Create(int sessionId, int editSessionId, EncEditSessionInfo editSession) - { - return KeyValueLogMessage.Create(m => CreateSessionEditKeyValue(m, sessionId, editSessionId, editSession)); - } - - public static KeyValueLogMessage Create(int sessionId, int editSessionId, string error) - { - return KeyValueLogMessage.Create(m => CreateEditSessionErrorId(m, sessionId, editSessionId, error)); - } - - public static KeyValueLogMessage Create(int sessionId, int editSessionId, ValueTuple rudeEdit, bool blocking) - { - return KeyValueLogMessage.Create(m => CreateEditSessionRudeEdit(m, sessionId, editSessionId, rudeEdit, blocking)); - } - - public static int GetNextId() - { - return LogAggregator.GetNextId(); - } - - private static void CreateSessionKeyValue(Dictionary map, int sessionId, EncDebuggingSessionInfo session) - { - map[SessionId] = sessionId; - map[SessionCount] = session.EditSessions.Count; - map[EmptySessionCount] = session.EmptyEditSessions; - } - - private static void CreateSessionEditKeyValue(Dictionary map, int sessionId, int editSessionId, EncEditSessionInfo editSession) - { - map[SessionId] = sessionId; - map[EditSessionId] = editSessionId; - - map[HadCompilationErrors] = editSession.HadCompilationErrors; - map[HadRudeEdits] = editSession.HadRudeEdits; - map[HadValidChanges] = editSession.HadValidChanges; - map[HadValidInsignificantChanges] = editSession.HadValidInsignificantChanges; - - map[RudeEditsCount] = editSession.RudeEdits.Count; - map[EmitDeltaErrorIdCount] = editSession.EmitDeltaErrorIds != null ? editSession.EmitDeltaErrorIds.Count() : 0; - } - - private static void CreateEditSessionErrorId(Dictionary map, int sessionId, int editSessionId, string error) - { - map[SessionId] = sessionId; - map[EditSessionId] = editSessionId; - - map[ErrorId] = error; - } - - private static void CreateEditSessionRudeEdit(Dictionary map, int sessionId, int editSessionId, ValueTuple rudeEdit, bool blocking) - { - map[SessionId] = sessionId; - map[EditSessionId] = editSessionId; - - map[RudeEditKind] = rudeEdit.Item1; - map[RudeEditSyntaxKind] = rudeEdit.Item2; - map[RudeEditBlocking] = blocking; - } - } -} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/DebuggerComponent.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/DebuggerComponent.cs index 768098c54f156..2f793aaa280f6 100644 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/DebuggerComponent.cs +++ b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/DebuggerComponent.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Threading; using Microsoft.VisualStudio.Debugger; namespace Microsoft.VisualStudio.LanguageServices.EditAndContinue @@ -22,7 +23,15 @@ public struct ThreadInitializer : IDisposable public ThreadInitializer(Guid id) { - DkmComponentManager.InitializeThread(id, out _alreadyInitialized); + if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) + { + _alreadyInitialized = true; + } + else + { + DkmComponentManager.InitializeThread(id, out _alreadyInitialized); + } + _id = id; } diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/ENCPROG_ACTIVE_STATEMENT_REMAP.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/ENCPROG_ACTIVE_STATEMENT_REMAP.cs deleted file mode 100644 index 1974240348674..0000000000000 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/ENCPROG_ACTIVE_STATEMENT_REMAP.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Runtime.InteropServices; - -namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop -{ - [StructLayout(LayoutKind.Sequential)] - internal struct ENCPROG_ACTIVE_STATEMENT_REMAP - { - public Guid ThreadId; - public int MethodToken; - public int OldMethodVersion; - public int OldILOffset; - public int NewStartLine; - public int NewStartCol; - public int NewEndLine; - public int NewEndCol; - } -} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/ENCPROG_EXCEPTION_RANGE.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/ENCPROG_EXCEPTION_RANGE.cs deleted file mode 100644 index e0b06e959f38d..0000000000000 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/ENCPROG_EXCEPTION_RANGE.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Runtime.InteropServices; - -namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop -{ - [StructLayout(LayoutKind.Sequential)] - internal struct ENCPROG_EXCEPTION_RANGE - { - public int MethodToken; - public int MethodVersion; - public int StartLine; - public int StartCol; - public int EndLine; - public int EndCol; - public int Delta; - } -} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/IDebugEncNotify.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/IDebugEncNotify.cs deleted file mode 100644 index 10e93567adb88..0000000000000 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/IDebugEncNotify.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Runtime.InteropServices; - -namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop -{ - [ComImport] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - [Guid("347C45E1-5C42-4e0e-9E15-DEFF9CFC7841")] - internal interface IDebugEncNotify - { - // This method allows the ENCManager to tell the package that ENC - // is not available as soon as it can be determined rather than waiting for a call from the package. - void __NotifyEncIsUnavailable(/*EncUnavailableReason reason,bool fEditWasApplied*/); - - // This method allows the Lang Service to Notify the package that the Current Statement - // must be updated due to an edit. - void NotifyEncUpdateCurrentStatement(); - - // This method allows the Lang Service to Notify the package that an edit was attempted - // when the debuggee is in a state that cannot accept changes. - void NotifyEncEditAttemptedAtInvalidStopState(); - - // This allows the Lang Service or project to tell the package that it prevented - // an edit from occurring. - // The package is responsible for asking the ENC manager why ENC would not be - // allowed at this point. - void NotifyEncEditDisallowedByProject([MarshalAs(UnmanagedType.IUnknown)]object pProject); - } -} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/IDebugUpdateInMemoryPE.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/IDebugUpdateInMemoryPE.cs deleted file mode 100644 index f66a1832c9651..0000000000000 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/IDebugUpdateInMemoryPE.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.ComTypes; -using Microsoft.CodeAnalysis.EditAndContinue; - -namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop -{ - [StructLayout(LayoutKind.Sequential)] - internal struct LINEUPDATE - { - public uint Line; - public uint UpdatedLine; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct LINEDELTA - { - public uint MethodToken; - public int Delta; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct FILEUPDATE - { - [MarshalAs(UnmanagedType.BStr)] - public string FileName; - - /// - /// This is really an pointer to an array of "cLineUpdate" LINEUPDATE struct. - /// - public IntPtr LineUpdates; - - public uint LineUpdateCount; - } - - [ComImport] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - [Guid("9E2BD568-7CEE-4166-ABC9-495BA8D3054A")] - internal interface IDebugUpdateInMemoryPE - { - void GetMetadataEmit([MarshalAs(UnmanagedType.IUnknown)]out object ppMetadataEmit); - - // The compiler must provide updated IL for modified - // methods. - void SetDeltaIL([In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]byte[] pbIL, uint cbIL); - - // This stream holds the pdb output of recompiling - // modified methods. See ISymUnmanagedWriter. - void SetDeltaPdb(IStream pDeltaPdbStream); - - // The LangSvc is required to provide line information - // for non-recompiled methods that have moved source location. - // Any method where line movement cannot be represented - // by a single delta must be recompiled and represented in - // the delta pdb. - void SetDeltaLines([In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]LINEDELTA[] pMethodLocationDeltas, uint cMethodLocationDeltas); - - // This method is used to determine the current slot - // location of local variables. - void GetENCDebugInfo(out IENCDebugInfo ppDebugInfo); - - // This method provides the debugger with the tokens of methods - // that have been compiled in the update. - void SetRemapMethods([In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]int[] pmdRemapMethodTokens, uint cRemapMethods); - - // This is an alternative to SetDeltaLines. It is subject to - // the same restriction as SetDeltaLines in that it can only update - // whole methods. It is provided for lang services that cannot - // determine the method tokens for all methods in a file. - // The lineUpdates array in each FILEUPDATE provides the line from the - // last version of the file and where it is in the new version of the file. - // Both lines, and lineUpdates must be in monotonically increasing order - // within the array. - void SetFileUpdates([In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]FILEUPDATE[] pFileUpdates, [In]uint cFileUpdates); - } - - [ComImport] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - [Guid("8A9E5AAE-BEF6-47A8-879B-690463516D73")] - internal interface IDebugUpdateInMemoryPE2 : IDebugUpdateInMemoryPE - { - // leave a vtable gap for IDebugUpdateInMemoryPE methods - void _VtblGap0_7(); - - void GetMetadataByteCount(out uint cb); - - void GetMetadataBytes(uint cb, IntPtr pbMetadata, out uint cbFetched); - - void SetDeltaMetadata([In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]byte[] pbMetadata, uint cbMetadata); - } - - [ComImport] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - [Guid("AE2FF3A4-2FA6-487C-AE74-9FB3D9276742")] - internal interface IDebugUpdateInMemoryPE3 : IDebugUpdateInMemoryPE2 - { - // leave a vtable gap for IDebugUpdateInMemoryPE2 methods - void _VtblGap0_10(); - - void SetExceptionRanges([In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]ENCPROG_EXCEPTION_RANGE[] pRanges, int cRanges); - void SetRemapActiveStatements([In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]ENCPROG_ACTIVE_STATEMENT_REMAP[] pRemapActiveStatements, int cRemapActiveStatements); - } -} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/IENCDebugInfo.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/IENCDebugInfo.cs deleted file mode 100644 index 9f866d71ba36b..0000000000000 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/IENCDebugInfo.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Runtime.InteropServices; - -namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop -{ - [StructLayout(LayoutKind.Sequential)] - internal struct ENC_LOCALINFO - { - [MarshalAs(UnmanagedType.BStr)] - public readonly string LocalName; // SysFreeString - - public readonly uint Attributes; - - public readonly IntPtr Signature; // CoTaskMemFree this - public readonly int SignatureSize; - - public readonly int Slot; - } - - [ComImport] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - [Guid("1DA15C39-7E02-4ee8-8F60-FFF81275EE14")] - internal interface IENCDebugInfo - { - [PreserveSig] - int GetLocalVariableCount(uint methodToken, out int pcLocals); - - [PreserveSig] - int GetLocalVariableLayout( - uint methodToken, - int cLocals, - [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] ENC_LOCALINFO[] rgLocalInfo, - out int pceltFetched); - - // not implemented in Concord: - void __GetCountOfExpressionContextsForMethod(/*...*/); - void __GetExpressionContextsForMethod(/*...*/); - } -} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/IENCSymbolReaderProvider.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/IENCSymbolReaderProvider.cs deleted file mode 100644 index 4c9a6d94b5d15..0000000000000 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/IENCSymbolReaderProvider.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Runtime.InteropServices; - -namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop -{ - [ComImport] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - [Guid("B69910A9-4AD6-475F-859A-5DC0B1072A5D")] - internal interface IENCSymbolReaderProvider - { - void GetSymbolReader([MarshalAs(UnmanagedType.IUnknown)] out object ppSymbolReader); - } -} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/NativeMethods.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/NativeMethods.cs deleted file mode 100644 index f79afbf2a36ca..0000000000000 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/Interop/NativeMethods.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Runtime.InteropServices; - -namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop -{ - internal static class NativeMethods - { - private static Guid s_IID_IUnknown = new Guid(0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46); - - [DllImport("ole32.dll")] - private static extern int CoMarshalInterThreadInterfaceInStream([In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] object pUnk, out IntPtr ppStm); - - [DllImport("ole32.dll")] - private static extern int CoGetInterfaceAndReleaseStream(IntPtr pStm, [In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); - - public static int GetStreamForObject(object pUnk, out IntPtr stream) - { - return CoMarshalInterThreadInterfaceInStream(ref s_IID_IUnknown, pUnk, out stream); - } - - public static object GetObjectAndRelease(IntPtr stream) - { - Marshal.ThrowExceptionForHR(CoGetInterfaceAndReleaseStream(stream, ref s_IID_IUnknown, out var pUnk)); - return pUnk; - } - } -} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/ModuleUtilities.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/ModuleUtilities.cs new file mode 100644 index 0000000000000..ed46d00255255 --- /dev/null +++ b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/ModuleUtilities.cs @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Immutable; +using System.Diagnostics; +using System.IO; +using System.Runtime.CompilerServices; +using System.Threading; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.EditAndContinue; +using Microsoft.CodeAnalysis.Text; +using Microsoft.DiaSymReader; +using Microsoft.VisualStudio.Debugger.Clr; +using Microsoft.VisualStudio.Debugger.UI.Interfaces; +using Roslyn.Utilities; + +namespace Microsoft.VisualStudio.LanguageServices.EditAndContinue +{ + internal static class ModuleUtilities + { + internal static bool TryGetModuleInfo(this DkmClrModuleInstance module, out DebuggeeModuleInfo info) + { + Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA, "SymReader requires MTA"); + + IntPtr metadataPtr; + uint metadataSize; + try + { + metadataPtr = module.GetBaselineMetaDataBytesPtr(out metadataSize); + } + catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) + { + info = null; + return false; + } + + var symReader = module.GetSymUnmanagedReader() as ISymUnmanagedReader5; + if (symReader == null) + { + info = null; + return false; + } + + var metadata = ModuleMetadata.CreateFromMetadata(metadataPtr, (int)metadataSize); + info = new DebuggeeModuleInfo(metadata, symReader); + return true; + } + + internal static ManagedModuleUpdate ToModuleUpdate(this Deltas delta) + { + var sequencePointUpdates = delta.LineEdits.SelectAsArray(documentChanges => new SequencePointsUpdate( + fileName: documentChanges.SourceFilePath, + lineUpdates: documentChanges.Deltas.SelectAsArray(lineChange => new SourceLineUpdate(lineChange.OldLine, lineChange.NewLine)))); + + TextManager.Interop.TextSpan toDebuggerSpan(LinePositionSpan span, int lineDelta) + => new TextManager.Interop.TextSpan() + { + // the debugger expects these to be 0-based + iStartLine = span.Start.Line + lineDelta, + iStartIndex = span.Start.Character, + iEndLine = span.End.Line + lineDelta, + iEndIndex = span.End.Character, + }; + + var activeStatementUpdates = delta.ActiveStatementsInUpdatedMethods.SelectAsArray(activeStatement => new ActiveStatementUpdate( + threadId: activeStatement.ThreadId, + methodToken: activeStatement.OldInstructionId.MethodId.Token, + methodVersion: activeStatement.OldInstructionId.MethodId.Version, + ilOffset: activeStatement.OldInstructionId.ILOffset, + newSpan: toDebuggerSpan(activeStatement.NewSpan, 0))); + + var exceptionRegions = delta.NonRemappableRegions.SelectAsArray( + predicate: regionInfo => regionInfo.Region.IsExceptionRegion, + selector: regionInfo => new ExceptionRegionUpdate( + methodToken: regionInfo.Method.Token, + methodVersion: regionInfo.Method.Version, + newSpan: toDebuggerSpan(regionInfo.Region.Span, regionInfo.Region.LineDelta), + // The range span is the new span. Deltas are inverse. + // old = new + delta + // new = old – delta + delta: -regionInfo.Region.LineDelta)); + + return new ManagedModuleUpdate( + delta.Mvid, + delta.IL.Value, + delta.Metadata.Bytes, + delta.Pdb.Stream, + sequencePointUpdates, + delta.Pdb.UpdatedMethods, + activeStatementUpdates, + exceptionRegions); + } + + internal static ManagedModuleUpdateStatus ToModuleUpdateStatus(this SolutionUpdateStatus status) + { + switch (status) + { + case SolutionUpdateStatus.None: + return ManagedModuleUpdateStatus.None; + + case SolutionUpdateStatus.Ready: + return ManagedModuleUpdateStatus.Ready; + + case SolutionUpdateStatus.Blocked: + return ManagedModuleUpdateStatus.Blocked; + + default: + throw ExceptionUtilities.UnexpectedValue(status); + } + } + } +} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioActiveStatementTracker.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioActiveStatementTracker.cs index 5b94d6c1bfca7..c82935a8f82d6 100644 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioActiveStatementTracker.cs +++ b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioActiveStatementTracker.cs @@ -14,18 +14,18 @@ namespace Microsoft.VisualStudio.LanguageServices.EditAndContinue [Export(typeof(IManagedActiveStatementTracker)), Shared] internal sealed class VisualStudioActiveStatementTracker : IManagedActiveStatementTracker { - private readonly IEditAndContinueService _editAndContinueService; + private readonly IEditAndContinueWorkspaceService _encService; [ImportingConstructor] - public VisualStudioActiveStatementTracker(IEditAndContinueService editAndContinueService) + public VisualStudioActiveStatementTracker(VisualStudioWorkspace workspace) { - _editAndContinueService = editAndContinueService; + _encService = workspace.Services.GetRequiredService(); } public async Task GetCurrentActiveStatementPositionAsync(Guid moduleId, int methodToken, int methodVersion, int ilOffset, CancellationToken cancellationToken) - => (await _editAndContinueService.GetCurrentActiveStatementPositionAsync(new ActiveInstructionId(moduleId, methodToken, methodVersion, ilOffset), cancellationToken).ConfigureAwait(false))?.ToVsTextSpan(); + => (await _encService.GetCurrentActiveStatementPositionAsync(new ActiveInstructionId(moduleId, methodToken, methodVersion, ilOffset), cancellationToken).ConfigureAwait(false))?.ToVsTextSpan(); public Task IsActiveStatementInExceptionRegionAsync(Guid moduleId, int methodToken, int methodVersion, int ilOffset, CancellationToken cancellationToken) - => _editAndContinueService.IsActiveStatementInExceptionRegionAsync(new ActiveInstructionId(moduleId, methodToken, methodVersion, ilOffset), cancellationToken); + => _encService.IsActiveStatementInExceptionRegionAsync(new ActiveInstructionId(moduleId, methodToken, methodVersion, ilOffset), cancellationToken); } } diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioDebugStateChangeListener.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioDebugStateChangeListener.cs new file mode 100644 index 0000000000000..ccf64817e439d --- /dev/null +++ b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioDebugStateChangeListener.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.ComponentModel.Composition; +using Microsoft.CodeAnalysis.Debugging; +using Microsoft.CodeAnalysis.EditAndContinue; +using Microsoft.VisualStudio.Debugger; +using Microsoft.VisualStudio.Debugger.Clr; +using Microsoft.VisualStudio.Debugger.ComponentInterfaces; +using Microsoft.VisualStudio.Debugger.UI.Interfaces; + +namespace Microsoft.VisualStudio.LanguageServices.EditAndContinue +{ + [Export(typeof(IDebugStateChangeListener))] + internal sealed class VisualStudioDebugStateChangeListener : IDebugStateChangeListener + { + private readonly IDebuggingWorkspaceService _debuggingService; + private readonly IEditAndContinueWorkspaceService _encService; + private readonly VisualStudioDebuggeeModuleMetadataProvider _moduleMetadataProvider; + + /// + /// Concord component. Singleton created on demand during debugging session and discarded as soon as the session ends. + /// + private sealed class DebuggerService : IDkmCustomMessageForwardReceiver, IDkmModuleInstanceLoadNotification, IDkmModuleInstanceUnloadNotification + { + private VisualStudioDebugStateChangeListener _listener; + + /// + /// Message source id as specified in ManagedEditAndContinueService.vsdconfigxml. + /// + public static readonly Guid MessageSourceId = new Guid("730432E7-1B68-4B3A-BD6A-BD4C13E0566B"); + + DkmCustomMessage IDkmCustomMessageForwardReceiver.SendLower(DkmCustomMessage customMessage) + { + _listener = (VisualStudioDebugStateChangeListener)customMessage.Parameter1; + return null; + } + + /// + /// is implemented by components that want to listen + /// for the ModuleInstanceLoad event. When this notification fires, the target process + /// will be suspended and can be examined. ModuleInstanceLoad is fired when a module is + /// loaded by a target process. Among other things, this event is used for symbol + /// providers to load symbols, and for the breakpoint manager to set breakpoints. + /// ModuleInstanceLoad fires for all modules, even if there are no symbols loaded. + /// + void IDkmModuleInstanceLoadNotification.OnModuleInstanceLoad(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptorS eventDescriptor) + { + if (moduleInstance is DkmClrModuleInstance clrModuleInstance) + { + _listener.OnManagedModuleInstanceLoaded(clrModuleInstance); + } + } + + /// + /// is implemented by components that want to listen + /// for the ModuleInstanceUnload event. When this notification fires, the target process + /// will be suspended and can be examined. ModuleInstanceUnload is sent when the monitor + /// detects that a module has unloaded from within the target process. + /// + public void OnModuleInstanceUnload(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptor eventDescriptor) + { + if (moduleInstance is DkmClrModuleInstance clrModuleInstance) + { + _listener.OnManagedModuleInstanceUnloaded(clrModuleInstance); + } + } + } + + [ImportingConstructor] + public VisualStudioDebugStateChangeListener(VisualStudioWorkspace workspace, VisualStudioDebuggeeModuleMetadataProvider moduleMetadataProvider) + { + _moduleMetadataProvider = moduleMetadataProvider; + _debuggingService = workspace.Services.GetRequiredService(); + _encService = workspace.Services.GetRequiredService(); + } + + public void StartDebugging() + { + // hook up a callbacks (the call blocks until the message is processed): + using (DebuggerComponent.ManagedEditAndContinueService()) + { + DkmCustomMessage.Create( + Connection: null, + Process: null, + SourceId: DebuggerService.MessageSourceId, + MessageCode: 0, + Parameter1: this, + Parameter2: null).SendLower(); + } + + _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); + + _encService.StartDebuggingSession(); + } + + public void EnterBreakState(BreakStateKind kind) + { + // When stopped at exception - start an edit session as usual and report a rude edit for all changes we see. + bool stoppedAtException = kind == BreakStateKind.StoppedAtException; + + _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); + _encService.StartEditSession(); + } + + public void ExitBreakState() + { + _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); + _encService.EndEditSession(); + } + + public void StopDebugging() + { + _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); + _encService.EndDebuggingSession(); + } + + internal void OnManagedModuleInstanceLoaded(DkmClrModuleInstance moduleInstance) + => _encService.OnManagedModuleInstanceLoaded(moduleInstance.Mvid); + + internal void OnManagedModuleInstanceUnloaded(DkmClrModuleInstance moduleInstance) + => _encService.OnManagedModuleInstanceUnloaded(moduleInstance.Mvid); + } +} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/DebuggeeModuleMetadataProvider.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioDebuggeeModuleMetadataProvider.cs similarity index 54% rename from src/VisualStudio/Core/Def/Implementation/EditAndContinue/DebuggeeModuleMetadataProvider.cs rename to src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioDebuggeeModuleMetadataProvider.cs index f99d342b43988..537ef84afc821 100644 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/DebuggeeModuleMetadataProvider.cs +++ b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioDebuggeeModuleMetadataProvider.cs @@ -1,11 +1,11 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Collections.Generic; using System.Composition; -using System.Diagnostics; +using System.Linq; using System.Threading; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Debugging; +using System.Threading.Tasks; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger; @@ -15,8 +15,10 @@ namespace Microsoft.VisualStudio.LanguageServices.EditAndContinue { - [Export(typeof(IDebuggeeModuleMetadataProvider)), Shared] - internal sealed class DebuggeeModuleMetadataProvider : IDebuggeeModuleMetadataProvider + [Shared] + [Export(typeof(IDebuggeeModuleMetadataProvider))] + [Export(typeof(VisualStudioDebuggeeModuleMetadataProvider))] + internal sealed class VisualStudioDebuggeeModuleMetadataProvider : IDebuggeeModuleMetadataProvider { /// /// Concord component. Singleton created on demand during debugging session and discarded as soon as the session ends. @@ -30,10 +32,10 @@ private sealed class DebuggerService : IDkmCustomMessageForwardReceiver private sealed class DataItem : DkmDataItem { - private readonly DebuggeeModuleMetadataProvider _provider; + private readonly VisualStudioDebuggeeModuleMetadataProvider _provider; private readonly Guid _mvid; - public DataItem(DebuggeeModuleMetadataProvider provider, Guid mvid) + public DataItem(VisualStudioDebuggeeModuleMetadataProvider provider, Guid mvid) { _provider = provider; _mvid = mvid; @@ -44,20 +46,20 @@ public DataItem(DebuggeeModuleMetadataProvider provider, Guid mvid) DkmCustomMessage IDkmCustomMessageForwardReceiver.SendLower(DkmCustomMessage customMessage) { - var provider = (DebuggeeModuleMetadataProvider)customMessage.Parameter1; + var provider = (VisualStudioDebuggeeModuleMetadataProvider)customMessage.Parameter1; var clrModuleInstance = (DkmClrModuleInstance)customMessage.Parameter2; // Note that this call has to be made in a Concord component. - // The debugger tracks what the current component is and associates the data item with it. + // The debugger tracks what the current Concord component is and associates the data item with it. clrModuleInstance.SetDataItem(DkmDataCreationDisposition.CreateAlways, new DataItem(provider, clrModuleInstance.Mvid)); return null; } } private readonly DebuggeeModuleInfoCache _baselineMetadata; + private readonly object _moduleApplyGuard = new object(); - [ImportingConstructor] - public DebuggeeModuleMetadataProvider() + public VisualStudioDebuggeeModuleMetadataProvider() { _baselineMetadata = new DebuggeeModuleInfoCache(); } @@ -70,6 +72,7 @@ private void OnModuleInstanceUnload(Guid mvid) /// Shall only be called while in debug mode. /// Shall only be called on MTA thread. /// + /// Null, if the module with the specified MVID is not found. public DebuggeeModuleInfo TryGetBaselineModuleInfo(Guid mvid) { Contract.ThrowIfFalse(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); @@ -78,15 +81,22 @@ public DebuggeeModuleInfo TryGetBaselineModuleInfo(Guid mvid) { using (DebuggerComponent.ManagedEditAndContinueService()) { - var clrModuleInstance = FindClrModuleInstance(m); + var clrModuleInstance = EnumerateClrModuleInstances(m).FirstOrDefault(); if (clrModuleInstance == null) { - return default; + return null; } - if (!TryGetBaselineModuleInfo(clrModuleInstance, out var metadata, out var symReader)) + // The DebuggeeModuleInfo holds on a pointer to module metadata and on a SymReader instance. + // + // The module metadata lifetime is that of the module instance, so we need to stop using the module + // as soon as the module instance is unloaded. We do so by associating a DataItem with the module + // instance and removing the metadata from our cache when the DataItem is disposed. + // + // The SymReader instance is shared across all instancese of the module. + if (!clrModuleInstance.TryGetModuleInfo(out var info)) { - return default; + return null; } // hook up a callback on module unload (the call blocks until the message is processed): @@ -98,41 +108,35 @@ public DebuggeeModuleInfo TryGetBaselineModuleInfo(Guid mvid) Parameter1: this, Parameter2: clrModuleInstance).SendLower(); - return new DebuggeeModuleInfo(metadata, symReader); + return info; } }); } - private static bool TryGetBaselineModuleInfo(DkmClrModuleInstance module, out ModuleMetadata metadata, out ISymUnmanagedReader5 symReader) + /// + /// Check that EnC is available for all instances of the given module. + /// + public bool IsEditAndContinueAvailable(Guid mvid, out int errorCode, out string localizedMessage) { - Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); - - IntPtr metadataPtr; - uint metadataSize; - try + using (DebuggerComponent.ManagedEditAndContinueService()) { - metadataPtr = module.GetBaselineMetaDataBytesPtr(out metadataSize); - } - catch (Exception e) when (DkmExceptionUtilities.IsBadOrMissingMetadataException(e)) - { - metadata = null; - symReader = null; - return false; - } - - symReader = module.GetSymUnmanagedReader() as ISymUnmanagedReader5; - if (symReader == null) - { - metadata = null; - symReader = null; - return false; + foreach (var clrModuleInstance in EnumerateClrModuleInstances(mvid)) + { + var availability = clrModuleInstance.GetEncAvailability(out localizedMessage); + if (availability != DkmEncAvailableStatus.Available) + { + errorCode = (int)availability; + return false; + } + } } - metadata = ModuleMetadata.CreateFromMetadata(metadataPtr, (int)metadataSize); + errorCode = -1; + localizedMessage = null; return true; } - private static DkmClrModuleInstance FindClrModuleInstance(Guid mvid) + private static IEnumerable EnumerateClrModuleInstances(Guid? mvid) { foreach (var process in DkmProcess.GetProcesses()) { @@ -144,16 +148,32 @@ private static DkmClrModuleInstance FindClrModuleInstance(Guid mvid) { if (moduleInstance.TagValue == DkmModuleInstance.Tag.ClrModuleInstance && moduleInstance is DkmClrModuleInstance clrModuleInstance && - clrModuleInstance.Mvid == mvid) + (!mvid.HasValue || clrModuleInstance.Mvid == mvid.Value)) { - return clrModuleInstance; + yield return clrModuleInstance; } } } } } + } + + public void PrepareModuleForUpdate(Guid mvid) + { + // fire and forget + _ = Task.Run(new Action(() => + { + Contract.ThrowIfFalse(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); - return null; + using (DebuggerComponent.ManagedEditAndContinueService()) + { + var clrModuleInstance = EnumerateClrModuleInstances(mvid).FirstOrDefault(); + if (clrModuleInstance != null) + { + ((ISymUnmanagedEncUpdate)clrModuleInstance.GetSymUnmanagedReader()).InitializeForEnc(); + } + } + })); } } } diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioEditAndContinueService.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioEditAndContinueService.cs deleted file mode 100644 index 98b9caa7aefd6..0000000000000 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioEditAndContinueService.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Composition; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.EditAndContinue; - -namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue -{ - [Export(typeof(IEditAndContinueService)), Shared] - internal sealed class VisualStudioEditAndContinueService : EditAndContinueService - { - [ImportingConstructor] - public VisualStudioEditAndContinueService(IDiagnosticAnalyzerService diagnosticService, IActiveStatementProvider activeStatementProvider) - : base(diagnosticService, activeStatementProvider) - { - } - } -} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioManagedModuleUpdateProvider.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioManagedModuleUpdateProvider.cs new file mode 100644 index 0000000000000..16c243e170924 --- /dev/null +++ b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VisualStudioManagedModuleUpdateProvider.cs @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Immutable; +using System.Composition; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.EditAndContinue; +using Microsoft.CodeAnalysis.ErrorReporting; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.VisualStudio.Debugger.UI.Interfaces; +using Roslyn.Utilities; + +namespace Microsoft.VisualStudio.LanguageServices.EditAndContinue +{ + [Export(typeof(IEditAndContinueManagedModuleUpdateProvider)), Shared] + internal sealed class VisualStudioManagedModuleUpdateProvider : IEditAndContinueManagedModuleUpdateProvider + { + private readonly IEditAndContinueWorkspaceService _encService; + + [ImportingConstructor] + [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] + public VisualStudioManagedModuleUpdateProvider(VisualStudioWorkspace workspace) + { + _encService = workspace.Services.GetRequiredService(); + } + + public Task GetStatusAsync(CancellationToken cancellationToken) + => GetStatusAsync(null, cancellationToken); + + /// + /// Returns the state of the changes made to the source. + /// The EnC manager calls this to determine whether there are any changes to the source + /// and if so whether there are any rude edits. + /// + public async Task GetStatusAsync(string sourceFilePath, CancellationToken cancellationToken) + { + try + { + return (await _encService.GetSolutionUpdateStatusAsync(sourceFilePath, cancellationToken).ConfigureAwait(false)).ToModuleUpdateStatus(); + } + catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) + { + return ManagedModuleUpdateStatus.Blocked; + } + } + + public async Task GetManagedModuleUpdatesAsync(CancellationToken cancellationToken) + { + try + { + var (summary, deltas) = await _encService.EmitSolutionUpdateAsync(cancellationToken).ConfigureAwait(false); + return new ManagedModuleUpdates(summary.ToModuleUpdateStatus(), deltas.SelectAsArray(ModuleUtilities.ToModuleUpdate)); + } + catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) + { + _encService.ReportApplyChangesException(e.Message); + return new ManagedModuleUpdates(ManagedModuleUpdateStatus.Blocked, ImmutableArray.Empty); + } + } + + public void CommitUpdates() + { + try + { + _encService.CommitSolutionUpdate(); + } + catch (Exception e) when (FatalError.ReportWithoutCrash(e)) + { + } + } + + public void DiscardUpdates() + { + try + { + _encService.DiscardSolutionUpdate(); + } + catch (Exception e) when (FatalError.ReportWithoutCrash(e)) + { + } + } + } +} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VsENCRebuildableProjectImpl.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VsENCRebuildableProjectImpl.cs deleted file mode 100644 index a3ec953ad46c9..0000000000000 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VsENCRebuildableProjectImpl.cs +++ /dev/null @@ -1,1059 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Reflection.Metadata; -using System.Reflection.Metadata.Ecma335; -using System.Reflection.PortableExecutable; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Debugging; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.EditAndContinue; -using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; -using Microsoft.CodeAnalysis.Editor.Shared.Utilities; -using Microsoft.CodeAnalysis.Emit; -using Microsoft.CodeAnalysis.ErrorReporting; -using Microsoft.CodeAnalysis.Internal.Log; -using Microsoft.CodeAnalysis.Notification; -using Microsoft.CodeAnalysis.Text; -using Microsoft.DiaSymReader; -using Microsoft.VisualStudio.ComponentModelHost; -using Microsoft.VisualStudio.Editor; -using Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop; -using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; -using Microsoft.VisualStudio.Shell.Interop; -using Roslyn.Utilities; -using NativeMethods = Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop.NativeMethods; -using ShellInterop = Microsoft.VisualStudio.Shell.Interop; -using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; -using VsThreading = Microsoft.VisualStudio.Threading; - -namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue -{ - internal sealed class VsENCRebuildableProjectImpl - { - private readonly VisualStudioWorkspace _workspace; - private readonly VisualStudioProject _project; - - // number of projects that are in the debug state: - private static int s_debugStateProjectCount; - - // number of projects that are in the break state: - private static int s_breakStateProjectCount; - - // projects that entered the break state: - private static readonly List> s_breakStateEnteredProjects = new List>(); - private static readonly List> s_pendingNonRemappableRegions = new List>(); - - private static VsReadOnlyDocumentTracker s_readOnlyDocumentTracker; - - internal static readonly TraceLog log = new TraceLog(2048, "EnC"); - - private static Solution s_breakStateEntrySolution; - - private static EncDebuggingSessionInfo s_encDebuggingSessionInfo; - - private readonly IDebuggingWorkspaceService _debuggingService; - private readonly IEditAndContinueService _encService; - private readonly IActiveStatementTrackingService _trackingService; - private readonly IThreadingContext _threadingContext; - private readonly EditAndContinueDiagnosticUpdateSource _diagnosticProvider; - private readonly IDebugEncNotify _debugEncNotify; - private readonly INotificationService _notifications; - private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; - private readonly IDebuggeeModuleMetadataProvider _moduleMetadataProvider; - - #region Per Project State - - private bool _changesApplied; - - private ProjectAnalysisSummary _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; - private EmitBaseline _committedBaseline; - private EmitBaseline _pendingBaseline; - private Project _projectBeingEmitted; - private ImmutableArray<(ActiveMethodId Method, NonRemappableRegion Region)> _pendingNonRemappableRegions; - - private ImmutableArray _documentsWithEmitError = ImmutableArray.Empty; - - /// - /// Initialized when the project switches to debug state. - /// if the project has no output file or we can't read the MVID. - /// - private Guid _mvid; - - #endregion - - private readonly static ConditionalWeakTable _rebuildableProjectImpls = new ConditionalWeakTable(); - - private bool IsDebuggable => _mvid != Guid.Empty; - - internal VsENCRebuildableProjectImpl(VisualStudioWorkspace workspace, VisualStudioProject project, IServiceProvider serviceProvider) - { - Debug.Assert(workspace != null); - Debug.Assert(project != null); - - _workspace = workspace; - _project = project; - - _debuggingService = _workspace.Services.GetRequiredService(); - _trackingService = _workspace.Services.GetRequiredService(); - _notifications = _workspace.Services.GetService(); - - _debugEncNotify = (IDebugEncNotify)serviceProvider.GetService(typeof(SVsShellDebugger)); - - var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); - _threadingContext = componentModel.GetService(); - _diagnosticProvider = componentModel.GetService(); - _editorAdaptersFactoryService = componentModel.GetService(); - _moduleMetadataProvider = componentModel.GetService(); - _encService = _debuggingService.EditAndContinueServiceOpt; - - _rebuildableProjectImpls.Add(project.Id, this); - - Debug.Assert(_debugEncNotify != null); - Debug.Assert(_encService != null); - Debug.Assert(_trackingService != null); - Debug.Assert(_diagnosticProvider != null); - Debug.Assert(_editorAdaptersFactoryService != null); - Debug.Assert(_moduleMetadataProvider != null); - } - - internal static VsENCRebuildableProjectImpl TryGetRebuildableProject(ProjectId projectId) - { - _rebuildableProjectImpls.TryGetValue(projectId, out var rebuildableProject); - return rebuildableProject; - } - - // called from an edit filter if an edit of a read-only buffer is attempted: - internal bool OnEdit(DocumentId documentId) - { - if (_encService.IsProjectReadOnly(documentId.ProjectId, out var sessionReason, out var projectReason)) - { - OnReadOnlyDocumentEditAttempt(documentId, sessionReason, projectReason); - return true; - } - - return false; - } - - private void OnReadOnlyDocumentEditAttempt( - DocumentId documentId, - SessionReadOnlyReason sessionReason, - ProjectReadOnlyReason projectReason) - { - if (sessionReason == SessionReadOnlyReason.StoppedAtException) - { - _debugEncNotify.NotifyEncEditAttemptedAtInvalidStopState(); - return; - } - - if (documentId.ProjectId == _project.Id && _mvid != Guid.Empty) - { - _debugEncNotify.NotifyEncEditDisallowedByProject(_workspace.GetHierarchy(documentId.ProjectId)); - return; - } - - // NotifyEncEditDisallowedByProject is broken if the project isn't built at the time the debugging starts (debugger bug 877586). - string message; - if (sessionReason == SessionReadOnlyReason.Running) - { - message = ServicesVSResources.ChangesNotAllowedWhileCodeIsRunning; - } - else - { - Debug.Assert(sessionReason == SessionReadOnlyReason.None); - - switch (projectReason) - { - case ProjectReadOnlyReason.MetadataNotAvailable: - message = ServicesVSResources.ChangesNotAllowedIfProjectWasntBuildWhenDebuggingStarted; - break; - - case ProjectReadOnlyReason.NotLoaded: - message = ServicesVSResources.ChangesNotAllowedIFAssemblyHasNotBeenLoaded; - break; - - default: - throw ExceptionUtilities.UnexpectedValue(projectReason); - } - } - - _notifications.SendNotification(message, title: FeaturesResources.Edit_and_Continue1, severity: NotificationSeverity.Error); - } - - /// - /// Since we can't await asynchronous operations we need to wait for them to complete. - /// The default SynchronizationContext.Wait pumps messages giving the debugger a chance to - /// reenter our EnC implementation. To avoid that we use a specialized SynchronizationContext - /// that doesn't pump messages. We need to make sure though that the async methods we wait for - /// don't dispatch to foreground thread, otherwise we would end up in a deadlock. - /// - private static VsThreading.SpecializedSyncContext NonReentrantContext - { - get - { - return VsThreading.ThreadingTools.Apply(VsThreading.NoMessagePumpSyncContext.Default); - } - } - - public bool HasCustomMetadataEmitter() - { - return true; - } - - /// - /// Invoked when the debugger transitions from Design mode to Run mode or Break mode. - /// - public int StartDebuggingPE() - { - try - { - log.Write("Enter Debug Mode: project '{0}'", _project.Id.ToString()); - - // EnC service is global (per solution), but the debugger calls this for each project. - // Avoid starting the debug session if it has already been started. - if (_encService.DebuggingSession == null) - { - Debug.Assert(s_debugStateProjectCount == 0); - Debug.Assert(s_breakStateProjectCount == 0); - Debug.Assert(s_breakStateEnteredProjects.Count == 0); - Debug.Assert(s_pendingNonRemappableRegions.Count == 0); - - _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); - - _encService.StartDebuggingSession(_workspace.CurrentSolution); - s_encDebuggingSessionInfo = new EncDebuggingSessionInfo(); - - s_readOnlyDocumentTracker = new VsReadOnlyDocumentTracker(_threadingContext, _encService, _editorAdaptersFactoryService); - } - - var outputPath = _project.IntermediateOutputFilePath; - - // The project doesn't produce a debuggable binary or we can't read it. - // Continue on since the debugger ignores HResults and we need to handle subsequent calls. - if (outputPath != null) - { - try - { - _mvid = ReadMvid(outputPath); - } - catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException) - { - // If the project isn't referenced by the project being debugged it might not be built. - // In that case EnC is never allowed for the project, and thus we can assume the project hasn't entered debug state. - log.Write("StartDebuggingPE: '{0}' metadata file not found: '{1}'", _project.Id.ToString(), outputPath); - _mvid = Guid.Empty; - } - catch (Exception e) - { - log.Write("StartDebuggingPE: error reading MVID of '{0}' ('{1}'): {2}", _project.Id.ToString(), outputPath, e.Message); - _mvid = Guid.Empty; - ReportInternalError(InternalErrorCode.ErrorReadingFile, new[] { outputPath, e.Message }); - } - } - else - { - log.Write("StartDebuggingPE: project has no output path '{0}'", _project.Id.ToString()); - _mvid = Guid.Empty; - } - - if (_mvid != Guid.Empty) - { - // The debugger doesn't call EnterBreakStateOnPE for projects that don't have MVID. - // However a project that's initially not loaded (but it might be in future) enters - // both the debug and break states. - s_debugStateProjectCount++; - } - - // The HResult is ignored by the debugger. - return VSConstants.S_OK; - } - catch (Exception e) when (FatalError.ReportWithoutCrash(e)) - { - return VSConstants.E_FAIL; - } - } - - /// - /// Given a path to an assembly, returns its MVID (Module Version ID). - /// May throw. - /// - /// If the file at does not exist or cannot be accessed. - /// If the file is not an assembly or is somehow corrupted. - private static Guid ReadMvid(string filePath) - { - Debug.Assert(filePath != null); - Debug.Assert(PathUtilities.IsAbsolute(filePath)); - - using (var reader = new PEReader(FileUtilities.OpenRead(filePath))) - { - var metadataReader = reader.GetMetadataReader(); - var mvidHandle = metadataReader.GetModuleDefinition().Mvid; - var fileMvid = metadataReader.GetGuid(mvidHandle); - - return fileMvid; - } - } - - public int StopDebuggingPE() - { - try - { - log.Write("Exit Debug Mode: project '{0}'", _project.Id.ToString()); - Debug.Assert(s_breakStateEnteredProjects.Count == 0); - Debug.Assert(s_pendingNonRemappableRegions.Count == 0); - - // Clear the solution stored while projects were entering break mode. - // It should be cleared as soon as all tracked projects enter the break mode - // but if the entering break mode fails for some projects we should avoid leaking the solution. - Debug.Assert(s_breakStateEntrySolution == null); - s_breakStateEntrySolution = null; - - // EnC service is global (per solution), but the debugger calls this for each project. - // Avoid ending the debug session if it has already been ended. - if (_encService.DebuggingSession != null) - { - _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); - - _encService.EndDebuggingSession(); - LogEncSession(); - - s_encDebuggingSessionInfo = null; - s_readOnlyDocumentTracker.Dispose(); - s_readOnlyDocumentTracker = null; - } - - if (_mvid != Guid.Empty) - { - _mvid = Guid.Empty; - s_debugStateProjectCount--; - } - else - { - // an error might have been reported: - var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.InternalErrorId); - _diagnosticProvider.ClearDiagnostics(errorId, _workspace.CurrentSolution, _project.Id, documentIdOpt: null); - } - - _committedBaseline = null; - _projectBeingEmitted = null; - - // The HResult is ignored by the debugger. - return VSConstants.S_OK; - } - catch (Exception e) when (FatalError.ReportWithoutCrash(e)) - { - return VSConstants.E_FAIL; - } - } - - private static void LogEncSession() - { - var sessionId = DebugLogMessage.GetNextId(); - Logger.Log(FunctionId.Debugging_EncSession, DebugLogMessage.Create(sessionId, s_encDebuggingSessionInfo)); - - foreach (var editSession in s_encDebuggingSessionInfo.EditSessions) - { - var editSessionId = DebugLogMessage.GetNextId(); - Logger.Log(FunctionId.Debugging_EncSession_EditSession, DebugLogMessage.Create(sessionId, editSessionId, editSession)); - - if (editSession.EmitDeltaErrorIds != null) - { - foreach (var error in editSession.EmitDeltaErrorIds) - { - Logger.Log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, DebugLogMessage.Create(sessionId, editSessionId, error)); - } - } - - foreach (var rudeEdit in editSession.RudeEdits) - { - Logger.Log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, DebugLogMessage.Create(sessionId, editSessionId, rudeEdit, blocking: editSession.HadRudeEdits)); - } - } - } - - /// - /// Get MVID and file name of the project's output file. - /// - /// - /// The MVID is used by the debugger to identify modules loaded into debuggee that correspond to this project. - /// The path seems to be unused. - /// - /// The output file path might be different from the path of the module loaded into the process. - /// For example, the binary produced by the C# compiler is stores in obj directory, - /// and then copied to bin directory from which it is loaded to the debuggee. - /// - /// The binary produced by the compiler can also be rewritten by post-processing tools. - /// The debugger assumes that the MVID of the compiler's output file at the time we start debugging session - /// is the same as the MVID of the module loaded into debuggee. The original MVID might be different though. - /// - public int GetPEidentity(Guid[] pMVID, string[] pbstrPEName) - { - Debug.Assert(_encService.DebuggingSession != null); - - if (_mvid == Guid.Empty) - { - return VSConstants.E_FAIL; - } - - if (pMVID != null && pMVID.Length != 0) - { - pMVID[0] = _mvid; - } - - if (pbstrPEName != null && pbstrPEName.Length != 0) - { - var outputPath = _project.IntermediateOutputFilePath; - Debug.Assert(outputPath != null); - - pbstrPEName[0] = Path.GetFileName(outputPath); - } - - return VSConstants.S_OK; - } - - /// - /// Called by the debugger when entering a Break state. - /// - /// Reason for transition to Break state. - /// Statements active when the debuggee is stopped. - /// Length of . - public int EnterBreakStateOnPE(ENC_BREAKSTATE_REASON encBreakReason, ENC_ACTIVE_STATEMENT[] pActiveStatements, uint cActiveStatements) - { - try - { - using (NonReentrantContext) - { - log.Write("Enter {2}Break Mode: project '{0}', AS#: {1}", _project.Id.ToString(), pActiveStatements != null ? pActiveStatements.Length : -1, encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION ? "Exception " : ""); - - Debug.Assert(cActiveStatements == (pActiveStatements != null ? pActiveStatements.Length : 0)); - Debug.Assert(s_breakStateProjectCount < s_debugStateProjectCount); - Debug.Assert(s_breakStateProjectCount == s_breakStateEnteredProjects.Count); - Debug.Assert(s_pendingNonRemappableRegions.Count == 0); - Debug.Assert(IsDebuggable); - - if (s_breakStateEntrySolution == null) - { - _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); - - s_breakStateEntrySolution = _workspace.CurrentSolution; - - // TODO: This is a workaround for a debugger bug in which not all projects exit the break state. - // Reset the project count. - s_breakStateProjectCount = 0; - } - - ProjectReadOnlyReason state; - if (pActiveStatements != null) - { - state = ProjectReadOnlyReason.None; - } - else - { - // unfortunately the debugger doesn't provide details: - state = ProjectReadOnlyReason.NotLoaded; - } - - // If pActiveStatements is null the EnC Manager failed to retrieve the module corresponding - // to the project in the debuggee. We won't include such projects in the edit session. - s_breakStateEnteredProjects.Add(KeyValuePairUtil.Create(_project.Id, state)); - s_breakStateProjectCount++; - - // EnC service is global, but the debugger calls this for each project. - // Avoid starting the edit session until all projects enter break state. - if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount) - { - Debug.Assert(_encService.EditSession == null); - - // When stopped at exception: All documents are read-only, but the files might be changed outside of VS. - // So we start an edit session as usual and report a rude edit for all changes we see. - var stoppedAtException = encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION; - - var projectStates = ImmutableDictionary.CreateRange(s_breakStateEnteredProjects); - - _encService.StartEditSession(s_breakStateEntrySolution, projectStates, stoppedAtException); - _trackingService.StartTracking(_encService.EditSession); - - s_readOnlyDocumentTracker.UpdateWorkspaceDocuments(); - - // When tracking is started the tagger is notified and the active statements are highlighted. - // Add the handler that notifies the debugger *after* that initial tagger notification, - // so that it's not triggered unless an actual change in leaf AS occurs. - _trackingService.TrackingSpansChanged += TrackingSpansChanged; - } - } - - // The debugger ignores the result. - return VSConstants.S_OK; - } - catch (Exception e) when (FatalError.ReportWithoutCrash(e)) - { - return VSConstants.E_FAIL; - } - finally - { - // TODO: This is a workaround for a debugger bug. - // Ensure that the state gets reset even if if `GroupActiveStatements` throws an exception. - if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount) - { - // we don't need these anymore: - s_breakStateEnteredProjects.Clear(); - s_breakStateEntrySolution = null; - } - } - } - - private void TrackingSpansChanged(bool leafChanged) - { - //log.Write("Tracking spans changed: {0}", leafChanged); - - //if (leafChanged) - //{ - // // fire and forget: - // Application.Current.Dispatcher.InvokeAsync(() => - // { - // log.Write("Notifying debugger of active statement change."); - // var debugNotify = (IDebugEncNotify)_vsProject.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger)); - // debugNotify.NotifyEncUpdateCurrentStatement(); - // }); - //} - } - - // obsolete - public int GetExceptionSpanCount(out uint pcExceptionSpan) - => throw ExceptionUtilities.Unreachable; - - // obsolete - public int GetExceptionSpans(uint celt, ENC_EXCEPTION_SPAN[] rgelt, ref uint pceltFetched) - => throw ExceptionUtilities.Unreachable; - - // obsolete - public int GetCurrentActiveStatementPosition(uint vsId, VsTextSpan[] ptsNewPosition) - => throw ExceptionUtilities.Unreachable; - - // obsolete - public int GetCurrentExceptionSpanPosition(uint exceptionRegionId, VsTextSpan[] ptsNewPosition) - => throw ExceptionUtilities.Unreachable; - - /// - /// Returns the state of the changes made to the source. - /// The EnC manager calls this to determine whether there are any changes to the source - /// and if so whether there are any rude edits. - /// - public int GetENCBuildState(ENC_BUILD_STATE[] pENCBuildState) - { - try - { - using (NonReentrantContext) - { - Debug.Assert(pENCBuildState != null && pENCBuildState.Length == 1); - - // GetENCBuildState is called outside of edit session (at least) in following cases: - // 1) when the debugger is determining whether a source file checksum matches the one in PDB. - // 2) when the debugger is setting the next statement and a change is pending - // See CDebugger::SetNextStatement(CTextPos* pTextPos, bool WarnOnFunctionChange): - // - // pENC2->ExitBreakState(); - // >>> hr = GetCodeContextOfPosition(pTextPos, &pCodeContext, &pProgram, true, true); - // pENC2->EnterBreakState(m_pSession, GetEncBreakReason()); - // - // The debugger seem to expect ENC_NOT_MODIFIED in these cases, otherwise errors occur. - - if (_changesApplied || _encService.EditSession == null) - { - _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; - } - else - { - // Fetch the latest snapshot of the project and get an analysis summary for any changes - // made since the break mode was entered. - var currentProject = _workspace.CurrentSolution.GetProject(_project.Id); - if (currentProject == null) - { - // If the project has yet to be loaded into the solution (which may be the case, - // since they are loaded on-demand), then it stands to reason that it has not yet - // been modified. - // TODO (https://github.com/dotnet/roslyn/issues/1204): this check should be unnecessary, - // especially because projects themselves are always added to the workspace, even if their contents - // are not. - _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; - log.Write("Project '{0}' has not yet been loaded into the solution", _project.Id.ToString()); - } - else - { - _projectBeingEmitted = currentProject; - _lastEditSessionSummary = GetProjectAnalysisSummary(_projectBeingEmitted); - } - - _encService.EditSession.LogBuildState(_lastEditSessionSummary); - } - - switch (_lastEditSessionSummary) - { - case ProjectAnalysisSummary.NoChanges: - pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NOT_MODIFIED; - break; - - case ProjectAnalysisSummary.CompilationErrors: - pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_COMPILE_ERRORS; - break; - - case ProjectAnalysisSummary.RudeEdits: - pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NONCONTINUABLE_ERRORS; - break; - - case ProjectAnalysisSummary.ValidChanges: - case ProjectAnalysisSummary.ValidInsignificantChanges: - // The debugger doesn't distinguish between these two. - pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_APPLY_READY; - break; - - default: - throw ExceptionUtilities.UnexpectedValue(_lastEditSessionSummary); - } - - log.Write("EnC state of '{0}' queried: {1}{2}", - _project.Id.ToString(), - EncStateToString(pENCBuildState[0]), - _encService.EditSession != null ? "" : " (no session)"); - - return VSConstants.S_OK; - } - } - catch (Exception e) when (FatalError.ReportWithoutCrash(e)) - { - return VSConstants.E_FAIL; - } - } - - private static string EncStateToString(ENC_BUILD_STATE state) - { - switch (state) - { - case ENC_BUILD_STATE.ENC_NOT_MODIFIED: return "ENC_NOT_MODIFIED"; - case ENC_BUILD_STATE.ENC_NONCONTINUABLE_ERRORS: return "ENC_NONCONTINUABLE_ERRORS"; - case ENC_BUILD_STATE.ENC_COMPILE_ERRORS: return "ENC_COMPILE_ERRORS"; - case ENC_BUILD_STATE.ENC_APPLY_READY: return "ENC_APPLY_READY"; - default: return state.ToString(); - } - } - - private ProjectAnalysisSummary GetProjectAnalysisSummary(Project project) - { - if (!IsDebuggable) - { - return ProjectAnalysisSummary.NoChanges; - } - - var cancellationToken = default(CancellationToken); - return _encService.EditSession.GetProjectAnalysisSummaryAsync(project, cancellationToken).Result; - } - - public int ExitBreakStateOnPE() - { - try - { - using (NonReentrantContext) - { - // The debugger calls Exit without previously calling Enter if the project's MVID isn't available. - if (!IsDebuggable) - { - return VSConstants.S_OK; - } - - log.Write("Exit Break Mode: project '{0}'", _project.Id.ToString()); - - // EnC service is global, but the debugger calls this for each project. - // Avoid ending the edit session if it has already been ended. - if (_encService.EditSession != null) - { - Debug.Assert(s_breakStateProjectCount == s_debugStateProjectCount); - - _debuggingService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); - - _encService.EditSession.LogEditSession(s_encDebuggingSessionInfo); - - // If no edits were made the pending list will be empty and we need to keep the previous regions. - var newNonRemappableRegions = (s_pendingNonRemappableRegions.Count == 0) ? null : - GroupToImmutable( - from regionsPerModule in s_pendingNonRemappableRegions - from region in regionsPerModule - group region.Region by region.Method); - - _encService.EndEditSession(newNonRemappableRegions); - - s_pendingNonRemappableRegions.Clear(); - - _trackingService.EndTracking(); - - s_readOnlyDocumentTracker.UpdateWorkspaceDocuments(); - - _trackingService.TrackingSpansChanged -= TrackingSpansChanged; - } - - s_breakStateProjectCount--; - Debug.Assert(s_breakStateProjectCount >= 0); - - _changesApplied = false; - - _diagnosticProvider.ClearDiagnostics( - new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId), - _workspace.CurrentSolution, - _project.Id, - _documentsWithEmitError); - - _documentsWithEmitError = ImmutableArray.Empty; - } - - // HResult ignored by the debugger - return VSConstants.S_OK; - } - catch (Exception e) when (FatalError.ReportWithoutCrash(e)) - { - return VSConstants.E_FAIL; - } - } - - private static ImmutableDictionary> GroupToImmutable(IEnumerable> items) - { - var builder = ImmutableDictionary.CreateBuilder>(); - - foreach (var item in items) - { - builder.Add(item.Key, item.ToImmutableArray()); - } - - return builder.ToImmutable(); - } - - public unsafe int BuildForEnc(object pUpdatePE) - { - try - { - log.Write("Applying changes to {0}", _project.Id.ToString()); - - Debug.Assert(_encService.EditSession != null); - Debug.Assert(!_encService.EditSession.StoppedAtException); - - // Non-debuggable project has no changes. - Debug.Assert(IsDebuggable); - - if (_changesApplied) - { - log.Write("Changes already applied to {0}, can't apply again", _project.Id.ToString()); - throw ExceptionUtilities.Unreachable; - } - - // The debugger always calls GetENCBuildState right before BuildForEnc. - Debug.Assert(_projectBeingEmitted != null); - Debug.Assert(_lastEditSessionSummary == GetProjectAnalysisSummary(_projectBeingEmitted)); - - // The debugger should have called GetENCBuildState before calling BuildForEnc. - // Unfortunately, there is no way how to tell the debugger that the changes were not significant, - // so we'll to emit an empty delta. See bug 839558. - Debug.Assert(_lastEditSessionSummary == ProjectAnalysisSummary.ValidInsignificantChanges || - _lastEditSessionSummary == ProjectAnalysisSummary.ValidChanges); - - // ISymUnmanagedReader can only be accessed from an MTA thread, - // so dispatch emit to one of thread pool threads, which are MTA. - var emitTask = Task.Factory.SafeStartNew(EmitProjectDelta, CancellationToken.None, TaskScheduler.Default); - - Deltas delta; - using (NonReentrantContext) - { - delta = emitTask.Result; - - if (delta == null) - { - // A diagnostic has already been reported by the emit task - return VSConstants.E_FAIL; - } - } - - var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId); - - // Clear diagnostics, in case the project was built before and failed due to errors. - _diagnosticProvider.ClearDiagnostics(errorId, _projectBeingEmitted.Solution, _project.Id, _documentsWithEmitError); - - if (!delta.EmitResult.Success) - { - var errors = delta.EmitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error); - _documentsWithEmitError = _diagnosticProvider.ReportDiagnostics(errorId, _projectBeingEmitted.Solution, _project.Id, errors); - _encService.EditSession.LogEmitProjectDeltaErrors(errors.Select(e => e.Id)); - - return VSConstants.E_FAIL; - } - - _documentsWithEmitError = ImmutableArray.Empty; - - var updater = (IDebugUpdateInMemoryPE3)pUpdatePE; - SetFileUpdates(updater, delta.LineEdits); - - updater.SetDeltaIL(delta.IL.Value, (uint)delta.IL.Value.Length); - updater.SetDeltaPdb(SymUnmanagedStreamFactory.CreateStream(delta.Pdb.Stream)); - updater.SetRemapMethods(delta.Pdb.UpdatedMethods, (uint)delta.Pdb.UpdatedMethods.Length); - updater.SetDeltaMetadata(delta.Metadata.Bytes, (uint)delta.Metadata.Bytes.Length); - - var ranges = GetExceptionRanges(delta.NonRemappableRegions); - updater.SetExceptionRanges(ranges, ranges.Length); - - var remapActiveStatements = GetRemapActiveStatements(delta.ActiveStatementsInUpdatedMethods); - updater.SetRemapActiveStatements(remapActiveStatements, remapActiveStatements.Length); - - _pendingBaseline = delta.EmitResult.Baseline; - _pendingNonRemappableRegions = delta.NonRemappableRegions; - -#if DEBUG - fixed (byte* deltaMetadataPtr = &delta.Metadata.Bytes[0]) - { - var reader = new System.Reflection.Metadata.MetadataReader(deltaMetadataPtr, delta.Metadata.Bytes.Length); - var moduleDef = reader.GetModuleDefinition(); - - log.DebugWrite("Gen {0}: MVID={1}, BaseId={2}, EncId={3}", - moduleDef.Generation, - reader.GetGuid(moduleDef.Mvid).ToString(), - reader.GetGuid(moduleDef.BaseGenerationId).ToString(), - reader.GetGuid(moduleDef.GenerationId).ToString()); - } -#endif - - return VSConstants.S_OK; - } - catch (Exception e) when (FatalError.ReportWithoutCrash(e)) - { - ReportInternalError(InternalErrorCode.CantApplyChangesUnexpectedError, new[] { e.ToString() }); - return VSConstants.E_FAIL; - } - } - - internal static ENCPROG_ACTIVE_STATEMENT_REMAP[] GetRemapActiveStatements(ImmutableArray<(Guid ThreadId, ActiveInstructionId OldInstructionId, LinePositionSpan NewSpan)> remaps) - { - var result = new ENCPROG_ACTIVE_STATEMENT_REMAP[remaps.Length]; - for (var i = 0; i < remaps.Length; i++) - { - result[i] = new ENCPROG_ACTIVE_STATEMENT_REMAP - { - ThreadId = remaps[i].ThreadId, - MethodToken = remaps[i].OldInstructionId.MethodId.Token, - OldMethodVersion = remaps[i].OldInstructionId.MethodId.Version, - OldILOffset = remaps[i].OldInstructionId.ILOffset, - // the debugger expects these to be 0-based - NewStartLine = remaps[i].NewSpan.Start.Line, - NewStartCol = remaps[i].NewSpan.Start.Character, - NewEndLine = remaps[i].NewSpan.End.Line, - NewEndCol = remaps[i].NewSpan.End.Character, - }; - } - - return result; - } - - // internal for testing - internal static ENCPROG_EXCEPTION_RANGE[] GetExceptionRanges(ImmutableArray<(ActiveMethodId Method, NonRemappableRegion Region)> nonRemappableRegions) - { - var exceptionRegionCount = nonRemappableRegions.Count(d => d.Region.IsExceptionRegion); - - var result = new ENCPROG_EXCEPTION_RANGE[exceptionRegionCount]; - var i = 0; - foreach (var (method, region) in nonRemappableRegions) - { - if (region.IsExceptionRegion) - { - // Debugger line and column numbers are 1-based. - // - // The range span is the new span. Deltas are inverse. - // old = new + delta - // new = old – delta - - var delta = region.LineDelta; - - result[i++] = new ENCPROG_EXCEPTION_RANGE - { - MethodToken = method.Token, - MethodVersion = method.Version, - // the debugger expects these to be 0-based - StartLine = region.Span.Start.Line + delta, - StartCol = region.Span.Start.Character, - EndLine = region.Span.End.Line + delta, - EndCol = region.Span.End.Character, - Delta = -delta, - }; - } - } - - return result; - } - - private unsafe void SetFileUpdates( - IDebugUpdateInMemoryPE2 updater, - ImmutableArray<(DocumentId DocumentId, ImmutableArray Deltas)> edits) - { - var totalEditCount = edits.Sum(e => e.Deltas.Length); - if (totalEditCount == 0) - { - return; - } - - var lineUpdates = new LINEUPDATE[totalEditCount]; - fixed (LINEUPDATE* lineUpdatesPtr = lineUpdates) - { - var index = 0; - var fileUpdates = new FILEUPDATE[edits.Length]; - for (var f = 0; f < fileUpdates.Length; f++) - { - var (documentId, deltas) = edits[f]; - - fileUpdates[f].FileName = _workspace.CurrentSolution.GetProject(_project.Id).GetDocument(documentId).FilePath; - fileUpdates[f].LineUpdateCount = (uint)deltas.Length; - fileUpdates[f].LineUpdates = (IntPtr)(lineUpdatesPtr + index); - - for (var l = 0; l < deltas.Length; l++) - { - lineUpdates[index + l].Line = (uint)deltas[l].OldLine; - lineUpdates[index + l].UpdatedLine = (uint)deltas[l].NewLine; - } - - index += deltas.Length; - } - - // The updater makes a copy of all data, we can release the buffer after the call. - updater.SetFileUpdates(fileUpdates, (uint)fileUpdates.Length); - } - } - - private Deltas EmitProjectDelta() - { - Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); - - var baseline = _committedBaseline; - if (baseline == null) - { - var info = _moduleMetadataProvider.TryGetBaselineModuleInfo(_mvid); - if (info != null) - { - var infoReader = EditAndContinueMethodDebugInfoReader.Create(info.SymReader, version: 1); - - baseline = EmitBaseline.CreateInitialBaseline( - info.Metadata, - infoReader.GetDebugInfo, - infoReader.GetLocalSignature, - infoReader.IsPortable); - } - } - - if (baseline == null || baseline.OriginalMetadata.IsDisposed) - { - var moduleName = PathUtilities.GetFileName(_project.IntermediateOutputFilePath); - - // The metadata blob is guaranteed to not be disposed while BuildForEnc is being executed. - // If it is disposed it means it had been disposed when entering BuildForEnc. - log.Write("Module has been unloaded: module '{0}', project '{1}', MVID: {2}", moduleName, _project.Id.ToString(), _mvid.ToString()); - - ReportInternalError(InternalErrorCode.CantApplyChangesModuleHasBeenUnloaded, new[] { moduleName }); - return null; - } - - var emitTask = _encService.EditSession.EmitProjectDeltaAsync(_projectBeingEmitted, baseline, CancellationToken.None); - if (emitTask.Exception != null) - { - ReportInternalError(InternalErrorCode.CantApplyChangesUnexpectedError, new[] { emitTask.Exception.ToString() }); - return null; - } - - return emitTask.Result; - } - - public int EncApplySucceeded(int hrApplyResult) - { - try - { - log.Write("Change applied to {0}", _project.Id.ToString()); - Debug.Assert(IsDebuggable); - Debug.Assert(_encService.EditSession != null); - Debug.Assert(!_encService.EditSession.StoppedAtException); - Debug.Assert(_pendingBaseline != null); - Debug.Assert(!_pendingNonRemappableRegions.IsDefault); - - // Since now on until exiting the break state, we consider the changes applied and the project state should be NoChanges. - _changesApplied = true; - - _committedBaseline = _pendingBaseline; - _pendingBaseline = null; - - s_pendingNonRemappableRegions.Add(_pendingNonRemappableRegions); - _pendingNonRemappableRegions = default; - - return VSConstants.S_OK; - } - catch (Exception e) when (FatalError.ReportWithoutCrash(e)) - { - return VSConstants.E_FAIL; - } - } - - private enum InternalErrorCode - { - CantApplyChangesModuleHasBeenUnloaded = 1, - ErrorReadingFile = 2, - CantApplyChangesUnexpectedError = 3, - } - - private void ReportInternalError(InternalErrorCode errorId, object[] args) - { - try - { - string resourceName; - string resourceString; - - switch (errorId) - { - case InternalErrorCode.CantApplyChangesModuleHasBeenUnloaded: - resourceName = nameof(ServicesVSResources.CantApplyChangesModuleHasBeenUnloaded); - resourceString = ServicesVSResources.CantApplyChangesModuleHasBeenUnloaded; - break; - - case InternalErrorCode.CantApplyChangesUnexpectedError: - resourceName = nameof(ServicesVSResources.CantApplyChangesUnexpectedError); - resourceString = ServicesVSResources.CantApplyChangesUnexpectedError; - break; - - case InternalErrorCode.ErrorReadingFile: - resourceName = nameof(ServicesVSResources.ErrorReadingFile); - resourceString = ServicesVSResources.ErrorReadingFile; - break; - - default: - throw ExceptionUtilities.Unreachable; - } - - var descriptor = new DiagnosticDescriptor( - $"ENC{(int)errorId:D4}", - new LocalizableResourceString(resourceName, ServicesVSResources.ResourceManager, typeof(ServicesVSResources)), - resourceString, - DiagnosticCategory.EditAndContinue, - DiagnosticSeverity.Error, - isEnabledByDefault: true, - customTags: DiagnosticCustomTags.EditAndContinue); - - _diagnosticProvider.ReportDiagnostics( - new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.InternalErrorId), - _encService.DebuggingSession.InitialSolution, - _project.Id, - new[] { Diagnostic.Create(descriptor, Location.None, args) }); - } - catch (Exception e) when (FatalError.ReportWithoutCrash(e)) - { - // nop - } - } - } -} diff --git a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VsReadOnlyDocumentTracker.cs b/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VsReadOnlyDocumentTracker.cs deleted file mode 100644 index 669740497943e..0000000000000 --- a/src/VisualStudio/Core/Def/Implementation/EditAndContinue/VsReadOnlyDocumentTracker.cs +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using Microsoft.CodeAnalysis.EditAndContinue; -using Microsoft.CodeAnalysis.Editor.Shared.Utilities; -using Microsoft.CodeAnalysis.Text; -using Microsoft.VisualStudio.Editor; -using Microsoft.VisualStudio.LanguageServices; -using Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue; -using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; -using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; -using Microsoft.VisualStudio.Text; -using Microsoft.VisualStudio.TextManager.Interop; - -namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue -{ - internal sealed class VsReadOnlyDocumentTracker : ForegroundThreadAffinitizedObject, IDisposable - { - private readonly IEditAndContinueService _encService; - private readonly IVsEditorAdaptersFactoryService _adapters; - private readonly Workspace _workspace; - - private bool _isDisposed; - - internal static readonly TraceLog log = new TraceLog(2048, "VsReadOnlyDocumentTracker"); - - public VsReadOnlyDocumentTracker(IThreadingContext threadingContext, IEditAndContinueService encService, IVsEditorAdaptersFactoryService adapters) - : base(threadingContext, assertIsForeground: true) - { - Debug.Assert(encService.DebuggingSession != null); - - _encService = encService; - _adapters = adapters; - _workspace = encService.DebuggingSession.InitialSolution.Workspace; - - _workspace.DocumentOpened += OnDocumentOpened; - UpdateWorkspaceDocuments(); - } - - private void OnDocumentOpened(object sender, DocumentEventArgs e) - { - InvokeBelowInputPriorityAsync(() => - { - if (!_isDisposed) - { - SetReadOnly(e.Document); - } - }); - } - - internal void UpdateWorkspaceDocuments() - { - foreach (var documentId in _workspace.GetOpenDocumentIds()) - { - var document = _workspace.CurrentSolution.GetDocument(documentId); - if (document != null) - { - SetReadOnly(document); - } - } - } - - public void Dispose() - { - AssertIsForeground(); - - if (_isDisposed) - { - return; - } - - _workspace.DocumentOpened -= OnDocumentOpened; - - UpdateWorkspaceDocuments(); - - // event handlers may be queued after the disposal - they will be a no-op - _isDisposed = true; - } - - private void SetReadOnly(Document document) - { - // Only set documents read-only if they're part of a project that supports Enc. - var workspace = document.Project.Solution.Workspace as VisualStudioWorkspace; - - if (workspace != null && VsENCRebuildableProjectImpl.TryGetRebuildableProject(document.Project.Id) != null) - { - SetReadOnly(document.Id, _encService.IsProjectReadOnly(document.Project.Id, out var sessionReason, out var projectReason) && AllowsReadOnly(document.Id)); - } - } - - private bool AllowsReadOnly(DocumentId documentId) - { - // All documents of regular running projects are read-only until the debugger breaks the app. - // However, ASP.NET doesn’t want its views (aspx, cshtml, or vbhtml) to be read-only, so they can be editable - // while the code is running and get refreshed next time the web page is hit. - - // Note that Razor-like views are modelled as a ContainedDocument - var containedDocument = ContainedDocument.TryGetContainedDocument(documentId); - return containedDocument == null; - } - - internal void SetReadOnly(DocumentId documentId, bool value) - { - AssertIsForeground(); - Debug.Assert(!_isDisposed); - - var textBuffer = GetTextBuffer(_workspace, documentId); - if (textBuffer != null) - { - var vsBuffer = _adapters.GetBufferAdapter(textBuffer); - if (vsBuffer != null) - { - SetReadOnlyFlag(vsBuffer, value); - } - } - } - - private void SetReadOnlyFlag(IVsTextBuffer buffer, bool value) - { - uint newFlags; - buffer.GetStateFlags(out var oldFlags); - if (value) - { - newFlags = oldFlags | (uint)BUFFERSTATEFLAGS.BSF_USER_READONLY; - } - else - { - newFlags = oldFlags & ~(uint)BUFFERSTATEFLAGS.BSF_USER_READONLY; - } - - if (oldFlags != newFlags) - { - buffer.SetStateFlags(newFlags); - } - } - - private static ITextBuffer GetTextBuffer(Workspace workspace, DocumentId documentId) - { - var doc = workspace.CurrentSolution.GetDocument(documentId); - if (doc == null) - { - // TODO (https://github.com/dotnet/roslyn/issues/1204): this check should be unnecessary. - if (documentId != null) - { - log.Write("GetTextBuffer: document not found for '#{0} - {1}'", documentId.Id.ToString(), documentId.DebugName); - } - else - { - log.Write("GetTextBuffer: document not found"); - } - - return null; - } - - if (!doc.TryGetText(out var text)) - { - // TODO: should not happen since the document is open (see bug 896058) - return null; - } - - var snapshot = text.FindCorrespondingEditorTextSnapshot(); - if (snapshot == null) - { - return null; - } - - return snapshot.TextBuffer; - } - } -} diff --git a/src/VisualStudio/Core/Def/Implementation/LanguageClient/AbstractLanguageServerClient.cs b/src/VisualStudio/Core/Def/Implementation/LanguageClient/AbstractLanguageServerClient.cs new file mode 100644 index 0000000000000..234df5d217489 --- /dev/null +++ b/src/VisualStudio/Core/Def/Implementation/LanguageClient/AbstractLanguageServerClient.cs @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.VisualStudio.LanguageServer.Client; +using Microsoft.VisualStudio.Threading; +using Microsoft.CodeAnalysis.Remote; +using Microsoft.ServiceHub.Client; +using Microsoft.VisualStudio.LanguageServices.Remote; +using Microsoft.CodeAnalysis.Host; +using System.Composition; +using Microsoft.CodeAnalysis.Shared.TestHooks; +using Microsoft.CodeAnalysis.Editor.Shared.Utilities; +using Microsoft.CodeAnalysis.Options; +using System.Linq; +using Microsoft.CodeAnalysis.Experiments; + +namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService +{ + internal abstract class AbstractLanguageServerClient : ILanguageClient + { + private readonly IThreadingContext _threadingContext; + private readonly Workspace _workspace; + private readonly IEnumerable> _lazyOptions; + private readonly LanguageServerClientEventListener _eventListener; + private readonly IAsynchronousOperationListener _asyncListener; + + private readonly string _serviceHubClientName; + private readonly string _languageServerName; + + /// + /// Gets the name of the language client (displayed to the user). + /// + public abstract string Name { get; } + + /// + /// Gets the configuration section names for the language client. This may be null if the language client + /// does not provide settings. + /// + public virtual IEnumerable ConfigurationSections { get; } = null; + + /// + /// Gets the initialization options object the client wants to send when 'initialize' message is sent. + /// This may be null if the client does not need custom initialization options. + /// + public virtual object InitializationOptions { get; } = null; + + /// + /// Gets the list of file names to watch for changes. Changes will be sent to the server via 'workspace/didChangeWatchedFiles' + /// message. The files to watch must be under the current active workspace. The file names can be specified as a relative + /// paths to the exact file, or as glob patterns following the standard in .gitignore see https://www.kernel.org/pub/software/scm/git/docs/gitignore.html files. + /// + public virtual IEnumerable FilesToWatch { get; } = null; + +#pragma warning disable CS0067 // event never used - implementing interface ILanguageClient + public event AsyncEventHandler StartAsync; + public event AsyncEventHandler StopAsync; +#pragma warning restore CS0067 // event never used + + public AbstractLanguageServerClient( + IThreadingContext threadingContext, + Workspace workspace, + IEnumerable> lazyOptions, + LanguageServerClientEventListener eventListener, + IAsynchronousOperationListenerProvider listenerProvider, + string languageServerName, + string serviceHubClientName) + { + _threadingContext = threadingContext; + _workspace = workspace; + _lazyOptions = lazyOptions; + _eventListener = eventListener; + _asyncListener = listenerProvider.GetListener(FeatureAttribute.FindReferences); + + _serviceHubClientName = serviceHubClientName; + _languageServerName = languageServerName; + } + + public async Task ActivateAsync(CancellationToken cancellationToken) + { + var client = await _workspace.TryGetRemoteHostClientAsync(cancellationToken).ConfigureAwait(false); + if (client == null) + { + // there is no OOP. either user turned it off, or process got killed. + return null; + } + + var hostGroup = new HostGroup(client.ClientId); + var hubClient = new HubClient(_serviceHubClientName); + + var stream = await ServiceHubRemoteHostClient.Connections.RequestServiceAsync( + _workspace, + hubClient, + _languageServerName, + hostGroup, + TimeSpan.FromMinutes(60), + cancellationToken).ConfigureAwait(false); + + return new Connection(stream, stream); + } + + /// + /// Signals that the extension has been loaded. The server can be started immediately, or wait for user action to start. + /// To start the server, invoke the event; + /// + public Task OnLoadedAsync() + { + var token = _asyncListener.BeginAsyncOperation("OnLoadedAsync"); + + // set up event stream so that we start LSP server once Roslyn is loaded + _eventListener.WorkspaceStarted.ContinueWith(async _ => + { + // initialize things on UI thread + await InitializeOnUIAsync().ConfigureAwait(false); + + // this might get called before solution is fully loaded and before file is opened. + // we delay our OOP start until then, but user might do vsstart before that. so we make sure we start OOP if + // it is not running yet. multiple start is no-op + ((RemoteHostClientServiceFactory.RemoteHostClientService)_workspace.Services.GetService()).Enable(); + + // wait until remote host is available before let platform know that they can activate our LSP + var client = await _workspace.TryGetRemoteHostClientAsync(CancellationToken.None).ConfigureAwait(false); + if (client == null) + { + // there is no OOP. either user turned it off, or process got killed. + // don't ask platform to start LSP + return; + } + + // let platform know that they can start us + await StartAsync.InvokeAsync(this, EventArgs.Empty).ConfigureAwait(false); + }, TaskScheduler.Default).CompletesAsyncOperation(token); + + return Task.CompletedTask; + + async Task InitializeOnUIAsync() + { + await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(); + + // this doesn't attempt to solve our JTF and some services being not free-thread issue here, but + // try to fix this particular deadlock issue only. we already have long discussion on + // how we need to deal with JTF, Roslyn service requirements and VS services reality conflicting + // each others. architectural fix should come from the result of that discussion. + + // Ensure the options persisters are loaded since we have to fetch options from the shell + _lazyOptions.Select(o => o.Value); + + // experimentation service unfortunately uses JTF to jump to UI thread in certain cases + // which can cause deadlock if 2 parties try to enable OOP from BG and then FG before + // experimentation service tries to jump to UI thread. + var experimentationService = _workspace.Services.GetService(); + } + } + + /// + /// Signals the extension that the language server has been successfully initialized. + /// + public Task OnServerInitializedAsync() + { + return Task.CompletedTask; + } + + /// + /// Signals the extension that the language server failed to initialize. + /// + public Task OnServerInitializeFailedAsync(Exception e) + { + return Task.CompletedTask; + } + } + + // unfortunately, we can't implement this on LanguageServerClient since this uses MEF v2 and + // ILanguageClient requires MEF v1 and two can't be mixed exported in 1 class. + [Export] + [ExportEventListener(WellKnownEventListeners.Workspace, WorkspaceKind.Host), Shared] + internal class LanguageServerClientEventListener : IEventListener + { + private readonly TaskCompletionSource _taskCompletionSource; + + public Task WorkspaceStarted => _taskCompletionSource.Task; + + public LanguageServerClientEventListener() + { + _taskCompletionSource = new TaskCompletionSource(); + } + + public void StartListening(Workspace workspace, object serviceOpt) + { + // mark that roslyn solution is added + _taskCompletionSource.SetResult(null); + } + } +} diff --git a/src/VisualStudio/Core/Def/Implementation/Library/ClassView/AbstractSyncClassViewCommandHandler.cs b/src/VisualStudio/Core/Def/Implementation/Library/ClassView/AbstractSyncClassViewCommandHandler.cs index d05b4264f7f62..aea16031223c1 100644 --- a/src/VisualStudio/Core/Def/Implementation/Library/ClassView/AbstractSyncClassViewCommandHandler.cs +++ b/src/VisualStudio/Core/Def/Implementation/Library/ClassView/AbstractSyncClassViewCommandHandler.cs @@ -6,7 +6,6 @@ using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; -using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.Shell; @@ -49,8 +48,8 @@ public bool ExecuteCommand(SyncClassViewCommandArgs args, CommandExecutionContex using (var waitScope = context.OperationContext.AddScope(allowCancellation: true, string.Format(ServicesVSResources.Synchronizing_with_0, ClassView))) { - var document = snapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync( - context.OperationContext).WaitAndGetResult(context.OperationContext.UserCancellationToken); + var document = snapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChanges( + context.OperationContext, ThreadingContext); if (document == null) { return true; diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject.cs index b6a8215c05fae..8f83d260f05f6 100644 --- a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject.cs +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject.cs @@ -43,8 +43,6 @@ internal abstract partial class AbstractLegacyProject : ForegroundThreadAffiniti #region Mutable fields that should only be used from the UI thread - private readonly VsENCRebuildableProjectImpl _editAndContinueProject; - private readonly SolutionEventsBatchScopeCreator _batchScopeCreator; #endregion @@ -106,11 +104,13 @@ public AbstractLegacyProject( ConnectHierarchyEvents(); RefreshBinOutputPath(); - // TODO: remove this terrible hack, which is working around shims throwing in not-good ways + // TODO: https://github.com/dotnet/roslyn/issues/36065 + // The ctor of ExternalErrorDiagnosticUpdateSource throws when running in tests since UIContextImpl calls: + // (IVsMonitorSelection)ServiceProvider.GlobalProvider.GetService(typeof(IVsMonitorSelection))), + // which returns null. try { _externalErrorReporter = new ProjectExternalErrorReporter(VisualStudioProject.Id, externalErrorReportingPrefix, (VisualStudioWorkspaceImpl)Workspace); - _editAndContinueProject = new VsENCRebuildableProjectImpl(Workspace, VisualStudioProject, serviceProvider); } catch (Exception) { diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject_IVsENCRebuildableProjectCfg.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject_IVsENCRebuildableProjectCfg.cs index 70d46267a9d80..74fb418dfdc3e 100644 --- a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject_IVsENCRebuildableProjectCfg.cs +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject_IVsENCRebuildableProjectCfg.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using Roslyn.Utilities; using EncInterop = Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop; using ShellInterop = Microsoft.VisualStudio.Shell.Interop; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; @@ -12,75 +13,45 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.L internal partial class AbstractLegacyProject : EncInterop.IVsENCRebuildableProjectCfg2, EncInterop.IVsENCRebuildableProjectCfg4 { public int HasCustomMetadataEmitter(out bool value) - { - value = true; - return VSConstants.S_OK; - } + => throw ExceptionUtilities.Unreachable; public int StartDebuggingPE() - { - return _editAndContinueProject.StartDebuggingPE(); - } + => throw ExceptionUtilities.Unreachable; public int StopDebuggingPE() - { - return _editAndContinueProject.StopDebuggingPE(); - } + => throw ExceptionUtilities.Unreachable; public int GetPEidentity(Guid[] pMVID, string[] pbstrPEName) - { - return _editAndContinueProject.GetPEidentity(pMVID, pbstrPEName); - } + => throw ExceptionUtilities.Unreachable; public int EnterBreakStateOnPE(EncInterop.ENC_BREAKSTATE_REASON encBreakReason, ShellInterop.ENC_ACTIVE_STATEMENT[] pActiveStatements, uint cActiveStatements) - { - return _editAndContinueProject.EnterBreakStateOnPE(encBreakReason, pActiveStatements, cActiveStatements); - } + => throw ExceptionUtilities.Unreachable; + + public int ExitBreakStateOnPE() + => throw ExceptionUtilities.Unreachable; public int GetExceptionSpanCount(out uint pcExceptionSpan) - { - pcExceptionSpan = default; - return _editAndContinueProject.GetExceptionSpanCount(out pcExceptionSpan); - } + => throw ExceptionUtilities.Unreachable; public int GetExceptionSpans(uint celt, ShellInterop.ENC_EXCEPTION_SPAN[] rgelt, ref uint pceltFetched) - { - return _editAndContinueProject.GetExceptionSpans(celt, rgelt, ref pceltFetched); - } + => throw ExceptionUtilities.Unreachable; public int GetCurrentExceptionSpanPosition(uint id, VsTextSpan[] ptsNewPosition) - { - return _editAndContinueProject.GetCurrentExceptionSpanPosition(id, ptsNewPosition); - } + => throw ExceptionUtilities.Unreachable; public int GetENCBuildState(ShellInterop.ENC_BUILD_STATE[] pENCBuildState) - { - return _editAndContinueProject.GetENCBuildState(pENCBuildState); - } - - public int ExitBreakStateOnPE() - { - return _editAndContinueProject.ExitBreakStateOnPE(); - } + => throw ExceptionUtilities.Unreachable; public int GetCurrentActiveStatementPosition(uint id, VsTextSpan[] ptsNewPosition) - { - return _editAndContinueProject.GetCurrentActiveStatementPosition(id, ptsNewPosition); - } + => throw ExceptionUtilities.Unreachable; public int EncApplySucceeded(int hrApplyResult) - { - return _editAndContinueProject.EncApplySucceeded(hrApplyResult); - } + => throw ExceptionUtilities.Unreachable; public int GetPEBuildTimeStamp(Microsoft.VisualStudio.OLE.Interop.FILETIME[] pTimeStamp) - { - return VSConstants.E_NOTIMPL; - } + => throw ExceptionUtilities.Unreachable; public int BuildForEnc(object pUpdatePE) - { - return _editAndContinueProject.BuildForEnc(pUpdatePE); - } + => throw ExceptionUtilities.Unreachable; } } diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProject.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProject.cs index c4f4fd20945c5..7a5cb23e7d9ad 100644 --- a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProject.cs +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProject.cs @@ -228,8 +228,6 @@ public ParseOptions ParseOptions /// /// The path to the output in obj. /// - /// This is internal for now, as it's only consumed by - /// which directly takes a . internal string IntermediateOutputFilePath { get => _intermediateOutputFilePath; diff --git a/src/VisualStudio/Core/Def/Implementation/Remote/RemoteHostClientServiceFactory.RemoteHostClientService.cs b/src/VisualStudio/Core/Def/Implementation/Remote/RemoteHostClientServiceFactory.RemoteHostClientService.cs index 380eff64a0f89..c23fc2fa03827 100644 --- a/src/VisualStudio/Core/Def/Implementation/Remote/RemoteHostClientServiceFactory.RemoteHostClientService.cs +++ b/src/VisualStudio/Core/Def/Implementation/Remote/RemoteHostClientServiceFactory.RemoteHostClientService.cs @@ -181,8 +181,7 @@ private void SetRemoteHostBitness() var x64 = _workspace.Options.GetOption(RemoteHostOptions.OOP64Bit); if (!x64) { - x64 = _workspace.Services.GetService().IsExperimentEnabled( - WellKnownExperimentNames.RoslynOOP64bit); + x64 = _workspace.Services.GetService().IsExperimentEnabled(WellKnownExperimentNames.RoslynOOP64bit); } // log OOP bitness diff --git a/src/VisualStudio/Core/Def/Implementation/Remote/ServiceHubRemoteHostClient.Connections.cs b/src/VisualStudio/Core/Def/Implementation/Remote/ServiceHubRemoteHostClient.Connections.cs index 993f04cf4d473..986b98ad5c130 100644 --- a/src/VisualStudio/Core/Def/Implementation/Remote/ServiceHubRemoteHostClient.Connections.cs +++ b/src/VisualStudio/Core/Def/Implementation/Remote/ServiceHubRemoteHostClient.Connections.cs @@ -6,8 +6,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.ErrorReporting; -using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Remote; using Microsoft.ServiceHub.Client; using Roslyn.Utilities; @@ -17,7 +15,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Remote { internal sealed partial class ServiceHubRemoteHostClient : RemoteHostClient { - private static class Connections + internal static class Connections { /// /// call and retry up to if the call throws diff --git a/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioWorkspaceStatusServiceFactory.cs b/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioWorkspaceStatusServiceFactory.cs index f522e7259ebde..a443ba217e809 100644 --- a/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioWorkspaceStatusServiceFactory.cs +++ b/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioWorkspaceStatusServiceFactory.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.ComponentModel; using System.Composition; using System.Threading; using System.Threading.Tasks; @@ -64,7 +65,7 @@ private class Service : IWorkspaceStatusService private bool _initialized = false; - public event EventHandler StatusChanged; + public event EventHandler StatusChanged; public Service(IAsyncServiceProvider2 serviceProvider, IAsynchronousOperationListener listener) { @@ -76,6 +77,9 @@ public Service(IAsyncServiceProvider2 serviceProvider, IAsynchronousOperationLis Task.Run(() => EnsureInitializationAsync(CancellationToken.None), CancellationToken.None).CompletesAsyncOperation(asyncToken); } + // unfortunately, IVsOperationProgressStatusService requires UI thread to let project system to proceed to next stages. + // this method should only be used with either await or JTF.Run, it should be never used with Task.Wait otherwise, it can + // deadlock public async Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.PartialLoad_FullyLoaded, KeyValueLogMessage.NoProperty, cancellationToken)) @@ -97,6 +101,9 @@ public async Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken) } } + // unfortunately, IVsOperationProgressStatusService requires UI thread to let project system to proceed to next stages. + // this method should only be used with either await or JTF.Run, it should be never used with Task.Wait otherwise, it can + // deadlock public async Task IsFullyLoadedAsync(CancellationToken cancellationToken) { await EnsureInitializationAsync(cancellationToken).ConfigureAwait(false); @@ -107,15 +114,15 @@ public async Task IsFullyLoadedAsync(CancellationToken cancellationToken) return false; } - return !status.Status.IsInProgress; + return !status.IsInProgress; } - private async Task GetProgressStageStatusAsync(CancellationToken cancellationToken) + private async Task GetProgressStageStatusAsync(CancellationToken cancellationToken) { var service = await _serviceProvider.GetServiceAsync(throwOnFailure: false) .WithCancellation(cancellationToken).ConfigureAwait(false); - return service?.GetStageStatus(CommonOperationProgressStageIds.Intellisense); + return service?.GetStageStatusForSolutionLoad(CommonOperationProgressStageIds.Intellisense); } private async Task EnsureInitializationAsync(CancellationToken cancellationToken) @@ -137,7 +144,7 @@ private async Task EnsureInitializationAsync(CancellationToken cancellationToken return; } - status.InProgressChanged += (_, e) => this.StatusChanged?.Invoke(this, !e.Status.IsInProgress); + status.PropertyChanged += (_, e) => this.StatusChanged?.Invoke(this, EventArgs.Empty); } } } diff --git a/src/VisualStudio/Core/Def/ManagedEditAndContinueService.vsdconfigxml b/src/VisualStudio/Core/Def/ManagedEditAndContinueService.vsdconfigxml index 05562c972b2b4..030ae813d680a 100644 --- a/src/VisualStudio/Core/Def/ManagedEditAndContinueService.vsdconfigxml +++ b/src/VisualStudio/Core/Def/ManagedEditAndContinueService.vsdconfigxml @@ -2,21 +2,37 @@ - + + - + - + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/VisualStudio/Core/Def/Microsoft.VisualStudio.LanguageServices.csproj b/src/VisualStudio/Core/Def/Microsoft.VisualStudio.LanguageServices.csproj index 00fdd8f33a0f5..12167e805ba6b 100644 --- a/src/VisualStudio/Core/Def/Microsoft.VisualStudio.LanguageServices.csproj +++ b/src/VisualStudio/Core/Def/Microsoft.VisualStudio.LanguageServices.csproj @@ -180,6 +180,7 @@ + diff --git a/src/VisualStudio/Core/Def/ServicesVSResources.Designer.cs b/src/VisualStudio/Core/Def/ServicesVSResources.Designer.cs index e47d327f1f503..dd1471057bef5 100644 --- a/src/VisualStudio/Core/Def/ServicesVSResources.Designer.cs +++ b/src/VisualStudio/Core/Def/ServicesVSResources.Designer.cs @@ -69,15 +69,6 @@ internal static string _0_encountered_an_error_and_has_been_disabled { } } - /// - /// Looks up a localized string similar to {0} reference. - /// - internal static string _0_reference { - get { - return ResourceManager.GetString("_0_reference", resourceCulture); - } - } - /// /// Looks up a localized string similar to {0} references. /// @@ -550,24 +541,6 @@ internal static string Cancel { } } - /// - /// Looks up a localized string similar to Can't apply changes -- module '{0}' has been unloaded.. - /// - internal static string CantApplyChangesModuleHasBeenUnloaded { - get { - return ResourceManager.GetString("CantApplyChangesModuleHasBeenUnloaded", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Can't apply changes -- unexpected error: '{0}'. - /// - internal static string CantApplyChangesUnexpectedError { - get { - return ResourceManager.GetString("CantApplyChangesUnexpectedError", resourceCulture); - } - } - /// /// Looks up a localized string similar to Capitalization:. /// @@ -586,44 +559,6 @@ internal static string Change_Signature { } } - /// - /// Looks up a localized string similar to Changes are not allowed if the assembly has not been loaded.. - /// - internal static string ChangesNotAllowedIFAssemblyHasNotBeenLoaded { - get { - return ResourceManager.GetString("ChangesNotAllowedIFAssemblyHasNotBeenLoaded", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Changes are not allowed if the project wasn't built when debugging started.. - /// - internal static string ChangesNotAllowedIfProjectWasntBuildWhenDebuggingStarted { - get { - return ResourceManager.GetString("ChangesNotAllowedIfProjectWasntBuildWhenDebuggingStarted", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Changes are not allowed if the project wasn't loaded and built when debugging started. - /// - ///'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts.. - /// - internal static string ChangesNotAllowedIfProjectWasntLoadedWhileDebugging { - get { - return ResourceManager.GetString("ChangesNotAllowedIfProjectWasntLoadedWhileDebugging", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Changes are not allowed while code is running.. - /// - internal static string ChangesNotAllowedWhileCodeIsRunning { - get { - return ResourceManager.GetString("ChangesNotAllowedWhileCodeIsRunning", resourceCulture); - } - } - /// /// Looks up a localized string similar to Choose a Symbol Specification and a Naming Style.. /// @@ -1006,15 +941,6 @@ internal static string Error_reading_ruleset_file_0_1 { } } - /// - /// Looks up a localized string similar to Error while reading file '{0}': {1}. - /// - internal static string ErrorReadingFile { - get { - return ResourceManager.GetString("ErrorReadingFile", resourceCulture); - } - } - /// /// Looks up a localized string similar to ErrorReadingRuleset. /// @@ -1569,15 +1495,6 @@ internal static string Members { } } - /// - /// Looks up a localized string similar to method. - /// - internal static string method { - get { - return ResourceManager.GetString("method", resourceCulture); - } - } - /// /// Looks up a localized string similar to Miscellaneous Files. /// @@ -2629,15 +2546,6 @@ internal static string Project_References { } } - /// - /// Looks up a localized string similar to property. - /// - internal static string property { - get { - return ResourceManager.GetString("property", resourceCulture); - } - } - /// /// Looks up a localized string similar to Pull Members Up. /// @@ -2674,15 +2582,6 @@ internal static string Reference_to_0_in_project_1 { } } - /// - /// Looks up a localized string similar to References. - /// - internal static string References { - get { - return ResourceManager.GetString("References", resourceCulture); - } - } - /// /// Looks up a localized string similar to Regular Expressions. /// @@ -3243,15 +3142,6 @@ internal static string This_is_an_invalid_namespace { } } - /// - /// Looks up a localized string similar to This {0} has {1} reference(s). - /// - internal static string This_0_has_1_references { - get { - return ResourceManager.GetString("This_0_has_1_references", resourceCulture); - } - } - /// /// Looks up a localized string similar to This item cannot be deleted because it is used by an existing Naming Rule.. /// @@ -3342,15 +3232,6 @@ internal static string Type_Parameters_colon { } } - /// - /// Looks up a localized string similar to type. - /// - internal static string type1 { - get { - return ResourceManager.GetString("type1", resourceCulture); - } - } - /// /// Looks up a localized string similar to Unfortunately, a process used by Visual Studio has encountered an unrecoverable error. We recommend saving your work, and then closing and restarting Visual Studio.. /// diff --git a/src/VisualStudio/Core/Def/ServicesVSResources.resx b/src/VisualStudio/Core/Def/ServicesVSResources.resx index dd93a269693d0..24cf1183d2d67 100644 --- a/src/VisualStudio/Core/Def/ServicesVSResources.resx +++ b/src/VisualStudio/Core/Def/ServicesVSResources.resx @@ -231,9 +231,6 @@ Could not find location of folder on disk - - Error while reading file '{0}': {1} - Assembly @@ -960,20 +957,6 @@ Additional information: {1} Fading - - Changes are not allowed if the assembly has not been loaded. - - - Changes are not allowed if the project wasn't built when debugging started. - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - - - Changes are not allowed while code is running. - Prefer local function over anonymous function @@ -995,12 +978,6 @@ Additional information: {1} Module has been unloaded. - - Can't apply changes -- module '{0}' has been unloaded. - - - Can't apply changes -- unexpected error: '{0}' - Prefer deconstructed variable declaration diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.cs.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.cs.xlf index e391a4afb6f54..12997987af423 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.cs.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.cs.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + Seřadit direktivy &using SortUsings - SortUsings + SortUsings diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.de.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.de.xlf index 59304e23d7010..62c261c8f7cb1 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.de.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.de.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + &Using-Anweisungen sortieren SortUsings - SortUsings + SortUsings diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.es.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.es.xlf index fdf90bd482838..1db15981f5348 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.es.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.es.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + Ordenar instrucciones &Using SortUsings - SortUsings + SortUsings diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.fr.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.fr.xlf index cc9c8a5bb0217..f36db96c164a8 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.fr.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.fr.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + Trier les &using SortUsings - SortUsings + SortUsings diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.it.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.it.xlf index 196ee12a3fe0f..1fb34697e0f24 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.it.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.it.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + Ordina &using SortUsings - SortUsings + SortUsings diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.ja.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.ja.xlf index 5c0becfc89c69..a621fc159cba9 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.ja.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.ja.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + using の並べ替え(&U) SortUsings - SortUsings + SortUsings diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.ko.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.ko.xlf index c1af6a37a7337..20f544cea3a85 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.ko.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.ko.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + Using 정렬(&U) SortUsings - SortUsings + SortUsings diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.pl.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.pl.xlf index f91d04c66b58e..1c25c5d4d30da 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.pl.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.pl.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + Sortuj &użycia SortUsings - SortUsings + SortUsings diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.pt-BR.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.pt-BR.xlf index 763e4b1226545..98bff88859c9d 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.pt-BR.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.pt-BR.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + Classificar &Usos SortUsings - SortUsings + SortUsings diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.ru.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.ru.xlf index f99b50607e7ff..904224971915b 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.ru.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.ru.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + Сортировать д&ирективы using SortUsings - SortUsings + SortUsings diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.tr.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.tr.xlf index 8acbf37068e35..485072befb858 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.tr.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.tr.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + &Using’leri Sırala SortUsings - SortUsings + SortUsings diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hans.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hans.xlf index dee9f3ad633c9..295e220c27e4d 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hans.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hans.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + 对 using 排序(&U) SortUsings - SortUsings + SortUsings @@ -184,7 +184,7 @@ None - 没有 + diff --git a/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hant.xlf b/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hant.xlf index 06f3fafccc06b..ea1212c4a2c0f 100644 --- a/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hant.xlf +++ b/src/VisualStudio/Core/Def/xlf/Commands.vsct.zh-Hant.xlf @@ -4,12 +4,12 @@ Sort &Usings - Sort &Usings + 排序 Using(&U) SortUsings - SortUsings + SortUsings diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.cs.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.cs.xlf index 1b67d0fe43dfd..140788f13fb3f 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.cs.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.cs.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + Vytvoří se nový obor názvů. @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + Sestavení + živá analýza (balíček NuGet) @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + Povolit funkce rozhraní IDE pro analýzu odkazů, které můžou mít hodnotu null Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + Vyhodnocování (počet úloh ve frontě: {0}) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + Nainstalujte Microsoftem doporučené analyzátory Roslyn, které poskytují další diagnostiku a opravy pro běžné problémy s návrhem, zabezpečením, výkonem a spolehlivostí rozhraní API. @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + Živá analýza (rozšíření VSIX) @@ -159,12 +159,12 @@ Move to Namespace - Move to Namespace + Přesunout do oboru názvů Namespace - Namespace + Obor názvů @@ -194,7 +194,7 @@ field - field + pole This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + místní This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + lokální funkce This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + metoda This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + parametr This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + vlastnost This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + parametr typu This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + Pole This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + Místní This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + metoda This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + Parametr This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + Parametr typu This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + Pozastaveno (počet úloh ve frontě: {0}) @@ -354,7 +354,7 @@ Prefer readonly fields - Preferovat pole jen pro čtení + Preferovat pole s modifikátorem readonly @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + Spouštění procesů s nízkou prioritou na pozadí @@ -444,17 +444,17 @@ Show completion list - Zobrazit seznamy dokončení + Zobrazit seznam pro doplňování Target Namespace: - Target Namespace: + Cílový obor názvů: This is an invalid namespace - This is an invalid namespace + Toto je neplatný obor názvů. @@ -469,7 +469,7 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + Použít režim kompatibility .editorconfig (vyžaduje restart) @@ -1868,30 +1868,6 @@ Další informace: {1} Zesvětlení - - Changes are not allowed if the assembly has not been loaded. - Změny nejsou povolené, pokud sestavení nebylo načteno. - - - - Changes are not allowed if the project wasn't built when debugging started. - Změny nejsou povolené, pokud projekt nebyl sestaven při zahájení ladění. - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - Změny nejsou povolené, pokud projekt nebyl načten a sestaven při zahájení ladění. - -Pro aktuální řešení je povolené zjednodušené načtení řešení. Jeho zakázáním zajistíte, aby se všechny projekty načetly při zahájení ladění. - - - - Changes are not allowed while code is running. - Změny nejsou povolené, pokud je spuštěný kód. - - Prefer local function over anonymous function Preferovat lokální funkci před anonymní funkcí @@ -1927,21 +1903,11 @@ Pro aktuální řešení je povolené zjednodušené načtení řešení. Jeho z preferovat automatické vlastnosti - - Error while reading file '{0}': {1} - Při čtení souboru {0} došlo k chybě: {1} - - Module has been unloaded. Modul byl uvolněn. - - Can't apply changes -- module '{0}' has been unloaded. - Změny nelze aplikovat – modul {0} byl uvolněn. - - Enable navigation to decompiled sources (experimental) Povolit navigaci na dekompilované zdroje (experimentální) @@ -1975,7 +1941,7 @@ Souhlasím se všemi výše uvedenými podmínkami: Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - Nastavení nakonfigurovaná zde platí pouze pro váš počítač. Pokud je chcete nakonfigurovat tak, aby byla součástí vašeho řešení a přecházela mezi zařízeními, použijte soubory .editorconfig. + Váš soubor .editorconfig může přepsat místní nastavení nakonfigurovaná na této stránce, která platí jenom pro váš počítač. Pokud chcete tato nastavení nakonfigurovat tak, aby se přesouvala s vaším řešením, použijte soubory EditorConfig. Další informace @@ -1983,11 +1949,6 @@ Souhlasím se všemi výše uvedenými podmínkami: Synchronizovat Zobrazení tříd - - Can't apply changes -- unexpected error: '{0}' - Změny nelze použít – neočekávaná chyba: {0} - - Analyzing '{0}' Analyzuje se {0}. diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.de.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.de.xlf index 9610d1a305924..9b0986e1c310f 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.de.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.de.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + Ein neuer Namespace wird erstellt. @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + Build + Liveanalyse (NuGet-Paket) @@ -69,7 +69,7 @@ Classifications - Klassifikationen + Klassifizierungen @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + IDE-Features zur Analyse von Nullable-Verweisen aktivieren Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + Auswertung ({0} Tasks in der Warteschlange) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + Installieren Sie von Microsoft empfohlene Roslyn-Analysetools, die zusätzliche Diagnosen und Fixes für allgemeine Design-, Sicherheits-, Leistungs- und Zuverlässigkeitsprobleme bei APIs bereitstellen. @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + Liveanalyse (VSIX-Erweiterung) @@ -154,17 +154,17 @@ Modifier preferences: - Modifizierereinstellungen: + Einstellungen für Modifizierer: Move to Namespace - Move to Namespace + In Namespace verschieben Namespace - Namespace + Namespace @@ -194,7 +194,7 @@ field - field + Feld This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + lokal This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + Lokale Funktion This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + Methode This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + Parameter This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + Eigenschaft This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + Typparameter This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + Feld This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + Lokal This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + Methode This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + Parameter This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + Typparameter This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + Angehalten ({0} Tasks in der Warteschlange) @@ -354,17 +354,17 @@ Prefer readonly fields - Schreibgeschützte Felder vorziehen + readonly-Felder bevorzugen Prefer simple 'using' statement - Einfache using-Anweisung vorziehen + Einfache using-Anweisung bevorzugen Prefer static local functions - Statische lokale Funktionen vorziehen + Statische lokale Funktionen bevorzugen @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + Hintergrundprozesse mit niedriger Priorität werden ausgeführt. @@ -414,12 +414,12 @@ Select _Dependents - A_bhängige Objekte auswählen + Abhängige _Objekte auswählen Select _Public - Ö_ffentliche Objekte auswählen + Öffentliche _auswählen @@ -449,12 +449,12 @@ Target Namespace: - Target Namespace: + Zielnamespace: This is an invalid namespace - This is an invalid namespace + Dies ist ein ungültiger Namespace. @@ -469,7 +469,7 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + .EDITORCONFIG-Kompatibilitätsmodus verwenden (Neustart erforderlich) @@ -504,7 +504,7 @@ This workspace does not support updating Visual Basic compilation options. - Das Aktualisieren von Visual Basic-Kompilieroptionen wird von diesem Arbeitsbereich nicht unterstützt. + Das Aktualisieren von Visual Basic-Kompilierungsoptionen wird von diesem Arbeitsbereich nicht unterstützt. @@ -1868,30 +1868,6 @@ Zusätzliche Informationen: {1} Ausblenden - - Changes are not allowed if the assembly has not been loaded. - Änderungen sind nicht zulässig, wenn die Assembly nicht geladen wurde. - - - - Changes are not allowed if the project wasn't built when debugging started. - Änderungen sind nicht zulässig, wenn das Projekt nicht beim Starten des Debugvorgangs erstellt wurde. - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - Änderungen sind nicht zulässig, wenn das Projekt nicht beim Start des Debugvorgangs geladen und erstellt wurde. - -Für die aktuelle Projektmappe ist die Option "Lightweight-Ladevorgang für Projektmappen" aktiviert. Deaktivieren Sie sie, um sicherzustellen, dass alle Projekte beim Starten des Debugvorgangs geladen werden. - - - - Changes are not allowed while code is running. - Während der Ausführung von Code sind keine Änderungen zulässig. - - Prefer local function over anonymous function Lokale Funktion gegenüber anonymer Funktion bevorzugen @@ -1927,21 +1903,11 @@ Für die aktuelle Projektmappe ist die Option "Lightweight-Ladevorgang für Proj automatische Eigenschaften bevorzugen - - Error while reading file '{0}': {1} - Fehler beim Lesen der Datei "{0}": {1} - - Module has been unloaded. Das Modul wurde entladen. - - Can't apply changes -- module '{0}' has been unloaded. - Änderungen können nicht angewendet werden. Das Modul "{0}" wurde entladen. - - Enable navigation to decompiled sources (experimental) Aktivieren der Navigation zu dekompilierten Quellen (experimentell) @@ -1975,7 +1941,7 @@ Ich stimme allen vorstehenden Bedingungen zu: Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - Die hier konfigurierten Einstellungen gelten nur für Ihren Computer. Verwenden Sie die .editorconfig-Dateien, um diese Einstellungen in Ihrer Projektmappe zu konfigurieren. + Ihre EditorConfig-Datei setzt möglicherweise die auf dieser Seite konfigurierten lokalen Einstellungen außer Kraft, die nur für Ihren Computer gelten. Verwenden Sie EditorConfig-Dateien, um diese Einstellungen für Ihre Projektmappe "mitzunehmen". Erfahren Sie mehr. @@ -1983,11 +1949,6 @@ Ich stimme allen vorstehenden Bedingungen zu: Synchronisierungsklassenansicht - - Can't apply changes -- unexpected error: '{0}' - Änderungen können nicht angewendet werden -- unerwarteter Fehler: {0} - - Analyzing '{0}' "{0}" wird analysiert. diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.es.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.es.xlf index e3b10ba97e5ac..94877774a99e1 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.es.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.es.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + Se creará un espacio de nombres @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + Compilación y análisis en directo (paquete NuGet) @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + Habilitar características de IDE de análisis de referencias que aceptan valores NULL Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + Evaluando ({0} tareas en cola) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + Instale los analizadores de Roslyn recomendados por Microsoft, que proporcionan diagnósticos y correcciones adicionales para problemas comunes de confiabilidad, rendimiento, seguridad y diseño de API. @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + Análisis en directo (extensión VSIX) @@ -159,12 +159,12 @@ Move to Namespace - Move to Namespace + Mover a espacio de nombres Namespace - Namespace + Espacio de nombres @@ -194,7 +194,7 @@ field - field + campo This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + Local This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + función local This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + método This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + parámetro This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + propiedad This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + parámetro de tipo This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + Campo This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + Local This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + método This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + Parámetro This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + Parámetro de tipo This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + En pausa ({0} tareas en cola) @@ -359,7 +359,7 @@ Prefer simple 'using' statement - Preferir instrucción "using" sencilla + Preferir la instrucción "using" sencilla @@ -379,7 +379,7 @@ Rename {0} to {1} - Cambiar el nombre de {0} a {1} + Cambiar nombre de {0} a {1} @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + Ejecutando procesos en segundo plano de baja prioridad @@ -419,7 +419,7 @@ Select _Public - _Seleccionar público + Seleccionar _público @@ -449,12 +449,12 @@ Target Namespace: - Target Namespace: + Espacio de nombres de destino: This is an invalid namespace - This is an invalid namespace + Este espacio de nombres no es válido @@ -469,12 +469,12 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + Usar el modo de compatibilidad .editorconfig (requiere reiniciar el equipo) Use enhanced colors for C# and Basic - Usar los colores mejorados para C# y Basic + Use los colores mejorados para C# y Basic @@ -779,7 +779,7 @@ The given DocumentId did not come from the Visual Studio workspace. - El DocumentID en cuestión no provenía del área de trabajo de Visual Studio. + El DocumentId en cuestión no provenía del área de trabajo de Visual Studio. @@ -1868,30 +1868,6 @@ Información adicional: {1} Atenuando - - Changes are not allowed if the assembly has not been loaded. - No se permiten cambios si no se ha cargado el ensamblado. - - - - Changes are not allowed if the project wasn't built when debugging started. - No se permiten cambios si el proyecto no se compiló al iniciar la depuración. - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - No se permiten cambios si el proyecto no se cargó y compiló al iniciar la depuración. - -La opción "Carga de solución ligera" está habilitada para la solución actual. Deshabilítela para asegurarse de que todos los proyectos se cargan al iniciar la depuración. - - - - Changes are not allowed while code is running. - No se permiten cambios mientras se ejecuta código. - - Prefer local function over anonymous function Preferir una función local frente a una función anónima @@ -1927,21 +1903,11 @@ La opción "Carga de solución ligera" está habilitada para la solución actual preferir propiedades automáticas - - Error while reading file '{0}': {1} - Error al leer el archivo "{0}": {1} - - Module has been unloaded. El módulo se descargó. - - Can't apply changes -- module '{0}' has been unloaded. - No se pueden aplicar cambios: el módulo "{0}" se ha descargado. - - Enable navigation to decompiled sources (experimental) Habilitar la navegación a orígenes decompilados (experimental) @@ -1975,7 +1941,7 @@ Estoy de acuerdo con todo lo anterior: Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - Los parámetros configurados aquí solo son aplicables a su equipo. Para configurar estos parámetros de manera que se desplacen con su solución, use los archivos .editorconfig. + El archivo .editorconfig puede invalidar la configuración local definida en esta página que solo se aplica a su máquina. Para configurar estos valores de manera que se desplacen con su solución, use los archivos EditorConfig. Mas información @@ -1983,11 +1949,6 @@ Estoy de acuerdo con todo lo anterior: Sincronizar vista de clases - - Can't apply changes -- unexpected error: '{0}' - No se pueden aplicar los cambios: error inesperado "{0}" - - Analyzing '{0}' Analizando “{0}” diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.fr.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.fr.xlf index 56aad1e685871..5b7d7b007391d 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.fr.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.fr.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + Un espace de noms va être créé @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + Build + analyse en temps réel (package NuGet) @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + Activer les fonctionnalités de l'IDE pour l'analyse des références Nullable Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + Évaluation ({0} tâches en file d'attente) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + Installer les analyseurs Roslyn recommandés par Microsoft, qui fournissent des diagnostics et des correctifs supplémentaires pour les problèmes usuels liés à la conception, à la sécurité, au niveau de performance et à la fiabilité des API @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + Analyse en temps réel (extension VSIX) @@ -154,17 +154,17 @@ Modifier preferences: - Préférences du modificateur : + Préférences de modificateur : Move to Namespace - Move to Namespace + Déplacer vers un espace de noms Namespace - Namespace + Espace de noms @@ -194,7 +194,7 @@ field - field + Champ This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + variable locale This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + fonction locale This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + méthode This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + paramètre This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + propriété This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + paramètre de type This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + Champ This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + Local This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + méthode This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + Paramètre This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + Paramètre de type This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + Suspendu ({0} tâches en file d'attente) @@ -354,12 +354,12 @@ Prefer readonly fields - Préférer les champs en lecture seule + Préférer les champs readonly Prefer simple 'using' statement - Préférer une déclaration 'using' simple + Préférer une instruction 'using' simple @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + Exécution des processus d’arrière-plan basse priorité @@ -449,12 +449,12 @@ Target Namespace: - Target Namespace: + Espace de noms cible : This is an invalid namespace - This is an invalid namespace + Ceci est un espace de noms non valide @@ -469,7 +469,7 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + Utiliser le mode de compatibilité de .editorconfig (nécessite un redémarrage) @@ -1868,30 +1868,6 @@ Informations supplémentaires : {1} Suppression - - Changes are not allowed if the assembly has not been loaded. - Les changements ne sont pas autorisés si l'assembly n'a pas été chargé. - - - - Changes are not allowed if the project wasn't built when debugging started. - Les changements ne sont pas autorisés si le projet n'est pas généré au démarrage du débogage. - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - Les changements ne sont pas autorisés si le projet n'est pas chargé et généré au démarrage du débogage. - -'Chargement de solution allégé' est activé pour la solution actuelle. Désactivez cette fonctionnalité pour avoir la certitude que tous les projets sont chargés au démarrage du débogage. - - - - Changes are not allowed while code is running. - Les changements ne sont pas autorisés durant l'exécution du code. - - Prefer local function over anonymous function Préférer une fonction locale à une fonction anonyme @@ -1927,21 +1903,11 @@ Informations supplémentaires : {1} préférer les propriétés automatiques - - Error while reading file '{0}': {1} - Erreur durant la lecture du fichier '{0}' : {1} - - Module has been unloaded. Le module a été déchargé. - - Can't apply changes -- module '{0}' has been unloaded. - Impossible d'appliquer les changements -- Le module '{0}' a été déchargé. - - Enable navigation to decompiled sources (experimental) Activer la navigation vers des sources décompilées (expérimental) @@ -1975,7 +1941,7 @@ Je suis d'accord avec tout ce qui précède : Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - Les paramètres configurés ici s'appliquent uniquement à votre machine. Pour configurer ces paramètres afin qu'ils soient liés à votre solution, utilisez les fichiers .editorconfig. + Votre fichier .editorconfig peut remplacer les paramètres locaux configurés sur cette page, qui s'appliquent uniquement à votre machine. Pour configurer ces paramètres afin qu'ils soient liés à votre solution, utilisez les fichiers EditorConfig. En savoir plus @@ -1983,11 +1949,6 @@ Je suis d'accord avec tout ce qui précède : Synchroniser l'affichage de classes - - Can't apply changes -- unexpected error: '{0}' - Impossible d'appliquer les changements -- Erreur inattendue : '{0}' - - Analyzing '{0}' Analyse de '{0}' diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.it.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.it.xlf index a9a54717e39d0..213290ff6c536 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.it.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.it.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + Verrà creato un nuovo spazio dei nomi @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + Compilazione + analisi in tempo reale (pacchetto NuGet) @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + Abilita le funzionalità IDE per l'analisi dei riferimenti nullable Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + In fase di valutazione ({0} attività in coda) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + Installare gli analizzatori Roslyn consigliati da Microsoft, che offrono ulteriori funzionalità di diagnostica e correzioni per problemi comuni di sicurezza, prestazioni, affidabilità e progettazione di API @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + Analisi in tempo reale (estensione VSIX) @@ -159,12 +159,12 @@ Move to Namespace - Move to Namespace + Sposta nello spazio dei nomi Namespace - Namespace + Spazio dei nomi @@ -194,7 +194,7 @@ field - field + campo This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + variabile locale This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + funzione locale This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + metodo This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + parametro This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + proprietà This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + parametro di tipo This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + Campo This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + Locale This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + metodo This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + Parametro This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + Parametro di tipo This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + Sospeso ({0} attività in coda) @@ -354,7 +354,7 @@ Prefer readonly fields - Preferisci campi di sola lettura + Preferisci campi readonly @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + Esecuzione di processi in background con priorità bassa @@ -449,12 +449,12 @@ Target Namespace: - Target Namespace: + Spazio dei nomi di destinazione: This is an invalid namespace - This is an invalid namespace + Questo è uno spazio dei nomi non valido @@ -469,7 +469,7 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + Usa la modalità di compatibilità di .editorconfig (richiede il riavvio) @@ -764,7 +764,7 @@ DocumentPath is illegal - Il percorso del documento non è valido + Il valore di DocumentPath non è valido @@ -1868,30 +1868,6 @@ Informazioni aggiuntive: {1} Dissolvenza - - Changes are not allowed if the assembly has not been loaded. - Le modifiche non sono consentite se l'assembly non è stato caricato. - - - - Changes are not allowed if the project wasn't built when debugging started. - Le modifiche non sono consentite se il progetto non era stato compilato quando è stato avviato il debug. - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - Le modifiche non sono consentite se il progetto non era stato caricato e compilato quando è stato avviato il debug. - -L'opzione 'Caricamento leggero soluzioni' è abilitata per la soluzione corrente. Disabilitarla per essere certi che tutti i progetti siano stati caricati all'avvio del debug. - - - - Changes are not allowed while code is running. - Le modifiche non sono consentite se il codice è in esecuzione. - - Prefer local function over anonymous function Preferisci la funzione locale a quella anonima @@ -1927,21 +1903,11 @@ L'opzione 'Caricamento leggero soluzioni' è abilitata per la soluzione corrente preferisci proprietà automatiche - - Error while reading file '{0}': {1} - Si è verificato un errore durante la lettura del file '{0}': {1} - - Module has been unloaded. Il modulo è stato scaricato. - - Can't apply changes -- module '{0}' has been unloaded. - Non è possibile applicare le modifiche. Il modulo '{0}' è stato scaricato. - - Enable navigation to decompiled sources (experimental) Abilita lo spostamento in origini decompilate (sperimentale) @@ -1975,7 +1941,7 @@ L'utente accetta le condizioni sopra riportate: Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - Le impostazioni configurate qui si applicano solo al computer locale. Per configurare queste impostazioni in modo che siano associate alla soluzione, usare file con estensione editorconfig. + Il file con estensione editorconfig potrebbe eseguire l'override delle impostazioni locali configurate in questa pagina che si applicano solo al computer locale. Per configurare queste impostazioni in modo che siano associate alla soluzione, usare file con estensione editorconfig. Altre informazioni @@ -1983,11 +1949,6 @@ L'utente accetta le condizioni sopra riportate: Sincronizza visualizzazione classi - - Can't apply changes -- unexpected error: '{0}' - Non è possibile applicare le modifiche. Errore imprevisto: '{0}' - - Analyzing '{0}' Analisi di '{0}' diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ja.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ja.xlf index ea66496a664e7..a1fb69d3afa74 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ja.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ja.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + 新しい名前空間が作成されます @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + ビルド + ライブ分析 (NuGet パッケージ) @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + NULL 許容参照分析の IDE 機能を有効にします Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + 評価中 ({0} 個のタスクがキューにあります) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + Microsoft で推奨されている Roslyn アナライザーをインストールします。これにより、一般的な API の設計、セキュリティ、パフォーマンス、信頼性の問題に対する追加の診断と修正が提供されます @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + ライブ分析 (VSIX 拡張機能) @@ -154,17 +154,17 @@ Modifier preferences: - 修飾子の優先順位: + 修飾子設定: Move to Namespace - Move to Namespace + 名前空間に移動します Namespace - Namespace + 名前空間 @@ -194,7 +194,7 @@ field - field + フィールド This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + ローカル This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + ローカル関数 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + メソッド This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + パラメーター This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + プロパティ This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + 型パラメーター This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + フィールド This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + ローカル This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + メソッド This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + パラメーター This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + 型パラメーター This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + 一時停止中 ({0} 個のタスクがキューにあります) @@ -354,17 +354,17 @@ Prefer readonly fields - 読み取り専用フィールドを優先 + readonly フィールドを優先する Prefer simple 'using' statement - 単純な 'using' ステートメントを優先 + 単純な 'using' ステートメントを優先する Prefer static local functions - 静的ローカル関数を優先 + 静的ローカル関数を優先する @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + 優先度の低いバックグラウンド プロセスを実行しています @@ -449,12 +449,12 @@ Target Namespace: - Target Namespace: + ターゲット名前空間: This is an invalid namespace - This is an invalid namespace + これは無効な名前空間です @@ -469,12 +469,12 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + .editorconfig 互換性モードを使用する (再起動が必要) Use enhanced colors for C# and Basic - C# および Basic で拡張された色を使用します + C# および Basic 用に拡張された色を使用 @@ -504,7 +504,7 @@ This workspace does not support updating Visual Basic compilation options. - このワークスペースでは、Visual Basic のコンパイル オプションの更新はサポートされていません。 + このワークスペースでは、Visual Basic コンパイル オプションの更新がサポートされていません。 @@ -1868,30 +1868,6 @@ Additional information: {1} フェード - - Changes are not allowed if the assembly has not been loaded. - アセンブリが読み込まれていない場合、変更は許可されません。 - - - - Changes are not allowed if the project wasn't built when debugging started. - デバッグを開始したときにプロジェクトがビルドされていない場合、変更は許可されません。 - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - デバッグを開始したときにプロジェクトが読み込みおよびビルドされていない場合、変更は許可されません。 - -現在のソリューションで 'ライトウェイト ソリューション ロード' が有効になっています。無効にして、デバッグの開始時にすべてのプロジェクトが読み込まれていることを確認します。 - - - - Changes are not allowed while code is running. - コードの実行中は変更が許可されません。 - - Prefer local function over anonymous function 匿名関数よりローカル関数を優先します @@ -1927,21 +1903,11 @@ Additional information: {1} 自動プロパティを優先する - - Error while reading file '{0}': {1} - ファイル {0}' の読み取り中にエラーが発生しました: {1} - - Module has been unloaded. モジュールがアンロードされました。 - - Can't apply changes -- module '{0}' has been unloaded. - 変更を適用できません -- モジュール '{0}' がアンロードされています。 - - Enable navigation to decompiled sources (experimental) 逆コンパイルされたソースへのナビゲーションを有効にする (試験段階) @@ -1975,7 +1941,7 @@ I agree to all of the foregoing: Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - ここで構成される設定は、ご使用のマシンにのみ適用されます。これらの設定をソリューションで使用するように構成するには、.editorconfig ファイルを使用します。 + このページに構成されているローカル設定 (ご使用のマシンにのみ適用される) が .editorconfig ファイルによって上書きされる可能性があります。これらの設定をソリューション全体に適用するよう構成するには、EditorConfig ファイルを使用します。詳細情報 @@ -1983,11 +1949,6 @@ I agree to all of the foregoing: クラス ビューの同期 - - Can't apply changes -- unexpected error: '{0}' - 変更を適用できません。予期しないエラー: '{0}' - - Analyzing '{0}' '{0}' の分析 diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ko.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ko.xlf index febe93d1e1f29..0c90d1d746254 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ko.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ko.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + 새 네임스페이스가 만들어집니다. @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + 빌드 + 실시간 분석(NuGet 패키지) @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + nullable 참조 분석 IDE 기능 사용 Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + 평가 중(큐의 {0}개 작업) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + 일반적인 API 디자인, 보안, 성능 및 안정성 문제에 대한 추가 진단 및 수정을 제공하는 Microsoft 권장 Roslyn 분석기를 설치합니다. @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + 실시간 분석(VSIX 확장) @@ -159,12 +159,12 @@ Move to Namespace - Move to Namespace + 네임스페이스로 이동 Namespace - Namespace + 네임스페이스 @@ -194,7 +194,7 @@ field - field + 필드 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + 로컬 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + 로컬 함수 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + 메서드 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + 매개 변수 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + 속성 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + 형식 매개 변수 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + 필드 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + 로컬 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + 메서드 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + 매개 변수 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + 형식 매개 변수 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + 일시 중지됨(큐의 {0}개 작업) @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + 낮은 우선 순위 백그라운드 프로세스 실행 중 @@ -449,12 +449,12 @@ Target Namespace: - Target Namespace: + 대상 네임스페이스: This is an invalid namespace - This is an invalid namespace + 잘못된 네임스페이스입니다. @@ -469,12 +469,12 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + .editorconfig 호환성 모드 사용(다시 시작해야 함) Use enhanced colors for C# and Basic - C# 및 Basic에 향상된 색 사용 + C# 및 Basic용 향상된 색 사용 @@ -1116,7 +1116,7 @@ Use the dropdown to view and switch to other projects this file may belong to. Suppression state is supported only for intellisense diagnostics, which are for the current solution snapshot. Switch to 'Intellisense' diagnostics for suppression. - 비표시 오류(Suppression) 상태는 현재 솔루션 스냅숏인 intellisense 진단에 대해서만 지원됩니다. 비표시 오류(Suppression)에 대해 'Intellisense' 진단으로 전환하세요. + 비표시 오류(Suppression) 상태는 현재 솔루션 스냅샷인 intellisense 진단에 대해서만 지원됩니다. 비표시 오류(Suppression)에 대해 'Intellisense' 진단으로 전환하세요. @@ -1868,30 +1868,6 @@ Additional information: {1} 페이딩 - - Changes are not allowed if the assembly has not been loaded. - 어셈블리가 로드되지 않은 경우에는 변경할 수 없습니다. - - - - Changes are not allowed if the project wasn't built when debugging started. - 디버깅을 시작할 때 프로젝트가 작성되지 않은 경우에는 변경할 수 없습니다. - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - 디버깅을 시작할 때 프로젝트가 로드 및 작성되지 않은 경우에는 변경할 수 없습니다. - -현재 솔루션에 대해 '경량 솔루션 로드'가 사용되었습니다. 이 기능을 사용하지 않도록 설정하여 디버깅을 시작할 때 모든 프로젝트가 로드되도록 하세요. - - - - Changes are not allowed while code is running. - 코드가 실행되고 있을 때는 변경할 수 없습니다. - - Prefer local function over anonymous function 익명 함수보다 로컬 함수 선호 @@ -1927,21 +1903,11 @@ Additional information: {1} 자동 속성 선호 - - Error while reading file '{0}': {1} - '{0}' 파일을 읽는 동안 오류가 발생했습니다. {1} - - Module has been unloaded. 모듈이 언로드되었습니다. - - Can't apply changes -- module '{0}' has been unloaded. - 변경 내용을 적용할 수 없습니다. '{0}' 모듈이 언로드되었습니다. - - Enable navigation to decompiled sources (experimental) 디컴파일된 소스에 탐색을 사용하도록 설정(실험적) @@ -1975,7 +1941,7 @@ I agree to all of the foregoing: Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - 여기서 구성하는 설정은 사용자의 컴퓨터에만 적용됩니다. 이러한 설정을 사용자의 솔루션에서 사용하도록 구성하려면 .editorconfig 파일을 사용하세요. + .editorconfig 파일이 이 페이지에서 구성된 로컬 설정을 재정의할 수 있으며 해당 내용은 사용자의 머신에만 적용됩니다. 솔루션과 함께 이동하도록 해당 설정을 구성하려면 EditorConfig 파일을 사용하세요. 추가 정보 @@ -1983,11 +1949,6 @@ I agree to all of the foregoing: 클래스 뷰 동기화 - - Can't apply changes -- unexpected error: '{0}' - 변경 내용을 적용할 수 없음 - 예기치 않은 오류: '{0}' - - Analyzing '{0}' '{0}' 분석 중 diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pl.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pl.xlf index 37b897a623481..e5eff64640c45 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pl.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pl.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + Zostanie utworzona nowa przestrzeń nazw @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + Kompilacja i analiza na żywo (pakiet NuGet) @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + Włącz funkcje środowiska IDE do analizy odwołań dopuszczających wartość null Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + Szacowanie (zadania w kolejce: {0}) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + Zainstaluj analizatory Roslyn rekomendowane przez firmę Microsoft, które oferują dodatkową diagnostykę i poprawki w zakresie typowego projektu interfejsu API, zabezpieczeń, wydajności i niezawodności @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + Analiza na żywo (rozszerzenie VSIX) @@ -154,17 +154,17 @@ Modifier preferences: - Preferencje dotyczące modyfikatorów: + Preferencje modyfikatora: Move to Namespace - Move to Namespace + Przenieś do przestrzeni nazw Namespace - Namespace + Obszar nazw @@ -194,7 +194,7 @@ field - field + pole This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + lokalne This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + funkcja lokalna This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + metoda This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + parametr This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + właściwość This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + parametr typu This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + Pole This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + Lokalny This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + metoda This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + Parametr This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + Parametr typu This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + Wstrzymano (zadania w kolejce: {0}) @@ -379,7 +379,7 @@ Rename {0} to {1} - Zmień nazwę elementu {0} na {1} + Zmień nazwę {0} na {1} @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + Uruchamianie procesów w tle o niskim priorytecie @@ -419,7 +419,7 @@ Select _Public - Wybierz elementy _publiczne + _Wybierz elementy publiczne @@ -449,12 +449,12 @@ Target Namespace: - Target Namespace: + Docelowa przestrzeń nazw: This is an invalid namespace - This is an invalid namespace + To jest nieprawidłowa przestrzeń nazw @@ -469,12 +469,12 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + Użyj trybu zgodności pliku editorconfig (wymaga ponownego uruchomienia) Use enhanced colors for C# and Basic - Użyj ulepszonych kolorów dla języków C# i Basic + Użyj kolorów rozszerzonych dla języków C# i Basic @@ -504,7 +504,7 @@ This workspace does not support updating Visual Basic compilation options. - Ten obszar roboczy nie obsługuje aktualizowania opcji kompilacji języka Visual Basic. + Ten obszar roboczy nie obsługuje aktualizowania opcji kompilacji dla języka Visual Basic. @@ -1868,30 +1868,6 @@ Dodatkowe informacje: {1} Zanikanie - - Changes are not allowed if the assembly has not been loaded. - Zmiany są niedozwolone, jeśli zestaw nie został załadowany. - - - - Changes are not allowed if the project wasn't built when debugging started. - Zmiany są niedozwolone, jeśli projekt nie był skompilowany podczas uruchamiania debugowania. - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - Zmiany są niedozwolone, jeśli projekt nie był załadowany i skompilowany podczas uruchamiania debugowania. - -Funkcja „Uproszczone ładowanie rozwiązania” jest włączona dla bieżącego rozwiązania. Wyłącz ją, aby zapewnić załadowanie wszystkich projektów podczas uruchamiania debugowania. - - - - Changes are not allowed while code is running. - Zmiany są niedozwolone, gdy kod jest uruchomiony. - - Prefer local function over anonymous function Preferuj funkcję lokalną zamiast funkcji anonimowej @@ -1927,21 +1903,11 @@ Funkcja „Uproszczone ładowanie rozwiązania” jest włączona dla bieżąceg preferuj właściwości automatyczne - - Error while reading file '{0}': {1} - Błąd podczas odczytywania pliku „{0}”: {1} - - Module has been unloaded. Moduł został zwolniony. - - Can't apply changes -- module '{0}' has been unloaded. - Nie można zastosować zmian — moduł „{0}” został zwolniony. - - Enable navigation to decompiled sources (experimental) Włącz nawigowanie do dekompilowanych źródeł (funkcja eksperymentalna) @@ -1975,7 +1941,7 @@ Wyrażam zgodę na wszystkie następujące postanowienia: Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - Ustawienia skonfigurowane w tym miejscu mają zastosowanie tylko do Twojej maszyny. Aby skonfigurować te ustawienia tak, aby były przenoszone z Twoim rozwiązaniem, użyj plików .editorconfig. + Plik editorconfig może przesłonić ustawienia lokalne skonfigurowane na tej stronie, które mają zastosowanie tylko do maszyny. Aby skonfigurować te ustawienia w celu ich przenoszenia wraz z rozwiązaniem, skorzystaj z plików EditorConfig. Więcej informacji @@ -1983,11 +1949,6 @@ Wyrażam zgodę na wszystkie następujące postanowienia: Synchronizuj widok klasy - - Can't apply changes -- unexpected error: '{0}' - Nie można zastosować zmian — nieoczekiwany błąd: „{0}” - - Analyzing '{0}' Analizowanie elementu „{0}” diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pt-BR.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pt-BR.xlf index 31d3fe66d1243..95b86f9066baa 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pt-BR.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.pt-BR.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + Um namespace será criado @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + Build + análise em tempo real (pacote NuGet) @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + Habilitar recursos do IDE de análise de referência que permite valor nulo Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + Avaliando ({0} tarefas na fila) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + Instale os analisadores Roslyn recomendados pela Microsoft, que fornecem diagnósticos adicionais e correções para problemas comuns de confiabilidade, desempenho, segurança e design de API @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + Análise em tempo real (extensão do VSIX) @@ -154,17 +154,17 @@ Modifier preferences: - Preferências de modificador: + Preferências do modificador: Move to Namespace - Move to Namespace + Mover para o Namespace Namespace - Namespace + Namespace @@ -194,7 +194,7 @@ field - field + Campo This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + local This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + função local This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + método This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + parâmetro This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + Propriedade. This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + parâmetro de tipo This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + Campo This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + Local This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + método This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + Parâmetro This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + Parâmetro de Tipo This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + Em pausa ({0} tarefas na fila) @@ -354,17 +354,17 @@ Prefer readonly fields - Preferir campos somente leitura + Preferir campos readonly Prefer simple 'using' statement - Preferir instrução 'using' simples + Preferir a instrução 'using' simples Prefer static local functions - Preferir funções locais estáticas + Preferir as funções locais estáticas @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + Executando processos de baixa prioridade em segundo plano @@ -444,17 +444,17 @@ Show completion list - Mostrar lista de conclusão + Mostrar a lista de conclusão Target Namespace: - Target Namespace: + Namespace de Destino: This is an invalid namespace - This is an invalid namespace + Este é um namespace inválido @@ -469,7 +469,7 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + Usar o modo de compatibilidade .editorconfig (exige reinicialização) @@ -1868,30 +1868,6 @@ Informações adicionais: {1} Esmaecimento - - Changes are not allowed if the assembly has not been loaded. - As alterações não serão permitidas se o assembly não tiver sido carregado. - - - - Changes are not allowed if the project wasn't built when debugging started. - Não serão permitidas alterações se o projeto não for criado quando a depuração iniciar. - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - Não serão permitidas alterações se o projeto não for carregado e compilado quando a depuração iniciar. - -O 'Carregamento da solução leve' está habilitado para a solução atual. Desabilite-o para garantir que todos os projetos estejam carregados quando a depuração iniciar. - - - - Changes are not allowed while code is running. - As alterações não são permitidas enquanto o código está em execução. - - Prefer local function over anonymous function Preferir usar função anônima em vez de local @@ -1927,21 +1903,11 @@ O 'Carregamento da solução leve' está habilitado para a solução atual. Desa preferir propriedades automáticas - - Error while reading file '{0}': {1} - Erro ao ler o arquivo '{0}': {1} - - Module has been unloaded. O módulo foi descarregado. - - Can't apply changes -- module '{0}' has been unloaded. - Não é possível aplicar alterações -- o módulo '{0}' foi descarregado. - - Enable navigation to decompiled sources (experimental) Habilitar a navegação para origens descompiladas (experimental) @@ -1975,7 +1941,7 @@ Eu concordo com todo o conteúdo supracitado: Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - As configurações definidas aqui se aplicam somente a seu computador. Para definir essas configurações para viajar com sua solução, use arquivos .editorconfig. + O arquivo .editorconfig pode substituir as configurações locais definidas nesta página que se aplicam somente ao seu computador. Para definir que essas configurações se desloquem com a sua solução, use arquivos EditorConfig. Mais informações @@ -1983,11 +1949,6 @@ Eu concordo com todo o conteúdo supracitado: Sincronizar Modo de Exibição de Classe - - Can't apply changes -- unexpected error: '{0}' - Não é possível aplicar as alterações – erro inesperado: '{0}' - - Analyzing '{0}' Analisando '{0}' diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ru.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ru.xlf index b67263e558f80..be3d13a6ee084 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ru.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.ru.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + Будет создано пространство имен @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + Сборка и динамический анализ (пакет NuGet) @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + Включить функции IDE для анализа ссылок, допускающих значение NULL Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + Оценка (задач в очереди: {0}) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + Установите рекомендуемые корпорацией Майкрософт анализаторы Roslyn, которые предоставляют дополнительные средства диагностики и исправления для распространенных проблем, связанных с разработкой, безопасностью, производительностью и надежностью API. @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + Динамический анализ (расширение VSIX) @@ -149,22 +149,22 @@ Members - Элементы + Члены Modifier preferences: - Предпочтения для модификатора: + Предпочтения модификатора: Move to Namespace - Move to Namespace + Переместить в пространство имен Namespace - Namespace + Пространство имен @@ -194,7 +194,7 @@ field - field + Поле This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + локальный This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + локальная функция This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + метод This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + параметр This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + свойство This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + параметр типа This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + Поле This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + Локальные This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + метод This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + Параметр This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + Параметр типа This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + Приостановлено (задач в очереди: {0}) @@ -369,7 +369,7 @@ Pull Members Up - Поиск элементов + Повышение элементов @@ -379,7 +379,7 @@ Rename {0} to {1} - Переименовать "{0}" в "{1}" + Переименовать {0} в {1} @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + Запуск фоновых процессов с низким приоритетом @@ -414,7 +414,7 @@ Select _Dependents - Выбрать _зависимые + Выбрать _зависимости @@ -449,12 +449,12 @@ Target Namespace: - Target Namespace: + Целевое пространство имен: This is an invalid namespace - This is an invalid namespace + Это недопустимое пространство имен. @@ -469,7 +469,7 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + Использовать режим совместимости с .editorconfig (требуется перезапуск) @@ -504,7 +504,7 @@ This workspace does not support updating Visual Basic compilation options. - Эта рабочая область не поддерживает изменение параметров компиляции Visual Basic. + Эта рабочая область не поддерживает обновление параметров компиляции Visual Basic. @@ -1868,30 +1868,6 @@ Additional information: {1} Исчезание - - Changes are not allowed if the assembly has not been loaded. - Изменения не разрешены, если сборка не загружена. - - - - Changes are not allowed if the project wasn't built when debugging started. - Изменения не разрешены, если проект не был построен при запуске отладки. - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - Изменения не разрешены, если проект не был загружен и построен при запуске отладки. - -"Упрощенная загрузка решения" включена для текущего решения. Отключите ее, чтобы гарантировать загрузку всех проектов при запуске отладки. - - - - Changes are not allowed while code is running. - Изменения не разрешены во время выполнения кода. - - Prefer local function over anonymous function Предпочитать локальную функцию анонимной функции @@ -1927,21 +1903,11 @@ Additional information: {1} предпочитать автосвойства - - Error while reading file '{0}': {1} - Ошибка при чтении файла "{0}": {1} - - Module has been unloaded. Модуль был выгружен. - - Can't apply changes -- module '{0}' has been unloaded. - Не удается применить изменения — модуль "{0}" был выгружен. - - Enable navigation to decompiled sources (experimental) Включить переход к декомпилированным источникам (экспериментальная функция) @@ -1975,7 +1941,7 @@ I agree to all of the foregoing: Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - Заданные здесь параметры применяются только на вашем компьютере. Чтобы привязать параметры к решению, используйте EDITORCONFIG-файлы. + Файл EditorConfig может переопределять локальные параметры, настроенные на этой странице, только для этого компьютера. Чтобы эти параметры были привязаны к решению, используйте файлы EditorConfig. Дополнительные сведения. @@ -1983,11 +1949,6 @@ I agree to all of the foregoing: Синхронизировать представление классов - - Can't apply changes -- unexpected error: '{0}' - Не удается применить изменения, так как возникла непредвиденная ошибка: "{0}" - - Analyzing '{0}' Выполняется анализ "{0}" diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.tr.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.tr.xlf index dcd914d755808..22d442d197fb7 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.tr.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.tr.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + Yeni bir ad alanı oluşturulacak @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + Derleme ve canlı analiz (NuGet paketi) @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + Boş değer atanabilir başvuru analizi IDE özelliklerini etkinleştir Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + Değerlendiriliyor (kuyrukta {0} görev var) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + Microsoft'un önerdiği, genel API tasarımı, güvenlik, performans ve güvenilirlik sorunları için ek tanılama ve düzeltmeler sağlayan Roslyn çözümleyicilerini yükleyin @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + Canlı analiz (VSIX uzantısı) @@ -159,12 +159,12 @@ Move to Namespace - Move to Namespace + Ad Alanına Taşı Namespace - Namespace + Ad alanı @@ -194,7 +194,7 @@ field - field + alan This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + yerel This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + yerel işlev This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + yöntem This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + parametre This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + özellik This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + tür parametresi This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + Alan This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + Yerel This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + yöntem This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + Parametre This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + Tür Parametresi This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + Duraklatıldı (kuyrukta {0} görev var) @@ -354,7 +354,7 @@ Prefer readonly fields - Salt okunur alanları tercih et + Saltokunur alanları tercih et @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + Düşük öncelikli arka plan işlemleri çalıştırılıyor @@ -414,12 +414,12 @@ Select _Dependents - Bağımlıları _seçin + _Bağımlıları Seçin Select _Public - Ortak _seçin + _Geneli Seçin @@ -444,17 +444,17 @@ Show completion list - Tamamlanma listesini göster + Tamamlama listesini göster Target Namespace: - Target Namespace: + Hedef Ad Alanı: This is an invalid namespace - This is an invalid namespace + Bu geçersiz bir ad alanı @@ -469,7 +469,7 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + .editorconfig uyumluluk modunu kullanın (yeniden başlatma gerektirir) @@ -1868,30 +1868,6 @@ Ek bilgiler: {1} Soluklaştırılıyor - - Changes are not allowed if the assembly has not been loaded. - Bütünleştirilmiş kod yüklenmediyse değişikliklere izin verilmez. - - - - Changes are not allowed if the project wasn't built when debugging started. - Hata ayıklama başlatıldığında proje derlenemişse değişikliklere izin verilmez. - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - Hata ayıklama başlatıldığında proje yüklenmemiş ve derlenmemişse değişikliklere izin verilmez. - -Geçerli durum için 'basit çözüm yükü' etkin. Hata ayıklama başlatıldığında tüm projelerin yüklenmiş olduğundan emin olmak için bunu devre dışı bırakın. - - - - Changes are not allowed while code is running. - Kod çalışırken değişikliklere izin verilmez. - - Prefer local function over anonymous function Anonim işlevler yerine yerel işlevleri tercih et @@ -1927,21 +1903,11 @@ Geçerli durum için 'basit çözüm yükü' etkin. Hata ayıklama başlatıldı otomatik özellikleri tercih et - - Error while reading file '{0}': {1} - '{0}' dosyası okunurken hata: {1} - - Module has been unloaded. Modül kaldırıldı. - - Can't apply changes -- module '{0}' has been unloaded. - Değişiklikler uygulanamıyor -- '{0}' modülü kaldırıldı. - - Enable navigation to decompiled sources (experimental) Derlemesi ayrılan kaynaklar için gezintiyi etkinleştirme (deneysel) @@ -1975,7 +1941,7 @@ Aşağıdakilerin tümünü onaylıyorum: Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - Burada yapılandırılan ayarlar yalnızca makineniz için geçerlidir. Bu ayarları çözümünüzle birlikte taşımak için .editorconfig dosyalarını kullanın. + .editorconfig dosyanız, bu sayfada yapılandırılan ve yalnızca makinenizde uygulanan yerel ayarları geçersiz kılabilir. Bu ayarları çözümünüzle birlikte hareket etmek üzere yapılandırmak için EditorConfig dosyalarını kullanın. Daha fazla bilgi @@ -1983,11 +1949,6 @@ Aşağıdakilerin tümünü onaylıyorum: Sınıf Görünümünü Eşitle - - Can't apply changes -- unexpected error: '{0}' - Değişiklikler uygulanamıyor - beklenmeyen hata: '{0}' - - Analyzing '{0}' '{0}' Analiz Ediliyor diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hans.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hans.xlf index f41ccedd66e74..5eb6c7bf56837 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hans.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hans.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + 将创建一个新的命名空间 @@ -24,7 +24,7 @@ Allow: - Allow: + 允许: @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + 生成 + 实时分析(NuGet 包) @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + 启用可为 null 的引用分析 IDE 功能 Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + 正在评估(队列中有 {0} 个任务) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + 安装 Microsoft 推荐的 Roslyn 分析器,它提供了针对常见 API 设计、安全性、性能和可靠性问题的额外诊断和修补程序 @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + 实时分析(VSIX 扩展) @@ -159,12 +159,12 @@ Move to Namespace - Move to Namespace + 移动到命名空间 Namespace - Namespace + 命名空间 @@ -194,7 +194,7 @@ field - field + 字段 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + 局部 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + 本地函数 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + 方法 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + 参数 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + 属性 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + 类型形参 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + 字段 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + 本地 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + 方法 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + 参数 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + 类型参数 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + 已暂停(队列中有 {0} 个任务) @@ -359,7 +359,7 @@ Prefer simple 'using' statement - 首选简单的 “using” 语句 + 首选简单的 "using" 语句 @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + 正在运行低优先级后台进程 @@ -449,12 +449,12 @@ Target Namespace: - Target Namespace: + 目标命名空间: This is an invalid namespace - This is an invalid namespace + 这是一个无效的命名空间 @@ -469,7 +469,7 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + 使用 .editorconfig 兼容模式(需要重启) @@ -504,7 +504,7 @@ This workspace does not support updating Visual Basic compilation options. - 此工作区不支持更新 Visual Basic 完成选项。 + 此工作区不支持更新 Visual Basic 编译选项。 @@ -779,7 +779,7 @@ The given DocumentId did not come from the Visual Studio workspace. - 给定的文档 ID 并非来自 Visual Studio 工作区。 + 给定的 DocumentId 并非来自 Visual Studio 工作区。 @@ -1868,30 +1868,6 @@ Additional information: {1} 淡入淡出 - - Changes are not allowed if the assembly has not been loaded. - 未加载程序集时不允许进行更改。 - - - - Changes are not allowed if the project wasn't built when debugging started. - 如果项目不是在启动调试时生成的,则不允许进行更改。 - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - 如果项目不是在启动调试时加载和生成的,则不允许进行更改。 - -已为当前解决方案启用“轻型解决方案加载”。在开始调试时将其禁用,以确保加载全部项目。 - - - - Changes are not allowed while code is running. - 代码正在运行,此时不允许进行更改。 - - Prefer local function over anonymous function 首选本地函数而不是匿名函数 @@ -1927,21 +1903,11 @@ Additional information: {1} 首选自动属性 - - Error while reading file '{0}': {1} - 读取文件“{0}”时出错: {1} - - Module has been unloaded. 已卸载模块。 - - Can't apply changes -- module '{0}' has been unloaded. - 无法应用更改 - 已卸载模块“{0}”。 - - Enable navigation to decompiled sources (experimental) 支持导航到反编译源(实验) @@ -1975,7 +1941,7 @@ I agree to all of the foregoing: Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - 此处配置的设置仅适用于计算机。要配置这些设置以使用解决方案,请使用 .editorconfig 文件。 + .editorconfig 文件可能会替代在本页上配置的仅适用于你的计算机的本地设置。要配置这些设置,使其始终随解决方案一起提供,请使用 EditorConfig 文件。详细信息 @@ -1983,11 +1949,6 @@ I agree to all of the foregoing: 同步类视图 - - Can't apply changes -- unexpected error: '{0}' - 无法应用更改 - 意外错误:“{0}” - - Analyzing '{0}' 分析“{0}” diff --git a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hant.xlf b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hant.xlf index 9ee0c5c01025a..918b73d99f70c 100644 --- a/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hant.xlf +++ b/src/VisualStudio/Core/Def/xlf/ServicesVSResources.zh-Hant.xlf @@ -4,7 +4,7 @@ A new namespace will be created - A new namespace will be created + 將會建立新的命名空間 @@ -59,7 +59,7 @@ Build + live analysis (NuGet package) - Build + live analysis (NuGet package) + 組建 + 即時分析 (NuGet 套件) @@ -84,12 +84,12 @@ Enable nullable reference analysis IDE features - Enable nullable reference analysis IDE features + 啟用可為 null 的參考分析 IDE 功能 Evaluating ({0} tasks in queue) - Evaluating ({0} tasks in queue) + 正在評估 (佇列中的 {0} 工作) @@ -114,7 +114,7 @@ Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues - Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues + 安裝 Microsoft 建議的 Roslyn 分析器,其可為一般 API 設計、安全性、效能及可靠性問題提供額外的診斷與修正 @@ -134,7 +134,7 @@ Live analysis (VSIX extension) - Live analysis (VSIX extension) + 即時分析 (VSIX 延伸模組) @@ -159,12 +159,12 @@ Move to Namespace - Move to Namespace + 移到命名空間 Namespace - Namespace + 命名空間 @@ -194,7 +194,7 @@ field - field + 欄位 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data). @@ -204,17 +204,17 @@ local - local + 區域 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable". local function - local function + 區域函式 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function. method - method + 方法 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code. @@ -224,12 +224,12 @@ parameter - parameter + 參數 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method. property - property + 屬性 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data). @@ -239,7 +239,7 @@ type parameter - type parameter + 類型參數 This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter". @@ -264,7 +264,7 @@ Field - Field + 欄位 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data). @@ -274,12 +274,12 @@ Local - Local + 本機 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable". Method - Method + 方法 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method". @@ -294,7 +294,7 @@ Parameter - Parameter + 參數 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method. @@ -309,7 +309,7 @@ Type Parameter - Type Parameter + 型別參數 This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter". @@ -334,7 +334,7 @@ Paused ({0} tasks in queue) - Paused ({0} tasks in queue) + 已暫停 (佇列中的 {0} 工作) @@ -354,17 +354,17 @@ Prefer readonly fields - 建議使用唯讀欄位 + 優先使用唯讀欄位 Prefer simple 'using' statement - 建議使用簡單的 'using' 陳述式 + 優先使用簡單的 'using' 陳述式 Prefer static local functions - 建議使用靜態區域函式 + 優先使用靜態區域函式 @@ -399,7 +399,7 @@ Running low priority background processes - Running low priority background processes + 正在執行低優先順序背景流程 @@ -449,12 +449,12 @@ Target Namespace: - Target Namespace: + 目標命名空間: This is an invalid namespace - This is an invalid namespace + 這是無效的命名空間 @@ -469,12 +469,12 @@ Use .editorconfig compatibility mode (requires restart) - Use .editorconfig compatibility mode (requires restart) + 使用 .editorconfig 相容性模式 (需要重新啟動) Use enhanced colors for C# and Basic - 使用 C# 和 Basic 的增強色彩 + 使用 C# 和 Basic 的進階色彩 @@ -504,7 +504,7 @@ This workspace does not support updating Visual Basic compilation options. - 此工作區不支援更新的 Visual Basic 編譯選項。 + 此工作區不支援更新 Visual Basic 編譯選項。 @@ -1868,30 +1868,6 @@ Additional information: {1} 淡出 - - Changes are not allowed if the assembly has not been loaded. - 如果組件尚未載入,就不允許變更。 - - - - Changes are not allowed if the project wasn't built when debugging started. - 如果在偵錯開始時,專案未建置,就不允許變更。 - - - - Changes are not allowed if the project wasn't loaded and built when debugging started. - -'Lightweight solution load' is enabled for the current solution. Disable it to ensure that all projects are loaded when debugging starts. - 如果在偵錯開始時,專案未載入和建置,就不允許變更。 - -目前的解決方案已啟用「輕量型解決方案負載」。請將其停用,以確保偵錯開始時,會載入所有專案。 - - - - Changes are not allowed while code is running. - 當程式碼正在執行時,不允許變更。 - - Prefer local function over anonymous function 使用區域函式優先於匿名函式 @@ -1927,21 +1903,11 @@ Additional information: {1} 建議使用自動屬性 - - Error while reading file '{0}': {1} - 讀取檔案 '{0}' 時發生錯誤: {1} - - Module has been unloaded. 模組已卸載。 - - Can't apply changes -- module '{0}' has been unloaded. - 無法套用變更 -- 模組 '{0}' 已卸載。 - - Enable navigation to decompiled sources (experimental) 啟用反編譯來源的瀏覽 (實驗性) @@ -1975,7 +1941,7 @@ I agree to all of the foregoing: Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info - 在此處進行的設定僅適用於您的電腦。若要這些設定隨著您的解決方案移動,請使用 .editorconfig 檔案。 + 您的 .editorconfig 檔案可能會覆寫於此頁面上設定的本機設定 (僅適用於您的電腦)。如果要進行設定以讓這些設定隨附於您的解決方案,請使用 EditorConfig 檔案。詳細資訊 @@ -1983,11 +1949,6 @@ I agree to all of the foregoing: 同步類別檢視 - - Can't apply changes -- unexpected error: '{0}' - 無法套用變更 -- 未預期的錯誤: '{0}' - - Analyzing '{0}' 正在分析 '{0}' diff --git a/src/VisualStudio/Core/Impl/Microsoft.VisualStudio.LanguageServices.Implementation.csproj b/src/VisualStudio/Core/Impl/Microsoft.VisualStudio.LanguageServices.Implementation.csproj index 1aaf8e4965cd7..37158674fa5c7 100644 --- a/src/VisualStudio/Core/Impl/Microsoft.VisualStudio.LanguageServices.Implementation.csproj +++ b/src/VisualStudio/Core/Impl/Microsoft.VisualStudio.LanguageServices.Implementation.csproj @@ -66,6 +66,7 @@ + diff --git a/src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_IVsENCRebuildableProjectCfg.cs b/src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_IVsENCRebuildableProjectCfg.cs index 93bf703dc86c0..2a8405b10dd26 100644 --- a/src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_IVsENCRebuildableProjectCfg.cs +++ b/src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_IVsENCRebuildableProjectCfg.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using Roslyn.Utilities; using EncInterop = Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop; using ShellInterop = Microsoft.VisualStudio.Shell.Interop; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; @@ -10,75 +11,45 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.C internal partial class CPSProject : EncInterop.IVsENCRebuildableProjectCfg2, EncInterop.IVsENCRebuildableProjectCfg4 { public int HasCustomMetadataEmitter(out bool value) - { - value = true; - return VSConstants.S_OK; - } + => throw ExceptionUtilities.Unreachable; public int StartDebuggingPE() - { - return _editAndContinueProject.StartDebuggingPE(); - } + => throw ExceptionUtilities.Unreachable; public int StopDebuggingPE() - { - return _editAndContinueProject.StopDebuggingPE(); - } + => throw ExceptionUtilities.Unreachable; public int GetPEidentity(Guid[] pMVID, string[] pbstrPEName) - { - return _editAndContinueProject.GetPEidentity(pMVID, pbstrPEName); - } + => throw ExceptionUtilities.Unreachable; public int EnterBreakStateOnPE(EncInterop.ENC_BREAKSTATE_REASON encBreakReason, ShellInterop.ENC_ACTIVE_STATEMENT[] pActiveStatements, uint cActiveStatements) - { - return _editAndContinueProject.EnterBreakStateOnPE(encBreakReason, pActiveStatements, cActiveStatements); - } + => throw ExceptionUtilities.Unreachable; public int GetExceptionSpanCount(out uint pcExceptionSpan) - { - pcExceptionSpan = default; - return _editAndContinueProject.GetExceptionSpanCount(out pcExceptionSpan); - } + => throw ExceptionUtilities.Unreachable; public int GetExceptionSpans(uint celt, ShellInterop.ENC_EXCEPTION_SPAN[] rgelt, ref uint pceltFetched) - { - return _editAndContinueProject.GetExceptionSpans(celt, rgelt, ref pceltFetched); - } + => throw ExceptionUtilities.Unreachable; public int GetCurrentExceptionSpanPosition(uint id, VsTextSpan[] ptsNewPosition) - { - return _editAndContinueProject.GetCurrentExceptionSpanPosition(id, ptsNewPosition); - } + => throw ExceptionUtilities.Unreachable; public int GetENCBuildState(ShellInterop.ENC_BUILD_STATE[] pENCBuildState) - { - return _editAndContinueProject.GetENCBuildState(pENCBuildState); - } + => throw ExceptionUtilities.Unreachable; public int ExitBreakStateOnPE() - { - return _editAndContinueProject.ExitBreakStateOnPE(); - } + => throw ExceptionUtilities.Unreachable; public int GetCurrentActiveStatementPosition(uint id, VsTextSpan[] ptsNewPosition) - { - return _editAndContinueProject.GetCurrentActiveStatementPosition(id, ptsNewPosition); - } + => throw ExceptionUtilities.Unreachable; public int EncApplySucceeded(int hrApplyResult) - { - return _editAndContinueProject.EncApplySucceeded(hrApplyResult); - } + => throw ExceptionUtilities.Unreachable; public int GetPEBuildTimeStamp(Microsoft.VisualStudio.OLE.Interop.FILETIME[] pTimeStamp) - { - return VSConstants.E_NOTIMPL; - } + => throw ExceptionUtilities.Unreachable; public int BuildForEnc(object pUpdatePE) - { - return _editAndContinueProject.BuildForEnc(pUpdatePE); - } + => throw ExceptionUtilities.Unreachable; } } diff --git a/src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_IWorkspaceProjectContext.cs b/src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_IWorkspaceProjectContext.cs index b117fa3783157..1920b552bf7e2 100644 --- a/src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_IWorkspaceProjectContext.cs +++ b/src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_IWorkspaceProjectContext.cs @@ -28,7 +28,6 @@ internal sealed partial class CPSProject : IWorkspaceProjectContext private readonly VisualStudioWorkspaceImpl _visualStudioWorkspace; private readonly IProjectCodeModel _projectCodeModel; private readonly Lazy _externalErrorReporterOpt; - private readonly EditAndContinue.VsENCRebuildableProjectImpl _editAndContinueProject; public string DisplayName { @@ -83,14 +82,6 @@ public CPSProject(VisualStudioProject visualStudioProject, VisualStudioWorkspace () => _visualStudioProjectOptionsProcessor.EffectiveRuleSetFilePath); } - // We don't have a SVsShellDebugger service in unit tests, in that case we can't implement ENC. We're OK - // leaving the field null in that case. - if (Shell.ServiceProvider.GlobalProvider.GetService(typeof(SVsShellDebugger)) != null) - { - // TODO: make this lazier, as fetching all the services up front during load shoudn't be necessary - _editAndContinueProject = new EditAndContinue.VsENCRebuildableProjectImpl(_visualStudioWorkspace, _visualStudioProject, Shell.ServiceProvider.GlobalProvider); - } - Guid = projectGuid; BinOutputPath = binOutputPath; } diff --git a/src/VisualStudio/Core/SolutionExplorerShim/Microsoft.VisualStudio.LanguageServices.SolutionExplorer.csproj b/src/VisualStudio/Core/SolutionExplorerShim/Microsoft.VisualStudio.LanguageServices.SolutionExplorer.csproj index 1df9ee7a016f2..8bf8f85a9bd5e 100644 --- a/src/VisualStudio/Core/SolutionExplorerShim/Microsoft.VisualStudio.LanguageServices.SolutionExplorer.csproj +++ b/src/VisualStudio/Core/SolutionExplorerShim/Microsoft.VisualStudio.LanguageServices.SolutionExplorer.csproj @@ -43,6 +43,7 @@ + diff --git a/src/VisualStudio/Core/Test.Next/Roslyn.VisualStudio.Next.UnitTests.csproj b/src/VisualStudio/Core/Test.Next/Roslyn.VisualStudio.Next.UnitTests.csproj index 497030be3bfea..d6506542087b7 100644 --- a/src/VisualStudio/Core/Test.Next/Roslyn.VisualStudio.Next.UnitTests.csproj +++ b/src/VisualStudio/Core/Test.Next/Roslyn.VisualStudio.Next.UnitTests.csproj @@ -71,6 +71,7 @@ + diff --git a/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpIntelliSense.cs b/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpIntelliSense.cs index 2fb43a9f21b05..86eb5ae776567 100644 --- a/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpIntelliSense.cs +++ b/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpIntelliSense.cs @@ -2,6 +2,7 @@ using System; using System.Linq; +using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; @@ -22,6 +23,14 @@ public CSharpIntelliSense(VisualStudioInstanceFactory instanceFactory, ITestOutp { } + public override async Task InitializeAsync() + { + await base.InitializeAsync().ConfigureAwait(true); + + // Disable import completion. + VisualStudio.Workspace.SetImportCompletionOption(false); + } + [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public void AtNamespaceLevel() { diff --git a/src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicEditAndContinue.cs b/src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicEditAndContinue.cs index 4cab90155d12e..cbc8f8dc161f8 100644 --- a/src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicEditAndContinue.cs +++ b/src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicEditAndContinue.cs @@ -34,7 +34,8 @@ public override async Task InitializeAsync() VisualStudio.SolutionExplorer.AddProject(testProj, WellKnownProjectTemplates.ConsoleApplication, LanguageNames.VisualBasic); } - [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37689")] + // Also "https://github.com/dotnet/roslyn/issues/37689")] + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] [Trait(Traits.Feature, Traits.Features.DebuggingEditAndContinue)] public void UpdateActiveStatementLeafNode() { @@ -67,7 +68,8 @@ End Module VisualStudio.Debugger.CheckExpression("names(1)", "String", "\"bar\""); } - [WpfFact] + // Also "https://github.com/dotnet/roslyn/issues/37689")] + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] [Trait(Traits.Feature, Traits.Features.DebuggingEditAndContinue)] public void AddTryCatchAroundActiveStatement() { @@ -97,7 +99,8 @@ Catch ex As Exception VisualStudio.Editor.Verify.CurrentLineText("End Try"); } - [WpfFact] + // Also "https://github.com/dotnet/roslyn/issues/37689")] + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] [Trait(Traits.Feature, Traits.Features.DebuggingEditAndContinue)] public void EditLambdaExpression() { @@ -131,7 +134,8 @@ End Sub VisualStudio.ErrorList.Verify.NoBuildErrors(); } - [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37689")] + // Also "https://github.com/dotnet/roslyn/issues/37689")] + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] [Trait(Traits.Feature, Traits.Features.DebuggingEditAndContinue)] public void EnCWhileDebuggingFromImmediateWindow() { @@ -196,7 +200,8 @@ End Module VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); } - [WpfFact] + // Also https://github.com/dotnet/roslyn/issues/36763 + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] [Trait(Traits.Feature, Traits.Features.DebuggingEditAndContinue)] public void MultiProjectDebuggingWhereNotAllModulesAreLoaded() { @@ -209,59 +214,8 @@ public void MultiProjectDebuggingWhereNotAllModulesAreLoaded() VisualStudio.ErrorList.Verify.NoErrors(); } - [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37689")] - [Trait(Traits.Feature, Traits.Features.DebuggingEditAndContinue)] - [WorkItem(33829, "https://github.com/dotnet/roslyn/issues/33829")] - public void DocumentStateTrackingReadonlyInRunMode() - { - SetupMultiProjectSolution(); - var project = new ProjectUtils.Project(ProjectName); - var basicLibrary = new ProjectUtils.Project("BasicLibrary1"); - var cSharpLibrary = new ProjectUtils.Project("CSharpLibrary1"); - - VisualStudio.Editor.SetText(@" -Imports System -Imports BasicLibrary1 -Module Module1 - Sub Main() - Console.Read() - End Sub -End Module -"); - VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); - VisualStudio.Debugger.Go(waitForBreakMode: false); - VisualStudio.ActivateMainWindow(); - VisualStudio.SolutionExplorer.OpenFile(project, module1FileName); - - VisualStudio.SendKeys.Send(VirtualKey.T); - string editAndContinueDialogName = "Edit and Continue"; - VisualStudio.Dialog.VerifyOpen(editAndContinueDialogName); - VisualStudio.Dialog.Click(editAndContinueDialogName, "OK"); - VisualStudio.Dialog.VerifyClosed(editAndContinueDialogName); - VisualStudio.Editor.Verify.IsProjectItemDirty(expectedValue: false); - - // This module is referred by the loaded module, but not used. So this will not be loaded - VisualStudio.SolutionExplorer.OpenFile(basicLibrary, "Class1.vb"); - VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); - VisualStudio.SendKeys.Send(VirtualKey.T); - VisualStudio.Dialog.VerifyOpen(editAndContinueDialogName); - VisualStudio.Dialog.Click(editAndContinueDialogName, "OK"); - VisualStudio.Dialog.VerifyClosed(editAndContinueDialogName); - VisualStudio.Editor.Verify.IsProjectItemDirty(expectedValue: false); - - // This module is not referred by the loaded module. this will not be loaded - VisualStudio.SolutionExplorer.OpenFile(cSharpLibrary, "File1.cs"); - VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); - VisualStudio.SendKeys.Send(VirtualKey.T); - - string microsoftVisualStudioDialogName = "Microsoft Visual Studio"; - VisualStudio.Dialog.VerifyOpen(microsoftVisualStudioDialogName); - VisualStudio.Dialog.Click(microsoftVisualStudioDialogName, "OK"); - VisualStudio.Dialog.VerifyClosed(microsoftVisualStudioDialogName); - VisualStudio.Editor.Verify.IsProjectItemDirty(expectedValue: false); - } - - [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37689")] + // Also "https://github.com/dotnet/roslyn/issues/37689")] + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] [Trait(Traits.Feature, Traits.Features.DebuggingEditAndContinue)] public void LocalsWindowUpdatesAfterLocalGetsItsTypeUpdatedDuringEnC() { @@ -286,7 +240,8 @@ End Module VisualStudio.LocalsWindow.Verify.CheckEntry("goo", "Single", "10"); } - [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37689")] + // Also "https://github.com/dotnet/roslyn/issues/37689")] + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] [Trait(Traits.Feature, Traits.Features.DebuggingEditAndContinue)] public void LocalsWindowUpdatesCorrectlyDuringEnC() { @@ -321,7 +276,8 @@ End Module VisualStudio.LocalsWindow.Verify.CheckEntry("lLng", "Long", "444"); } - [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/37689")] + // Also "https://github.com/dotnet/roslyn/issues/37689")] + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] [Trait(Traits.Feature, Traits.Features.DebuggingEditAndContinue)] public void WatchWindowUpdatesCorrectlyDuringEnC() { diff --git a/src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicExpressionEvaluator.cs b/src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicExpressionEvaluator.cs index 6f5065b2b152f..9fe9e6af1aa27 100644 --- a/src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicExpressionEvaluator.cs +++ b/src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicExpressionEvaluator.cs @@ -65,7 +65,7 @@ End Sub End Module"); } - [WpfFact] + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] public void ValidateLocalsWindow() { VisualStudio.Debugger.Go(waitForBreakMode: true); @@ -93,7 +93,7 @@ public void ValidateLocalsWindow() VisualStudio.LocalsWindow.Verify.CheckEntry("myMulticastDelegate", "System.MulticastDelegate", "Nothing"); } - [WpfFact] + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] public void EvaluatePrimitiveValues() { VisualStudio.Debugger.Go(waitForBreakMode: true); @@ -114,14 +114,14 @@ public void EvaluateLambdaExpressions() VisualStudio.Debugger.CheckExpression("(Function(val)(val+val))(1)", "Integer", "2"); } - [WpfFact] + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] public void EvaluateInvalidExpressions() { VisualStudio.Debugger.Go(waitForBreakMode: true); VisualStudio.Debugger.CheckExpression("myNonsense", "", "error BC30451: 'myNonsense' is not declared. It may be inaccessible due to its protection level."); } - [WpfFact] + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] public void StateMachineTypeParameters() { VisualStudio.Editor.SetText(@" diff --git a/src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicIntelliSense.cs b/src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicIntelliSense.cs index 676931dde118c..605198ba30d57 100644 --- a/src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicIntelliSense.cs +++ b/src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicIntelliSense.cs @@ -1,5 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; @@ -20,6 +21,14 @@ public BasicIntelliSense(VisualStudioInstanceFactory instanceFactory, ITestOutpu { } + public override async Task InitializeAsync() + { + await base.InitializeAsync().ConfigureAwait(true); + + // Disable import completion. + VisualStudio.Workspace.SetImportCompletionOption(false); + } + [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/38301"), Trait(Traits.Feature, Traits.Features.Completion)] public void IntelliSenseTriggersOnParenWithBraceCompletionAndCorrectUndoMerging() { diff --git a/src/VisualStudio/IntegrationTest/TestSetup/Microsoft.VisualStudio.IntegrationTest.Setup.csproj b/src/VisualStudio/IntegrationTest/TestSetup/Microsoft.VisualStudio.IntegrationTest.Setup.csproj index 0d32b690b79fc..48c2ca072a040 100644 --- a/src/VisualStudio/IntegrationTest/TestSetup/Microsoft.VisualStudio.IntegrationTest.Setup.csproj +++ b/src/VisualStudio/IntegrationTest/TestSetup/Microsoft.VisualStudio.IntegrationTest.Setup.csproj @@ -46,6 +46,8 @@ + + diff --git a/src/VisualStudio/IntegrationTest/TestUtilities/InProcess/SolutionExplorer_InProc.cs b/src/VisualStudio/IntegrationTest/TestUtilities/InProcess/SolutionExplorer_InProc.cs index ab697b55b2598..dd8d7f65365a4 100644 --- a/src/VisualStudio/IntegrationTest/TestUtilities/InProcess/SolutionExplorer_InProc.cs +++ b/src/VisualStudio/IntegrationTest/TestUtilities/InProcess/SolutionExplorer_InProc.cs @@ -11,10 +11,12 @@ using System.Xml.Linq; using EnvDTE80; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.CodingConventions; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; +using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.ProjectSystem.Properties; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; @@ -403,7 +405,7 @@ public void CleanUpOpenSolution() _sendKeys.Send(VirtualKey.Escape); dte.Debugger.TerminateAll(); - WaitForDesignMode(); + WaitForDesignMode(dte); } CloseSolution(); @@ -415,10 +417,9 @@ public void CleanUpOpenSolution() } } - private static void WaitForDesignMode() + private static void WaitForDesignMode(EnvDTE.DTE dte) { - var stopwatch = Stopwatch.StartNew(); - +#if TODO// https://github.com/dotnet/roslyn/issues/35965 // This delay was originally added to address test failures in BasicEditAndContinue. When running // multiple tests in sequence, situations were observed where the Edit and Continue state was not reset: // @@ -431,17 +432,28 @@ private static void WaitForDesignMode() // state believing a debugger session was active. // // This delay should be replaced with a proper wait condition once the correct one is determined. - var editAndContinueService = GetComponentModelService(); - do + var debugService = GetComponentModelService().Services.GetRequiredService(); + using (var debugSessionEndedEvent = new ManualResetEventSlim(initialState: false)) { - if (stopwatch.Elapsed >= Helper.HangMitigatingTimeout) + debugService.BeforeDebuggingStateChanged += (_, e) => { - throw new TimeoutException("Failed to enter design mode in a timely manner."); + if (e.After == DebuggingState.Design) + { + debugSessionEndedEvent.Set(); + } + }; + + if (dte.Debugger.CurrentMode == EnvDTE.dbgDebugMode.dbgDesignMode) + { + return; } - Thread.Yield(); + if (!debugSessionEndedEvent.Wait(Helper.HangMitigatingTimeout)) + { + throw new TimeoutException("Failed to enter design mode in a timely manner."); + } } - while (editAndContinueService?.DebuggingSession != null); +#endif } private void CloseSolution() diff --git a/src/VisualStudio/IntegrationTest/TestUtilities/Microsoft.VisualStudio.IntegrationTest.Utilities.csproj b/src/VisualStudio/IntegrationTest/TestUtilities/Microsoft.VisualStudio.IntegrationTest.Utilities.csproj index 1c8defaaf96b3..85f73a8c87735 100644 --- a/src/VisualStudio/IntegrationTest/TestUtilities/Microsoft.VisualStudio.IntegrationTest.Utilities.csproj +++ b/src/VisualStudio/IntegrationTest/TestUtilities/Microsoft.VisualStudio.IntegrationTest.Utilities.csproj @@ -61,6 +61,7 @@ + diff --git a/src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/VisualStudioWorkspace_OutOfProc.cs b/src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/VisualStudioWorkspace_OutOfProc.cs index 9b101e012f871..37a45ca8abafd 100644 --- a/src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/VisualStudioWorkspace_OutOfProc.cs +++ b/src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/VisualStudioWorkspace_OutOfProc.cs @@ -55,6 +55,21 @@ public void CleanUpWaitingService() public void SetQuickInfo(bool value) => _inProc.EnableQuickInfo(value); + public void SetImportCompletionOption(bool value) + { + SetPerLanguageOption( + optionName: "ShowItemsFromUnimportedNamespaces", + feature: "CompletionOptions", + language: LanguageNames.CSharp, + value: value); + + SetPerLanguageOption( + optionName: "ShowItemsFromUnimportedNamespaces", + feature: "CompletionOptions", + language: LanguageNames.VisualBasic, + value: value); + } + public void SetFullSolutionAnalysis(bool value) { SetPerLanguageOption( diff --git a/src/VisualStudio/LiveShare/Impl/DiagnosticHandler.cs b/src/VisualStudio/LiveShare/Impl/DiagnosticHandler.cs index eb19a2c91b364..ce439206cb369 100644 --- a/src/VisualStudio/LiveShare/Impl/DiagnosticHandler.cs +++ b/src/VisualStudio/LiveShare/Impl/DiagnosticHandler.cs @@ -35,7 +35,9 @@ public DiagnosticsHandler(IDiagnosticService diagnosticService) _diagnosticService.DiagnosticsUpdated += DiagnosticService_DiagnosticsUpdated; } +#pragma warning disable VSTHRD100 // Avoid async void methods private async void DiagnosticService_DiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e) +#pragma warning restore VSTHRD100 // Avoid async void methods { // Since this is an async void method, exceptions here will crash the host VS. We catch exceptions here to make sure that we don't crash the host since // the worst outcome here is that guests may not see all diagnostics. diff --git a/src/VisualStudio/LiveShare/Impl/Microsoft.VisualStudio.LanguageServices.LiveShare.csproj b/src/VisualStudio/LiveShare/Impl/Microsoft.VisualStudio.LanguageServices.LiveShare.csproj index 8de935aa773d2..5ec56a6b70f53 100644 --- a/src/VisualStudio/LiveShare/Impl/Microsoft.VisualStudio.LanguageServices.LiveShare.csproj +++ b/src/VisualStudio/LiveShare/Impl/Microsoft.VisualStudio.LanguageServices.LiveShare.csproj @@ -19,8 +19,11 @@ + + + diff --git a/src/VisualStudio/LiveShare/Test/Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests.csproj b/src/VisualStudio/LiveShare/Test/Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests.csproj index 10c26be3c3dd2..bc21c4a040f1d 100644 --- a/src/VisualStudio/LiveShare/Test/Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests.csproj +++ b/src/VisualStudio/LiveShare/Test/Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests.csproj @@ -8,6 +8,11 @@ UnitTest + + + + + diff --git a/src/VisualStudio/RemoteHostClientMock/Roslyn.VisualStudio.RemoteHostClientMock.csproj b/src/VisualStudio/RemoteHostClientMock/Roslyn.VisualStudio.RemoteHostClientMock.csproj index 122d548c36224..62e1b1244df1a 100644 --- a/src/VisualStudio/RemoteHostClientMock/Roslyn.VisualStudio.RemoteHostClientMock.csproj +++ b/src/VisualStudio/RemoteHostClientMock/Roslyn.VisualStudio.RemoteHostClientMock.csproj @@ -44,6 +44,7 @@ + diff --git a/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj b/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj index 2b5f1d1267657..888d60122dddf 100644 --- a/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj +++ b/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj @@ -314,6 +314,8 @@ + + diff --git a/src/VisualStudio/Setup/source.extension.vsixmanifest b/src/VisualStudio/Setup/source.extension.vsixmanifest index d4babdac84dda..0c08add71626f 100644 --- a/src/VisualStudio/Setup/source.extension.vsixmanifest +++ b/src/VisualStudio/Setup/source.extension.vsixmanifest @@ -34,10 +34,14 @@ + + + + diff --git a/src/VisualStudio/TestUtilities2/CallHierarchy/CallHierarchyTestState.vb b/src/VisualStudio/TestUtilities2/CallHierarchy/CallHierarchyTestState.vb index 955cc4bf909c9..4a856ac8f68d6 100644 --- a/src/VisualStudio/TestUtilities2/CallHierarchy/CallHierarchyTestState.vb +++ b/src/VisualStudio/TestUtilities2/CallHierarchy/CallHierarchyTestState.vb @@ -5,6 +5,7 @@ Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy Imports Microsoft.CodeAnalysis.Editor.Implementation.Notification +Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Notification @@ -103,8 +104,9 @@ Namespace Microsoft.CodeAnalysis.Editor.UnitTests.CallHierarchy Dim notificationService = DirectCast(workspace.Services.GetService(Of INotificationService)(), INotificationServiceCallback) notificationService.NotificationCallback = Sub(message, title, severity) NotificationMessage = message + Dim threadingContext = workspace.ExportProvider.GetExportedValue(Of IThreadingContext)() _presenter = New MockCallHierarchyPresenter() - _commandHandler = New CallHierarchyCommandHandler({_presenter}, provider) + _commandHandler = New CallHierarchyCommandHandler(threadingContext, {_presenter}, provider) End Sub Private Shared Function CreateExportProvider(additionalTypes As IEnumerable(Of Type)) As ExportProvider diff --git a/src/VisualStudio/TestUtilities2/Microsoft.VisualStudio.LanguageServices.Test.Utilities2.vbproj b/src/VisualStudio/TestUtilities2/Microsoft.VisualStudio.LanguageServices.Test.Utilities2.vbproj index 6c50004182beb..1cf0893b3ea02 100644 --- a/src/VisualStudio/TestUtilities2/Microsoft.VisualStudio.LanguageServices.Test.Utilities2.vbproj +++ b/src/VisualStudio/TestUtilities2/Microsoft.VisualStudio.LanguageServices.Test.Utilities2.vbproj @@ -81,6 +81,7 @@ + diff --git a/src/VisualStudio/VisualBasic/Impl/BasicVSResources.Designer.vb b/src/VisualStudio/VisualBasic/Impl/BasicVSResources.Designer.vb index 4f1f8190a9119..e35c56f33d8ec 100644 --- a/src/VisualStudio/VisualBasic/Impl/BasicVSResources.Designer.vb +++ b/src/VisualStudio/VisualBasic/Impl/BasicVSResources.Designer.vb @@ -612,5 +612,14 @@ Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic Return ResourceManager.GetString("VB_Coding_Conventions", resourceCulture) End Get End Property + + ''' + ''' Looks up a localized string similar to Visual Basic Language Server Client. + ''' + Friend Shared ReadOnly Property Visual_Basic_language_server_client() As String + Get + Return ResourceManager.GetString("Visual_Basic_language_server_client", resourceCulture) + End Get + End Property End Class End Namespace diff --git a/src/VisualStudio/VisualBasic/Impl/BasicVSResources.resx b/src/VisualStudio/VisualBasic/Impl/BasicVSResources.resx index 79c4c1f86a350..cc3d684779239 100644 --- a/src/VisualStudio/VisualBasic/Impl/BasicVSResources.resx +++ b/src/VisualStudio/VisualBasic/Impl/BasicVSResources.resx @@ -300,4 +300,7 @@ Show items from unimported namespaces (experimental) + + Visual Basic Language Server Client + \ No newline at end of file diff --git a/src/VisualStudio/VisualBasic/Impl/LanguageClient/VisualBasicLanguageServerClient.vb b/src/VisualStudio/VisualBasic/Impl/LanguageClient/VisualBasicLanguageServerClient.vb new file mode 100644 index 0000000000000..40e3fbb80fc7d --- /dev/null +++ b/src/VisualStudio/VisualBasic/Impl/LanguageClient/VisualBasicLanguageServerClient.vb @@ -0,0 +1,48 @@ +' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +Imports System.ComponentModel.Composition +Imports Microsoft.CodeAnalysis.Editor +Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities +Imports Microsoft.CodeAnalysis.Host.Mef +Imports Microsoft.CodeAnalysis.Options +Imports Microsoft.CodeAnalysis.Remote +Imports Microsoft.CodeAnalysis.Shared.TestHooks +Imports Microsoft.VisualStudio.LanguageServer.Client +Imports Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService +Imports Microsoft.VisualStudio.Utilities + +Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.LanguageClient + + ' currently, platform doesn't allow multiple content types + ' to be associated with 1 ILanguageClient forcing us to + ' create multiple ILanguageClients for each content type + ' https://devdiv.visualstudio.com/DevDiv/_workitems/edit/952373 + + + + Friend Class VisualBasicLanguageServerClient + Inherits AbstractLanguageServerClient + + + + Public Sub New(threadingContext As IThreadingContext, + workspace As VisualStudioWorkspace, + lazyOptions As IEnumerable(Of Lazy(Of IOptionPersister)), + eventListener As LanguageServerClientEventListener, + listenerProvider As IAsynchronousOperationListenerProvider) + MyBase.New(threadingContext, + workspace, + lazyOptions, + eventListener, + listenerProvider, + languageServerName:=WellKnownServiceHubServices.VisualBasicLanguageServer, + serviceHubClientName:="ManagedLanguage.IDE.VisualBasicLanguageServer") + End Sub + + Public Overrides ReadOnly Property Name As String + Get + Return BasicVSResources.Visual_Basic_language_server_client + End Get + End Property + End Class +End Namespace diff --git a/src/VisualStudio/VisualBasic/Impl/Microsoft.VisualStudio.LanguageServices.VisualBasic.vbproj b/src/VisualStudio/VisualBasic/Impl/Microsoft.VisualStudio.LanguageServices.VisualBasic.vbproj index fe0cd45c3c6e9..9c30359478c61 100644 --- a/src/VisualStudio/VisualBasic/Impl/Microsoft.VisualStudio.LanguageServices.VisualBasic.vbproj +++ b/src/VisualStudio/VisualBasic/Impl/Microsoft.VisualStudio.LanguageServices.VisualBasic.vbproj @@ -49,11 +49,13 @@ + + diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.cs.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.cs.xlf index d038ff89c4c9a..808cd7fc1fe21 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.cs.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.cs.xlf @@ -277,6 +277,11 @@ Konvence kódování ve VB + + Visual Basic Language Server Client + Klient serveru pro jazyk Visual Basic + + 'nothing' checking: 'Kontrola hodnot nothing: diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.de.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.de.xlf index e3a7661f85552..3c2c015189849 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.de.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.de.xlf @@ -277,6 +277,11 @@ VB-Codierungskonvention + + Visual Basic Language Server Client + Client des Visual Basic-Sprachservers + + 'nothing' checking: 'Überprüfung auf "nothing": diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.es.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.es.xlf index bd4f9a06ccdff..cc97b0c212381 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.es.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.es.xlf @@ -277,6 +277,11 @@ Convenciones de código de VB + + Visual Basic Language Server Client + Cliente de servidor del lenguaje Visual Basic + + 'nothing' checking: 'Comprobación de "nothing": diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.fr.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.fr.xlf index dda9385fe7770..b6aa85d7cab0d 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.fr.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.fr.xlf @@ -277,6 +277,11 @@ Conventions de codage VB + + Visual Basic Language Server Client + Client du serveur de langage Visual Basic + + 'nothing' checking: 'Contrôle de 'nothing' : diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.it.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.it.xlf index 8f6f79fd7cd75..21d892bd646e5 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.it.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.it.xlf @@ -277,6 +277,11 @@ Convenzioni di scrittura codice VB + + Visual Basic Language Server Client + Client del server di linguaggio Visual Basic + + 'nothing' checking: 'Controllo 'nothing': diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ja.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ja.xlf index 7cf4319c839b9..01fbdea88d82f 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ja.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ja.xlf @@ -277,6 +277,11 @@ VB コーディング規約 + + Visual Basic Language Server Client + Visual Basic 言語サーバー クライアント + + 'nothing' checking: 'nothing' のチェック中: diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ko.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ko.xlf index 67bfc8b0d533a..84a50c49e9b32 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ko.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ko.xlf @@ -277,6 +277,11 @@ VB 코딩 규칙 + + Visual Basic Language Server Client + Visual Basic 언어 서버 클라이언트 + + 'nothing' checking: 'nothing' 검사: diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pl.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pl.xlf index a108bab4b2a6e..a5be0dcf8da0c 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pl.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pl.xlf @@ -277,6 +277,11 @@ Konwencje kodowania w języku VB + + Visual Basic Language Server Client + Klient serwera języka Visual Basic + + 'nothing' checking: 'Sprawdzanie „nothing”: diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pt-BR.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pt-BR.xlf index ac39d603e78ab..41855f858ae98 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pt-BR.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.pt-BR.xlf @@ -277,6 +277,11 @@ Convenções do Codificação do VB + + Visual Basic Language Server Client + Cliente do Servidor de Linguagem do Visual Basic + + 'nothing' checking: 'verificação de 'nothing': diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ru.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ru.xlf index ce26d0d1f1e6c..e8371106108f7 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ru.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.ru.xlf @@ -277,6 +277,11 @@ Рекомендации по написанию кода VB + + Visual Basic Language Server Client + Клиент языкового сервера Visual Basic + + 'nothing' checking: 'Проверка значений "nothing": diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.tr.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.tr.xlf index 692ee3067a72b..e6d8b582cb26e 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.tr.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.tr.xlf @@ -277,6 +277,11 @@ VB kodlama kuralları + + Visual Basic Language Server Client + Visual Basic Dil Sunucusu İstemcisi + + 'nothing' checking: 'nothing' denetimi: diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hans.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hans.xlf index c7849b10a6614..a8414f674fc48 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hans.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hans.xlf @@ -277,6 +277,11 @@ vb 编码约定 + + Visual Basic Language Server Client + Visual Basic 语言服务器客户端 + + 'nothing' checking: '"nothing" 检查: diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hant.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hant.xlf index bbca021c91efb..3a74136c4516a 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hant.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hant.xlf @@ -277,6 +277,11 @@ VB 編碼慣例 + + Visual Basic Language Server Client + Visual Basic 語言伺服器用戶端 + + 'nothing' checking: 'nothing' 檢查: diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.cs.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.cs.xlf index b884a69eb3c03..0daabcff16a38 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.cs.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.cs.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Editor stránky kódu Microsoft Visual Basic + Visual Basic Editor s kódováním Visual Basic Editor - Microsoft Visual Basic Editor + Visual Basic Editor diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.de.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.de.xlf index 30f3263357292..74c82fb8b4d30 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.de.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.de.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Microsoft Visual Basic-Codepage-Editor + Visual Basic-Editor mit Codierung Visual Basic Editor - Microsoft Visual Basic-Editor + Visual Basic-Editor diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.es.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.es.xlf index e5287054648e9..f1e3003bdd332 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.es.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.es.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Editor de páginas de código de Microsoft Visual Basic + Editor de Visual Basic con Encoding Visual Basic Editor - Editor de Microsoft Visual Basic + Editor de Visual Basic diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.fr.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.fr.xlf index 4f00f03469326..d415bcc2a27f8 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.fr.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.fr.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Éditeur de page de codes Microsoft Visual Basic + Visual Basic Editor avec encodage Visual Basic Editor - Microsoft Visual Basic Editor + Visual Basic Editor diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.it.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.it.xlf index 8ccd9ac3da3ff..ebeb428686f90 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.it.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.it.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Editor tabella codici di Microsoft Visual Basic + Visual Basic Editor con codifica Visual Basic Editor - Microsoft Visual Basic Editor + Visual Basic Editor diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ja.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ja.xlf index cf86aafa71609..463ed3f338884 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ja.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ja.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Microsoft Visual Basic コード ページ エディター + エンコード付き Visual Basic エディター Visual Basic Editor - Microsoft Visual Basic エディター + Visual Basic エディター diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ko.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ko.xlf index 2ea473711f2e0..65429c45e19e7 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ko.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ko.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Microsoft Visual Basic 코드 페이지 편집기 + Visual Basic Editor(인코딩 사용) Visual Basic Editor - Microsoft Visual Basic Editor + Visual Basic Editor diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pl.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pl.xlf index 63c0cf3503c3d..fd3ec4e7f0954 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pl.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pl.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Edytor strony kodowej Microsoft Visual Basic + Edytor Visual Basic z kodowaniem Visual Basic Editor - Edytor Microsoft Visual Basic + Edytor Visual Basic diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pt-BR.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pt-BR.xlf index 073df57de2d64..5625147003be1 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pt-BR.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.pt-BR.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Editor de Página de Código do Microsoft Visual Basic + Editor do Visual Basic com Codificação Visual Basic Editor - Editor do Microsoft Visual Basic + Editor do Visual Basic diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ru.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ru.xlf index 707e39e630387..7844fbfc7256a 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ru.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.ru.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Редактор кодовых страниц Microsoft Visual Basic + Редактор Visual Basic с кодировкой Visual Basic Editor - Редактор Microsoft Visual Basic + Редактор Visual Basic diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.tr.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.tr.xlf index f0b4c08a0c2f4..f5e8d9c5b285a 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.tr.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.tr.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Microsoft Visual Basic Kod Sayfası Düzenleyicisi + Kodlamalı Visual Basic Düzenleyicisi Visual Basic Editor - Microsoft Visual Basic Düzenleyicisi + Visual Basic Düzenleyicisi diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hans.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hans.xlf index 0cd194c3c9268..45937129ec1c7 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hans.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hans.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Microsoft Visual Basic 代码页编辑器 + 带编码功能的 Visual Basic 编辑器 Visual Basic Editor - Microsoft Visual Basic 编辑器 + Visual Basic 编辑器 diff --git a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hant.xlf b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hant.xlf index f22eceee59533..462a5a431f370 100644 --- a/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hant.xlf +++ b/src/VisualStudio/VisualBasic/Impl/xlf/VSPackage.zh-Hant.xlf @@ -9,12 +9,12 @@ Visual Basic Editor with Encoding - Microsoft Visual Basic 字碼頁編輯器 + 具備編碼功能的 Visual Basic 編輯器 Visual Basic Editor - Microsoft Visual Basic 編輯器 + Visual Basic 編輯器 diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Roslyn.VisualStudio.DiagnosticsWindow.csproj b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Roslyn.VisualStudio.DiagnosticsWindow.csproj index 3d8deb9469ab6..c07c2e3d42de3 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Roslyn.VisualStudio.DiagnosticsWindow.csproj +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Roslyn.VisualStudio.DiagnosticsWindow.csproj @@ -65,6 +65,7 @@ + diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Telemetry/TelemetryPanel.xaml.cs b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Telemetry/TelemetryPanel.xaml.cs index e7d05c35dfe58..37906f841353f 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Telemetry/TelemetryPanel.xaml.cs +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Telemetry/TelemetryPanel.xaml.cs @@ -25,7 +25,9 @@ public TelemetryPanel() InitializeComponent(); } +#pragma warning disable VSTHRD100 // Avoid async void methods private async void OnDump(object sender, RoutedEventArgs e) +#pragma warning restore VSTHRD100 // Avoid async void methods { using (Disable(DumpButton)) using (Disable(CopyButton)) diff --git a/src/VisualStudio/Xaml/Impl/Microsoft.VisualStudio.LanguageServices.Xaml.csproj b/src/VisualStudio/Xaml/Impl/Microsoft.VisualStudio.LanguageServices.Xaml.csproj index d36846ee0a7b3..5b41634a33110 100644 --- a/src/VisualStudio/Xaml/Impl/Microsoft.VisualStudio.LanguageServices.Xaml.csproj +++ b/src/VisualStudio/Xaml/Impl/Microsoft.VisualStudio.LanguageServices.Xaml.csproj @@ -31,6 +31,7 @@ + diff --git a/src/Workspaces/Core/Portable/CodeFixes/CodeFixContext.cs b/src/Workspaces/Core/Portable/CodeFixes/CodeFixContext.cs index b3d0e3f2accb3..0d66a8d6a2e7a 100644 --- a/src/Workspaces/Core/Portable/CodeFixes/CodeFixContext.cs +++ b/src/Workspaces/Core/Portable/CodeFixes/CodeFixContext.cs @@ -13,7 +13,7 @@ namespace Microsoft.CodeAnalysis.CodeFixes /// /// Context for code fixes provided by a . /// - public struct CodeFixContext + public struct CodeFixContext : ITypeScriptCodeFixContext { private readonly Document _document; private readonly Project _project; @@ -48,6 +48,9 @@ public struct CodeFixContext /// public CancellationToken CancellationToken => _cancellationToken; + private readonly bool _isBlocking; + bool ITypeScriptCodeFixContext.IsBlocking => _isBlocking; + /// /// Creates a code fix context to be passed into method. /// @@ -102,7 +105,19 @@ internal CodeFixContext( Action> registerCodeFix, bool verifyArguments, CancellationToken cancellationToken) - : this(document, document.Project, span, diagnostics, registerCodeFix, verifyArguments, cancellationToken) + : this(document, document.Project, span, diagnostics, registerCodeFix, verifyArguments, isBlocking: false, cancellationToken) + { + } + + internal CodeFixContext( + Document document, + TextSpan span, + ImmutableArray diagnostics, + Action> registerCodeFix, + bool verifyArguments, + bool isBlocking, + CancellationToken cancellationToken) + : this(document, document.Project, span, diagnostics, registerCodeFix, verifyArguments, isBlocking, cancellationToken) { } @@ -111,7 +126,7 @@ internal CodeFixContext( ImmutableArray diagnostics, Action> registerCodeFix, CancellationToken cancellationToken) - : this(document: null, project: project, span: default, diagnostics: diagnostics, registerCodeFix: registerCodeFix, verifyArguments: false, cancellationToken: cancellationToken) + : this(document: null, project: project, span: default, diagnostics: diagnostics, registerCodeFix: registerCodeFix, verifyArguments: false, isBlocking: false, cancellationToken: cancellationToken) { } @@ -122,6 +137,7 @@ private CodeFixContext( ImmutableArray diagnostics, Action> registerCodeFix, bool verifyArguments, + bool isBlocking, CancellationToken cancellationToken) { if (verifyArguments) @@ -145,6 +161,8 @@ private CodeFixContext( _diagnostics = diagnostics; _registerCodeFix = registerCodeFix; _cancellationToken = cancellationToken; + + _isBlocking = isBlocking; } internal CodeFixContext( @@ -237,4 +255,9 @@ private static void VerifyDiagnosticsArgument(ImmutableArray diagnos } } } + + internal interface ITypeScriptCodeFixContext + { + bool IsBlocking { get; } + } } diff --git a/src/Workspaces/Core/Portable/CodeRefactorings/CodeRefactoringContext.cs b/src/Workspaces/Core/Portable/CodeRefactorings/CodeRefactoringContext.cs index 891819e29c078..605607a08b016 100644 --- a/src/Workspaces/Core/Portable/CodeRefactorings/CodeRefactoringContext.cs +++ b/src/Workspaces/Core/Portable/CodeRefactorings/CodeRefactoringContext.cs @@ -10,7 +10,7 @@ namespace Microsoft.CodeAnalysis.CodeRefactorings /// /// Context for code refactorings provided by a . /// - public struct CodeRefactoringContext + public struct CodeRefactoringContext : ITypeScriptCodeRefactoringContext { /// /// Document corresponding to the to refactor. @@ -27,6 +27,9 @@ public struct CodeRefactoringContext /// public CancellationToken CancellationToken { get; } + private readonly bool _isBlocking; + bool ITypeScriptCodeRefactoringContext.IsBlocking => _isBlocking; + private readonly Action _registerRefactoring; /// @@ -37,10 +40,21 @@ public CodeRefactoringContext( TextSpan span, Action registerRefactoring, CancellationToken cancellationToken) + : this(document, span, registerRefactoring, isBlocking: false, cancellationToken) + { + } + + internal CodeRefactoringContext( + Document document, + TextSpan span, + Action registerRefactoring, + bool isBlocking, + CancellationToken cancellationToken) { Document = document ?? throw new ArgumentNullException(nameof(document)); Span = span; _registerRefactoring = registerRefactoring ?? throw new ArgumentNullException(nameof(registerRefactoring)); + _isBlocking = isBlocking; CancellationToken = cancellationToken; } @@ -65,4 +79,9 @@ internal void Deconstruct(out Document document, out TextSpan span, out Cancella cancellationToken = CancellationToken; } } + + internal interface ITypeScriptCodeRefactoringContext + { + bool IsBlocking { get; } + } } diff --git a/src/Workspaces/Core/Portable/Remote/WellKnownServiceHubServices.cs b/src/Workspaces/Core/Portable/Remote/WellKnownServiceHubServices.cs index d7decd808015a..486750428ac13 100644 --- a/src/Workspaces/Core/Portable/Remote/WellKnownServiceHubServices.cs +++ b/src/Workspaces/Core/Portable/Remote/WellKnownServiceHubServices.cs @@ -11,11 +11,15 @@ public static void Set64bit(bool x64) SnapshotService = "roslynSnapshot" + bit; CodeAnalysisService = "roslynCodeAnalysis" + bit; RemoteSymbolSearchUpdateEngine = "roslynRemoteSymbolSearchUpdateEngine" + bit; + CSharpLanguageServer = "roslynCSharpLanguageServer" + bit; + VisualBasicLanguageServer = "roslynVisualBasicLanguageServer" + bit; } public static string SnapshotService { get; private set; } = "roslynSnapshot"; public static string CodeAnalysisService { get; private set; } = "roslynCodeAnalysis"; public static string RemoteSymbolSearchUpdateEngine { get; private set; } = "roslynRemoteSymbolSearchUpdateEngine"; + public static string CSharpLanguageServer { get; private set; } = "roslynCSharpLanguageServer"; + public static string VisualBasicLanguageServer { get; private set; } = "roslynVisualBasicLanguageServer"; // these are OOP implementation itself should care. not features that consume OOP care public const string ServiceHubServiceBase_Initialize = "Initialize"; diff --git a/src/Workspaces/Core/Portable/Shared/TestHooks/FeatureAttribute_Names.cs b/src/Workspaces/Core/Portable/Shared/TestHooks/FeatureAttribute_Names.cs index cf834d4c505e0..59d5f24ac2b49 100644 --- a/src/Workspaces/Core/Portable/Shared/TestHooks/FeatureAttribute_Names.cs +++ b/src/Workspaces/Core/Portable/Shared/TestHooks/FeatureAttribute_Names.cs @@ -38,6 +38,7 @@ internal partial class FeatureAttribute public const string Snippets = nameof(Snippets); public const string SolutionCrawler = nameof(SolutionCrawler); public const string TodoCommentList = nameof(TodoCommentList); + public const string LanguageServerWorkspaceSymbolSearch = nameof(LanguageServerWorkspaceSymbolSearch); public const string Workspace = nameof(Workspace); } } diff --git a/src/Workspaces/Core/Portable/Utilities/SerializableBytes.cs b/src/Workspaces/Core/Portable/Utilities/SerializableBytes.cs index 51fbabc68ba9b..30103fdd69bcd 100644 --- a/src/Workspaces/Core/Portable/Utilities/SerializableBytes.cs +++ b/src/Workspaces/Core/Portable/Utilities/SerializableBytes.cs @@ -6,6 +6,7 @@ using System.IO; using System.Threading; using System.Threading.Tasks; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { @@ -330,6 +331,36 @@ private void EnsureCapacity(long value) } } + public override void SetLength(long value) + { + EnsureCapacity(value); + + if (value < length) + { + // truncate the stream + + var chunkIndex = GetChunkIndex(value); + var chunkOffset = GetChunkOffset(value); + + Array.Clear(chunks[chunkIndex], chunkOffset, chunks[chunkIndex].Length - chunkOffset); + + var trimIndex = chunkIndex + 1; + for (int i = trimIndex; i < chunks.Count; i++) + { + SharedPools.ByteArray.Free(chunks[i]); + } + + chunks.RemoveRange(trimIndex, chunks.Count - trimIndex); + } + + length = value; + + if (position > value) + { + position = value; + } + } + public override void WriteByte(byte value) { EnsureCapacity(this.position + 1); diff --git a/src/Workspaces/Core/Portable/Workspace/Host/Status/IWorkspaceStatusService.cs b/src/Workspaces/Core/Portable/Workspace/Host/Status/IWorkspaceStatusService.cs index 06da6a0a7b688..0f3092996d670 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/Status/IWorkspaceStatusService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/Status/IWorkspaceStatusService.cs @@ -20,21 +20,24 @@ internal interface IWorkspaceStatusService : IWorkspaceService { /// /// Indicate that status has changed - /// - /// event argument, true, means solution is fully loaded. - /// - /// but right now, bool doesn't mean much but having it since platform API we decide to start with bool rather than - /// more richer information /// - event EventHandler StatusChanged; + event EventHandler StatusChanged; /// /// Wait until workspace is fully loaded + /// + /// unfortunately, some hosts, such as VS, use services (ex, IVsOperationProgressStatusService) that require UI thread to let project system to proceed to next stages. + /// what that means is that this method should only be used with either await or JTF.Run, it should be never used with Task.Wait otherwise, it can + /// deadlock /// Task WaitUntilFullyLoadedAsync(CancellationToken cancellationToken); /// /// Indicates whether workspace is fully loaded + /// + /// unfortunately, some hosts, such as VS, use services (ex, IVsOperationProgressStatusService) that require UI thread to let project system to proceed to next stages. + /// what that means is that this method should only be used with either await or JTF.Run, it should be never used with Task.Wait otherwise, it can + /// deadlock /// Task IsFullyLoadedAsync(CancellationToken cancellationToken); } diff --git a/src/Workspaces/Core/Portable/Workspace/Host/Status/WorkspaceStatusService.cs b/src/Workspaces/Core/Portable/Workspace/Host/Status/WorkspaceStatusService.cs index d928901addac9..8cb9172630a22 100644 --- a/src/Workspaces/Core/Portable/Workspace/Host/Status/WorkspaceStatusService.cs +++ b/src/Workspaces/Core/Portable/Workspace/Host/Status/WorkspaceStatusService.cs @@ -19,7 +19,7 @@ public WorkspaceStatusService() { } - event EventHandler IWorkspaceStatusService.StatusChanged + event EventHandler IWorkspaceStatusService.StatusChanged { add { } remove { } diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf index b4039cc89f3c9..01d8926532d8a 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf @@ -703,7 +703,7 @@ If the RegexOptions parameter of a regular expression pattern matching method in "Name" ist ein gültiger Gruppenname, und "Teilausdruck" ist ein gültiges Muster für reguläre Ausdrücke. "Name" darf keine Satzzeichen enthalten und nicht mit einer Zahl beginnen. -Wenn der RegexOptions-Parameter einer Methode zum Abgleich von Mustern für reguläre Ausdrücke das Flag "RegexOptions.ExplicitCapture" enthält oder wenn die Option "n" auf das diesen Teilausdruck angewendet wird, besteht die einzige Möglichkeit zum Erfassen eines Unterausdrucks darin, die Erfassungsgruppen explizit zu benennen. +Wenn der RegexOptions-Parameter einer Methode zum Abgleich von Mustern für reguläre Ausdrücke das Flag "RegexOptions.ExplicitCapture" enthält oder wenn die Option "n" auf diesen Teilausdruck angewendet wird, besteht die einzige Möglichkeit zum Erfassen eines Unterausdrucks darin, die Erfassungsgruppen explizit zu benennen. @@ -838,7 +838,7 @@ Wenn das ECMAScript-konforme Verhalten angegeben wird, ist "\W" gleichbedeutend This construct disables backtracking. The regular expression engine will match as many characters in the input string as it can. When no further match is possible, it will not backtrack to attempt alternate pattern matches. (That is, the subexpression matches only strings that would be matched by the subexpression alone; it does not attempt to match a string based on the subexpression and any subexpressions that follow it.) This option is recommended if you know that backtracking will not succeed. Preventing the regular expression engine from performing unnecessary searching improves performance. - Dieses Konstrukt deaktiviert die Rückverfolgung. Die Engine für reguläre Ausdrücke gleicht so viele Zeichen in der Eingabezeichenfolge wie möglich ab. Wenn kein weiterer Abgleich möglich ist, wird keine Rückverfolgung durchgeführt, um alternative Musterabgleiche zu versuchen. (Das heißt, der Teilausdruck stimmt mit nur mit Zeichenfolgen überein, die dem Teilausdruck allein entsprechen; es wird nicht versucht, eine Zeichenfolge basierend auf dem Teilausdruck und allen nachfolgenden Teilausdrücken abzugleichen.) + Dieses Konstrukt deaktiviert die Rückverfolgung. Die Engine für reguläre Ausdrücke gleicht so viele Zeichen in der Eingabezeichenfolge wie möglich ab. Wenn kein weiterer Abgleich möglich ist, wird keine Rückverfolgung durchgeführt, um alternative Musterabgleiche zu versuchen. (Das heißt, der Teilausdruck stimmt nur mit Zeichenfolgen überein, die dem Teilausdruck allein entsprechen; es wird nicht versucht, eine Zeichenfolge basierend auf dem Teilausdruck und allen nachfolgenden Teilausdrücken abzugleichen.) Diese Option empfiehlt sich, wenn Sie wissen, dass die Rückverfolgung nicht zum Erfolg führt. Indem Sie die Ausführung unnötiger Suchvorgänge durch die Engine für reguläre Ausdrücke verhindern, erzielen Sie eine verbesserte Leistung. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.xlf index e0b106bf931e2..ed5ea53bcfd92 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.es.xlf @@ -1148,7 +1148,7 @@ If ECMAScript-compliant behavior is specified, \w is equivalent to [a-zA-Z_0-9]< Nd Número, dígito decimal Pc Puntuación, conector -Si se especifica un comportamiento compatible con ECMAScript, \w equivale a [^a-zA-Z_0-9] +Si se especifica un comportamiento compatible con ECMAScript, \w equivale a [a-zA-Z_0-9] Note: Ll, Lu, Lt, Lo, Lm, Mn, Nd, and Pc are all things that should not be localized. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ko.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ko.xlf index b18e80ded7a73..2a27be8352461 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ko.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ko.xlf @@ -184,12 +184,12 @@ The period character (.) matches any character except \n (the newline character, \u000A). If a regular expression pattern is modified by the RegexOptions.Singleline option, or if the portion of the pattern that contains the . character class is modified by the 's' option, . matches any character. - 마침표(.) 문자는 \n(줄 바꿈 문자, \u000A)을 제외한 임의의 문자와 일치시킵니다. 정규식 패턴이 RegexOptions.Singleline 옵션으로 수정되거나 . 문자 클래스가 포함된 패턴의 일부가 's' 옵션으로 수정된 경우 .는 임의의 문자와 일치시킵니다. + 마침표(.) 문자는 \n(줄 바꿈 문자, \u000A)을 제외한 모든 문자와 일치시킵니다. 정규식 패턴이 RegexOptions.Singleline 옵션으로 수정되거나 . 문자 클래스가 포함된 패턴의 일부가 's' 옵션으로 수정된 경우 .는 모든 문자와 일치시킵니다. any character - 임의 문자 + 모든 문자 @@ -741,7 +741,7 @@ Two or more character ranges can be concatenated. For example, to specify the ra The regular expression construct \P{ name } matches any character that does not belong to a Unicode general category or named block, where name is the category abbreviation or named block name. - 정규식 구문 \P{ name }는 유니코드 일반 범주 또는 명명된 블록에 속하지 않는 임의의 문자와 일치시킵니다. 여기서, name은 범주 약어 또는 명명된 블록 이름입니다. + 정규식 구문 \P{ name }는 유니코드 일반 범주 또는 명명된 블록에 속하지 않는 모든 문자와 일치시킵니다. 여기서, name은 범주 약어 또는 명명된 블록 이름입니다. @@ -782,7 +782,7 @@ ECMAScript 규격 동작을 지정한 경우 \D는 [^0-9]와 같습니다.\S matches any non-white-space character. It is equivalent to the [^\f\n\r\t\v\x85\p{Z}] regular expression pattern, or the opposite of the regular expression pattern that is equivalent to \s, which matches white-space characters. If ECMAScript-compliant behavior is specified, \S is equivalent to [^ \f\n\r\t\v] - \S는 공백이 아닌 문자와 일치시킵니다. [^\f\n\r\t\v\x85\p{Z}] 정규식 패턴과 같거나, 공백 문자와 일치시키는 \s와 같은 정규식 패턴의 반대입니다. + \S는 공백이 아닌 문자와 일치시킵니다. [^\f\n\r\t\v\x85\p{Z}] 정규식 패턴과 같거나, 공백 문자와 일치시키는 \s와 같은 정규식 패턴과 반대됩니다. ECMAScript 규격 동작을 지정한 경우 \S는 [^ \f\n\r\t\v]와 같습니다. @@ -815,7 +815,7 @@ ECMAScript 규격 동작을 지정한 경우 \S는 [^ \f\n\r\t\v]와 같습니 Pc Punctuation, Connector If ECMAScript-compliant behavior is specified, \W is equivalent to [^a-zA-Z_0-9] - \W는 단어가 아닌 문자와 일치시킵니다. 다음 유니코드 범주의 문자를 제외한 임의의 문자와 일치시킵니다. + \W는 단어가 아닌 문자와 일치시킵니다. 다음 유니코드 범주의 문자를 제외한 모든 문자와 일치시킵니다. Ll 문자, 소문자 Lu 문자, 대문자 @@ -1047,7 +1047,7 @@ There is an ambiguity between octal escape codes (such as \16) and \number backr The regular expression construct \p{ name } matches any character that belongs to a Unicode general category or named block, where name is the category abbreviation or named block name. - 정규식 구문 \p{ name }는 유니코드 일반 범주 또는 명명된 블록에 속하는 임의의 문자와 일치시킵니다. 여기서, name은 범주 약어 또는 명명된 블록 이름입니다. + 정규식 구문 \p{ name }는 유니코드 일반 범주 또는 명명된 블록에 속하는 모든 문자와 일치시킵니다. 여기서, name은 범주 약어 또는 명명된 블록 이름입니다. @@ -1114,7 +1114,7 @@ ECMAScript와 호환되는 동작을 지정한 경우 \s는 [ \f\n\r\t\v]와 같 The \b anchor specifies that the match must occur on a boundary between a word character (the \w language element) and a non-word character (the \W language element). Word characters consist of alphanumeric characters and underscores; a non-word character is any character that is not alphanumeric or an underscore. The match may also occur on a word boundary at the beginning or end of the string. The \b anchor is frequently used to ensure that a subexpression matches an entire word instead of just the beginning or end of a word. - \b 앵커는 단어 문자(\w 언어 요소)와 단어가 아닌 문자(\W 언어 요소) 사이의 경계에서 일치 항목을 찾도록 지정합니다. 단어 문자는 영숫자 문자 및 밑줄로 구성되고, 단어가 아닌 문자는 영숫자나 밑줄이 아닌 임의의 문자입니다. 문자열의 시작 또는 끝부분 단어 경계에서 일치 항목을 찾을 수도 있습니다. + \b 앵커는 단어 문자(\w 언어 요소)와 단어가 아닌 문자(\W 언어 요소) 사이의 경계에서 일치 항목을 찾도록 지정합니다. 단어 문자는 영숫자 문자 및 밑줄로 구성되고, 단어가 아닌 문자는 영숫자나 밑줄이 아닌 모든 문자입니다. 문자열의 시작 또는 끝부분 단어 경계에서 일치 항목을 찾을 수도 있습니다. \b 앵커는 하위 식이 단어의 시작 또는 끝부분이 아닌 전체 단어를 일치시키도록 하는 데 자주 사용됩니다. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pt-BR.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pt-BR.xlf index 29a9db485e634..95b6d1c04b6d1 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pt-BR.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.pt-BR.xlf @@ -273,9 +273,9 @@ A definição de grupo de balanceamento usa 'name2' como uma pilha. O caractere This language element attempts to match one of two patterns depending on whether it can match an initial pattern. 'expression' is the initial pattern to match, 'yes' is the pattern to match if expression is matched, and 'no' is the optional pattern to match if expression is not matched. - Este elemento de linguagem tenta corresponder a um de dois padrões, dependendo se consegue corresponder a um padrão inicial. + Este elemento de linguagem tenta corresponder a um de dois padrões, dependendo da possibilidade de correspondência com um padrão inicial. -'expression' é o padrão inicial a ser correspondido, 'yes' é o padrão a ser correspondido quando a expressão é correspondida e 'no' é o padrão opcional a ser correspondido quando a expressão não é correspondida. +'expression' é o padrão inicial, 'yes' é o padrão quando a expressão é correspondida e 'no' é o padrão opcional quando a expressão não é correspondida. @@ -369,9 +369,9 @@ A âncora \Z corresponde a \n, mas não corresponde à \r\n (à combinação de The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions.Multiline option, the match can also occur at the end of a line. The $ anchor matches \n but does not match \r\n (the combination of carriage return and newline characters, or CR/LF). To match the CR/LF character combination, include \r?$ in the regular expression pattern. - A âncora $ especifica que o padrão anterior precisa ocorrer no final da cadeia de caracteres de entrada ou antes \n do final da cadeia de caracteres de entrada. Se você usar $ com a opção RegexOptions.Multiline, a correspondência também poderá ocorrer no final de uma linha. + A âncora $ especifica que o padrão anterior precisa ocorrer no final da cadeia de caracteres de entrada ou antes de \n no final da cadeia de caracteres de entrada. Se você usar $ com a opção RegexOptions.Multiline, a correspondência também poderá ocorrer no final de uma linha. -A âncora $ corresponde a \n, mas não corresponde a \r\n (a combinação dos caracteres de retorno de carro e de nova linha ou CR/LF). Para corresponder à combinação de caracteres CR/LF, inclua \r?$ no padrão de expressão regular. +A âncora $ corresponde a \n, mas não corresponde a \r\n (a combinação dos caracteres de retorno de carro e de nova linha ou CR/LF). Para a âncora corresponder à combinação de caracteres CR/LF, inclua \r?$ no padrão de expressão regular. @@ -741,7 +741,7 @@ Dois ou mais intervalos de caracteres podem ser concatenados. Por exemplo, para The regular expression construct \P{ name } matches any character that does not belong to a Unicode general category or named block, where name is the category abbreviation or named block name. - O constructo de expressão regular \P{ name } corresponde a qualquer caractere que não pertença a uma categoria genérica Unicode ou a um bloco nomeado, em que o nome seja a abreviação da categoria ou o nome do bloco nomeado. + O constructo de expressão regular \P{ name } corresponde a qualquer caractere que não pertença a uma categoria Unicode genérica nem a um bloco nomeado, em que o nome seja a abreviação da categoria ou o nome do bloco nomeado. @@ -782,7 +782,7 @@ Se o comportamento em conformidade com o ECMAScript for especificado, \D será e \S matches any non-white-space character. It is equivalent to the [^\f\n\r\t\v\x85\p{Z}] regular expression pattern, or the opposite of the regular expression pattern that is equivalent to \s, which matches white-space characters. If ECMAScript-compliant behavior is specified, \S is equivalent to [^ \f\n\r\t\v] - \S corresponde a qualquer caractere que não seja um espaço em branco. É equivalente ao padrão de expressão regular [^\f\n\r\t\v\x85\p{Z}] ou ao oposto do padrão de expressão regular equivalente a \s, que corresponde a caracteres de espaço em branco. + \S corresponde a qualquer caractere que não seja um espaço em branco. Ele equivale ao padrão de expressão regular [^\f\n\r\t\v\x85\p{Z}] ou ao oposto do padrão de expressão regular equivalente a \s, que corresponde a caracteres de espaço em branco. Se o comportamento em conformidade com o ECMAScript for especificado, \S será equivalente a [^ \f\n\r\t\v] @@ -856,9 +856,9 @@ The noncapturing group construct is typically used when a quantifier is applied If a regular expression includes nested grouping constructs, an outer noncapturing group construct does not apply to the inner nested group constructs. Este constructo não captura a substring correspondida por uma subexpressão: -O constructo do grupo que não é de captura geralmente é usada quando um quantificador é aplicado a um grupo, mas as substrings capturadas pelo grupo são de nenhum interesse. +O constructo do grupo que não é de captura geralmente é usado quando um quantificador é aplicado a um grupo, mas as substrings capturadas pelo grupo não são de interesse. -Se uma expressão regular inclui constructos de agrupamento aninhado, um constructo de grupo de não captura externa não se aplica aos constructos internos de grupo aninhado. +Se uma expressão regular inclui constructos de agrupamento aninhado, um constructo externo de grupo de não captura não se aplica aos constructos internos de grupo aninhado. @@ -1137,7 +1137,7 @@ A âncora \b é usada geralmente para garantir que uma subexpressão corresponda Pc Punctuation, Connector If ECMAScript-compliant behavior is specified, \w is equivalent to [a-zA-Z_0-9] - \w corresponde a qualquer caractere de palavra. Um caractere de palavra é membro de qualquer uma das categorias Unicode a seguir: + \w corresponde a qualquer caractere de palavra. Um caractere de palavra é membro de qualquer uma das seguintes categorias Unicode: Ll Letra, Minúscula Lu Letra, Maiúscula @@ -1148,7 +1148,7 @@ If ECMAScript-compliant behavior is specified, \w is equivalent to [a-zA-Z_0-9]< Nd Número, Dígito Decimal Pc Pontuação, Conector -Se o comportamento em conformidade com o ECMAScript for especificado, \w é equivalente a [a-zA-Z_0-9] +Se o comportamento em conformidade com o ECMAScript for especificado, \w será equivalente a [a-zA-Z_0-9] Note: Ll, Lu, Lt, Lo, Lm, Mn, Nd, and Pc are all things that should not be localized. @@ -1167,7 +1167,7 @@ Se o comportamento em conformidade com o ECMAScript for especificado, \w é equi A zero-width negative lookahead assertion is typically used either at the beginning or at the end of a regular expression. At the beginning of a regular expression, it can define a specific pattern that should not be matched when the beginning of the regular expression defines a similar but more general pattern to be matched. In this case, it is often used to limit backtracking. At the end of a regular expression, it can define a subexpression that cannot occur at the end of a match. Uma declaração de lookahead negativa de largura zero, em que, para que a correspondência seja bem-sucedida, a cadeia de caracteres de entrada não pode corresponder ao padrão de expressão regular na subexpressão. A cadeia de caracteres correspondente não está incluída no resultado correspondente. -Uma declaração de lookahead negativa de largura zero normalmente é usada no início ou no final de uma expressão regular. No início de uma expressão regular, ela pode definir um padrão específico que não deve ser correspondido quando o início da expressão regular define um padrão semelhante, mas mais geral a ser correspondido. Nesse caso, ela geralmente é usada para limitar o retrocesso. No final de uma expressão regular, ela pode definir uma subexpressão que não pode ocorrer no final de uma correspondência. +Uma declaração de lookahead negativa de largura zero normalmente é usada no início ou no final de uma expressão regular. No início de uma expressão regular, ela pode definir um padrão específico que não deve ser correspondido quando o início da expressão regular define um padrão semelhante, mas mais geral, a ser correspondido. Nesse caso, ela geralmente é usada para limitar o retrocesso. No final de uma expressão regular, ela pode definir uma subexpressão que não pode ocorrer no final de uma correspondência. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ru.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ru.xlf index 3419b9c96055a..092116529509f 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ru.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.ru.xlf @@ -817,14 +817,14 @@ If ECMAScript-compliant behavior is specified, \S is equivalent to [^ \f\n\r\t\v If ECMAScript-compliant behavior is specified, \W is equivalent to [^a-zA-Z_0-9] \W соответствует любому символу, не образующему слово. Он соответствует любому символу, кроме относящихся к следующим категориям Юникода: - Ll Буква, строчная - Lu Буква, прописная - Lt Буква, заглавная - Lo Буква, другая - Lm Буква, модификатор - Mn Метка, без пробела - Nd Число, десятичная цифра - Pc Пунктуация, соединитель + Ll буква, строчная + Lu буква, прописная + Lt буква, заглавная + Lo буква, другая + Lm буква, модификатор + Mn метка, без пробела + Nd число, десятичная цифра + Pc пунктуация, соединитель Если указано поведение, соответствующее ECMAScript, \W является эквивалентом [^a-zA-Z_0-9] Note: Ll, Lu, Lt, Lo, Lm, Mn, Nd, and Pc are all things that should not be localized. diff --git a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hans.xlf b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hans.xlf index 0cc36ecfb4c94..7d1ec8513b36e 100644 --- a/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hans.xlf +++ b/src/Workspaces/Core/Portable/xlf/WorkspacesResources.zh-Hans.xlf @@ -2009,7 +2009,7 @@ Zero-width positive lookbehind assertions are typically used at the beginning of None - 没有 + diff --git a/src/Workspaces/CoreTest/UtilityTest/SerializableBytesTests.cs b/src/Workspaces/CoreTest/UtilityTest/SerializableBytesTests.cs index f18abead48137..4891c528d3ded 100644 --- a/src/Workspaces/CoreTest/UtilityTest/SerializableBytesTests.cs +++ b/src/Workspaces/CoreTest/UtilityTest/SerializableBytesTests.cs @@ -175,6 +175,60 @@ public void WritableStreamTest4() StreamEqual(expected, stream); } + [Fact] + public void WritableStream_SetLength1() + { + using (var expected = new MemoryStream()) + { + expected.WriteByte(1); + expected.SetLength(10000); + expected.WriteByte(2); + expected.SetLength(1); + var expectedPosition = expected.Position; + expected.Position = 0; + + using (var stream = SerializableBytes.CreateWritableStream()) + { + stream.WriteByte(1); + stream.SetLength(10000); + stream.WriteByte(2); + stream.SetLength(1); + + StreamEqual(expected, stream); + Assert.Equal(expectedPosition, stream.Position); + } + } + } + + [Fact] + public void WritableStream_SetLength2() + { + using (var expected = new MemoryStream()) + { + expected.WriteByte(1); + expected.SetLength(10000); + expected.Position = 10000 - 1; + expected.WriteByte(2); + expected.SetLength(SharedPools.ByteBufferSize); + expected.WriteByte(3); + var expectedPosition = expected.Position; + expected.Position = 0; + + using (var stream = SerializableBytes.CreateWritableStream()) + { + stream.WriteByte(1); + stream.SetLength(10000); + stream.Position = 10000 - 1; + stream.WriteByte(2); + stream.SetLength(SharedPools.ByteBufferSize); + stream.WriteByte(3); + + StreamEqual(expected, stream); + Assert.Equal(expectedPosition, stream.Position); + } + } + } + private static void WriteByte(Stream expected, Stream stream, int position, int value) { expected.Position = position; diff --git a/src/Workspaces/Remote/ServiceHub/Microsoft.CodeAnalysis.Remote.ServiceHub.csproj b/src/Workspaces/Remote/ServiceHub/Microsoft.CodeAnalysis.Remote.ServiceHub.csproj index 3b9d9c0cd81a6..f09c3507abf23 100644 --- a/src/Workspaces/Remote/ServiceHub/Microsoft.CodeAnalysis.Remote.ServiceHub.csproj +++ b/src/Workspaces/Remote/ServiceHub/Microsoft.CodeAnalysis.Remote.ServiceHub.csproj @@ -19,6 +19,7 @@ + @@ -30,6 +31,8 @@ + + diff --git a/src/Workspaces/Remote/ServiceHub/Services/LanguageServer.cs b/src/Workspaces/Remote/ServiceHub/Services/LanguageServer.cs new file mode 100644 index 0000000000000..b4990334b533a --- /dev/null +++ b/src/Workspaces/Remote/ServiceHub/Services/LanguageServer.cs @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.CodeAnalysis.LanguageServer; +using Microsoft.CodeAnalysis.NavigateTo; +using Microsoft.VisualStudio.LanguageServer.Protocol; +using Newtonsoft.Json; +using Roslyn.Utilities; +using StreamJsonRpc; +using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; + +namespace Microsoft.CodeAnalysis.Remote +{ + // we need per language server for now since ILanguageClient + // doesn't allow multiple content types to be associated with + // one language server + internal class CSharpLanguageServer : LanguageServer + { + public CSharpLanguageServer(Stream stream, IServiceProvider serviceProvider) + : base(stream, serviceProvider, LanguageNames.CSharp) + { + } + } + + internal class VisualBasicLanguageServer : LanguageServer + { + public VisualBasicLanguageServer(Stream stream, IServiceProvider serviceProvider) + : base(stream, serviceProvider, LanguageNames.VisualBasic) + { + } + } + + internal abstract class LanguageServer : ServiceBase + { + private static readonly IImmutableSet s_supportedKinds = + ImmutableHashSet.Create( + NavigateToItemKind.Class, + NavigateToItemKind.Constant, + NavigateToItemKind.Delegate, + NavigateToItemKind.Enum, + NavigateToItemKind.EnumItem, + NavigateToItemKind.Event, + NavigateToItemKind.Field, + NavigateToItemKind.Interface, + NavigateToItemKind.Method, + NavigateToItemKind.Module, + NavigateToItemKind.Property, + NavigateToItemKind.Structure); + + private readonly string _languageName; + + public LanguageServer(Stream stream, IServiceProvider serviceProvider, string languageName) + : base(serviceProvider, stream, SpecializedCollections.EmptyEnumerable()) + { + _languageName = languageName; + + StartService(); + } + + [JsonRpcMethod(Methods.InitializeName)] + public object Initialize(int? processId, string rootPath, Uri rootUri, ClientCapabilities capabilities, TraceSetting trace, CancellationToken cancellationToken) + { + // our LSP server only supports WorkspaceStreamingSymbolProvider capability + // for now + return new InitializeResult() + { + Capabilities = new VSServerCapabilities() + { + WorkspaceStreamingSymbolProvider = true + } + }; + } + + [JsonRpcMethod(Methods.InitializedName)] + public Task Initialized() + { + return Task.CompletedTask; + } + + [JsonRpcMethod(Methods.ShutdownName)] + public void Shutdown(CancellationToken cancellationToken) + { + // our language server shutdown when VS shutdown + // we have this so that we don't get log file every time VS shutdown + } + + [JsonRpcMethod(Methods.ExitName)] + public void Exit() + { + // our language server exit when VS shutdown + // we have this so that we don't get log file every time VS shutdown + } + + [JsonRpcMethod(VSSymbolMethods.WorkspaceBeginSymbolName)] + public Task BeginWorkspaceSymbolAsync(string query, int searchId, CancellationToken cancellationToken) + { + return RunServiceAsync(async () => + { + using (UserOperationBooster.Boost()) + { + // for now, we use whatever solution we have currently. in future, we will add an ability to sync VS's current solution + // on demand from OOP side + // https://github.com/dotnet/roslyn/issues/37424 + await SearchAsync(SolutionService.PrimaryWorkspace.CurrentSolution, query, searchId, cancellationToken).ConfigureAwait(false); + return new VSBeginSymbolParams(); + } + }, cancellationToken); + } + + private async Task SearchAsync(Solution solution, string query, int searchId, CancellationToken cancellationToken) + { + var tasks = solution.Projects.Where(p => p.Language == _languageName).Select(p => SearchProjectAsync(p, cancellationToken)).ToArray(); + await Task.WhenAll(tasks).ConfigureAwait(false); + return; + + async Task SearchProjectAsync(Project project, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + var results = await AbstractNavigateToSearchService.SearchProjectInCurrentProcessAsync( + project, + ImmutableArray.Empty, + query, + s_supportedKinds, + cancellationToken).ConfigureAwait(false); + + var convertedResults = await ConvertAsync(results, cancellationToken).ConfigureAwait(false); + + await InvokeAsync( + VSSymbolMethods.WorkspacePublishSymbolName, + new object[] { new VSPublishSymbolParams() { SearchId = searchId, Symbols = convertedResults } }, + cancellationToken).ConfigureAwait(false); + } + } + + private static async Task ConvertAsync( + ImmutableArray results, CancellationToken cancellationToken) + { + var symbols = new VSSymbolInformation[results.Length]; + + for (var i = 0; i < results.Length; i++) + { + var result = results[i]; + var text = await result.NavigableItem.Document.GetTextAsync(cancellationToken).ConfigureAwait(false); + + symbols[i] = new VSSymbolInformation() + { + Name = result.Name, + ContainerName = result.AdditionalInformation, + Kind = ProtocolConversions.NavigateToKindToSymbolKind(result.Kind), + Location = new LSP.Location() + { + Uri = result.NavigableItem.Document.GetURI(), + Range = ProtocolConversions.TextSpanToRange(result.NavigableItem.SourceSpan, text) + }, + Icon = new VisualStudio.Text.Adornments.ImageElement(result.NavigableItem.Glyph.GetImageId()) + }; + } + + return symbols; + } + } +} diff --git a/src/Workspaces/Remote/ServiceHub/Shared/ServiceHubServiceBase.cs b/src/Workspaces/Remote/ServiceHub/Shared/ServiceHubServiceBase.cs index 0d2891b7eb044..e970c66dd4719 100644 --- a/src/Workspaces/Remote/ServiceHub/Shared/ServiceHubServiceBase.cs +++ b/src/Workspaces/Remote/ServiceHub/Shared/ServiceHubServiceBase.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; -using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; @@ -17,20 +16,8 @@ namespace Microsoft.CodeAnalysis.Remote { // TODO: all service hub service should be extract to interface so that it can support multiple hosts. // right now, tightly coupled to service hub - internal abstract class ServiceHubServiceBase : IDisposable + internal abstract class ServiceHubServiceBase : ServiceBase { - private static int s_instanceId; - - private readonly JsonRpc _rpc; - - protected readonly int InstanceId; - - protected readonly TraceSource Logger; - protected readonly AssetStorage AssetStorage; - - [Obsolete("don't use RPC directly but use it through StartService and InvokeAsync", error: true)] - protected readonly JsonRpc Rpc; - /// /// PinnedSolutionInfo.ScopeId. scope id of the solution. caller and callee share this id which one /// can use to find matching caller and callee while exchanging data @@ -46,14 +33,84 @@ internal abstract class ServiceHubServiceBase : IDisposable private RoslynServices _lazyRoslynServices; - private bool _disposed; - protected ServiceHubServiceBase(IServiceProvider serviceProvider, Stream stream) : this(serviceProvider, stream, SpecializedCollections.EmptyEnumerable()) { } protected ServiceHubServiceBase(IServiceProvider serviceProvider, Stream stream, IEnumerable jsonConverters) + : base(serviceProvider, stream, jsonConverters) + { + } + + protected RoslynServices RoslynServices + { + get + { + if (_lazyRoslynServices == null) + { + _lazyRoslynServices = new RoslynServices(_solutionInfo.ScopeId, AssetStorage, RoslynServices.HostServices); + } + + return _lazyRoslynServices; + } + } + + protected Task GetSolutionAsync(CancellationToken cancellationToken) + { + Contract.ThrowIfNull(_solutionInfo); + + return GetSolutionAsync(RoslynServices, _solutionInfo, cancellationToken); + } + + protected Task GetSolutionAsync(PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) + { + var localRoslynService = new RoslynServices(solutionInfo.ScopeId, AssetStorage, RoslynServices.HostServices); + return GetSolutionAsync(localRoslynService, solutionInfo, cancellationToken); + } + + public virtual void Initialize(PinnedSolutionInfo info) + { + // set pinned solution info + _lazyRoslynServices = null; + _solutionInfo = info; + } + + private static Task GetSolutionAsync(RoslynServices roslynService, PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) + { + var solutionController = (ISolutionController)roslynService.SolutionService; + return solutionController.GetSolutionAsync(solutionInfo.SolutionChecksum, solutionInfo.FromPrimaryBranch, solutionInfo.WorkspaceVersion, cancellationToken); + } + } + + /// + /// Base type with servicehub helper methods. this is not tied to how Roslyn OOP works. + /// + /// any type that derived from this type is supposed to be an entry point for servicehub services. + /// name of the type should match one appears in GenerateServiceHubConfigurationFiles.targets + /// and signature of either its constructor or static CreateAsync must follow the convension + /// ctor(Stream stream, IServiceProvider serviceProvider). + /// + /// see servicehub detail from VSIDE onenote + /// https://microsoft.sharepoint.com/teams/DD_VSIDE + /// + internal abstract class ServiceBase : IDisposable + { + private static int s_instanceId; + + private readonly JsonRpc _rpc; + + protected readonly int InstanceId; + + protected readonly TraceSource Logger; + protected readonly AssetStorage AssetStorage; + + [Obsolete("don't use RPC directly but use it through StartService and InvokeAsync", error: true)] + protected readonly JsonRpc Rpc; + + private bool _disposed; + + protected ServiceBase(IServiceProvider serviceProvider, Stream stream, IEnumerable jsonConverters) { InstanceId = Interlocked.Add(ref s_instanceId, 1); _disposed = false; @@ -82,19 +139,6 @@ protected ServiceHubServiceBase(IServiceProvider serviceProvider, Stream stream, protected string DebugInstanceString => $"{GetType()} ({InstanceId})"; - protected RoslynServices RoslynServices - { - get - { - if (_lazyRoslynServices == null) - { - _lazyRoslynServices = new RoslynServices(_solutionInfo.ScopeId, AssetStorage, RoslynServices.HostServices); - } - - return _lazyRoslynServices; - } - } - protected bool IsDisposed => ((IDisposableObservable)_rpc).IsDisposed; protected void StartService() @@ -131,19 +175,6 @@ protected Task InvokeAsync( return _rpc.InvokeWithCancellationAsync(targetName, arguments?.AsArray(), cancellationToken); } - protected Task GetSolutionAsync(CancellationToken cancellationToken) - { - Contract.ThrowIfNull(_solutionInfo); - - return GetSolutionAsync(RoslynServices, _solutionInfo, cancellationToken); - } - - protected Task GetSolutionAsync(PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) - { - var localRoslynService = new RoslynServices(solutionInfo.ScopeId, AssetStorage, RoslynServices.HostServices); - return GetSolutionAsync(localRoslynService, solutionInfo, cancellationToken); - } - protected virtual void Dispose(bool disposing) { // do nothing here @@ -154,13 +185,6 @@ protected void LogError(string message) Log(TraceEventType.Error, message); } - public virtual void Initialize(PinnedSolutionInfo info) - { - // set pinned solution info - _lazyRoslynServices = null; - _solutionInfo = info; - } - public void Dispose() { if (_disposed)