repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.fr.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="fr" original="../VBFeaturesResources.resx">
<body>
<trans-unit id="Add_Await">
<source>Add Await</source>
<target state="translated">Ajouter Await</target>
<note />
</trans-unit>
<trans-unit id="Add_Await_and_ConfigureAwaitFalse">
<source>Add Await and 'ConfigureAwait(false)'</source>
<target state="translated">Ajouter Await et 'ConfigureAwait(false)'</target>
<note />
</trans-unit>
<trans-unit id="Add_Obsolete">
<source>Add <Obsolete></source>
<target state="translated">Ajouter <Obsolete></target>
<note />
</trans-unit>
<trans-unit id="Add_missing_Imports">
<source>Add missing Imports</source>
<target state="translated">Ajouter les Import manquants</target>
<note>{Locked="Import"}</note>
</trans-unit>
<trans-unit id="Add_Shadows">
<source>Add 'Shadows'</source>
<target state="translated">Ajouter 'Shadows'</target>
<note>{Locked="Shadows"} "Shadows" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Apply_Imports_directive_placement_preferences">
<source>Apply Imports directive placement preferences</source>
<target state="translated">Appliquer les préférences de placement de la directive Imports</target>
<note>{Locked="Import"} "Import" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Apply_Me_qualification_preferences">
<source>Apply Me qualification preferences</source>
<target state="translated">Appliquer les préférences de qualification pour Me</target>
<note>{Locked="Me"} "Me" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Change_to_DirectCast">
<source>Change to 'DirectCast'</source>
<target state="translated">Changer en 'DirectCast'</target>
<note />
</trans-unit>
<trans-unit id="Change_to_TryCast">
<source>Change to 'TryCast'</source>
<target state="translated">Changer en 'TryCast'</target>
<note />
</trans-unit>
<trans-unit id="Insert_0">
<source>Insert '{0}'.</source>
<target state="translated">Insérer '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Delete_the_0_statement1">
<source>Delete the '{0}' statement.</source>
<target state="translated">Supprimez l'instruction '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Create_event_0_in_1">
<source>Create event {0} in {1}</source>
<target state="translated">Créer un événement {0} dans {1}</target>
<note />
</trans-unit>
<trans-unit id="Insert_the_missing_End_Property_statement">
<source>Insert the missing 'End Property' statement.</source>
<target state="translated">Insérez l'instruction 'End Property' manquante.</target>
<note />
</trans-unit>
<trans-unit id="Insert_the_missing_0">
<source>Insert the missing '{0}'.</source>
<target state="translated">Insérez le '{0}' manquant.</target>
<note />
</trans-unit>
<trans-unit id="Inline_temporary_variable">
<source>Inline temporary variable</source>
<target state="translated">Variable temporaire inline</target>
<note />
</trans-unit>
<trans-unit id="Conflict_s_detected">
<source>Conflict(s) detected.</source>
<target state="translated">Conflit(s) détecté(s).</target>
<note />
</trans-unit>
<trans-unit id="Introduce_Using_statement">
<source>Introduce 'Using' statement</source>
<target state="translated">Introduire l'instruction 'Using'</target>
<note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Make_0_inheritable">
<source>Make '{0}' inheritable</source>
<target state="translated">Rendre '{0}' héritable</target>
<note />
</trans-unit>
<trans-unit id="Make_private_field_ReadOnly_when_possible">
<source>Make private field ReadOnly when possible</source>
<target state="translated">Rendre le champ privé ReadOnly quand cela est possible</target>
<note>{Locked="ReadOnly"} "ReadOnly" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Move_the_0_statement_to_line_1">
<source>Move the '{0}' statement to line {1}.</source>
<target state="translated">Déplacez l'instruction '{0}' à la ligne {1}.</target>
<note />
</trans-unit>
<trans-unit id="Delete_the_0_statement2">
<source>Delete the '{0}' statement.</source>
<target state="translated">Supprimez l'instruction '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Multiple_Types">
<source><Multiple Types></source>
<target state="translated"><Plusieurs types></target>
<note />
</trans-unit>
<trans-unit id="Organize_Imports">
<source>Organize Imports</source>
<target state="translated">Organiser les Imports</target>
<note>{Locked="Import"}</note>
</trans-unit>
<trans-unit id="Remove_shared_keyword_from_module_member">
<source>Remove 'Shared' keyword from Module member</source>
<target state="translated">Supprimer le mot clé 'Shared' du membre de module</target>
<note>{Locked="Shared"} "Shared" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Shared_constructor">
<source>Shared constructor</source>
<target state="translated">Constructeur partagé</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_new_field">
<source>Type a name here to declare a new field.</source>
<target state="translated">Tapez un nom ici pour déclarer un nouveau champ.</target>
<note />
</trans-unit>
<trans-unit id="Note_colon_Space_completion_is_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab">
<source>Note: Space completion is disabled to avoid potential interference. To insert a name from the list, use tab.</source>
<target state="translated">Remarque : la saisie semi-automatique à l'aide de l'espace est désactivée pour éviter toute interférence éventuelle. Pour insérer un nom de la liste, utilisez la touche Tab.</target>
<note />
</trans-unit>
<trans-unit id="_0_Events">
<source>({0} Events)</source>
<target state="translated">({0} événements)</target>
<note />
</trans-unit>
<trans-unit id="new_field">
<source><new field></source>
<target state="translated"><nouveau champ></target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_parameter_If_no_preceding_keyword_is_used_ByVal_will_be_assumed_and_the_argument_will_be_passed_by_value">
<source>Type a name here to declare a parameter. If no preceding keyword is used; 'ByVal' will be assumed and the argument will be passed by value.</source>
<target state="translated">Tapez un nom ici pour déclarer un paramètre. Si aucun mot clé ne précède, 'ByVal' est utilisé par défaut et l'argument est passé par valeur.</target>
<note />
</trans-unit>
<trans-unit id="parameter_name">
<source><parameter name></source>
<target state="translated"><nom de paramètre></target>
<note />
</trans-unit>
<trans-unit id="Type_a_new_name_for_the_column_followed_by_Otherwise_the_original_column_name_with_be_used">
<source>Type a new name for the column, followed by '='. Otherwise, the original column name with be used.</source>
<target state="translated">Tapez un nouveau nom pour la colonne, suivi de '='. Sinon, le nom de colonne d'origine sera utilisé.</target>
<note />
</trans-unit>
<trans-unit id="Note_colon_Use_tab_for_automatic_completion_space_completion_is_disabled_to_avoid_interfering_with_a_new_name">
<source>Note: Use tab for automatic completion; space completion is disabled to avoid interfering with a new name.</source>
<target state="translated">Remarque : utilisez la touche Tab pour effectuer une saisie semi-automatique ; la saisie semi-automatique à l'aide de l'espace est désactivée pour éviter toute interférence avec un nouveau nom.</target>
<note />
</trans-unit>
<trans-unit id="result_alias">
<source><result alias></source>
<target state="translated"><alias de résultat></target>
<note />
</trans-unit>
<trans-unit id="Type_a_new_variable_name">
<source>Type a new variable name</source>
<target state="translated">Tapez un nouveau nom de variable</target>
<note />
</trans-unit>
<trans-unit id="Note_colon_Space_and_completion_are_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab">
<source>Note: Space and '=' completion are disabled to avoid potential interference. To insert a name from the list, use tab.</source>
<target state="translated">Remarque : les saisies semi-automatiques à l'aide de l'espace et de '=' sont désactivées pour éviter toute interférence éventuelle. Pour insérer un nom de la liste, utilisez la touche Tab.</target>
<note />
</trans-unit>
<trans-unit id="new_resource">
<source><new resource></source>
<target state="translated"><nouvelle ressource></target>
<note />
</trans-unit>
<trans-unit id="AddHandler_statement">
<source>AddHandler statement</source>
<target state="translated">Instruction AddHandler</target>
<note />
</trans-unit>
<trans-unit id="RemoveHandler_statement">
<source>RemoveHandler statement</source>
<target state="translated">Instruction RemoveHandler</target>
<note />
</trans-unit>
<trans-unit id="_0_function">
<source>{0} function</source>
<target state="translated">Fonction {0}</target>
<note />
</trans-unit>
<trans-unit id="CType_function">
<source>CType function</source>
<target state="translated">Fonction CType</target>
<note />
</trans-unit>
<trans-unit id="DirectCast_function">
<source>DirectCast function</source>
<target state="translated">Fonction DirectCast</target>
<note />
</trans-unit>
<trans-unit id="TryCast_function">
<source>TryCast function</source>
<target state="translated">Fonction TryCast</target>
<note />
</trans-unit>
<trans-unit id="GetType_function">
<source>GetType function</source>
<target state="translated">Fonction GetType</target>
<note />
</trans-unit>
<trans-unit id="GetXmlNamespace_function">
<source>GetXmlNamespace function</source>
<target state="translated">Fonction GetXmlNamespace</target>
<note />
</trans-unit>
<trans-unit id="Mid_statement">
<source>Mid statement</source>
<target state="translated">Instruction Mid</target>
<note />
</trans-unit>
<trans-unit id="Fix_Incorrect_Function_Return_Type">
<source>Fix Incorrect Function Return Type</source>
<target state="translated">Corriger le type de retour de fonction incorrect</target>
<note />
</trans-unit>
<trans-unit id="Simplify_name_0">
<source>Simplify name '{0}'</source>
<target state="translated">Simplifier le nom '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Simplify_member_access_0">
<source>Simplify member access '{0}'</source>
<target state="translated">Simplifier l'accès au membre '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Remove_Me_qualification">
<source>Remove 'Me' qualification</source>
<target state="translated">Supprimer la qualification 'Me'</target>
<note>{Locked="Me"} "Me" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Name_can_be_simplified">
<source>Name can be simplified</source>
<target state="translated">Le nom peut être simplifié</target>
<note />
</trans-unit>
<trans-unit id="can_t_determine_valid_range_of_statements_to_extract_out">
<source>can't determine valid range of statements to extract out</source>
<target state="translated">impossible de déterminer la plage valide d'instructions à extraire</target>
<note />
</trans-unit>
<trans-unit id="Not_all_code_paths_return">
<source>Not all code paths return</source>
<target state="translated">Tous les chemins du code n'ont pas été retournés</target>
<note />
</trans-unit>
<trans-unit id="contains_invalid_selection">
<source>contains invalid selection</source>
<target state="translated">contient une sélection non valide</target>
<note />
</trans-unit>
<trans-unit id="the_selection_contains_syntactic_errors">
<source>the selection contains syntactic errors</source>
<target state="translated">la sélection contient des erreurs syntaxiques</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_t_be_crossed_over_preprocessors">
<source>Selection can't be crossed over preprocessors</source>
<target state="translated">La sélection ne peut pas traverser plusieurs préprocesseurs</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_t_contain_throw_without_enclosing_catch_block">
<source>Selection can't contain throw without enclosing catch block</source>
<target state="translated">La sélection ne peut pas contenir throw sans englober le bloc catch</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_t_be_parts_of_constant_initializer_expression">
<source>Selection can't be parts of constant initializer expression</source>
<target state="translated">La sélection ne peut pas faire partie d'une expression d'initialiseur de constante</target>
<note />
</trans-unit>
<trans-unit id="Argument_used_for_ByRef_parameter_can_t_be_extracted_out">
<source>Argument used for ByRef parameter can't be extracted out</source>
<target state="translated">Impossible d'extraire l'argument utilisé pour le paramètre ByRef</target>
<note />
</trans-unit>
<trans-unit id="all_static_local_usages_defined_in_the_selection_must_be_included_in_the_selection">
<source>all static local usages defined in the selection must be included in the selection</source>
<target state="translated">toutes les utilisations locales statiques définies dans la sélection doivent être incluses dans la sélection</target>
<note />
</trans-unit>
<trans-unit id="Implicit_member_access_can_t_be_included_in_the_selection_without_containing_statement">
<source>Implicit member access can't be included in the selection without containing statement</source>
<target state="translated">Impossible d'inclure l'accès au membre dans la sélection sans instruction contenante</target>
<note />
</trans-unit>
<trans-unit id="Selection_must_be_part_of_executable_statements">
<source>Selection must be part of executable statements</source>
<target state="translated">La sélection doit faire partie d'instructions exécutables</target>
<note />
</trans-unit>
<trans-unit id="next_statement_control_variable_doesn_t_have_matching_declaration_statement">
<source>next statement control variable doesn't have matching declaration statement</source>
<target state="translated">la variable de contrôle de l'instruction Next ne possède pas d'instruction declaration correspondante</target>
<note />
</trans-unit>
<trans-unit id="Selection_doesn_t_contain_any_valid_node">
<source>Selection doesn't contain any valid node</source>
<target state="translated">La sélection ne contient aucun nœud valide</target>
<note />
</trans-unit>
<trans-unit id="no_valid_statement_range_to_extract_out">
<source>no valid statement range to extract out</source>
<target state="translated">Aucune plage d'instructions valides à extraire</target>
<note />
</trans-unit>
<trans-unit id="Invalid_selection">
<source>Invalid selection</source>
<target state="translated">Sélection non valide</target>
<note />
</trans-unit>
<trans-unit id="Deprecated">
<source>Deprecated</source>
<target state="translated">Déconseillé</target>
<note />
</trans-unit>
<trans-unit id="Extension">
<source>Extension</source>
<target state="translated">Extension</target>
<note />
</trans-unit>
<trans-unit id="Awaitable">
<source>Awaitable</source>
<target state="translated">Pouvant être attendu(e)</target>
<note />
</trans-unit>
<trans-unit id="Awaitable_Extension">
<source>Awaitable, Extension</source>
<target state="translated">Awaitable, Extension</target>
<note />
</trans-unit>
<trans-unit id="new_variable">
<source><new variable></source>
<target state="translated"><nouvelle variable></target>
<note />
</trans-unit>
<trans-unit id="Creates_a_delegate_procedure_instance_that_references_the_specified_procedure_AddressOf_procedureName">
<source>Creates a delegate procedure instance that references the specified procedure.
AddressOf <procedureName></source>
<target state="translated">Crée une instance de procédure de délégué qui référence la procédure spécifiée.
AddressOf <procedureName></target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_an_external_procedure_has_another_name_in_its_DLL">
<source>Indicates that an external procedure has another name in its DLL.</source>
<target state="translated">Indique qu'une procédure externe a un autre nom dans sa DLL.</target>
<note />
</trans-unit>
<trans-unit id="Performs_a_short_circuit_logical_conjunction_on_two_expressions_Returns_True_if_both_operands_evaluate_to_True_If_the_first_expression_evaluates_to_False_the_second_is_not_evaluated_result_expression1_AndAlso_expression2">
<source>Performs a short-circuit logical conjunction on two expressions. Returns True if both operands evaluate to True. If the first expression evaluates to False, the second is not evaluated.
<result> = <expression1> AndAlso <expression2></source>
<target state="translated">Effectue une conjonction logique de court-circuit sur deux expressions. Retourne True si les deux opérandes ont la valeur True. Si la première expression a la valeur False, la seconde n'est pas évaluée.
<result> = <expression1> AndAlso <expression2></target>
<note />
</trans-unit>
<trans-unit id="Performs_a_logical_conjunction_on_two_Boolean_expressions_or_a_bitwise_conjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_both_operands_evaluate_to_True_Both_expressions_are_always_evaluated_result_expression1_And_expression2">
<source>Performs a logical conjunction on two Boolean expressions, or a bitwise conjunction on two numeric expressions. For Boolean expressions, returns True if both operands evaluate to True. Both expressions are always evaluated.
<result> = <expression1> And <expression2></source>
<target state="translated">Effectue une conjonction logique sur deux expressions Boolean ou une conjonction d'opérations de bits sur deux expressions numériques. Pour les expressions Boolean, retourne True si les deux opérandes ont la valeur True. Les deux expressions sont toujours évaluées.
<result> = <expression1> And <expression2></target>
<note />
</trans-unit>
<trans-unit id="Used_in_a_Declare_statement_The_Ansi_modifier_specifies_that_Visual_Basic_should_marshal_all_strings_to_ANSI_values_and_should_look_up_the_procedure_without_modifying_its_name_during_the_search_If_no_character_set_is_specified_ANSI_is_the_default">
<source>Used in a Declare statement. The Ansi modifier specifies that Visual Basic should marshal all strings to ANSI values, and should look up the procedure without modifying its name during the search. If no character set is specified, ANSI is the default.</source>
<target state="translated">S'utilise dans une instruction Declare. Le modificateur Ansi spécifie que Visual Basic doit marshaler toutes les chaînes en valeurs ANSI et rechercher la procédure sans modifier son nom durant la recherche. Si aucun jeu de caractères n'est spécifié, ANSI est la valeur par défaut.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_data_type_in_a_declaration_statement">
<source>Specifies a data type in a declaration statement.</source>
<target state="translated">Spécifie un type de données dans une instruction declaration.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_assembly_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property">
<source>Specifies that an attribute at the beginning of a source file applies to the entire assembly. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</source>
<target state="translated">Spécifie qu'un attribut situé au début d'un fichier source s'applique à l'intégralité de l'assembly. Sinon, l'attribut s'applique uniquement à un élément de programmation individuel, par exemple une classe ou une propriété.</target>
<note />
</trans-unit>
<trans-unit id="Indicates_an_asynchronous_method_that_can_use_the_Await_operator">
<source>Indicates an asynchronous method that can use the Await operator.</source>
<target state="translated">Indique une méthode asynchrone pouvant utiliser l'opérateur Await.</target>
<note />
</trans-unit>
<trans-unit id="Used_in_a_Declare_statement_The_Auto_modifier_specifies_that_Visual_Basic_should_marshal_strings_according_to_NET_Framework_rules_and_should_determine_the_base_character_set_of_the_run_time_platform_and_possibly_modify_the_external_procedure_name_if_the_initial_search_fails">
<source>Used in a Declare statement. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules, and should determine the base character set of the run-time platform and possibly modify the external procedure name if the initial search fails.</source>
<target state="translated">S'utilise dans une instruction Declare. Le modificateur Auto spécifie que Visual Basic doit marshaler les chaînes selon les règles du .NET Framework, déterminer le jeu de caractères de base de la plateforme d'exécution et éventuellement modifier le nom de la procédure externe en cas d'échec de la recherche initiale.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_can_change_the_underlying_value_of_the_argument_in_the_calling_code">
<source>Specifies that an argument is passed in such a way that the called procedure can change the underlying value of the argument in the calling code.</source>
<target state="translated">Spécifie qu'un argument est passé de sorte que la procédure appelée peut modifier la valeur sous-jacente de l'argument dans le code appelant.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_or_property_cannot_change_the_underlying_value_of_the_argument_in_the_calling_code">
<source>Specifies that an argument is passed in such a way that the called procedure or property cannot change the underlying value of the argument in the calling code.</source>
<target state="translated">Spécifie qu'un argument est passé de sorte que la procédure ou propriété appelée ne peut pas modifier la valeur sous-jacente de l'argument dans le code appelant.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_class_and_introduces_the_definitions_of_the_variables_properties_and_methods_that_make_up_the_class">
<source>Declares the name of a class and introduces the definitions of the variables, properties, and methods that make up the class.</source>
<target state="translated">Déclare le nom d'une classe et introduit les définitions des variables, propriétés et méthodes qui constituent la classe.</target>
<note />
</trans-unit>
<trans-unit id="Generates_a_string_concatenation_of_two_expressions">
<source>Generates a string concatenation of two expressions.</source>
<target state="translated">Génère une concaténation de chaîne de deux expressions.</target>
<note />
</trans-unit>
<trans-unit id="Declares_and_defines_one_or_more_constants">
<source>Declares and defines one or more constants.</source>
<target state="translated">Déclare et définit une ou plusieurs constantes.</target>
<note />
</trans-unit>
<trans-unit id="Use_In_for_a_type_that_will_only_be_used_for_ByVal_arguments_to_functions">
<source>Use 'In' for a type that will only be used for ByVal arguments to functions.</source>
<target state="translated">Utilisez 'In' pour un type qui ne sera utilisé que pour les arguments ByVal transmis à des fonctions.</target>
<note />
</trans-unit>
<trans-unit id="Use_Out_for_a_type_that_will_only_be_used_as_a_return_from_functions">
<source>Use 'Out' for a type that will only be used as a return from functions.</source>
<target state="translated">Utilisez 'Out' pour un type qui ne sera utilisé que comme un retour de fonctions.</target>
<note />
</trans-unit>
<trans-unit id="Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type_object_structure_class_or_interface_CType_Object_As_Expression_Object_As_Type_As_Type">
<source>Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface.
CType(Object As Expression, Object As Type) As Type</source>
<target state="translated">Retourne le résultat d'une conversion explicite d'une expression en un type de données, objet, structure, classe ou interface spécifié.
CType(Object As Expression, Object As Type) As Type</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_event_has_additional_specialized_code_for_adding_handlers_removing_handlers_and_raising_events">
<source>Specifies that an event has additional, specialized code for adding handlers, removing handlers, and raising events.</source>
<target state="translated">Spécifie qu'un événement dispose d'un code spécialisé supplémentaire pour l'ajout de gestionnaires, la suppression de gestionnaires et le déclenchement d'événements.</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_reference_to_a_procedure_implemented_in_an_external_file">
<source>Declares a reference to a procedure implemented in an external file.</source>
<target state="translated">Déclare une référence à une procédure implémentée dans un fichier externe.</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_property_as_the_default_property_of_its_class_structure_or_interface">
<source>Identifies a property as the default property of its class, structure, or interface.</source>
<target state="translated">Identifie une propriété en tant que propriété par défaut de sa classe, structure ou interface.</target>
<note />
</trans-unit>
<trans-unit id="Used_to_declare_a_delegate_A_delegate_is_a_reference_type_that_refers_to_a_shared_method_of_a_type_or_to_an_instance_method_of_an_object_Any_procedure_that_is_convertible_or_that_has_matching_parameter_types_and_return_type_may_be_used_to_create_an_instance_of_this_delegate_class">
<source>Used to declare a delegate. A delegate is a reference type that refers to a shared method of a type or to an instance method of an object. Any procedure that is convertible, or that has matching parameter types and return type may be used to create an instance of this delegate class.</source>
<target state="translated">Permet de déclarer un délégué. Un délégué est un type référence qui fait référence à une méthode partagée d'un type ou à une méthode d'instance d'un objet. Toute procédure susceptible d'être convertie, ou ayant des types de paramètres et un type de retour correspondants, peut être utilisée pour créer une instance de cette classe déléguée.</target>
<note />
</trans-unit>
<trans-unit id="Declares_and_allocates_storage_space_for_one_or_more_variables_Dim_var_bracket_As_bracket_New_bracket_dataType_bracket_boundList_bracket_bracket_bracket_initializer_bracket_bracket_var2_bracket">
<source>Declares and allocates storage space for one or more variables.
Dim {<var> [As [New] dataType [(boundList)]][= initializer]}[, var2]</source>
<target state="translated">Déclare et alloue de l'espace de stockage pour une ou plusieurs variables.
Dim {<var> [As [New] dataType [(boundList)]][= initializer]}[, var2]</target>
<note />
</trans-unit>
<trans-unit id="Divides_two_numbers_and_returns_a_floating_point_result">
<source>Divides two numbers and returns a floating-point result.</source>
<target state="translated">Effectue la division de deux nombres et retourne un résultat à virgule flottante.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_0_block">
<source>Terminates a {0} block.</source>
<target state="translated">Termine un bloc {0}.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_an_0_block">
<source>Terminates an {0} block.</source>
<target state="translated">Termine un bloc {0}.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_the_definition_of_a_0_statement">
<source>Terminates the definition of a {0} statement.</source>
<target state="translated">Termine la définition d'une instruction {0}.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_the_definition_of_an_0_statement">
<source>Terminates the definition of an {0} statement.</source>
<target state="translated">Termine la définition d'une instruction {0}.</target>
<note />
</trans-unit>
<trans-unit id="Declares_an_enumeration_and_defines_the_values_of_its_members">
<source>Declares an enumeration and defines the values of its members.</source>
<target state="translated">Déclare une énumération et définit les valeurs de ses membres.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_they_are_equal_Otherwise_returns_False">
<source>Compares two expressions and returns True if they are equal. Otherwise, returns False.</source>
<target state="translated">Compare deux expressions et retourne la valeur True si elles sont égales. Sinon, retourne la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Used_to_release_array_variables_and_deallocate_the_memory_used_for_their_elements">
<source>Used to release array variables and deallocate the memory used for their elements.</source>
<target state="translated">Sert à libérer des variables tableau ainsi que la mémoire utilisée pour leurs éléments.</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_user_defined_event">
<source>Declares a user-defined event.</source>
<target state="translated">Déclare un événement défini par l'utilisateur.</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Sub_procedure_and_transfers_execution_immediately_to_the_statement_following_the_call_to_the_Sub_procedure">
<source>Exits a Sub procedure and transfers execution immediately to the statement following the call to the Sub procedure.</source>
<target state="translated">Quitte une procédure Sub et transfère immédiatement l'exécution à l'instruction qui suit l'appel de la procédure Sub.</target>
<note />
</trans-unit>
<trans-unit id="Raises_a_number_to_the_power_of_another_number">
<source>Raises a number to the power of another number.</source>
<target state="translated">Élève un nombre à la puissance d'un autre nombre.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Function">
<source>Specifies that the external procedure being referenced in the Declare statement is a Function.</source>
<target state="translated">Spécifie que la procédure externe référencée dans l'instruction Declare est une procédure Function.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Sub">
<source>Specifies that the external procedure being referenced in the Declare statement is a Sub.</source>
<target state="translated">Spécifie que la procédure externe référencée dans l'instruction Declare est une procédure Sub.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_the_assembly_that_contains_their_declaration">
<source>Specifies that one or more declared programming elements are accessible only from within the assembly that contains their declaration.</source>
<target state="translated">Spécifie qu'un ou plusieurs éléments de programmation déclarés sont accessibles uniquement à partir de l'assembly qui contient leur déclaration.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_collection_and_a_range_variable_to_use_in_a_query">
<source>Specifies a collection and a range variable to use in a query.</source>
<target state="translated">Spécifie une collection et une variable de plage à utiliser dans une requête.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code">
<source>Declares the name, parameters, and code that define a Function procedure, that is, a procedure that returns a value to the calling code.</source>
<target state="translated">Déclare le nom, les paramètres et le code qui définissent une procédure Function, en d'autres termes, une procédure qui retourne une valeur au code appelant.</target>
<note />
</trans-unit>
<trans-unit id="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_reference_type">
<source>Constrains a generic type parameter to require that any type argument passed to it be a reference type.</source>
<target state="translated">Contraint un paramètre de type générique à exiger que tout argument de type soit passé en tant que type référence.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_constructor_constraint_on_a_generic_type_parameter">
<source>Specifies a constructor constraint on a generic type parameter.</source>
<target state="translated">Spécifie une contrainte de constructeur sur un paramètre de type générique.</target>
<note />
</trans-unit>
<trans-unit id="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_value_type">
<source>Constrains a generic type parameter to require that any type argument passed to it be a value type.</source>
<target state="translated">Contraint un paramètre de type générique à exiger que tout argument de type soit passé en tant que type valeur.</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_Get_property_procedure_that_is_used_to_return_the_current_value_of_a_property">
<source>Declares a Get property procedure that is used to return the current value of a property.</source>
<target state="translated">Déclare une procédure de propriété Get qui sert à retourner la valeur actuelle d'une propriété.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is greater than the second. Otherwise, returns False.</source>
<target state="translated">Compare deux expressions et retourne la valeur True si la première expression est supérieure à la seconde. Sinon, retourne la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_or_equal_to_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is greater than or equal to the second. Otherwise, returns False.</source>
<target state="translated">Compare deux expressions et retourne la valeur True si la première expression est supérieure ou égale à la seconde. Sinon, retourne la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Declares_that_a_procedure_handles_a_specified_event">
<source>Declares that a procedure handles a specified event.</source>
<target state="translated">Déclare qu'une procédure gère un événement spécifié.</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_class_or_structure_member_is_providing_the_implementation_for_a_member_defined_in_an_interface">
<source>Indicates that a class or structure member is providing the implementation for a member defined in an interface.</source>
<target state="translated">Indique qu'un membre de classe ou de structure fournit l'implémentation d'un membre défini dans une interface.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_one_or_more_interfaces_or_interface_members_that_must_be_implemented_in_the_class_or_structure_definition_in_which_the_Implements_statement_appears">
<source>Specifies one or more interfaces, or interface members, that must be implemented in the class or structure definition in which the Implements statement appears.</source>
<target state="translated">Spécifie une ou plusieurs interfaces, ou un ou plusieurs membres d'interface, à implémenter dans la définition de classe ou de structure qui contient l'instruction Implements.</target>
<note />
</trans-unit>
<trans-unit id="Imports_all_or_specified_elements_of_a_namespace_into_a_file">
<source>Imports all or specified elements of a namespace into a file.</source>
<target state="translated">Importe une partie spécifique ou l'ensemble des éléments d'un espace de noms dans un fichier.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_group_that_the_loop_variable_in_a_For_Each_statement_is_to_traverse">
<source>Specifies the group that the loop variable in a For Each statement is to traverse.</source>
<target state="translated">Spécifie le groupe que la variable de boucle doit parcourir dans une instruction For Each.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_group_that_the_loop_variable_is_to_traverse_in_a_For_Each_statement_or_specifies_the_range_variable_in_a_query">
<source>Specifies the group that the loop variable is to traverse in a For Each statement, or specifies the range variable in a query.</source>
<target state="translated">Spécifie le groupe que la variable de boucle doit parcourir dans une instruction For Each, ou spécifie la variable de plage dans une requête.</target>
<note />
</trans-unit>
<trans-unit id="Causes_the_current_class_or_interface_to_inherit_the_attributes_variables_properties_procedures_and_events_from_another_class_or_set_of_interfaces">
<source>Causes the current class or interface to inherit the attributes, variables, properties, procedures, and events from another class or set of interfaces.</source>
<target state="translated">Oblige la classe ou l'interface actuelle à hériter des attributs, variables, propriétés, procédures et événements d'une autre classe ou d'un autre ensemble d'interfaces.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_group_that_the_range_variable_is_to_traverse_in_a_query">
<source>Specifies the group that the range variable is to traverse in a query.</source>
<target state="translated">Spécifie le groupe que la variable de plage doit parcourir dans une requête.</target>
<note />
</trans-unit>
<trans-unit id="Divides_two_numbers_and_returns_an_integer_result">
<source>Divides two numbers and returns an integer result.</source>
<target state="translated">Effectue la division de deux nombres et retourne un résultat sous forme d'entier.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_an_interface_and_the_definitions_of_the_members_of_the_interface">
<source>Declares the name of an interface and the definitions of the members of the interface.</source>
<target state="translated">Déclare le nom d'une interface et les définitions des membres de l'interface.</target>
<note />
</trans-unit>
<trans-unit id="Determines_whether_an_expression_is_false_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsFalse_on_that_class_or_structure">
<source>Determines whether an expression is false. If instances of any class or structure will be used in an OrElse clause, you must define IsFalse on that class or structure.</source>
<target state="translated">Détermine si une expression a la valeur False. Si les instances d'une classe ou d'une structure sont utilisées dans une clause OrElse, vous devez définir IsFalse dans cette classe ou structure.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_equal_result_object1_Is_object2">
<source>Compares two object reference variables and returns True if the objects are equal.
<result> = <object1> Is <object2></source>
<target state="translated">Compare deux variables de référence d'objet et retourne True si les objets sont équivalents.
<result> = <object1> Is <object2></target>
<note />
</trans-unit>
<trans-unit id="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_not_equal_result_object1_IsNot_object2">
<source>Compares two object reference variables and returns True if the objects are not equal.
<result> = <object1> IsNot <object2></source>
<target state="translated">Compare deux variables de référence d'objet et retourne True si les objets ne sont pas équivalents.
<result> = <object1> IsNot <object2></target>
<note />
</trans-unit>
<trans-unit id="Determines_whether_an_expression_is_true_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsTrue_on_that_class_or_structure">
<source>Determines whether an expression is true. If instances of any class or structure will be used in an OrElse clause, you must define IsTrue on that class or structure.</source>
<target state="translated">Détermine si une expression a la valeur True. Si les instances d'une classe ou d'une structure sont utilisées dans une clause OrElse, vous devez définir IsTrue dans cette classe ou structure.</target>
<note />
</trans-unit>
<trans-unit id="Indicates_an_iterator_method_that_can_use_the_Yield_statement">
<source>Indicates an iterator method that can use the Yield statement.</source>
<target state="translated">Indique une méthode Iterator pouvant utiliser l'instruction Yield.</target>
<note />
</trans-unit>
<trans-unit id="Defines_an_iterator_lambda_expression_that_can_use_the_Yield_statement_Iterator_Function_parameterList_As_IEnumerable_Of_T">
<source>Defines an iterator lambda expression that can use the Yield statement.
Iterator Function(<parameterList>) As IEnumerable(Of <T>)</source>
<target state="translated">Définit une expression lambda Iterator pouvant utiliser l'instruction Yield.
Iterator Function(<parameterList>) As IEnumerable(Of <T>)</target>
<note />
</trans-unit>
<trans-unit id="Performs_an_arithmetic_left_shift_on_a_bit_pattern">
<source>Performs an arithmetic left shift on a bit pattern.</source>
<target state="translated">Effectue un décalage arithmétique vers la gauche au niveau du bit.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is less than the second. Otherwise, returns False.</source>
<target state="translated">Compare deux expressions et retourne la valeur True si la première expression est inférieure à la seconde. Sinon, retourne la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_or_equal_to_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is less than or equal to the second. Otherwise, returns False.</source>
<target state="translated">Compare deux expressions et retourne la valeur True si la première expression est inférieure ou égale à la seconde. Sinon, retourne la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_clause_that_identifies_the_external_file_DLL_or_code_resource_containing_an_external_procedure">
<source>Introduces a clause that identifies the external file (DLL or code resource) containing an external procedure.</source>
<target state="translated">Introduit une clause qui identifie le fichier externe (DLL ou ressource de code) contenant une procédure externe.</target>
<note />
</trans-unit>
<trans-unit id="Compares_a_string_against_a_pattern_Wildcards_available_include_to_match_1_character_and_to_match_0_or_more_characters_result_string_Like_pattern">
<source>Compares a string against a pattern. Wildcards available include ? to match 1 character and * to match 0 or more characters.
<result> = <string> Like <pattern></source>
<target state="translated">Compare une chaîne à un modèle. Les caractères génériques disponibles sont ? pour correspondre à 1 caractère et * pour correspondre à 0 ou plusieurs caractères.
<result> = <string> Like <pattern></target>
<note />
</trans-unit>
<trans-unit id="Returns_the_difference_between_two_numeric_expressions_or_the_negative_value_of_a_numeric_expression">
<source>Returns the difference between two numeric expressions, or the negative value of a numeric expression.</source>
<target state="translated">Retourne la différence entre deux expressions numériques, ou la valeur négative d'une expression numérique.</target>
<note />
</trans-unit>
<trans-unit id="Divides_two_numbers_and_returns_only_the_remainder_number1_Mod_number2">
<source>Divides two numbers and returns only the remainder.
<number1> Mod <number2></source>
<target state="translated">Divise deux nombres et retourne uniquement le reste.
<nombre1> Mod <nombre2></target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_module_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property">
<source>Specifies that an attribute at the beginning of a source file applies to the entire module. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</source>
<target state="translated">Spécifie qu'un attribut situé au début d'un fichier source s'applique à l'intégralité du module. Sinon, l'attribut s'applique uniquement à un élément de programmation individuel, par exemple une classe ou une propriété.</target>
<note />
</trans-unit>
<trans-unit id="Multiplies_two_numbers_and_returns_the_product">
<source>Multiplies two numbers and returns the product.</source>
<target state="translated">Multiplie deux nombres et retourne le produit.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_class_can_be_used_only_as_a_base_class_and_that_you_cannot_create_an_object_directly_from_it">
<source>Specifies that a class can be used only as a base class, and that you cannot create an object directly from it.</source>
<target state="translated">Spécifie qu'une classe ne peut être utilisée que comme classe de base, et que vous ne pouvez pas créer d'objet directement à partir de celle-ci.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_is_not_implemented_in_the_class_and_must_be_overridden_in_a_derived_class_before_it_can_be_used">
<source>Specifies that a property or procedure is not implemented in the class and must be overridden in a derived class before it can be used.</source>
<target state="translated">Spécifie qu'une propriété ou procédure n'est pas implémentée dans la classe et qu'elle doit être substituée dans une classe dérivée pour pouvoir être utilisée.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_namespace_and_causes_the_source_code_following_the_declaration_to_be_compiled_within_that_namespace">
<source>Declares the name of a namespace, and causes the source code following the declaration to be compiled within that namespace.</source>
<target state="translated">Déclare le nom d'un espace de noms et oblige le code source qui suit la déclaration à être compilé dans cet espace de noms.</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_might_not_be_able_to_hold_some_of_the_possible_values_of_the_original_class_or_structure">
<source>Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure.</source>
<target state="translated">Indique qu'un opérateur de conversion (CType) convertit une classe ou une structure en un type susceptible de ne pas pouvoir contenir certaines des valeurs possibles de la classe ou structure d'origine.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_they_are_not_equal_Otherwise_returns_False">
<source>Compares two expressions and returns True if they are not equal. Otherwise, returns False.</source>
<target state="translated">Compare deux expressions et retourne la valeur True si elles ne sont pas égales. Sinon, retourne la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_class_cannot_be_used_as_a_base_class">
<source>Specifies that a class cannot be used as a base class.</source>
<target state="translated">Spécifie qu'une classe ne peut pas être utilisée en tant que classe de base.</target>
<note />
</trans-unit>
<trans-unit id="Performs_logical_negation_on_a_Boolean_expression_or_bitwise_negation_on_a_numeric_expression_result_Not_expression">
<source>Performs logical negation on a Boolean expression, or bitwise negation on a numeric expression.
<result> = Not <expression></source>
<target state="translated">Effectue une négation logique sur une expression Boolean ou une négation d'opération de bits sur une expression numérique.
<result> = Not <expression></target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_cannot_be_overridden_in_a_derived_class">
<source>Specifies that a property or procedure cannot be overridden in a derived class.</source>
<target state="translated">Spécifie qu'une propriété ou procédure ne peut pas être substituée dans une classe dérivée.</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_type_parameter_on_a_generic_class_structure_interface_delegate_or_procedure">
<source>Identifies a type parameter on a generic class, structure, interface, delegate, or procedure.</source>
<target state="translated">Identifie un paramètre de type dans une classe, une structure, une interface, un délégué ou une procédure générique.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_operator_symbol_operands_and_code_that_define_an_operator_procedure_on_a_class_or_structure">
<source>Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.</source>
<target state="translated">Déclare le symbole, les opérandes et le code qui définissent une procédure d'opérateur dans une classe ou une structure.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_procedure_argument_can_be_omitted_when_the_procedure_is_called">
<source>Specifies that a procedure argument can be omitted when the procedure is called.</source>
<target state="translated">Spécifie qu'un argument de procédure peut être omis lorsque la procédure est appelée.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_that_specifies_a_compiler_option_that_applies_to_the_entire_source_file">
<source>Introduces a statement that specifies a compiler option that applies to the entire source file.</source>
<target state="translated">Introduit une instruction qui spécifie une option du compilateur s'appliquant à l'intégralité du fichier source.</target>
<note />
</trans-unit>
<trans-unit id="Performs_short_circuit_inclusive_logical_disjunction_on_two_expressions_Returns_True_if_either_operand_evaluates_to_True_If_the_first_expression_evaluates_to_True_the_second_expression_is_not_evaluated_result_expression1_OrElse_expression2">
<source>Performs short-circuit inclusive logical disjunction on two expressions. Returns True if either operand evaluates to True. If the first expression evaluates to True, the second expression is not evaluated.
<result> = <expression1> OrElse <expression2></source>
<target state="translated">Effectue une disjonction logique inclusive de court-circuit sur deux expressions. Retourne True si l'un des opérandes a la valeur True. Si la première expression a la valeur True, la seconde expression n'est pas évaluée.
<result> = <expression1> OrElse <expression2></target>
<note />
</trans-unit>
<trans-unit id="Performs_an_inclusive_logical_disjunction_on_two_Boolean_expressions_or_a_bitwise_disjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_at_least_one_operand_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Or_expression2">
<source>Performs an inclusive logical disjunction on two Boolean expressions, or a bitwise disjunction on two numeric expressions. For Boolean expressions, returns True if at least one operand evaluates to True. Both expressions are always evaluated.
<result> = <expression1> Or <expression2></source>
<target state="translated">Effectue une disjonction logique inclusive sur deux expressions Boolean ou une disjonction d'opérations de bits sur deux expressions numériques. Pour les expressions Boolean, retourne True si au moins un opérande a la valeur True. Les deux expressions sont toujours évaluées.
<result> = <expression1> Or <expression2></target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_re_declares_one_or_more_existing_properties_or_procedures_with_the_same_name">
<source>Specifies that a property or procedure re-declares one or more existing properties or procedures with the same name.</source>
<target state="translated">Spécifie qu'une propriété ou procédure redéclare une ou plusieurs propriétés ou procédures existantes avec le même nom.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_can_be_overridden_by_an_identically_named_property_or_procedure_in_a_derived_class">
<source>Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.</source>
<target state="translated">Spécifie qu'une propriété ou procédure peut être substituée par une propriété ou procédure ayant un nom identique dans une classe dérivée.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_overrides_an_identically_named_property_or_procedure_inherited_from_a_base_class">
<source>Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class.</source>
<target state="translated">Spécifie qu'une propriété ou procédure substitue une propriété ou procédure ayant un nom identique et ayant été héritée d'une classe de base.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_procedure_parameter_takes_an_optional_array_of_elements_of_the_specified_type">
<source>Specifies that a procedure parameter takes an optional array of elements of the specified type.</source>
<target state="translated">Spécifie qu'un paramètre de procédure accepte un tableau d'éléments facultatif du type spécifié.</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_method_class_or_structure_declaration_is_a_partial_definition_of_the_method_class_or_structure">
<source>Indicates that a method, class, or structure declaration is a partial definition of the method, class, or structure.</source>
<target state="translated">Indique qu'une déclaration de méthode, de classe ou de structure est une définition partielle de la méthode, de la classe ou de la structure.</target>
<note />
</trans-unit>
<trans-unit id="Returns_the_sum_of_two_numbers_or_the_positive_value_of_a_numeric_expression">
<source>Returns the sum of two numbers, or the positive value of a numeric expression.</source>
<target state="translated">Retourne la somme de deux nombres, ou la valeur positive d'une expression numérique.</target>
<note />
</trans-unit>
<trans-unit id="Prevents_the_contents_of_an_array_from_being_cleared_when_the_dimensions_of_the_array_are_changed">
<source>Prevents the contents of an array from being cleared when the dimensions of the array are changed.</source>
<target state="translated">Empêche le contenu d'un tableau d'être effacé lorsque les dimensions de ce dernier changent.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_module_class_or_structure">
<source>Specifies that one or more declared programming elements are accessible only from within their module, class, or structure.</source>
<target state="translated">Spécifie qu'un ou plusieurs éléments de programmation déclarés sont accessibles uniquement à partir de leur module, classe ou structure.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_property_and_the_property_procedures_used_to_store_and_retrieve_the_value_of_the_property">
<source>Declares the name of a property, and the property procedures used to store and retrieve the value of the property.</source>
<target state="translated">Déclare le nom d'une propriété, ainsi que les procédures de propriété utilisées pour stocker et récupérer la valeur de la propriété.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_members_of_a_class_are_accessible_from_anywhere_in_the_same_assembly_their_own_classes_and_derived_classes">
<source>Specifies that one or more declared members of a class are accessible from anywhere in the same assembly, their own classes, and derived classes.</source>
<target state="translated">Spécifie qu'un ou plusieurs membres déclarés d'une classe sont accessibles à partir de n'importe quel emplacement dans le même assembly, leurs propres classes et les classes dérivées.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_own_class_or_from_a_derived_class">
<source>Specifies that one or more declared programming elements are accessible only from within their own class or from a derived class.</source>
<target state="translated">Spécifie qu'un ou plusieurs éléments de programmation déclarés sont accessibles uniquement à partir de leur propre classe ou d'une classe dérivée.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_have_no_access_restrictions">
<source>Specifies that one or more declared programming elements have no access restrictions.</source>
<target state="translated">Spécifie qu'un ou plusieurs éléments de programmation déclarés n'ont pas de restrictions d'accès.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_variable_or_property_can_be_read_but_not_written_to">
<source>Specifies that a variable or property can be read but not written to.</source>
<target state="translated">Spécifie qu'une variable ou une propriété peut être accessible en lecture mais pas en écriture.</target>
<note />
</trans-unit>
<trans-unit id="Reallocates_storage_space_for_an_array_variable">
<source>Reallocates storage space for an array variable.</source>
<target state="translated">Réalloue l'espace de stockage d'une variable tableau.</target>
<note />
</trans-unit>
<trans-unit id="Performs_an_arithmetic_right_shift_on_a_bit_pattern">
<source>Performs an arithmetic right shift on a bit pattern</source>
<target state="translated">Effectue un décalage arithmétique vers la droite au niveau du bit</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_Set_property_procedure_that_is_used_to_assign_a_value_to_a_property">
<source>Declares a Set property procedure that is used to assign a value to a property.</source>
<target state="translated">Déclare une procédure de propriété Set qui sert à assigner une valeur à une propriété.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_declared_programming_element_redeclares_and_hides_an_identically_named_element_in_a_base_class">
<source>Specifies that a declared programming element redeclares and hides an identically named element in a base class.</source>
<target state="translated">Spécifie qu'un élément de programmation déclaré redéclare et masque un élément ayant un nom identique dans une classe de base.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_associated_with_all_instances_of_a_class_or_structure">
<source>Specifies that one or more declared programming elements are associated with all instances of a class or structure.</source>
<target state="translated">Spécifie qu'un ou plusieurs éléments de programmation déclarés sont associés à toutes les instances d'une classe ou d'une structure.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_local_variables_are_to_remain_in_existence_and_retain_their_latest_values_after_the_procedure_in_which_they_are_declared_terminates">
<source>Specifies that one or more declared local variables are to remain in existence and retain their latest values after the procedure in which they are declared terminates.</source>
<target state="translated">Spécifie qu'une ou plusieurs variables locales déclarées doivent continuer à exister et conserver leurs toutes dernières valeurs, une fois terminée la procédure dans laquelle elles sont déclarées.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_structure_and_introduces_the_definition_of_the_variables_properties_events_and_procedures_that_make_up_the_structure">
<source>Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that make up the structure.</source>
<target state="translated">Déclare le nom d'une structure et introduit la définition des variables, propriétés, événements et procédures qui constituent la structure.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code">
<source>Declares the name, parameters, and code that define a Sub procedure, that is, a procedure that does not return a value to the calling code.</source>
<target state="translated">Déclare le nom, les paramètres et le code qui définissent une procédure Sub, en d'autres termes, une procédure qui ne retourne pas de valeur au code appelant.</target>
<note />
</trans-unit>
<trans-unit id="Separates_the_beginning_and_ending_values_of_a_loop_counter_or_array_bounds_or_that_of_a_value_match_range">
<source>Separates the beginning and ending values of a loop counter or array bounds or that of a value match range.</source>
<target state="translated">Sépare les valeurs de début et de fin d'un compteur de boucles, de limites d'index de tableau ou d'une plage de correspondance de valeurs.</target>
<note />
</trans-unit>
<trans-unit id="Determines_the_run_time_type_of_an_object_reference_variable_and_compares_it_to_a_data_type_Returns_True_or_False_depending_on_whether_the_two_types_are_compatible_result_TypeOf_objectExpression_Is_typeName">
<source>Determines the run-time type of an object reference variable and compares it to a data type. Returns True or False depending, on whether the two types are compatible.
<result> = TypeOf <objectExpression> Is <typeName></source>
<target state="translated">Détermine le type au moment de l'exécution d'une variable de référence d'objet et le compare à un type de données. Retourne True ou False selon que les deux types sont compatibles ou non.
<result> = TypeOf <objectExpression> Is <typeName></target>
<note />
</trans-unit>
<trans-unit id="Used_in_a_Declare_statement_Specifies_that_Visual_Basic_should_marshal_all_strings_to_Unicode_values_in_a_call_into_an_external_procedure_and_should_look_up_the_procedure_without_modifying_its_name">
<source>Used in a Declare statement. Specifies that Visual Basic should marshal all strings to Unicode values in a call into an external procedure, and should look up the procedure without modifying its name.</source>
<target state="translated">Utilisé dans une instruction Declare. Spécifie que Visual Basic doit marshaler toutes les chaînes en valeurs Unicode lors d'un appel d'une procédure externe, et qu'il doit rechercher la procédure sans modifier son nom.</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_can_hold_all_possible_values_of_the_original_class_or_structure">
<source>Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure.</source>
<target state="translated">Indique qu'un opérateur de conversion (CType) convertit une classe ou une structure en un type qui peut contenir toutes les valeurs possibles de la classe ou structure d'origine.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_member_variables_refer_to_an_instance_of_a_class_that_can_raise_events">
<source>Specifies that one or more declared member variables refer to an instance of a class that can raise events</source>
<target state="translated">Spécifie qu'une ou plusieurs variables membres déclarées font référence à une instance d'une classe qui peut déclencher des événements</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_can_be_written_to_but_not_read">
<source>Specifies that a property can be written to but not read.</source>
<target state="translated">Spécifie qu'une propriété peut être accessible en écriture mais pas en lecture.</target>
<note />
</trans-unit>
<trans-unit id="Performs_a_logical_exclusion_on_two_Boolean_expressions_or_a_bitwise_exclusion_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_exactly_one_of_the_expressions_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Xor_expression2">
<source>Performs a logical exclusion on two Boolean expressions, or a bitwise exclusion on two numeric expressions. For Boolean expressions, returns True if exactly one of the expressions evaluates to True. Both expressions are always evaluated.
<result> = <expression1> Xor <expression2></source>
<target state="translated">Effectue une exclusion logique sur deux expressions Boolean ou une exclusion d'opérations de bits sur deux expressions numériques. Pour les expressions Boolean, retourne True si une seule des expressions a la valeur True. Les deux expressions sont toujours évaluées.
<result> = <expression1> Xor <expression2></target>
<note />
</trans-unit>
<trans-unit id="Applies_an_aggregation_function_such_as_Sum_Average_or_Count_to_a_sequence">
<source>Applies an aggregation function, such as Sum, Average, or Count to a sequence.</source>
<target state="translated">Applique une fonction d'agrégation, par exemple Sum, Average ou Count, à une séquence.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_smallest_element_will_appear_first">
<source>Specifies the sort order for an Order By clause in a query. The smallest element will appear first.</source>
<target state="translated">Spécifie l'ordre de tri d'une clause Order By dans une requête. Le plus petit élément apparaît en premier.</target>
<note />
</trans-unit>
<trans-unit id="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_strict_binary_sort_order">
<source>Sets the string comparison method specified in Option Compare to a strict binary sort order.</source>
<target state="translated">Définit la méthode de comparaison de chaînes spécifiée dans Option Compare selon un ordre de tri binaire strict.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_element_keys_used_for_grouping_in_Group_By_or_sort_order_in_Order_By">
<source>Specifies the element keys used for grouping (in Group By) or sort order (in Order By).</source>
<target state="translated">Spécifie les clés d'éléments utilisées pour le regroupement (dans Group By) ou l'ordre de tri (dans Order By).</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_to_a_Function_Sub_or_dynamic_link_library_DLL_procedure_bracket_Call_bracket_procedureName_bracket_argumentList_bracket">
<source>Transfers execution to a Function, Sub, or dynamic-link library (DLL) procedure.
[Call] <procedureName> [(<argumentList>)]</source>
<target state="translated">Transfère l'exécution vers une procédure Function, Sub ou de bibliothèque de liens dynamiques (DLL).
[Call] <procedureName> [(<argumentList>)]</target>
<note />
</trans-unit>
<trans-unit id="Introduces_the_statements_to_run_if_none_of_the_previous_cases_in_the_Select_Case_statement_returns_True">
<source>Introduces the statements to run if none of the previous cases in the Select Case statement returns True.</source>
<target state="translated">Introduit les instructions à exécuter si aucun des cas précédents de l'instruction Select Case ne retourne la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Followed_by_a_comparison_operator_and_then_an_expression_Case_Is_introduces_the_statements_to_run_if_the_Select_Case_expression_combined_with_the_Case_Is_expression_evaluates_to_True">
<source>Followed by a comparison operator and then an expression, Case Is introduces the statements to run if the Select Case expression combined with the Case Is expression evaluates to True.</source>
<target state="translated">Suivi d'un opérateur de comparaison et d'une expression, Case Is introduit les instructions à exécuter si l'expression Select Case combinée avec l'expression Case Is a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_value_or_set_of_values_against_which_the_value_of_an_expression_in_a_Select_Case_statement_is_to_be_tested_Case_expression_expression1_To_expression2_bracket_Is_bracket_comparisonOperator_expression">
<source>Introduces a value, or set of values, against which the value of an expression in a Select Case statement is to be tested.
Case {<expression>|<expression1> To <expression2>|[Is] <comparisonOperator> <expression>}</source>
<target state="translated">Introduit une valeur ou un ensemble de valeurs à tester par rapport à la valeur d'une expression dans une instruction Select Case.
Case {<expression>|<expression1> To <expression2>|[Is] <comparisonOperator> <expression>}</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_block_to_be_run_if_the_specified_exception_occurs_inside_a_Try_block">
<source>Introduces a statement block to be run if the specified exception occurs inside a Try block.</source>
<target state="translated">Introduit un bloc d'instructions à exécuter si l'exception spécifiée se produit à l'intérieur d'un bloc Try.</target>
<note />
</trans-unit>
<trans-unit id="Sets_the_default_comparison_method_to_use_when_comparing_string_data_When_set_to_Text_uses_a_text_sort_order_that_is_not_case_sensitive_When_set_to_Binary_uses_a_strict_binary_sort_order_Option_Compare_Binary_Text">
<source>Sets the default comparison method to use when comparing string data. When set to Text, uses a text sort order that is not case sensitive. When set to Binary, uses a strict binary sort order.
Option Compare {Binary | Text}</source>
<target state="translated">Définit la méthode de comparaison par défaut à utiliser pour comparer des données de type chaîne. Lorsqu'il a la valeur Text, il utilise un ordre de tri alphabétique sans respect de la casse. Lorsqu'il a la valeur Binary, il utilise un ordre de tri binaire strict.
Option Compare {Binary | Text}</target>
<note />
</trans-unit>
<trans-unit id="Defines_a_conditional_compiler_constant_Conditional_compiler_constants_are_always_private_to_the_file_in_which_they_appear_The_expressions_used_to_initialize_them_can_contain_only_conditional_compiler_constants_and_literals">
<source>Defines a conditional compiler constant. Conditional compiler constants are always private to the file in which they appear. The expressions used to initialize them can contain only conditional compiler constants and literals.</source>
<target state="translated">Définit une constante de compilation conditionnelle. Les constantes de compilation conditionnelle sont toujours privées pour le fichier dans lequel elles figurent. Les expressions servant à les initialiser ne peuvent contenir que des littéraux et des constantes de compilation conditionnelle.</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_Do_loop">
<source>Transfers execution immediately to the next iteration of the Do loop.</source>
<target state="translated">Transfère immédiatement l'exécution à la prochaine itération de la boucle Do.</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_For_loop">
<source>Transfers execution immediately to the next iteration of the For loop.</source>
<target state="translated">Transfère immédiatement l'exécution à la prochaine itération de la boucle For.</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_loop_Can_be_used_in_a_Do_loop_a_For_loop_or_a_While_loop">
<source>Transfers execution immediately to the next iteration of the loop. Can be used in a Do loop, a For loop, or a While loop.</source>
<target state="translated">Transfère immédiatement l'exécution à la prochaine itération de la boucle. S'utilise dans une boucle Do, For ou While.</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_While_loop">
<source>Transfers execution immediately to the next iteration of the While loop.</source>
<target state="translated">Transfère immédiatement l'exécution à la prochaine itération de la boucle While.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_largest_element_will_appear_first">
<source>Specifies the sort order for an Order By clause in a query. The largest element will appear first.</source>
<target state="translated">Spécifie l'ordre de tri d'une clause Order By dans une requête. Le plus grand élément apparaît en premier.</target>
<note />
</trans-unit>
<trans-unit id="Restricts_the_values_of_a_query_result_to_eliminate_duplicate_values">
<source>Restricts the values of a query result to eliminate duplicate values.</source>
<target state="translated">Restreint les valeurs du résultat d'une requête afin d'éliminer les valeurs dupliquées.</target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_or_until_the_condition_becomes_true_Do_Loop_While_Until_condition">
<source>Repeats a block of statements while a Boolean condition is true, or until the condition becomes true.
Do...Loop {While | Until} <condition></source>
<target state="translated">Répète un bloc d'instructions tant qu'une condition Boolean a la valeur True ou jusqu'à ce que la condition devienne True.
Do...Loop {While | Until} <condition></target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Until_condition_Loop">
<source>Repeats a block of statements until a Boolean condition becomes true.
Do Until <condition>...Loop</source>
<target state="translated">Répète un bloc d'instructions jusqu'à ce qu'une condition Boolean devienne True.
Do Until <condition>...Loop</target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_While_condition_Loop">
<source>Repeats a block of statements while a Boolean condition is true.
Do While <condition>...Loop</source>
<target state="translated">Répète un bloc d'instructions tant qu'une condition Boolean a la valeur True.
Do While <condition>...Loop</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_group_of_statements_in_an_SharpIf_statement_that_is_compiled_if_no_previous_condition_evaluates_to_True">
<source>Introduces a group of statements in an #If statement that is compiled if no previous condition evaluates to True.</source>
<target state="translated">Introduit un groupe d'instructions dans une instruction #If qui est compilée si aucune condition précédente n'a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_condition_in_an_SharpIf_statement_that_is_tested_if_the_previous_conditional_test_evaluates_to_False">
<source>Introduces a condition in an #If statement that is tested if the previous conditional test evaluates to False.</source>
<target state="translated">Introduit une condition dans une instruction #If qui est testée si le précédent test conditionnel a la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_condition_in_an_If_statement_that_is_to_be_tested_if_the_previous_conditional_test_fails">
<source>Introduces a condition in an If statement that is to be tested if the previous conditional test fails.</source>
<target state="translated">Introduit une condition dans une instruction If qui doit être testée en cas d'échec du précédent test conditionnel.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_group_of_statements_in_an_If_statement_that_is_executed_if_no_previous_condition_evaluates_to_True">
<source>Introduces a group of statements in an If statement that is executed if no previous condition evaluates to True.</source>
<target state="translated">Introduit un groupe d'instructions dans une instruction If qui est exécutée si aucune condition précédente n'a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_the_definition_of_an_SharpIf_block">
<source>Terminates the definition of an #If block.</source>
<target state="translated">Termine la définition d'un bloc #If.</target>
<note />
</trans-unit>
<trans-unit id="Stops_execution_immediately">
<source>Stops execution immediately.</source>
<target state="translated">Arrête l'exécution immédiatement.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_SharpRegion_block">
<source>Terminates a #Region block.</source>
<target state="translated">Termine un bloc #Region.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_relationship_between_element_keys_to_use_as_the_basis_of_a_join_operation">
<source>Specifies the relationship between element keys to use as the basis of a join operation.</source>
<target state="translated">Spécifie la relation qui existe entre les clés d'éléments à utiliser comme base d'une opération de jointure.</target>
<note />
</trans-unit>
<trans-unit id="Simulates_the_occurrence_of_an_error">
<source>Simulates the occurrence of an error.</source>
<target state="translated">Simule la présence d'une erreur.</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Do_loop_and_transfers_execution_immediately_to_the_statement_following_the_Loop_statement">
<source>Exits a Do loop and transfers execution immediately to the statement following the Loop statement.</source>
<target state="translated">Quitte une boucle Do et transfère immédiatement l'exécution à l'instruction qui suit l'instruction Loop.</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_For_loop_and_transfers_execution_immediately_to_the_statement_following_the_Next_statement">
<source>Exits a For loop and transfers execution immediately to the statement following the Next statement.</source>
<target state="translated">Quitte une boucle For et transfère immédiatement l'exécution à l'instruction qui suit l'instruction Next.</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_procedure_or_block_and_transfers_execution_immediately_to_the_statement_following_the_procedure_call_or_block_definition_Exit_Do_For_Function_Property_Select_Sub_Try_While">
<source>Exits a procedure or block and transfers execution immediately to the statement following the procedure call or block definition.
Exit {Do | For | Function | Property | Select | Sub | Try | While}</source>
<target state="translated">Quitte une procédure ou un bloc, puis transfère immédiatement l'exécution à l'instruction qui suit l'appel de procédure ou la définition de bloc.
Exit {Do | For | Function | Property | Select | Sub | Try | While}</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Select_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Select_statement">
<source>Exits a Select block and transfers execution immediately to the statement following the End Select statement.</source>
<target state="translated">Quitte un bloc Select et transfère immédiatement l'exécution à l'instruction qui suit l'instruction End Select.</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Try_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Try_statement">
<source>Exits a Try block and transfers execution immediately to the statement following the End Try statement.</source>
<target state="translated">Quitte un bloc Try et transfère immédiatement l'exécution à l'instruction qui suit l'instruction End Try.</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_While_loop_and_transfers_execution_immediately_to_the_statement_following_the_End_While_statement">
<source>Exits a While loop and transfers execution immediately to the statement following the End While statement.</source>
<target state="translated">Quitte une boucle While et transfère immédiatement l'exécution à l'instruction qui suit l'instruction End While.</target>
<note />
</trans-unit>
<trans-unit id="When_set_to_On_requires_explicit_declaration_of_all_variables_using_a_Dim_Private_Public_or_ReDim_statement_Option_Explicit_On_Off">
<source>When set to On, requires explicit declaration of all variables, using a Dim, Private, Public, or ReDim statement.
Option Explicit {On | Off}</source>
<target state="translated">Lorsqu'il a la valeur On, il requiert une déclaration explicite de toutes les variables, à l'aide de l'instruction Dim, Private, Public ou ReDim.
Option Explicit {On | Off}</target>
<note />
</trans-unit>
<trans-unit id="Represents_a_Boolean_value_that_fails_a_conditional_test">
<source>Represents a Boolean value that fails a conditional test.</source>
<target state="translated">Représente une valeur Boolean qui ne réussit pas un test conditionnel.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_block_to_be_run_before_exiting_a_Try_structure">
<source>Introduces a statement block to be run before exiting a Try structure.</source>
<target state="translated">Introduit un bloc d'instructions à exécuter avant de quitter une structure Try.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_loop_that_is_repeated_for_each_element_in_a_collection">
<source>Introduces a loop that is repeated for each element in a collection.</source>
<target state="translated">Introduit une boucle qui se répète pour chaque élément d'une collection.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_loop_that_is_iterated_a_specified_number_of_times">
<source>Introduces a loop that is iterated a specified number of times.</source>
<target state="translated">Introduit une boucle qui est itérée un nombre spécifique de fois.</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_list_of_values_as_a_collection_initializer">
<source>Identifies a list of values as a collection initializer</source>
<target state="translated">Identifie une liste de valeurs en tant qu'initialiseur de collection</target>
<note />
</trans-unit>
<trans-unit id="Branches_unconditionally_to_a_specified_line_in_a_procedure">
<source>Branches unconditionally to a specified line in a procedure.</source>
<target state="translated">Crée une branche inconditionnelle vers une ligne spécifiée d'une procédure.</target>
<note />
</trans-unit>
<trans-unit id="Groups_elements_that_have_a_common_key">
<source>Groups elements that have a common key.</source>
<target state="translated">Regroupe les éléments qui ont une clé commune.</target>
<note />
</trans-unit>
<trans-unit id="Combines_the_elements_of_two_sequences_and_groups_the_results_The_join_operation_is_based_on_matching_keys">
<source>Combines the elements of two sequences and groups the results. The join operation is based on matching keys.</source>
<target state="translated">Combine les éléments de deux séquences et regroupe les résultats. L'opération de jointure est basée sur les clés correspondantes.</target>
<note />
</trans-unit>
<trans-unit id="Use_Group_to_specify_that_a_group_named_0_should_be_created">
<source>Use 'Group' to specify that a group named '{0}' should be created.</source>
<target state="translated">Utilisez 'Group' pour spécifier qu'un groupe nommé '{0}' doit être créé.</target>
<note />
</trans-unit>
<trans-unit id="Use_Group_to_specify_that_a_group_named_Group_should_be_created">
<source>Use 'Group' to specify that a group named 'Group' should be created.</source>
<target state="translated">Utilisez 'Group' pour spécifier qu'un groupe nommé 'Group' doit être créé.</target>
<note />
</trans-unit>
<trans-unit id="Conditionally_compiles_selected_blocks_of_code_depending_on_the_value_of_an_expression">
<source>Conditionally compiles selected blocks of code, depending on the value of an expression.</source>
<target state="translated">Effectue une compilation conditionnelle des blocs de code sélectionnés, en fonction de la valeur d'une expression.</target>
<note />
</trans-unit>
<trans-unit id="Conditionally_executes_a_group_of_statements_depending_on_the_value_of_an_expression">
<source>Conditionally executes a group of statements, depending on the value of an expression.</source>
<target state="translated">Exécute un groupe d'instructions soumises à une condition, en fonction de la valeur d'une expression.</target>
<note />
</trans-unit>
<trans-unit id="When_set_to_On_allows_the_use_of_local_type_inference_in_declaring_variables_Option_Infer_On_Off">
<source>When set to On, allows the use of local type inference in declaring variables.
Option Infer {On | Off}</source>
<target state="translated">Lorsqu'il a la valeur On, il autorise l'utilisation d'une inférence de type locale lors de la déclaration de variables.
Option Infer {On | Off}</target>
<note />
</trans-unit>
<trans-unit id="Specifies_an_identifier_that_can_serve_as_a_reference_to_the_results_of_a_join_or_grouping_subexpression">
<source>Specifies an identifier that can serve as a reference to the results of a join or grouping subexpression.</source>
<target state="translated">Spécifie un identificateur qui peut servir de référence aux résultats d'une sous-expression de jointure ou de regroupement.</target>
<note />
</trans-unit>
<trans-unit id="Combines_the_elements_of_two_sequences_The_join_operation_is_based_on_matching_keys">
<source>Combines the elements of two sequences. The join operation is based on matching keys.</source>
<target state="translated">Combine les éléments de deux séquences. L'opération de jointure est basée sur les clés correspondantes.</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_key_field_in_an_anonymous_type_definition">
<source>Identifies a key field in an anonymous type definition.</source>
<target state="translated">Identifie un champ clé dans une définition de type anonyme.</target>
<note />
</trans-unit>
<trans-unit id="Computes_a_value_for_each_item_in_the_query_and_assigns_the_value_to_a_new_range_variable">
<source>Computes a value for each item in the query, and assigns the value to a new range variable.</source>
<target state="translated">Calcule une valeur pour chaque élément de la requête, puis assigne la valeur à une nouvelle variable de plage.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_loop_that_is_introduced_with_a_Do_statement">
<source>Terminates a loop that is introduced with a Do statement.</source>
<target state="translated">Termine une boucle introduite avec une instruction Do.</target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition">
<source>Repeats a block of statements until a Boolean condition becomes true.
Do...Loop Until <condition></source>
<target state="translated">Répète un bloc d'instructions jusqu'à ce qu'une condition Boolean devienne True.
Do...Loop Until <condition></target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition">
<source>Repeats a block of statements while a Boolean condition is true.
Do...Loop While <condition></source>
<target state="translated">Répète un bloc d'instructions tant qu'une condition Boolean a la valeur True.
Do...Loop While <condition></target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_refer_to_the_current_instance_of_a_class_or_structure_that_is_the_instance_in_which_the_code_is_running">
<source>Provides a way to refer to the current instance of a class or structure, that is, the instance in which the code is running.</source>
<target state="translated">Permet de faire référence à l'instance actuelle d'une classe ou d'une structure, en d'autres termes, l'instance dans laquelle le code s'exécute.</target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_refer_to_the_base_class_of_the_current_class_instance_You_cannot_use_MyBase_to_call_MustOverride_base_methods">
<source>Provides a way to refer to the base class of the current class instance. You cannot use MyBase to call MustOverride base methods.</source>
<target state="translated">Permet de faire référence à la classe de base de l'instance de classe actuelle. Vous ne pouvez pas utiliser MyBase pour appeler les méthodes de base MustOverride.</target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_refer_to_the_class_instance_members_as_originally_implemented_ignoring_any_derived_class_overrides">
<source>Provides a way to refer to the class instance members as originally implemented, ignoring any derived class overrides.</source>
<target state="translated">Permet de faire référence aux membres d'instance de classe implémentés à l'origine, en ignorant toute substitution de classe dérivée.</target>
<note />
</trans-unit>
<trans-unit id="Creates_a_new_object_instance">
<source>Creates a new object instance.</source>
<target state="translated">Crée une instance d'objet.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_loop_that_iterates_through_the_values_of_a_loop_variable">
<source>Terminates a loop that iterates through the values of a loop variable.</source>
<target state="translated">Termine une boucle qui itère au sein des valeurs d'une variable de boucle.</target>
<note />
</trans-unit>
<trans-unit id="Represents_the_default_value_of_any_data_type">
<source>Represents the default value of any data type.</source>
<target state="translated">Représente la valeur par défaut d'un type de données quelconque.</target>
<note />
</trans-unit>
<trans-unit id="Turns_a_compiler_option_off">
<source>Turns a compiler option off.</source>
<target state="translated">Désactive une option du compilateur.</target>
<note />
</trans-unit>
<trans-unit id="Enables_the_error_handling_routine_that_starts_at_the_line_specified_in_the_line_argument_The_specified_line_must_be_in_the_same_procedure_as_the_On_Error_statement_On_Error_GoTo_bracket_label_0_1_bracket">
<source>Enables the error-handling routine that starts at the line specified in the line argument.
The specified line must be in the same procedure as the On Error statement.
On Error GoTo [<label> | 0 | -1]</source>
<target state="translated">Active la routine de gestion des erreurs qui démarre à la ligne spécifiée dans l'argument de ligne.
La ligne spécifiée doit se trouver dans la même procédure que l'instruction On Error.
On Error GoTo [<label> | 0 | -1]</target>
<note />
</trans-unit>
<trans-unit id="When_a_run_time_error_occurs_execution_transfers_to_the_statement_following_the_statement_or_procedure_call_that_resulted_in_the_error">
<source>When a run-time error occurs, execution transfers to the statement following the statement or procedure call that resulted in the error.</source>
<target state="translated">Lorsqu'une erreur d'exécution se produit, l'exécution est transférée à l'instruction qui suit l'appel de l'instruction ou de la procédure ayant entraîné l'erreur.</target>
<note />
</trans-unit>
<trans-unit id="Turns_a_compiler_option_on">
<source>Turns a compiler option on.</source>
<target state="translated">Active une option du compilateur.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_element_keys_used_to_correlate_sequences_for_a_join_operation">
<source>Specifies the element keys used to correlate sequences for a join operation.</source>
<target state="translated">Spécifie les clés d'éléments utilisées pour mettre en corrélation les séquences d'une opération de jointure.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_sort_order_for_columns_in_a_query_Can_be_followed_by_either_the_Ascending_or_the_Descending_keyword_If_neither_is_specified_Ascending_is_used">
<source>Specifies the sort order for columns in a query. Can be followed by either the Ascending or the Descending keyword. If neither is specified, Ascending is used.</source>
<target state="translated">Spécifie l'ordre de tri des colonnes dans une requête. Cette clause peut être suivie du mot clé Ascending ou Descending. Si aucun mot clé n'est spécifié, Ascending est utilisé.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_statements_to_run_when_the_event_is_raised_by_the_RaiseEvent_statement_RaiseEvent_delegateSignature_End_RaiseEvent">
<source>Specifies the statements to run when the event is raised by the RaiseEvent statement.
RaiseEvent(<delegateSignature>)...End RaiseEvent</source>
<target state="translated">Spécifie les instructions à exécuter lorsque l'événement est déclenché par l'instruction RaiseEvent.
RaiseEvent(<delegateSignature>)...End RaiseEvent</target>
<note />
</trans-unit>
<trans-unit id="Triggers_an_event_declared_at_module_level_within_a_class_form_or_document_RaiseEvent_eventName_bracket_argumentList_bracket">
<source>Triggers an event declared at module level within a class, form, or document.
RaiseEvent <eventName> [(<argumentList>)]</source>
<target state="translated">Déclenche un événement déclaré au niveau du module dans une classe, un formulaire ou un document.
RaiseEvent <eventName> [(<argumentList>)]</target>
<note />
</trans-unit>
<trans-unit id="Collapses_and_hides_sections_of_code_in_Visual_Basic_files">
<source>Collapses and hides sections of code in Visual Basic files.</source>
<target state="translated">Réduit et masque des sections de code dans des fichiers Visual Basic.</target>
<note />
</trans-unit>
<trans-unit id="Returns_execution_to_the_code_that_called_the_Function_Sub_Get_Set_or_Operator_procedure_Return_or_Return_expression">
<source>Returns execution to the code that called the Function, Sub, Get, Set, or Operator procedure.
Return -or- Return <expression></source>
<target state="translated">Retourne l'exécution au code qui a appelé la procédure Function, Sub, Get, Set ou Operator.
Return -ou- Return <expression></target>
<note />
</trans-unit>
<trans-unit id="Runs_one_of_several_groups_of_statements_depending_on_the_value_of_an_expression">
<source>Runs one of several groups of statements, depending on the value of an expression.</source>
<target state="translated">Exécute l'un des multiples groupes d'instructions, en fonction de la valeur d'une expression.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_which_columns_to_include_in_the_result_of_a_query">
<source>Specifies which columns to include in the result of a query.</source>
<target state="translated">Spécifie les colonnes à inclure dans le résultat d'une requête.</target>
<note />
</trans-unit>
<trans-unit id="Skips_elements_up_to_a_specified_position_in_the_collection">
<source>Skips elements up to a specified position in the collection.</source>
<target state="translated">Ignore des éléments jusqu'à une position spécifique dans la collection.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_how_much_to_increment_between_each_loop_iteration">
<source>Specifies how much to increment between each loop iteration.</source>
<target state="translated">Spécifie la valeur à ajouter à chaque itération de boucle.</target>
<note />
</trans-unit>
<trans-unit id="Suspends_program_execution">
<source>Suspends program execution.</source>
<target state="translated">Suspend l'exécution du programme.</target>
<note />
</trans-unit>
<trans-unit id="When_set_to_On_restricts_implicit_data_type_conversions_to_only_widening_conversions_Option_Strict_On_Off">
<source>When set to On, restricts implicit data type conversions to only widening conversions.
Option Strict {On | Off}</source>
<target state="translated">Lorsqu'il a la valeur On, il restreint les conversions de types de données implicites à des conversions étendues uniquement.
Option Strict {On | Off}</target>
<note />
</trans-unit>
<trans-unit id="Ensures_that_multiple_threads_do_not_execute_the_statement_block_at_the_same_time_SyncLock_object_End_Synclock">
<source>Ensures that multiple threads do not execute the statement block at the same time.
SyncLock <object>...End Synclock</source>
<target state="translated">S'assure que plusieurs threads n'exécutent pas le bloc d'instructions en même temps.
SyncLock <object>...End Synclock</target>
<note />
</trans-unit>
<trans-unit id="Includes_elements_up_to_a_specified_position_in_the_collection">
<source>Includes elements up to a specified position in the collection.</source>
<target state="translated">Inclut des éléments jusqu'à une position spécifique dans la collection.</target>
<note />
</trans-unit>
<trans-unit id="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_text_sort_order_that_is_not_case_sensitive">
<source>Sets the string comparison method specified in Option Compare to a text sort order that is not case sensitive.</source>
<target state="translated">Définit la méthode de comparaison de chaînes spécifiée dans Option Compare selon un ordre de tri alphabétique sans respect de la casse.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_block_to_be_compiled_or_executed_if_a_tested_condition_is_true">
<source>Introduces a statement block to be compiled or executed if a tested condition is true.</source>
<target state="translated">Introduit un bloc d'instructions à compiler ou à exécuter si une condition testée a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Throws_an_exception_within_a_procedure_so_that_you_can_handle_it_with_structured_or_unstructured_exception_handling_code">
<source>Throws an exception within a procedure so that you can handle it with structured or unstructured exception-handling code.</source>
<target state="translated">Lève une exception dans une procédure de sorte que vous puissiez la gérer avec du code de gestion des exceptions structurée ou non structurée.</target>
<note />
</trans-unit>
<trans-unit id="Represents_a_Boolean_value_that_passes_a_conditional_test">
<source>Represents a Boolean value that passes a conditional test.</source>
<target state="translated">Représente une valeur Boolean qui réussit un test conditionnel.</target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_handle_some_or_all_possible_errors_that_might_occur_in_a_given_block_of_code_while_still_running_the_code_Try_bracket_Catch_bracket_Catch_Finally_End_Try">
<source>Provides a way to handle some or all possible errors that might occur in a given block of code, while still running the code.
Try...[Catch]...{Catch | Finally}...End Try</source>
<target state="translated">Permet de traiter une partie ou l'ensemble des erreurs possibles pouvant se produire dans un bloc de code donné, tout en continuant à exécuter le code.
Try...[Catch]...{Catch | Finally}...End Try</target>
<note />
</trans-unit>
<trans-unit id="A_Using_block_does_three_things_colon_it_creates_and_initializes_variables_in_the_resource_list_it_runs_the_code_in_the_block_and_it_disposes_of_the_variables_before_exiting_Resources_used_in_the_Using_block_must_implement_System_IDisposable_Using_resource1_bracket_resource2_bracket_End_Using">
<source>A Using block does three things: it creates and initializes variables in the resource list, it runs the code in the block, and it disposes of the variables before exiting. Resources used in the Using block must implement System.IDisposable.
Using <resource1>[, <resource2>]...End Using</source>
<target state="translated">Un bloc Using effectue trois actions : il crée et initialise des variables dans la liste des ressources, il exécute le code du bloc et supprime les variables avant de quitter. Les ressources utilisées dans le bloc Using doivent implémenter System.IDisposable.
Using <resource1>[, <resource2>]...End Using</target>
<note />
</trans-unit>
<trans-unit id="Adds_a_conditional_test_to_a_Catch_statement_Exceptions_are_caught_by_that_Catch_statement_only_when_the_conditional_test_that_follows_the_When_keyword_evaluates_to_True">
<source>Adds a conditional test to a Catch statement. Exceptions are caught by that Catch statement only when the conditional test that follows the When keyword evaluates to True.</source>
<target state="translated">Ajoute un test conditionnel à une instruction Catch. Les exceptions sont interceptées par cette instruction Catch uniquement lorsque le test conditionnel qui suit le mot clé When a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_filtering_condition_for_a_range_variable_in_a_query">
<source>Specifies the filtering condition for a range variable in a query.</source>
<target state="translated">Spécifie la condition de filtrage d'une variable de plage dans une requête.</target>
<note />
</trans-unit>
<trans-unit id="Runs_a_series_of_statements_as_long_as_a_given_condition_is_true">
<source>Runs a series of statements as long as a given condition is true.</source>
<target state="translated">Exécute une série d'instructions tant qu'une condition donnée a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_condition_for_Skip_and_Take_operations_Elements_will_be_bypassed_or_included_as_long_as_the_condition_is_true">
<source>Specifies a condition for Skip and Take operations. Elements will be bypassed or included as long as the condition is true.</source>
<target state="translated">Spécifie une condition pour les opérations Skip et Take. Les éléments sont ignorés ou inclus tant que la condition a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_declaration_of_property_initializations_in_an_object_initializer_New_typeName_With_bracket_property_expression_bracket_bracket_bracket">
<source>Specifies the declaration of property initializations in an object initializer.
New <typeName> With {[.<property> = <expression>][,...]}</source>
<target state="translated">Spécifie la déclaration des initialisations de propriétés dans un initialiseur d'objet.
New <typeName> With {[.<property> = <expression>][,...]}</target>
<note />
</trans-unit>
<trans-unit id="Runs_a_series_of_statements_that_refer_to_a_single_object_or_structure_With_object_End_With">
<source>Runs a series of statements that refer to a single object or structure.
With <object>...End With</source>
<target state="translated">Exécute une série d'instructions qui font référence à un objet ou une structure unique.
With <object>...End With</target>
<note />
</trans-unit>
<trans-unit id="Produces_an_element_of_an_IEnumerable_or_IEnumerator">
<source>Produces an element of an IEnumerable or IEnumerator.</source>
<target state="translated">Produit un élément d'un IEnumerable ou IEnumerator.</target>
<note />
</trans-unit>
<trans-unit id="Defines_an_asynchronous_lambda_expression_that_can_use_the_Await_operator_Can_be_used_wherever_a_delegate_type_is_expected_Async_Sub_Function_parameterList_expression">
<source>Defines an asynchronous lambda expression that can use the Await operator. Can be used wherever a delegate type is expected.
Async Sub/Function(<parameterList>) <expression></source>
<target state="translated">Définit une expression lambda asynchrone pouvant utiliser l'opérateur Await. S'utilise lorsqu'un type délégué est attendu.
Async Sub/Function(<parameterList>) <expression></target>
<note />
</trans-unit>
<trans-unit id="Defines_a_lambda_expression_that_calculates_and_returns_a_single_value_Can_be_used_wherever_a_delegate_type_is_expected_Function_parameterList_expression">
<source>Defines a lambda expression that calculates and returns a single value. Can be used wherever a delegate type is expected.
Function(<parameterList>) <expression></source>
<target state="translated">Définit une expression lambda qui calcule et retourne une valeur unique. S'utilise lorsqu'un type délégué est attendu.
Function(<parameterList>) <expression></target>
<note />
</trans-unit>
<trans-unit id="Defines_a_lambda_expression_that_can_execute_statements_and_does_not_return_a_value_Can_be_used_wherever_a_delegate_type_is_expected_Sub_parameterList_statement">
<source>Defines a lambda expression that can execute statements and does not return a value. Can be used wherever a delegate type is expected.
Sub(<parameterList>) <statement></source>
<target state="translated">Définit une expression lambda qui exécute des instructions, mais qui ne retourne aucune valeur. S'utilise lorsqu'un type délégué est attendu.
Sub(<parameterList>) <statement></target>
<note />
</trans-unit>
<trans-unit id="Disables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line">
<source>Disables reporting of specified warnings in the portion of the source file below the current line.</source>
<target state="translated">Désactive la création de rapports des avertissements spécifiés dans la partie du fichier source en dessous de la ligne active.</target>
<note />
</trans-unit>
<trans-unit id="Enables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line">
<source>Enables reporting of specified warnings in the portion of the source file below the current line.</source>
<target state="translated">Active la création de rapports des avertissements spécifiés dans la partie du fichier source en dessous de la ligne active.</target>
<note />
</trans-unit>
<trans-unit id="Insert_Await">
<source>Insert 'Await'.</source>
<target state="translated">Insérez 'Await'.</target>
<note />
</trans-unit>
<trans-unit id="Make_0_an_Async_Function">
<source>Make {0} an Async Function.</source>
<target state="translated">Faire de {0} une fonction Async.</target>
<note />
</trans-unit>
<trans-unit id="Convert_0_to_Iterator">
<source>Convert {0} to Iterator</source>
<target state="translated">Convertir {0} en itérateur</target>
<note />
</trans-unit>
<trans-unit id="Replace_Return_with_Yield">
<source>Replace 'Return' with 'Yield</source>
<target state="translated">Remplacer 'Return' par 'Yield</target>
<note />
</trans-unit>
<trans-unit id="Use_the_correct_control_variable">
<source>Use the correct control variable</source>
<target state="translated">Utiliser la variable de contrôle correcte</target>
<note />
</trans-unit>
<trans-unit id="NameOf_function">
<source>NameOf function</source>
<target state="translated">Fonction NameOf</target>
<note />
</trans-unit>
<trans-unit id="Generate_narrowing_conversion_in_0">
<source>Generate narrowing conversion in '{0}'</source>
<target state="translated">Générer une conversion restrictive dans '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Generate_widening_conversion_in_0">
<source>Generate widening conversion in '{0}'</source>
<target state="translated">Générer une conversation étendue dans '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Try_block">
<source>Try block</source>
<target state="translated">Bloc Try</target>
<note>{Locked="Try"} "Try" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Catch_clause">
<source>Catch clause</source>
<target state="translated">Clause Catch</target>
<note>{Locked="Catch"} "Catch" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Finally_clause">
<source>Finally clause</source>
<target state="translated">Clause Finally</target>
<note>{Locked="Finally"} "Finally" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Using_statement">
<source>Using statement</source>
<target state="translated">Instruction Using</target>
<note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Using_block">
<source>Using block</source>
<target state="translated">Bloc Using</target>
<note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="With_statement">
<source>With statement</source>
<target state="translated">Instruction With</target>
<note>{Locked="With"} "With" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="With_block">
<source>With block</source>
<target state="translated">Bloc With</target>
<note>{Locked="With"} "With" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="SyncLock_statement">
<source>SyncLock statement</source>
<target state="translated">Instruction SyncLock</target>
<note>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="SyncLock_block">
<source>SyncLock block</source>
<target state="translated">Bloc SyncLock</target>
<note>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="For_Each_statement">
<source>For Each statement</source>
<target state="translated">Instruction For Each</target>
<note>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="For_Each_block">
<source>For Each block</source>
<target state="translated">Bloc For Each</target>
<note>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="On_Error_statement">
<source>On Error statement</source>
<target state="translated">Instruction On Error</target>
<note>{Locked="On Error"} "On Error" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Resume_statement">
<source>Resume statement</source>
<target state="translated">Instruction Resume</target>
<note>{Locked="Resume"} "Resume" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Yield_statement">
<source>Yield statement</source>
<target state="translated">Instruction Yield</target>
<note>{Locked="Yield"} "Yield" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Await_expression">
<source>Await expression</source>
<target state="translated">Expression Await</target>
<note>{Locked="Await"} "Await" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Lambda">
<source>Lambda</source>
<target state="translated">Lambda</target>
<note />
</trans-unit>
<trans-unit id="Where_clause">
<source>Where clause</source>
<target state="translated">Clause Where</target>
<note>{Locked="Where"} "Where" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Select_clause">
<source>Select clause</source>
<target state="translated">Clause Select</target>
<note>{Locked="Select"} "Select" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="From_clause">
<source>From clause</source>
<target state="translated">Clause From</target>
<note>{Locked="From"} "From" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Aggregate_clause">
<source>Aggregate clause</source>
<target state="translated">Clause Aggregate</target>
<note>{Locked="Aggregate"} "Aggregate" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Let_clause">
<source>Let clause</source>
<target state="translated">Clause Let</target>
<note>{Locked="Let"} "Let" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Join_clause">
<source>Join clause</source>
<target state="translated">Clause Join</target>
<note>{Locked="Join"} "Join" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Group_Join_clause">
<source>Group Join clause</source>
<target state="translated">Clause Group Join</target>
<note>{Locked="Group Join"} "Group Join" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Group_By_clause">
<source>Group By clause</source>
<target state="translated">Clause Group By</target>
<note>{Locked="Group By"} "Group By" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Function_aggregation">
<source>Function aggregation</source>
<target state="translated">Agrégation de fonction</target>
<note />
</trans-unit>
<trans-unit id="Take_While_clause">
<source>Take While clause</source>
<target state="translated">Clause Take While</target>
<note>{Locked="Take While"} "Take While" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Skip_While_clause">
<source>Skip While clause</source>
<target state="translated">Clause Skip While</target>
<note>{Locked="Skip While"} "Skip While" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Ordering_clause">
<source>Ordering clause</source>
<target state="translated">Clause Ordering</target>
<note>{Locked="Ordering"} "Ordering" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Join_condition">
<source>Join condition</source>
<target state="translated">Condition Join</target>
<note>{Locked="Join"} "Join" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="WithEvents_field">
<source>WithEvents field</source>
<target state="translated">Champ WithEvents</target>
<note>{Locked="WithEvents"} "WithEvents" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="as_clause">
<source>as clause</source>
<target state="translated">Clause as</target>
<note>{Locked="as"} "as" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="type_parameters">
<source>type parameters</source>
<target state="translated">paramètres de type</target>
<note />
</trans-unit>
<trans-unit id="parameters">
<source>parameters</source>
<target state="translated">paramètres</target>
<note />
</trans-unit>
<trans-unit id="attributes">
<source>attributes</source>
<target state="translated">attributs</target>
<note />
</trans-unit>
<trans-unit id="Too_many_arguments_to_0">
<source>Too many arguments to '{0}'.</source>
<target state="translated">Arguments trop nombreux pour '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Type_0_is_not_defined">
<source>Type '{0}' is not defined.</source>
<target state="translated">Le type '{0}' n'est pas défini.</target>
<note />
</trans-unit>
<trans-unit id="Add_Overloads">
<source>Add 'Overloads'</source>
<target state="translated">Ajouter 'Overloads'</target>
<note>{Locked="Overloads"} "Overloads" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Add_a_metadata_reference_to_specified_assembly_and_all_its_dependencies_e_g_Sharpr_myLib_dll">
<source>Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll".</source>
<target state="translated">Permet d'ajouter une référence de métadonnées à l'assembly spécifié et toutes ses dépendances. Exemple : #r "myLib.dll".</target>
<note />
</trans-unit>
<trans-unit id="Properties">
<source>Properties</source>
<target state="translated">Propriétés</target>
<note />
</trans-unit>
<trans-unit id="namespace_name">
<source><namespace name></source>
<target state="translated"><nom de l'espace de noms></target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_namespace">
<source>Type a name here to declare a namespace.</source>
<target state="translated">Tapez un nom ici pour déclarer un espace de noms.</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_class">
<source>Type a name here to declare a partial class.</source>
<target state="translated">Tapez un nom ici pour déclarer une classe partielle.</target>
<note />
</trans-unit>
<trans-unit id="class_name">
<source><class name></source>
<target state="translated"><nom de la classe></target>
<note />
</trans-unit>
<trans-unit id="interface_name">
<source><interface name></source>
<target state="translated"><nom de l'interface></target>
<note />
</trans-unit>
<trans-unit id="module_name">
<source><module name></source>
<target state="translated"><nom du module></target>
<note />
</trans-unit>
<trans-unit id="structure_name">
<source><structure name></source>
<target state="translated"><nom de la structure></target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_interface">
<source>Type a name here to declare a partial interface.</source>
<target state="translated">Tapez un nom ici pour déclarer une interface partielle.</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_module">
<source>Type a name here to declare a partial module.</source>
<target state="translated">Tapez un nom ici pour déclarer un module partiel.</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_structure">
<source>Type a name here to declare a partial structure.</source>
<target state="translated">Tapez un nom ici pour déclarer une structure partielle.</target>
<note />
</trans-unit>
<trans-unit id="Event_add_handler_name">
<source>{0}.add</source>
<target state="translated">{0}.add</target>
<note>The name of an event add handler where "{0}" is the event name.</note>
</trans-unit>
<trans-unit id="Event_remove_handler_name">
<source>{0}.remove</source>
<target state="translated">{0}.remove</target>
<note>The name of an event remove handler where "{0}" is the event name.</note>
</trans-unit>
<trans-unit id="Property_getter_name">
<source>{0}.get</source>
<target state="translated">{0}.get</target>
<note>The name of a property getter like "public int MyProperty { get; }" where "{0}" is the property name</note>
</trans-unit>
<trans-unit id="Property_setter_name">
<source>{0}.set</source>
<target state="translated">{0}.set</target>
<note>The name of a property setter like "public int MyProperty { set; }" where "{0}" is the property name</note>
</trans-unit>
<trans-unit id="Make_Async_Function">
<source>Make Async Function</source>
<target state="translated">Rendre la fonction asynchrone</target>
<note />
</trans-unit>
<trans-unit id="Make_Async_Sub">
<source>Make Async Sub</source>
<target state="translated">Rendre le Sub asynchrone</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_Select_Case">
<source>Convert to 'Select Case'</source>
<target state="translated">Convertir en 'Select Case'</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_For_Each">
<source>Convert to 'For Each'</source>
<target state="translated">Convertir en 'For Each'</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_For">
<source>Convert to 'For'</source>
<target state="translated">Convertir en 'For'</target>
<note />
</trans-unit>
<trans-unit id="Invert_If">
<source>Invert If</source>
<target state="translated">Inverser If</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="fr" original="../VBFeaturesResources.resx">
<body>
<trans-unit id="Add_Await">
<source>Add Await</source>
<target state="translated">Ajouter Await</target>
<note />
</trans-unit>
<trans-unit id="Add_Await_and_ConfigureAwaitFalse">
<source>Add Await and 'ConfigureAwait(false)'</source>
<target state="translated">Ajouter Await et 'ConfigureAwait(false)'</target>
<note />
</trans-unit>
<trans-unit id="Add_Obsolete">
<source>Add <Obsolete></source>
<target state="translated">Ajouter <Obsolete></target>
<note />
</trans-unit>
<trans-unit id="Add_missing_Imports">
<source>Add missing Imports</source>
<target state="translated">Ajouter les Import manquants</target>
<note>{Locked="Import"}</note>
</trans-unit>
<trans-unit id="Add_Shadows">
<source>Add 'Shadows'</source>
<target state="translated">Ajouter 'Shadows'</target>
<note>{Locked="Shadows"} "Shadows" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Apply_Imports_directive_placement_preferences">
<source>Apply Imports directive placement preferences</source>
<target state="translated">Appliquer les préférences de placement de la directive Imports</target>
<note>{Locked="Import"} "Import" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Apply_Me_qualification_preferences">
<source>Apply Me qualification preferences</source>
<target state="translated">Appliquer les préférences de qualification pour Me</target>
<note>{Locked="Me"} "Me" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Change_to_DirectCast">
<source>Change to 'DirectCast'</source>
<target state="translated">Changer en 'DirectCast'</target>
<note />
</trans-unit>
<trans-unit id="Change_to_TryCast">
<source>Change to 'TryCast'</source>
<target state="translated">Changer en 'TryCast'</target>
<note />
</trans-unit>
<trans-unit id="Insert_0">
<source>Insert '{0}'.</source>
<target state="translated">Insérer '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Delete_the_0_statement1">
<source>Delete the '{0}' statement.</source>
<target state="translated">Supprimez l'instruction '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Create_event_0_in_1">
<source>Create event {0} in {1}</source>
<target state="translated">Créer un événement {0} dans {1}</target>
<note />
</trans-unit>
<trans-unit id="Insert_the_missing_End_Property_statement">
<source>Insert the missing 'End Property' statement.</source>
<target state="translated">Insérez l'instruction 'End Property' manquante.</target>
<note />
</trans-unit>
<trans-unit id="Insert_the_missing_0">
<source>Insert the missing '{0}'.</source>
<target state="translated">Insérez le '{0}' manquant.</target>
<note />
</trans-unit>
<trans-unit id="Inline_temporary_variable">
<source>Inline temporary variable</source>
<target state="translated">Variable temporaire inline</target>
<note />
</trans-unit>
<trans-unit id="Conflict_s_detected">
<source>Conflict(s) detected.</source>
<target state="translated">Conflit(s) détecté(s).</target>
<note />
</trans-unit>
<trans-unit id="Introduce_Using_statement">
<source>Introduce 'Using' statement</source>
<target state="translated">Introduire l'instruction 'Using'</target>
<note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Make_0_inheritable">
<source>Make '{0}' inheritable</source>
<target state="translated">Rendre '{0}' héritable</target>
<note />
</trans-unit>
<trans-unit id="Make_private_field_ReadOnly_when_possible">
<source>Make private field ReadOnly when possible</source>
<target state="translated">Rendre le champ privé ReadOnly quand cela est possible</target>
<note>{Locked="ReadOnly"} "ReadOnly" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Move_the_0_statement_to_line_1">
<source>Move the '{0}' statement to line {1}.</source>
<target state="translated">Déplacez l'instruction '{0}' à la ligne {1}.</target>
<note />
</trans-unit>
<trans-unit id="Delete_the_0_statement2">
<source>Delete the '{0}' statement.</source>
<target state="translated">Supprimez l'instruction '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Multiple_Types">
<source><Multiple Types></source>
<target state="translated"><Plusieurs types></target>
<note />
</trans-unit>
<trans-unit id="Organize_Imports">
<source>Organize Imports</source>
<target state="translated">Organiser les Imports</target>
<note>{Locked="Import"}</note>
</trans-unit>
<trans-unit id="Remove_shared_keyword_from_module_member">
<source>Remove 'Shared' keyword from Module member</source>
<target state="translated">Supprimer le mot clé 'Shared' du membre de module</target>
<note>{Locked="Shared"} "Shared" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Shared_constructor">
<source>Shared constructor</source>
<target state="translated">Constructeur partagé</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_new_field">
<source>Type a name here to declare a new field.</source>
<target state="translated">Tapez un nom ici pour déclarer un nouveau champ.</target>
<note />
</trans-unit>
<trans-unit id="Note_colon_Space_completion_is_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab">
<source>Note: Space completion is disabled to avoid potential interference. To insert a name from the list, use tab.</source>
<target state="translated">Remarque : la saisie semi-automatique à l'aide de l'espace est désactivée pour éviter toute interférence éventuelle. Pour insérer un nom de la liste, utilisez la touche Tab.</target>
<note />
</trans-unit>
<trans-unit id="_0_Events">
<source>({0} Events)</source>
<target state="translated">({0} événements)</target>
<note />
</trans-unit>
<trans-unit id="new_field">
<source><new field></source>
<target state="translated"><nouveau champ></target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_parameter_If_no_preceding_keyword_is_used_ByVal_will_be_assumed_and_the_argument_will_be_passed_by_value">
<source>Type a name here to declare a parameter. If no preceding keyword is used; 'ByVal' will be assumed and the argument will be passed by value.</source>
<target state="translated">Tapez un nom ici pour déclarer un paramètre. Si aucun mot clé ne précède, 'ByVal' est utilisé par défaut et l'argument est passé par valeur.</target>
<note />
</trans-unit>
<trans-unit id="parameter_name">
<source><parameter name></source>
<target state="translated"><nom de paramètre></target>
<note />
</trans-unit>
<trans-unit id="Type_a_new_name_for_the_column_followed_by_Otherwise_the_original_column_name_with_be_used">
<source>Type a new name for the column, followed by '='. Otherwise, the original column name with be used.</source>
<target state="translated">Tapez un nouveau nom pour la colonne, suivi de '='. Sinon, le nom de colonne d'origine sera utilisé.</target>
<note />
</trans-unit>
<trans-unit id="Note_colon_Use_tab_for_automatic_completion_space_completion_is_disabled_to_avoid_interfering_with_a_new_name">
<source>Note: Use tab for automatic completion; space completion is disabled to avoid interfering with a new name.</source>
<target state="translated">Remarque : utilisez la touche Tab pour effectuer une saisie semi-automatique ; la saisie semi-automatique à l'aide de l'espace est désactivée pour éviter toute interférence avec un nouveau nom.</target>
<note />
</trans-unit>
<trans-unit id="result_alias">
<source><result alias></source>
<target state="translated"><alias de résultat></target>
<note />
</trans-unit>
<trans-unit id="Type_a_new_variable_name">
<source>Type a new variable name</source>
<target state="translated">Tapez un nouveau nom de variable</target>
<note />
</trans-unit>
<trans-unit id="Note_colon_Space_and_completion_are_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab">
<source>Note: Space and '=' completion are disabled to avoid potential interference. To insert a name from the list, use tab.</source>
<target state="translated">Remarque : les saisies semi-automatiques à l'aide de l'espace et de '=' sont désactivées pour éviter toute interférence éventuelle. Pour insérer un nom de la liste, utilisez la touche Tab.</target>
<note />
</trans-unit>
<trans-unit id="new_resource">
<source><new resource></source>
<target state="translated"><nouvelle ressource></target>
<note />
</trans-unit>
<trans-unit id="AddHandler_statement">
<source>AddHandler statement</source>
<target state="translated">Instruction AddHandler</target>
<note />
</trans-unit>
<trans-unit id="RemoveHandler_statement">
<source>RemoveHandler statement</source>
<target state="translated">Instruction RemoveHandler</target>
<note />
</trans-unit>
<trans-unit id="_0_function">
<source>{0} function</source>
<target state="translated">Fonction {0}</target>
<note />
</trans-unit>
<trans-unit id="CType_function">
<source>CType function</source>
<target state="translated">Fonction CType</target>
<note />
</trans-unit>
<trans-unit id="DirectCast_function">
<source>DirectCast function</source>
<target state="translated">Fonction DirectCast</target>
<note />
</trans-unit>
<trans-unit id="TryCast_function">
<source>TryCast function</source>
<target state="translated">Fonction TryCast</target>
<note />
</trans-unit>
<trans-unit id="GetType_function">
<source>GetType function</source>
<target state="translated">Fonction GetType</target>
<note />
</trans-unit>
<trans-unit id="GetXmlNamespace_function">
<source>GetXmlNamespace function</source>
<target state="translated">Fonction GetXmlNamespace</target>
<note />
</trans-unit>
<trans-unit id="Mid_statement">
<source>Mid statement</source>
<target state="translated">Instruction Mid</target>
<note />
</trans-unit>
<trans-unit id="Fix_Incorrect_Function_Return_Type">
<source>Fix Incorrect Function Return Type</source>
<target state="translated">Corriger le type de retour de fonction incorrect</target>
<note />
</trans-unit>
<trans-unit id="Simplify_name_0">
<source>Simplify name '{0}'</source>
<target state="translated">Simplifier le nom '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Simplify_member_access_0">
<source>Simplify member access '{0}'</source>
<target state="translated">Simplifier l'accès au membre '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Remove_Me_qualification">
<source>Remove 'Me' qualification</source>
<target state="translated">Supprimer la qualification 'Me'</target>
<note>{Locked="Me"} "Me" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Name_can_be_simplified">
<source>Name can be simplified</source>
<target state="translated">Le nom peut être simplifié</target>
<note />
</trans-unit>
<trans-unit id="can_t_determine_valid_range_of_statements_to_extract_out">
<source>can't determine valid range of statements to extract out</source>
<target state="translated">impossible de déterminer la plage valide d'instructions à extraire</target>
<note />
</trans-unit>
<trans-unit id="Not_all_code_paths_return">
<source>Not all code paths return</source>
<target state="translated">Tous les chemins du code n'ont pas été retournés</target>
<note />
</trans-unit>
<trans-unit id="contains_invalid_selection">
<source>contains invalid selection</source>
<target state="translated">contient une sélection non valide</target>
<note />
</trans-unit>
<trans-unit id="the_selection_contains_syntactic_errors">
<source>the selection contains syntactic errors</source>
<target state="translated">la sélection contient des erreurs syntaxiques</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_t_be_crossed_over_preprocessors">
<source>Selection can't be crossed over preprocessors</source>
<target state="translated">La sélection ne peut pas traverser plusieurs préprocesseurs</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_t_contain_throw_without_enclosing_catch_block">
<source>Selection can't contain throw without enclosing catch block</source>
<target state="translated">La sélection ne peut pas contenir throw sans englober le bloc catch</target>
<note />
</trans-unit>
<trans-unit id="Selection_can_t_be_parts_of_constant_initializer_expression">
<source>Selection can't be parts of constant initializer expression</source>
<target state="translated">La sélection ne peut pas faire partie d'une expression d'initialiseur de constante</target>
<note />
</trans-unit>
<trans-unit id="Argument_used_for_ByRef_parameter_can_t_be_extracted_out">
<source>Argument used for ByRef parameter can't be extracted out</source>
<target state="translated">Impossible d'extraire l'argument utilisé pour le paramètre ByRef</target>
<note />
</trans-unit>
<trans-unit id="all_static_local_usages_defined_in_the_selection_must_be_included_in_the_selection">
<source>all static local usages defined in the selection must be included in the selection</source>
<target state="translated">toutes les utilisations locales statiques définies dans la sélection doivent être incluses dans la sélection</target>
<note />
</trans-unit>
<trans-unit id="Implicit_member_access_can_t_be_included_in_the_selection_without_containing_statement">
<source>Implicit member access can't be included in the selection without containing statement</source>
<target state="translated">Impossible d'inclure l'accès au membre dans la sélection sans instruction contenante</target>
<note />
</trans-unit>
<trans-unit id="Selection_must_be_part_of_executable_statements">
<source>Selection must be part of executable statements</source>
<target state="translated">La sélection doit faire partie d'instructions exécutables</target>
<note />
</trans-unit>
<trans-unit id="next_statement_control_variable_doesn_t_have_matching_declaration_statement">
<source>next statement control variable doesn't have matching declaration statement</source>
<target state="translated">la variable de contrôle de l'instruction Next ne possède pas d'instruction declaration correspondante</target>
<note />
</trans-unit>
<trans-unit id="Selection_doesn_t_contain_any_valid_node">
<source>Selection doesn't contain any valid node</source>
<target state="translated">La sélection ne contient aucun nœud valide</target>
<note />
</trans-unit>
<trans-unit id="no_valid_statement_range_to_extract_out">
<source>no valid statement range to extract out</source>
<target state="translated">Aucune plage d'instructions valides à extraire</target>
<note />
</trans-unit>
<trans-unit id="Invalid_selection">
<source>Invalid selection</source>
<target state="translated">Sélection non valide</target>
<note />
</trans-unit>
<trans-unit id="Deprecated">
<source>Deprecated</source>
<target state="translated">Déconseillé</target>
<note />
</trans-unit>
<trans-unit id="Extension">
<source>Extension</source>
<target state="translated">Extension</target>
<note />
</trans-unit>
<trans-unit id="Awaitable">
<source>Awaitable</source>
<target state="translated">Pouvant être attendu(e)</target>
<note />
</trans-unit>
<trans-unit id="Awaitable_Extension">
<source>Awaitable, Extension</source>
<target state="translated">Awaitable, Extension</target>
<note />
</trans-unit>
<trans-unit id="new_variable">
<source><new variable></source>
<target state="translated"><nouvelle variable></target>
<note />
</trans-unit>
<trans-unit id="Creates_a_delegate_procedure_instance_that_references_the_specified_procedure_AddressOf_procedureName">
<source>Creates a delegate procedure instance that references the specified procedure.
AddressOf <procedureName></source>
<target state="translated">Crée une instance de procédure de délégué qui référence la procédure spécifiée.
AddressOf <procedureName></target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_an_external_procedure_has_another_name_in_its_DLL">
<source>Indicates that an external procedure has another name in its DLL.</source>
<target state="translated">Indique qu'une procédure externe a un autre nom dans sa DLL.</target>
<note />
</trans-unit>
<trans-unit id="Performs_a_short_circuit_logical_conjunction_on_two_expressions_Returns_True_if_both_operands_evaluate_to_True_If_the_first_expression_evaluates_to_False_the_second_is_not_evaluated_result_expression1_AndAlso_expression2">
<source>Performs a short-circuit logical conjunction on two expressions. Returns True if both operands evaluate to True. If the first expression evaluates to False, the second is not evaluated.
<result> = <expression1> AndAlso <expression2></source>
<target state="translated">Effectue une conjonction logique de court-circuit sur deux expressions. Retourne True si les deux opérandes ont la valeur True. Si la première expression a la valeur False, la seconde n'est pas évaluée.
<result> = <expression1> AndAlso <expression2></target>
<note />
</trans-unit>
<trans-unit id="Performs_a_logical_conjunction_on_two_Boolean_expressions_or_a_bitwise_conjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_both_operands_evaluate_to_True_Both_expressions_are_always_evaluated_result_expression1_And_expression2">
<source>Performs a logical conjunction on two Boolean expressions, or a bitwise conjunction on two numeric expressions. For Boolean expressions, returns True if both operands evaluate to True. Both expressions are always evaluated.
<result> = <expression1> And <expression2></source>
<target state="translated">Effectue une conjonction logique sur deux expressions Boolean ou une conjonction d'opérations de bits sur deux expressions numériques. Pour les expressions Boolean, retourne True si les deux opérandes ont la valeur True. Les deux expressions sont toujours évaluées.
<result> = <expression1> And <expression2></target>
<note />
</trans-unit>
<trans-unit id="Used_in_a_Declare_statement_The_Ansi_modifier_specifies_that_Visual_Basic_should_marshal_all_strings_to_ANSI_values_and_should_look_up_the_procedure_without_modifying_its_name_during_the_search_If_no_character_set_is_specified_ANSI_is_the_default">
<source>Used in a Declare statement. The Ansi modifier specifies that Visual Basic should marshal all strings to ANSI values, and should look up the procedure without modifying its name during the search. If no character set is specified, ANSI is the default.</source>
<target state="translated">S'utilise dans une instruction Declare. Le modificateur Ansi spécifie que Visual Basic doit marshaler toutes les chaînes en valeurs ANSI et rechercher la procédure sans modifier son nom durant la recherche. Si aucun jeu de caractères n'est spécifié, ANSI est la valeur par défaut.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_data_type_in_a_declaration_statement">
<source>Specifies a data type in a declaration statement.</source>
<target state="translated">Spécifie un type de données dans une instruction declaration.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_assembly_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property">
<source>Specifies that an attribute at the beginning of a source file applies to the entire assembly. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</source>
<target state="translated">Spécifie qu'un attribut situé au début d'un fichier source s'applique à l'intégralité de l'assembly. Sinon, l'attribut s'applique uniquement à un élément de programmation individuel, par exemple une classe ou une propriété.</target>
<note />
</trans-unit>
<trans-unit id="Indicates_an_asynchronous_method_that_can_use_the_Await_operator">
<source>Indicates an asynchronous method that can use the Await operator.</source>
<target state="translated">Indique une méthode asynchrone pouvant utiliser l'opérateur Await.</target>
<note />
</trans-unit>
<trans-unit id="Used_in_a_Declare_statement_The_Auto_modifier_specifies_that_Visual_Basic_should_marshal_strings_according_to_NET_Framework_rules_and_should_determine_the_base_character_set_of_the_run_time_platform_and_possibly_modify_the_external_procedure_name_if_the_initial_search_fails">
<source>Used in a Declare statement. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules, and should determine the base character set of the run-time platform and possibly modify the external procedure name if the initial search fails.</source>
<target state="translated">S'utilise dans une instruction Declare. Le modificateur Auto spécifie que Visual Basic doit marshaler les chaînes selon les règles du .NET Framework, déterminer le jeu de caractères de base de la plateforme d'exécution et éventuellement modifier le nom de la procédure externe en cas d'échec de la recherche initiale.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_can_change_the_underlying_value_of_the_argument_in_the_calling_code">
<source>Specifies that an argument is passed in such a way that the called procedure can change the underlying value of the argument in the calling code.</source>
<target state="translated">Spécifie qu'un argument est passé de sorte que la procédure appelée peut modifier la valeur sous-jacente de l'argument dans le code appelant.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_or_property_cannot_change_the_underlying_value_of_the_argument_in_the_calling_code">
<source>Specifies that an argument is passed in such a way that the called procedure or property cannot change the underlying value of the argument in the calling code.</source>
<target state="translated">Spécifie qu'un argument est passé de sorte que la procédure ou propriété appelée ne peut pas modifier la valeur sous-jacente de l'argument dans le code appelant.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_class_and_introduces_the_definitions_of_the_variables_properties_and_methods_that_make_up_the_class">
<source>Declares the name of a class and introduces the definitions of the variables, properties, and methods that make up the class.</source>
<target state="translated">Déclare le nom d'une classe et introduit les définitions des variables, propriétés et méthodes qui constituent la classe.</target>
<note />
</trans-unit>
<trans-unit id="Generates_a_string_concatenation_of_two_expressions">
<source>Generates a string concatenation of two expressions.</source>
<target state="translated">Génère une concaténation de chaîne de deux expressions.</target>
<note />
</trans-unit>
<trans-unit id="Declares_and_defines_one_or_more_constants">
<source>Declares and defines one or more constants.</source>
<target state="translated">Déclare et définit une ou plusieurs constantes.</target>
<note />
</trans-unit>
<trans-unit id="Use_In_for_a_type_that_will_only_be_used_for_ByVal_arguments_to_functions">
<source>Use 'In' for a type that will only be used for ByVal arguments to functions.</source>
<target state="translated">Utilisez 'In' pour un type qui ne sera utilisé que pour les arguments ByVal transmis à des fonctions.</target>
<note />
</trans-unit>
<trans-unit id="Use_Out_for_a_type_that_will_only_be_used_as_a_return_from_functions">
<source>Use 'Out' for a type that will only be used as a return from functions.</source>
<target state="translated">Utilisez 'Out' pour un type qui ne sera utilisé que comme un retour de fonctions.</target>
<note />
</trans-unit>
<trans-unit id="Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type_object_structure_class_or_interface_CType_Object_As_Expression_Object_As_Type_As_Type">
<source>Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface.
CType(Object As Expression, Object As Type) As Type</source>
<target state="translated">Retourne le résultat d'une conversion explicite d'une expression en un type de données, objet, structure, classe ou interface spécifié.
CType(Object As Expression, Object As Type) As Type</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_event_has_additional_specialized_code_for_adding_handlers_removing_handlers_and_raising_events">
<source>Specifies that an event has additional, specialized code for adding handlers, removing handlers, and raising events.</source>
<target state="translated">Spécifie qu'un événement dispose d'un code spécialisé supplémentaire pour l'ajout de gestionnaires, la suppression de gestionnaires et le déclenchement d'événements.</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_reference_to_a_procedure_implemented_in_an_external_file">
<source>Declares a reference to a procedure implemented in an external file.</source>
<target state="translated">Déclare une référence à une procédure implémentée dans un fichier externe.</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_property_as_the_default_property_of_its_class_structure_or_interface">
<source>Identifies a property as the default property of its class, structure, or interface.</source>
<target state="translated">Identifie une propriété en tant que propriété par défaut de sa classe, structure ou interface.</target>
<note />
</trans-unit>
<trans-unit id="Used_to_declare_a_delegate_A_delegate_is_a_reference_type_that_refers_to_a_shared_method_of_a_type_or_to_an_instance_method_of_an_object_Any_procedure_that_is_convertible_or_that_has_matching_parameter_types_and_return_type_may_be_used_to_create_an_instance_of_this_delegate_class">
<source>Used to declare a delegate. A delegate is a reference type that refers to a shared method of a type or to an instance method of an object. Any procedure that is convertible, or that has matching parameter types and return type may be used to create an instance of this delegate class.</source>
<target state="translated">Permet de déclarer un délégué. Un délégué est un type référence qui fait référence à une méthode partagée d'un type ou à une méthode d'instance d'un objet. Toute procédure susceptible d'être convertie, ou ayant des types de paramètres et un type de retour correspondants, peut être utilisée pour créer une instance de cette classe déléguée.</target>
<note />
</trans-unit>
<trans-unit id="Declares_and_allocates_storage_space_for_one_or_more_variables_Dim_var_bracket_As_bracket_New_bracket_dataType_bracket_boundList_bracket_bracket_bracket_initializer_bracket_bracket_var2_bracket">
<source>Declares and allocates storage space for one or more variables.
Dim {<var> [As [New] dataType [(boundList)]][= initializer]}[, var2]</source>
<target state="translated">Déclare et alloue de l'espace de stockage pour une ou plusieurs variables.
Dim {<var> [As [New] dataType [(boundList)]][= initializer]}[, var2]</target>
<note />
</trans-unit>
<trans-unit id="Divides_two_numbers_and_returns_a_floating_point_result">
<source>Divides two numbers and returns a floating-point result.</source>
<target state="translated">Effectue la division de deux nombres et retourne un résultat à virgule flottante.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_0_block">
<source>Terminates a {0} block.</source>
<target state="translated">Termine un bloc {0}.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_an_0_block">
<source>Terminates an {0} block.</source>
<target state="translated">Termine un bloc {0}.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_the_definition_of_a_0_statement">
<source>Terminates the definition of a {0} statement.</source>
<target state="translated">Termine la définition d'une instruction {0}.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_the_definition_of_an_0_statement">
<source>Terminates the definition of an {0} statement.</source>
<target state="translated">Termine la définition d'une instruction {0}.</target>
<note />
</trans-unit>
<trans-unit id="Declares_an_enumeration_and_defines_the_values_of_its_members">
<source>Declares an enumeration and defines the values of its members.</source>
<target state="translated">Déclare une énumération et définit les valeurs de ses membres.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_they_are_equal_Otherwise_returns_False">
<source>Compares two expressions and returns True if they are equal. Otherwise, returns False.</source>
<target state="translated">Compare deux expressions et retourne la valeur True si elles sont égales. Sinon, retourne la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Used_to_release_array_variables_and_deallocate_the_memory_used_for_their_elements">
<source>Used to release array variables and deallocate the memory used for their elements.</source>
<target state="translated">Sert à libérer des variables tableau ainsi que la mémoire utilisée pour leurs éléments.</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_user_defined_event">
<source>Declares a user-defined event.</source>
<target state="translated">Déclare un événement défini par l'utilisateur.</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Sub_procedure_and_transfers_execution_immediately_to_the_statement_following_the_call_to_the_Sub_procedure">
<source>Exits a Sub procedure and transfers execution immediately to the statement following the call to the Sub procedure.</source>
<target state="translated">Quitte une procédure Sub et transfère immédiatement l'exécution à l'instruction qui suit l'appel de la procédure Sub.</target>
<note />
</trans-unit>
<trans-unit id="Raises_a_number_to_the_power_of_another_number">
<source>Raises a number to the power of another number.</source>
<target state="translated">Élève un nombre à la puissance d'un autre nombre.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Function">
<source>Specifies that the external procedure being referenced in the Declare statement is a Function.</source>
<target state="translated">Spécifie que la procédure externe référencée dans l'instruction Declare est une procédure Function.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Sub">
<source>Specifies that the external procedure being referenced in the Declare statement is a Sub.</source>
<target state="translated">Spécifie que la procédure externe référencée dans l'instruction Declare est une procédure Sub.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_the_assembly_that_contains_their_declaration">
<source>Specifies that one or more declared programming elements are accessible only from within the assembly that contains their declaration.</source>
<target state="translated">Spécifie qu'un ou plusieurs éléments de programmation déclarés sont accessibles uniquement à partir de l'assembly qui contient leur déclaration.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_collection_and_a_range_variable_to_use_in_a_query">
<source>Specifies a collection and a range variable to use in a query.</source>
<target state="translated">Spécifie une collection et une variable de plage à utiliser dans une requête.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code">
<source>Declares the name, parameters, and code that define a Function procedure, that is, a procedure that returns a value to the calling code.</source>
<target state="translated">Déclare le nom, les paramètres et le code qui définissent une procédure Function, en d'autres termes, une procédure qui retourne une valeur au code appelant.</target>
<note />
</trans-unit>
<trans-unit id="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_reference_type">
<source>Constrains a generic type parameter to require that any type argument passed to it be a reference type.</source>
<target state="translated">Contraint un paramètre de type générique à exiger que tout argument de type soit passé en tant que type référence.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_constructor_constraint_on_a_generic_type_parameter">
<source>Specifies a constructor constraint on a generic type parameter.</source>
<target state="translated">Spécifie une contrainte de constructeur sur un paramètre de type générique.</target>
<note />
</trans-unit>
<trans-unit id="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_value_type">
<source>Constrains a generic type parameter to require that any type argument passed to it be a value type.</source>
<target state="translated">Contraint un paramètre de type générique à exiger que tout argument de type soit passé en tant que type valeur.</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_Get_property_procedure_that_is_used_to_return_the_current_value_of_a_property">
<source>Declares a Get property procedure that is used to return the current value of a property.</source>
<target state="translated">Déclare une procédure de propriété Get qui sert à retourner la valeur actuelle d'une propriété.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is greater than the second. Otherwise, returns False.</source>
<target state="translated">Compare deux expressions et retourne la valeur True si la première expression est supérieure à la seconde. Sinon, retourne la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_or_equal_to_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is greater than or equal to the second. Otherwise, returns False.</source>
<target state="translated">Compare deux expressions et retourne la valeur True si la première expression est supérieure ou égale à la seconde. Sinon, retourne la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Declares_that_a_procedure_handles_a_specified_event">
<source>Declares that a procedure handles a specified event.</source>
<target state="translated">Déclare qu'une procédure gère un événement spécifié.</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_class_or_structure_member_is_providing_the_implementation_for_a_member_defined_in_an_interface">
<source>Indicates that a class or structure member is providing the implementation for a member defined in an interface.</source>
<target state="translated">Indique qu'un membre de classe ou de structure fournit l'implémentation d'un membre défini dans une interface.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_one_or_more_interfaces_or_interface_members_that_must_be_implemented_in_the_class_or_structure_definition_in_which_the_Implements_statement_appears">
<source>Specifies one or more interfaces, or interface members, that must be implemented in the class or structure definition in which the Implements statement appears.</source>
<target state="translated">Spécifie une ou plusieurs interfaces, ou un ou plusieurs membres d'interface, à implémenter dans la définition de classe ou de structure qui contient l'instruction Implements.</target>
<note />
</trans-unit>
<trans-unit id="Imports_all_or_specified_elements_of_a_namespace_into_a_file">
<source>Imports all or specified elements of a namespace into a file.</source>
<target state="translated">Importe une partie spécifique ou l'ensemble des éléments d'un espace de noms dans un fichier.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_group_that_the_loop_variable_in_a_For_Each_statement_is_to_traverse">
<source>Specifies the group that the loop variable in a For Each statement is to traverse.</source>
<target state="translated">Spécifie le groupe que la variable de boucle doit parcourir dans une instruction For Each.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_group_that_the_loop_variable_is_to_traverse_in_a_For_Each_statement_or_specifies_the_range_variable_in_a_query">
<source>Specifies the group that the loop variable is to traverse in a For Each statement, or specifies the range variable in a query.</source>
<target state="translated">Spécifie le groupe que la variable de boucle doit parcourir dans une instruction For Each, ou spécifie la variable de plage dans une requête.</target>
<note />
</trans-unit>
<trans-unit id="Causes_the_current_class_or_interface_to_inherit_the_attributes_variables_properties_procedures_and_events_from_another_class_or_set_of_interfaces">
<source>Causes the current class or interface to inherit the attributes, variables, properties, procedures, and events from another class or set of interfaces.</source>
<target state="translated">Oblige la classe ou l'interface actuelle à hériter des attributs, variables, propriétés, procédures et événements d'une autre classe ou d'un autre ensemble d'interfaces.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_group_that_the_range_variable_is_to_traverse_in_a_query">
<source>Specifies the group that the range variable is to traverse in a query.</source>
<target state="translated">Spécifie le groupe que la variable de plage doit parcourir dans une requête.</target>
<note />
</trans-unit>
<trans-unit id="Divides_two_numbers_and_returns_an_integer_result">
<source>Divides two numbers and returns an integer result.</source>
<target state="translated">Effectue la division de deux nombres et retourne un résultat sous forme d'entier.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_an_interface_and_the_definitions_of_the_members_of_the_interface">
<source>Declares the name of an interface and the definitions of the members of the interface.</source>
<target state="translated">Déclare le nom d'une interface et les définitions des membres de l'interface.</target>
<note />
</trans-unit>
<trans-unit id="Determines_whether_an_expression_is_false_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsFalse_on_that_class_or_structure">
<source>Determines whether an expression is false. If instances of any class or structure will be used in an OrElse clause, you must define IsFalse on that class or structure.</source>
<target state="translated">Détermine si une expression a la valeur False. Si les instances d'une classe ou d'une structure sont utilisées dans une clause OrElse, vous devez définir IsFalse dans cette classe ou structure.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_equal_result_object1_Is_object2">
<source>Compares two object reference variables and returns True if the objects are equal.
<result> = <object1> Is <object2></source>
<target state="translated">Compare deux variables de référence d'objet et retourne True si les objets sont équivalents.
<result> = <object1> Is <object2></target>
<note />
</trans-unit>
<trans-unit id="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_not_equal_result_object1_IsNot_object2">
<source>Compares two object reference variables and returns True if the objects are not equal.
<result> = <object1> IsNot <object2></source>
<target state="translated">Compare deux variables de référence d'objet et retourne True si les objets ne sont pas équivalents.
<result> = <object1> IsNot <object2></target>
<note />
</trans-unit>
<trans-unit id="Determines_whether_an_expression_is_true_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsTrue_on_that_class_or_structure">
<source>Determines whether an expression is true. If instances of any class or structure will be used in an OrElse clause, you must define IsTrue on that class or structure.</source>
<target state="translated">Détermine si une expression a la valeur True. Si les instances d'une classe ou d'une structure sont utilisées dans une clause OrElse, vous devez définir IsTrue dans cette classe ou structure.</target>
<note />
</trans-unit>
<trans-unit id="Indicates_an_iterator_method_that_can_use_the_Yield_statement">
<source>Indicates an iterator method that can use the Yield statement.</source>
<target state="translated">Indique une méthode Iterator pouvant utiliser l'instruction Yield.</target>
<note />
</trans-unit>
<trans-unit id="Defines_an_iterator_lambda_expression_that_can_use_the_Yield_statement_Iterator_Function_parameterList_As_IEnumerable_Of_T">
<source>Defines an iterator lambda expression that can use the Yield statement.
Iterator Function(<parameterList>) As IEnumerable(Of <T>)</source>
<target state="translated">Définit une expression lambda Iterator pouvant utiliser l'instruction Yield.
Iterator Function(<parameterList>) As IEnumerable(Of <T>)</target>
<note />
</trans-unit>
<trans-unit id="Performs_an_arithmetic_left_shift_on_a_bit_pattern">
<source>Performs an arithmetic left shift on a bit pattern.</source>
<target state="translated">Effectue un décalage arithmétique vers la gauche au niveau du bit.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is less than the second. Otherwise, returns False.</source>
<target state="translated">Compare deux expressions et retourne la valeur True si la première expression est inférieure à la seconde. Sinon, retourne la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_or_equal_to_the_second_Otherwise_returns_False">
<source>Compares two expressions and returns True if the first is less than or equal to the second. Otherwise, returns False.</source>
<target state="translated">Compare deux expressions et retourne la valeur True si la première expression est inférieure ou égale à la seconde. Sinon, retourne la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_clause_that_identifies_the_external_file_DLL_or_code_resource_containing_an_external_procedure">
<source>Introduces a clause that identifies the external file (DLL or code resource) containing an external procedure.</source>
<target state="translated">Introduit une clause qui identifie le fichier externe (DLL ou ressource de code) contenant une procédure externe.</target>
<note />
</trans-unit>
<trans-unit id="Compares_a_string_against_a_pattern_Wildcards_available_include_to_match_1_character_and_to_match_0_or_more_characters_result_string_Like_pattern">
<source>Compares a string against a pattern. Wildcards available include ? to match 1 character and * to match 0 or more characters.
<result> = <string> Like <pattern></source>
<target state="translated">Compare une chaîne à un modèle. Les caractères génériques disponibles sont ? pour correspondre à 1 caractère et * pour correspondre à 0 ou plusieurs caractères.
<result> = <string> Like <pattern></target>
<note />
</trans-unit>
<trans-unit id="Returns_the_difference_between_two_numeric_expressions_or_the_negative_value_of_a_numeric_expression">
<source>Returns the difference between two numeric expressions, or the negative value of a numeric expression.</source>
<target state="translated">Retourne la différence entre deux expressions numériques, ou la valeur négative d'une expression numérique.</target>
<note />
</trans-unit>
<trans-unit id="Divides_two_numbers_and_returns_only_the_remainder_number1_Mod_number2">
<source>Divides two numbers and returns only the remainder.
<number1> Mod <number2></source>
<target state="translated">Divise deux nombres et retourne uniquement le reste.
<nombre1> Mod <nombre2></target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_module_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property">
<source>Specifies that an attribute at the beginning of a source file applies to the entire module. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</source>
<target state="translated">Spécifie qu'un attribut situé au début d'un fichier source s'applique à l'intégralité du module. Sinon, l'attribut s'applique uniquement à un élément de programmation individuel, par exemple une classe ou une propriété.</target>
<note />
</trans-unit>
<trans-unit id="Multiplies_two_numbers_and_returns_the_product">
<source>Multiplies two numbers and returns the product.</source>
<target state="translated">Multiplie deux nombres et retourne le produit.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_class_can_be_used_only_as_a_base_class_and_that_you_cannot_create_an_object_directly_from_it">
<source>Specifies that a class can be used only as a base class, and that you cannot create an object directly from it.</source>
<target state="translated">Spécifie qu'une classe ne peut être utilisée que comme classe de base, et que vous ne pouvez pas créer d'objet directement à partir de celle-ci.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_is_not_implemented_in_the_class_and_must_be_overridden_in_a_derived_class_before_it_can_be_used">
<source>Specifies that a property or procedure is not implemented in the class and must be overridden in a derived class before it can be used.</source>
<target state="translated">Spécifie qu'une propriété ou procédure n'est pas implémentée dans la classe et qu'elle doit être substituée dans une classe dérivée pour pouvoir être utilisée.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_namespace_and_causes_the_source_code_following_the_declaration_to_be_compiled_within_that_namespace">
<source>Declares the name of a namespace, and causes the source code following the declaration to be compiled within that namespace.</source>
<target state="translated">Déclare le nom d'un espace de noms et oblige le code source qui suit la déclaration à être compilé dans cet espace de noms.</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_might_not_be_able_to_hold_some_of_the_possible_values_of_the_original_class_or_structure">
<source>Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure.</source>
<target state="translated">Indique qu'un opérateur de conversion (CType) convertit une classe ou une structure en un type susceptible de ne pas pouvoir contenir certaines des valeurs possibles de la classe ou structure d'origine.</target>
<note />
</trans-unit>
<trans-unit id="Compares_two_expressions_and_returns_True_if_they_are_not_equal_Otherwise_returns_False">
<source>Compares two expressions and returns True if they are not equal. Otherwise, returns False.</source>
<target state="translated">Compare deux expressions et retourne la valeur True si elles ne sont pas égales. Sinon, retourne la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_class_cannot_be_used_as_a_base_class">
<source>Specifies that a class cannot be used as a base class.</source>
<target state="translated">Spécifie qu'une classe ne peut pas être utilisée en tant que classe de base.</target>
<note />
</trans-unit>
<trans-unit id="Performs_logical_negation_on_a_Boolean_expression_or_bitwise_negation_on_a_numeric_expression_result_Not_expression">
<source>Performs logical negation on a Boolean expression, or bitwise negation on a numeric expression.
<result> = Not <expression></source>
<target state="translated">Effectue une négation logique sur une expression Boolean ou une négation d'opération de bits sur une expression numérique.
<result> = Not <expression></target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_cannot_be_overridden_in_a_derived_class">
<source>Specifies that a property or procedure cannot be overridden in a derived class.</source>
<target state="translated">Spécifie qu'une propriété ou procédure ne peut pas être substituée dans une classe dérivée.</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_type_parameter_on_a_generic_class_structure_interface_delegate_or_procedure">
<source>Identifies a type parameter on a generic class, structure, interface, delegate, or procedure.</source>
<target state="translated">Identifie un paramètre de type dans une classe, une structure, une interface, un délégué ou une procédure générique.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_operator_symbol_operands_and_code_that_define_an_operator_procedure_on_a_class_or_structure">
<source>Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.</source>
<target state="translated">Déclare le symbole, les opérandes et le code qui définissent une procédure d'opérateur dans une classe ou une structure.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_procedure_argument_can_be_omitted_when_the_procedure_is_called">
<source>Specifies that a procedure argument can be omitted when the procedure is called.</source>
<target state="translated">Spécifie qu'un argument de procédure peut être omis lorsque la procédure est appelée.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_that_specifies_a_compiler_option_that_applies_to_the_entire_source_file">
<source>Introduces a statement that specifies a compiler option that applies to the entire source file.</source>
<target state="translated">Introduit une instruction qui spécifie une option du compilateur s'appliquant à l'intégralité du fichier source.</target>
<note />
</trans-unit>
<trans-unit id="Performs_short_circuit_inclusive_logical_disjunction_on_two_expressions_Returns_True_if_either_operand_evaluates_to_True_If_the_first_expression_evaluates_to_True_the_second_expression_is_not_evaluated_result_expression1_OrElse_expression2">
<source>Performs short-circuit inclusive logical disjunction on two expressions. Returns True if either operand evaluates to True. If the first expression evaluates to True, the second expression is not evaluated.
<result> = <expression1> OrElse <expression2></source>
<target state="translated">Effectue une disjonction logique inclusive de court-circuit sur deux expressions. Retourne True si l'un des opérandes a la valeur True. Si la première expression a la valeur True, la seconde expression n'est pas évaluée.
<result> = <expression1> OrElse <expression2></target>
<note />
</trans-unit>
<trans-unit id="Performs_an_inclusive_logical_disjunction_on_two_Boolean_expressions_or_a_bitwise_disjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_at_least_one_operand_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Or_expression2">
<source>Performs an inclusive logical disjunction on two Boolean expressions, or a bitwise disjunction on two numeric expressions. For Boolean expressions, returns True if at least one operand evaluates to True. Both expressions are always evaluated.
<result> = <expression1> Or <expression2></source>
<target state="translated">Effectue une disjonction logique inclusive sur deux expressions Boolean ou une disjonction d'opérations de bits sur deux expressions numériques. Pour les expressions Boolean, retourne True si au moins un opérande a la valeur True. Les deux expressions sont toujours évaluées.
<result> = <expression1> Or <expression2></target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_re_declares_one_or_more_existing_properties_or_procedures_with_the_same_name">
<source>Specifies that a property or procedure re-declares one or more existing properties or procedures with the same name.</source>
<target state="translated">Spécifie qu'une propriété ou procédure redéclare une ou plusieurs propriétés ou procédures existantes avec le même nom.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_can_be_overridden_by_an_identically_named_property_or_procedure_in_a_derived_class">
<source>Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.</source>
<target state="translated">Spécifie qu'une propriété ou procédure peut être substituée par une propriété ou procédure ayant un nom identique dans une classe dérivée.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_or_procedure_overrides_an_identically_named_property_or_procedure_inherited_from_a_base_class">
<source>Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class.</source>
<target state="translated">Spécifie qu'une propriété ou procédure substitue une propriété ou procédure ayant un nom identique et ayant été héritée d'une classe de base.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_procedure_parameter_takes_an_optional_array_of_elements_of_the_specified_type">
<source>Specifies that a procedure parameter takes an optional array of elements of the specified type.</source>
<target state="translated">Spécifie qu'un paramètre de procédure accepte un tableau d'éléments facultatif du type spécifié.</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_method_class_or_structure_declaration_is_a_partial_definition_of_the_method_class_or_structure">
<source>Indicates that a method, class, or structure declaration is a partial definition of the method, class, or structure.</source>
<target state="translated">Indique qu'une déclaration de méthode, de classe ou de structure est une définition partielle de la méthode, de la classe ou de la structure.</target>
<note />
</trans-unit>
<trans-unit id="Returns_the_sum_of_two_numbers_or_the_positive_value_of_a_numeric_expression">
<source>Returns the sum of two numbers, or the positive value of a numeric expression.</source>
<target state="translated">Retourne la somme de deux nombres, ou la valeur positive d'une expression numérique.</target>
<note />
</trans-unit>
<trans-unit id="Prevents_the_contents_of_an_array_from_being_cleared_when_the_dimensions_of_the_array_are_changed">
<source>Prevents the contents of an array from being cleared when the dimensions of the array are changed.</source>
<target state="translated">Empêche le contenu d'un tableau d'être effacé lorsque les dimensions de ce dernier changent.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_module_class_or_structure">
<source>Specifies that one or more declared programming elements are accessible only from within their module, class, or structure.</source>
<target state="translated">Spécifie qu'un ou plusieurs éléments de programmation déclarés sont accessibles uniquement à partir de leur module, classe ou structure.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_property_and_the_property_procedures_used_to_store_and_retrieve_the_value_of_the_property">
<source>Declares the name of a property, and the property procedures used to store and retrieve the value of the property.</source>
<target state="translated">Déclare le nom d'une propriété, ainsi que les procédures de propriété utilisées pour stocker et récupérer la valeur de la propriété.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_members_of_a_class_are_accessible_from_anywhere_in_the_same_assembly_their_own_classes_and_derived_classes">
<source>Specifies that one or more declared members of a class are accessible from anywhere in the same assembly, their own classes, and derived classes.</source>
<target state="translated">Spécifie qu'un ou plusieurs membres déclarés d'une classe sont accessibles à partir de n'importe quel emplacement dans le même assembly, leurs propres classes et les classes dérivées.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_own_class_or_from_a_derived_class">
<source>Specifies that one or more declared programming elements are accessible only from within their own class or from a derived class.</source>
<target state="translated">Spécifie qu'un ou plusieurs éléments de programmation déclarés sont accessibles uniquement à partir de leur propre classe ou d'une classe dérivée.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_have_no_access_restrictions">
<source>Specifies that one or more declared programming elements have no access restrictions.</source>
<target state="translated">Spécifie qu'un ou plusieurs éléments de programmation déclarés n'ont pas de restrictions d'accès.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_variable_or_property_can_be_read_but_not_written_to">
<source>Specifies that a variable or property can be read but not written to.</source>
<target state="translated">Spécifie qu'une variable ou une propriété peut être accessible en lecture mais pas en écriture.</target>
<note />
</trans-unit>
<trans-unit id="Reallocates_storage_space_for_an_array_variable">
<source>Reallocates storage space for an array variable.</source>
<target state="translated">Réalloue l'espace de stockage d'une variable tableau.</target>
<note />
</trans-unit>
<trans-unit id="Performs_an_arithmetic_right_shift_on_a_bit_pattern">
<source>Performs an arithmetic right shift on a bit pattern</source>
<target state="translated">Effectue un décalage arithmétique vers la droite au niveau du bit</target>
<note />
</trans-unit>
<trans-unit id="Declares_a_Set_property_procedure_that_is_used_to_assign_a_value_to_a_property">
<source>Declares a Set property procedure that is used to assign a value to a property.</source>
<target state="translated">Déclare une procédure de propriété Set qui sert à assigner une valeur à une propriété.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_declared_programming_element_redeclares_and_hides_an_identically_named_element_in_a_base_class">
<source>Specifies that a declared programming element redeclares and hides an identically named element in a base class.</source>
<target state="translated">Spécifie qu'un élément de programmation déclaré redéclare et masque un élément ayant un nom identique dans une classe de base.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_programming_elements_are_associated_with_all_instances_of_a_class_or_structure">
<source>Specifies that one or more declared programming elements are associated with all instances of a class or structure.</source>
<target state="translated">Spécifie qu'un ou plusieurs éléments de programmation déclarés sont associés à toutes les instances d'une classe ou d'une structure.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_local_variables_are_to_remain_in_existence_and_retain_their_latest_values_after_the_procedure_in_which_they_are_declared_terminates">
<source>Specifies that one or more declared local variables are to remain in existence and retain their latest values after the procedure in which they are declared terminates.</source>
<target state="translated">Spécifie qu'une ou plusieurs variables locales déclarées doivent continuer à exister et conserver leurs toutes dernières valeurs, une fois terminée la procédure dans laquelle elles sont déclarées.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_of_a_structure_and_introduces_the_definition_of_the_variables_properties_events_and_procedures_that_make_up_the_structure">
<source>Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that make up the structure.</source>
<target state="translated">Déclare le nom d'une structure et introduit la définition des variables, propriétés, événements et procédures qui constituent la structure.</target>
<note />
</trans-unit>
<trans-unit id="Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code">
<source>Declares the name, parameters, and code that define a Sub procedure, that is, a procedure that does not return a value to the calling code.</source>
<target state="translated">Déclare le nom, les paramètres et le code qui définissent une procédure Sub, en d'autres termes, une procédure qui ne retourne pas de valeur au code appelant.</target>
<note />
</trans-unit>
<trans-unit id="Separates_the_beginning_and_ending_values_of_a_loop_counter_or_array_bounds_or_that_of_a_value_match_range">
<source>Separates the beginning and ending values of a loop counter or array bounds or that of a value match range.</source>
<target state="translated">Sépare les valeurs de début et de fin d'un compteur de boucles, de limites d'index de tableau ou d'une plage de correspondance de valeurs.</target>
<note />
</trans-unit>
<trans-unit id="Determines_the_run_time_type_of_an_object_reference_variable_and_compares_it_to_a_data_type_Returns_True_or_False_depending_on_whether_the_two_types_are_compatible_result_TypeOf_objectExpression_Is_typeName">
<source>Determines the run-time type of an object reference variable and compares it to a data type. Returns True or False depending, on whether the two types are compatible.
<result> = TypeOf <objectExpression> Is <typeName></source>
<target state="translated">Détermine le type au moment de l'exécution d'une variable de référence d'objet et le compare à un type de données. Retourne True ou False selon que les deux types sont compatibles ou non.
<result> = TypeOf <objectExpression> Is <typeName></target>
<note />
</trans-unit>
<trans-unit id="Used_in_a_Declare_statement_Specifies_that_Visual_Basic_should_marshal_all_strings_to_Unicode_values_in_a_call_into_an_external_procedure_and_should_look_up_the_procedure_without_modifying_its_name">
<source>Used in a Declare statement. Specifies that Visual Basic should marshal all strings to Unicode values in a call into an external procedure, and should look up the procedure without modifying its name.</source>
<target state="translated">Utilisé dans une instruction Declare. Spécifie que Visual Basic doit marshaler toutes les chaînes en valeurs Unicode lors d'un appel d'une procédure externe, et qu'il doit rechercher la procédure sans modifier son nom.</target>
<note />
</trans-unit>
<trans-unit id="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_can_hold_all_possible_values_of_the_original_class_or_structure">
<source>Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure.</source>
<target state="translated">Indique qu'un opérateur de conversion (CType) convertit une classe ou une structure en un type qui peut contenir toutes les valeurs possibles de la classe ou structure d'origine.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_one_or_more_declared_member_variables_refer_to_an_instance_of_a_class_that_can_raise_events">
<source>Specifies that one or more declared member variables refer to an instance of a class that can raise events</source>
<target state="translated">Spécifie qu'une ou plusieurs variables membres déclarées font référence à une instance d'une classe qui peut déclencher des événements</target>
<note />
</trans-unit>
<trans-unit id="Specifies_that_a_property_can_be_written_to_but_not_read">
<source>Specifies that a property can be written to but not read.</source>
<target state="translated">Spécifie qu'une propriété peut être accessible en écriture mais pas en lecture.</target>
<note />
</trans-unit>
<trans-unit id="Performs_a_logical_exclusion_on_two_Boolean_expressions_or_a_bitwise_exclusion_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_exactly_one_of_the_expressions_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Xor_expression2">
<source>Performs a logical exclusion on two Boolean expressions, or a bitwise exclusion on two numeric expressions. For Boolean expressions, returns True if exactly one of the expressions evaluates to True. Both expressions are always evaluated.
<result> = <expression1> Xor <expression2></source>
<target state="translated">Effectue une exclusion logique sur deux expressions Boolean ou une exclusion d'opérations de bits sur deux expressions numériques. Pour les expressions Boolean, retourne True si une seule des expressions a la valeur True. Les deux expressions sont toujours évaluées.
<result> = <expression1> Xor <expression2></target>
<note />
</trans-unit>
<trans-unit id="Applies_an_aggregation_function_such_as_Sum_Average_or_Count_to_a_sequence">
<source>Applies an aggregation function, such as Sum, Average, or Count to a sequence.</source>
<target state="translated">Applique une fonction d'agrégation, par exemple Sum, Average ou Count, à une séquence.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_smallest_element_will_appear_first">
<source>Specifies the sort order for an Order By clause in a query. The smallest element will appear first.</source>
<target state="translated">Spécifie l'ordre de tri d'une clause Order By dans une requête. Le plus petit élément apparaît en premier.</target>
<note />
</trans-unit>
<trans-unit id="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_strict_binary_sort_order">
<source>Sets the string comparison method specified in Option Compare to a strict binary sort order.</source>
<target state="translated">Définit la méthode de comparaison de chaînes spécifiée dans Option Compare selon un ordre de tri binaire strict.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_element_keys_used_for_grouping_in_Group_By_or_sort_order_in_Order_By">
<source>Specifies the element keys used for grouping (in Group By) or sort order (in Order By).</source>
<target state="translated">Spécifie les clés d'éléments utilisées pour le regroupement (dans Group By) ou l'ordre de tri (dans Order By).</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_to_a_Function_Sub_or_dynamic_link_library_DLL_procedure_bracket_Call_bracket_procedureName_bracket_argumentList_bracket">
<source>Transfers execution to a Function, Sub, or dynamic-link library (DLL) procedure.
[Call] <procedureName> [(<argumentList>)]</source>
<target state="translated">Transfère l'exécution vers une procédure Function, Sub ou de bibliothèque de liens dynamiques (DLL).
[Call] <procedureName> [(<argumentList>)]</target>
<note />
</trans-unit>
<trans-unit id="Introduces_the_statements_to_run_if_none_of_the_previous_cases_in_the_Select_Case_statement_returns_True">
<source>Introduces the statements to run if none of the previous cases in the Select Case statement returns True.</source>
<target state="translated">Introduit les instructions à exécuter si aucun des cas précédents de l'instruction Select Case ne retourne la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Followed_by_a_comparison_operator_and_then_an_expression_Case_Is_introduces_the_statements_to_run_if_the_Select_Case_expression_combined_with_the_Case_Is_expression_evaluates_to_True">
<source>Followed by a comparison operator and then an expression, Case Is introduces the statements to run if the Select Case expression combined with the Case Is expression evaluates to True.</source>
<target state="translated">Suivi d'un opérateur de comparaison et d'une expression, Case Is introduit les instructions à exécuter si l'expression Select Case combinée avec l'expression Case Is a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_value_or_set_of_values_against_which_the_value_of_an_expression_in_a_Select_Case_statement_is_to_be_tested_Case_expression_expression1_To_expression2_bracket_Is_bracket_comparisonOperator_expression">
<source>Introduces a value, or set of values, against which the value of an expression in a Select Case statement is to be tested.
Case {<expression>|<expression1> To <expression2>|[Is] <comparisonOperator> <expression>}</source>
<target state="translated">Introduit une valeur ou un ensemble de valeurs à tester par rapport à la valeur d'une expression dans une instruction Select Case.
Case {<expression>|<expression1> To <expression2>|[Is] <comparisonOperator> <expression>}</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_block_to_be_run_if_the_specified_exception_occurs_inside_a_Try_block">
<source>Introduces a statement block to be run if the specified exception occurs inside a Try block.</source>
<target state="translated">Introduit un bloc d'instructions à exécuter si l'exception spécifiée se produit à l'intérieur d'un bloc Try.</target>
<note />
</trans-unit>
<trans-unit id="Sets_the_default_comparison_method_to_use_when_comparing_string_data_When_set_to_Text_uses_a_text_sort_order_that_is_not_case_sensitive_When_set_to_Binary_uses_a_strict_binary_sort_order_Option_Compare_Binary_Text">
<source>Sets the default comparison method to use when comparing string data. When set to Text, uses a text sort order that is not case sensitive. When set to Binary, uses a strict binary sort order.
Option Compare {Binary | Text}</source>
<target state="translated">Définit la méthode de comparaison par défaut à utiliser pour comparer des données de type chaîne. Lorsqu'il a la valeur Text, il utilise un ordre de tri alphabétique sans respect de la casse. Lorsqu'il a la valeur Binary, il utilise un ordre de tri binaire strict.
Option Compare {Binary | Text}</target>
<note />
</trans-unit>
<trans-unit id="Defines_a_conditional_compiler_constant_Conditional_compiler_constants_are_always_private_to_the_file_in_which_they_appear_The_expressions_used_to_initialize_them_can_contain_only_conditional_compiler_constants_and_literals">
<source>Defines a conditional compiler constant. Conditional compiler constants are always private to the file in which they appear. The expressions used to initialize them can contain only conditional compiler constants and literals.</source>
<target state="translated">Définit une constante de compilation conditionnelle. Les constantes de compilation conditionnelle sont toujours privées pour le fichier dans lequel elles figurent. Les expressions servant à les initialiser ne peuvent contenir que des littéraux et des constantes de compilation conditionnelle.</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_Do_loop">
<source>Transfers execution immediately to the next iteration of the Do loop.</source>
<target state="translated">Transfère immédiatement l'exécution à la prochaine itération de la boucle Do.</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_For_loop">
<source>Transfers execution immediately to the next iteration of the For loop.</source>
<target state="translated">Transfère immédiatement l'exécution à la prochaine itération de la boucle For.</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_loop_Can_be_used_in_a_Do_loop_a_For_loop_or_a_While_loop">
<source>Transfers execution immediately to the next iteration of the loop. Can be used in a Do loop, a For loop, or a While loop.</source>
<target state="translated">Transfère immédiatement l'exécution à la prochaine itération de la boucle. S'utilise dans une boucle Do, For ou While.</target>
<note />
</trans-unit>
<trans-unit id="Transfers_execution_immediately_to_the_next_iteration_of_the_While_loop">
<source>Transfers execution immediately to the next iteration of the While loop.</source>
<target state="translated">Transfère immédiatement l'exécution à la prochaine itération de la boucle While.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_largest_element_will_appear_first">
<source>Specifies the sort order for an Order By clause in a query. The largest element will appear first.</source>
<target state="translated">Spécifie l'ordre de tri d'une clause Order By dans une requête. Le plus grand élément apparaît en premier.</target>
<note />
</trans-unit>
<trans-unit id="Restricts_the_values_of_a_query_result_to_eliminate_duplicate_values">
<source>Restricts the values of a query result to eliminate duplicate values.</source>
<target state="translated">Restreint les valeurs du résultat d'une requête afin d'éliminer les valeurs dupliquées.</target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_or_until_the_condition_becomes_true_Do_Loop_While_Until_condition">
<source>Repeats a block of statements while a Boolean condition is true, or until the condition becomes true.
Do...Loop {While | Until} <condition></source>
<target state="translated">Répète un bloc d'instructions tant qu'une condition Boolean a la valeur True ou jusqu'à ce que la condition devienne True.
Do...Loop {While | Until} <condition></target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Until_condition_Loop">
<source>Repeats a block of statements until a Boolean condition becomes true.
Do Until <condition>...Loop</source>
<target state="translated">Répète un bloc d'instructions jusqu'à ce qu'une condition Boolean devienne True.
Do Until <condition>...Loop</target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_While_condition_Loop">
<source>Repeats a block of statements while a Boolean condition is true.
Do While <condition>...Loop</source>
<target state="translated">Répète un bloc d'instructions tant qu'une condition Boolean a la valeur True.
Do While <condition>...Loop</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_group_of_statements_in_an_SharpIf_statement_that_is_compiled_if_no_previous_condition_evaluates_to_True">
<source>Introduces a group of statements in an #If statement that is compiled if no previous condition evaluates to True.</source>
<target state="translated">Introduit un groupe d'instructions dans une instruction #If qui est compilée si aucune condition précédente n'a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_condition_in_an_SharpIf_statement_that_is_tested_if_the_previous_conditional_test_evaluates_to_False">
<source>Introduces a condition in an #If statement that is tested if the previous conditional test evaluates to False.</source>
<target state="translated">Introduit une condition dans une instruction #If qui est testée si le précédent test conditionnel a la valeur False.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_condition_in_an_If_statement_that_is_to_be_tested_if_the_previous_conditional_test_fails">
<source>Introduces a condition in an If statement that is to be tested if the previous conditional test fails.</source>
<target state="translated">Introduit une condition dans une instruction If qui doit être testée en cas d'échec du précédent test conditionnel.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_group_of_statements_in_an_If_statement_that_is_executed_if_no_previous_condition_evaluates_to_True">
<source>Introduces a group of statements in an If statement that is executed if no previous condition evaluates to True.</source>
<target state="translated">Introduit un groupe d'instructions dans une instruction If qui est exécutée si aucune condition précédente n'a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_the_definition_of_an_SharpIf_block">
<source>Terminates the definition of an #If block.</source>
<target state="translated">Termine la définition d'un bloc #If.</target>
<note />
</trans-unit>
<trans-unit id="Stops_execution_immediately">
<source>Stops execution immediately.</source>
<target state="translated">Arrête l'exécution immédiatement.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_SharpRegion_block">
<source>Terminates a #Region block.</source>
<target state="translated">Termine un bloc #Region.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_relationship_between_element_keys_to_use_as_the_basis_of_a_join_operation">
<source>Specifies the relationship between element keys to use as the basis of a join operation.</source>
<target state="translated">Spécifie la relation qui existe entre les clés d'éléments à utiliser comme base d'une opération de jointure.</target>
<note />
</trans-unit>
<trans-unit id="Simulates_the_occurrence_of_an_error">
<source>Simulates the occurrence of an error.</source>
<target state="translated">Simule la présence d'une erreur.</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Do_loop_and_transfers_execution_immediately_to_the_statement_following_the_Loop_statement">
<source>Exits a Do loop and transfers execution immediately to the statement following the Loop statement.</source>
<target state="translated">Quitte une boucle Do et transfère immédiatement l'exécution à l'instruction qui suit l'instruction Loop.</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_For_loop_and_transfers_execution_immediately_to_the_statement_following_the_Next_statement">
<source>Exits a For loop and transfers execution immediately to the statement following the Next statement.</source>
<target state="translated">Quitte une boucle For et transfère immédiatement l'exécution à l'instruction qui suit l'instruction Next.</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_procedure_or_block_and_transfers_execution_immediately_to_the_statement_following_the_procedure_call_or_block_definition_Exit_Do_For_Function_Property_Select_Sub_Try_While">
<source>Exits a procedure or block and transfers execution immediately to the statement following the procedure call or block definition.
Exit {Do | For | Function | Property | Select | Sub | Try | While}</source>
<target state="translated">Quitte une procédure ou un bloc, puis transfère immédiatement l'exécution à l'instruction qui suit l'appel de procédure ou la définition de bloc.
Exit {Do | For | Function | Property | Select | Sub | Try | While}</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Select_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Select_statement">
<source>Exits a Select block and transfers execution immediately to the statement following the End Select statement.</source>
<target state="translated">Quitte un bloc Select et transfère immédiatement l'exécution à l'instruction qui suit l'instruction End Select.</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_Try_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Try_statement">
<source>Exits a Try block and transfers execution immediately to the statement following the End Try statement.</source>
<target state="translated">Quitte un bloc Try et transfère immédiatement l'exécution à l'instruction qui suit l'instruction End Try.</target>
<note />
</trans-unit>
<trans-unit id="Exits_a_While_loop_and_transfers_execution_immediately_to_the_statement_following_the_End_While_statement">
<source>Exits a While loop and transfers execution immediately to the statement following the End While statement.</source>
<target state="translated">Quitte une boucle While et transfère immédiatement l'exécution à l'instruction qui suit l'instruction End While.</target>
<note />
</trans-unit>
<trans-unit id="When_set_to_On_requires_explicit_declaration_of_all_variables_using_a_Dim_Private_Public_or_ReDim_statement_Option_Explicit_On_Off">
<source>When set to On, requires explicit declaration of all variables, using a Dim, Private, Public, or ReDim statement.
Option Explicit {On | Off}</source>
<target state="translated">Lorsqu'il a la valeur On, il requiert une déclaration explicite de toutes les variables, à l'aide de l'instruction Dim, Private, Public ou ReDim.
Option Explicit {On | Off}</target>
<note />
</trans-unit>
<trans-unit id="Represents_a_Boolean_value_that_fails_a_conditional_test">
<source>Represents a Boolean value that fails a conditional test.</source>
<target state="translated">Représente une valeur Boolean qui ne réussit pas un test conditionnel.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_block_to_be_run_before_exiting_a_Try_structure">
<source>Introduces a statement block to be run before exiting a Try structure.</source>
<target state="translated">Introduit un bloc d'instructions à exécuter avant de quitter une structure Try.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_loop_that_is_repeated_for_each_element_in_a_collection">
<source>Introduces a loop that is repeated for each element in a collection.</source>
<target state="translated">Introduit une boucle qui se répète pour chaque élément d'une collection.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_loop_that_is_iterated_a_specified_number_of_times">
<source>Introduces a loop that is iterated a specified number of times.</source>
<target state="translated">Introduit une boucle qui est itérée un nombre spécifique de fois.</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_list_of_values_as_a_collection_initializer">
<source>Identifies a list of values as a collection initializer</source>
<target state="translated">Identifie une liste de valeurs en tant qu'initialiseur de collection</target>
<note />
</trans-unit>
<trans-unit id="Branches_unconditionally_to_a_specified_line_in_a_procedure">
<source>Branches unconditionally to a specified line in a procedure.</source>
<target state="translated">Crée une branche inconditionnelle vers une ligne spécifiée d'une procédure.</target>
<note />
</trans-unit>
<trans-unit id="Groups_elements_that_have_a_common_key">
<source>Groups elements that have a common key.</source>
<target state="translated">Regroupe les éléments qui ont une clé commune.</target>
<note />
</trans-unit>
<trans-unit id="Combines_the_elements_of_two_sequences_and_groups_the_results_The_join_operation_is_based_on_matching_keys">
<source>Combines the elements of two sequences and groups the results. The join operation is based on matching keys.</source>
<target state="translated">Combine les éléments de deux séquences et regroupe les résultats. L'opération de jointure est basée sur les clés correspondantes.</target>
<note />
</trans-unit>
<trans-unit id="Use_Group_to_specify_that_a_group_named_0_should_be_created">
<source>Use 'Group' to specify that a group named '{0}' should be created.</source>
<target state="translated">Utilisez 'Group' pour spécifier qu'un groupe nommé '{0}' doit être créé.</target>
<note />
</trans-unit>
<trans-unit id="Use_Group_to_specify_that_a_group_named_Group_should_be_created">
<source>Use 'Group' to specify that a group named 'Group' should be created.</source>
<target state="translated">Utilisez 'Group' pour spécifier qu'un groupe nommé 'Group' doit être créé.</target>
<note />
</trans-unit>
<trans-unit id="Conditionally_compiles_selected_blocks_of_code_depending_on_the_value_of_an_expression">
<source>Conditionally compiles selected blocks of code, depending on the value of an expression.</source>
<target state="translated">Effectue une compilation conditionnelle des blocs de code sélectionnés, en fonction de la valeur d'une expression.</target>
<note />
</trans-unit>
<trans-unit id="Conditionally_executes_a_group_of_statements_depending_on_the_value_of_an_expression">
<source>Conditionally executes a group of statements, depending on the value of an expression.</source>
<target state="translated">Exécute un groupe d'instructions soumises à une condition, en fonction de la valeur d'une expression.</target>
<note />
</trans-unit>
<trans-unit id="When_set_to_On_allows_the_use_of_local_type_inference_in_declaring_variables_Option_Infer_On_Off">
<source>When set to On, allows the use of local type inference in declaring variables.
Option Infer {On | Off}</source>
<target state="translated">Lorsqu'il a la valeur On, il autorise l'utilisation d'une inférence de type locale lors de la déclaration de variables.
Option Infer {On | Off}</target>
<note />
</trans-unit>
<trans-unit id="Specifies_an_identifier_that_can_serve_as_a_reference_to_the_results_of_a_join_or_grouping_subexpression">
<source>Specifies an identifier that can serve as a reference to the results of a join or grouping subexpression.</source>
<target state="translated">Spécifie un identificateur qui peut servir de référence aux résultats d'une sous-expression de jointure ou de regroupement.</target>
<note />
</trans-unit>
<trans-unit id="Combines_the_elements_of_two_sequences_The_join_operation_is_based_on_matching_keys">
<source>Combines the elements of two sequences. The join operation is based on matching keys.</source>
<target state="translated">Combine les éléments de deux séquences. L'opération de jointure est basée sur les clés correspondantes.</target>
<note />
</trans-unit>
<trans-unit id="Identifies_a_key_field_in_an_anonymous_type_definition">
<source>Identifies a key field in an anonymous type definition.</source>
<target state="translated">Identifie un champ clé dans une définition de type anonyme.</target>
<note />
</trans-unit>
<trans-unit id="Computes_a_value_for_each_item_in_the_query_and_assigns_the_value_to_a_new_range_variable">
<source>Computes a value for each item in the query, and assigns the value to a new range variable.</source>
<target state="translated">Calcule une valeur pour chaque élément de la requête, puis assigne la valeur à une nouvelle variable de plage.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_loop_that_is_introduced_with_a_Do_statement">
<source>Terminates a loop that is introduced with a Do statement.</source>
<target state="translated">Termine une boucle introduite avec une instruction Do.</target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition">
<source>Repeats a block of statements until a Boolean condition becomes true.
Do...Loop Until <condition></source>
<target state="translated">Répète un bloc d'instructions jusqu'à ce qu'une condition Boolean devienne True.
Do...Loop Until <condition></target>
<note />
</trans-unit>
<trans-unit id="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition">
<source>Repeats a block of statements while a Boolean condition is true.
Do...Loop While <condition></source>
<target state="translated">Répète un bloc d'instructions tant qu'une condition Boolean a la valeur True.
Do...Loop While <condition></target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_refer_to_the_current_instance_of_a_class_or_structure_that_is_the_instance_in_which_the_code_is_running">
<source>Provides a way to refer to the current instance of a class or structure, that is, the instance in which the code is running.</source>
<target state="translated">Permet de faire référence à l'instance actuelle d'une classe ou d'une structure, en d'autres termes, l'instance dans laquelle le code s'exécute.</target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_refer_to_the_base_class_of_the_current_class_instance_You_cannot_use_MyBase_to_call_MustOverride_base_methods">
<source>Provides a way to refer to the base class of the current class instance. You cannot use MyBase to call MustOverride base methods.</source>
<target state="translated">Permet de faire référence à la classe de base de l'instance de classe actuelle. Vous ne pouvez pas utiliser MyBase pour appeler les méthodes de base MustOverride.</target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_refer_to_the_class_instance_members_as_originally_implemented_ignoring_any_derived_class_overrides">
<source>Provides a way to refer to the class instance members as originally implemented, ignoring any derived class overrides.</source>
<target state="translated">Permet de faire référence aux membres d'instance de classe implémentés à l'origine, en ignorant toute substitution de classe dérivée.</target>
<note />
</trans-unit>
<trans-unit id="Creates_a_new_object_instance">
<source>Creates a new object instance.</source>
<target state="translated">Crée une instance d'objet.</target>
<note />
</trans-unit>
<trans-unit id="Terminates_a_loop_that_iterates_through_the_values_of_a_loop_variable">
<source>Terminates a loop that iterates through the values of a loop variable.</source>
<target state="translated">Termine une boucle qui itère au sein des valeurs d'une variable de boucle.</target>
<note />
</trans-unit>
<trans-unit id="Represents_the_default_value_of_any_data_type">
<source>Represents the default value of any data type.</source>
<target state="translated">Représente la valeur par défaut d'un type de données quelconque.</target>
<note />
</trans-unit>
<trans-unit id="Turns_a_compiler_option_off">
<source>Turns a compiler option off.</source>
<target state="translated">Désactive une option du compilateur.</target>
<note />
</trans-unit>
<trans-unit id="Enables_the_error_handling_routine_that_starts_at_the_line_specified_in_the_line_argument_The_specified_line_must_be_in_the_same_procedure_as_the_On_Error_statement_On_Error_GoTo_bracket_label_0_1_bracket">
<source>Enables the error-handling routine that starts at the line specified in the line argument.
The specified line must be in the same procedure as the On Error statement.
On Error GoTo [<label> | 0 | -1]</source>
<target state="translated">Active la routine de gestion des erreurs qui démarre à la ligne spécifiée dans l'argument de ligne.
La ligne spécifiée doit se trouver dans la même procédure que l'instruction On Error.
On Error GoTo [<label> | 0 | -1]</target>
<note />
</trans-unit>
<trans-unit id="When_a_run_time_error_occurs_execution_transfers_to_the_statement_following_the_statement_or_procedure_call_that_resulted_in_the_error">
<source>When a run-time error occurs, execution transfers to the statement following the statement or procedure call that resulted in the error.</source>
<target state="translated">Lorsqu'une erreur d'exécution se produit, l'exécution est transférée à l'instruction qui suit l'appel de l'instruction ou de la procédure ayant entraîné l'erreur.</target>
<note />
</trans-unit>
<trans-unit id="Turns_a_compiler_option_on">
<source>Turns a compiler option on.</source>
<target state="translated">Active une option du compilateur.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_element_keys_used_to_correlate_sequences_for_a_join_operation">
<source>Specifies the element keys used to correlate sequences for a join operation.</source>
<target state="translated">Spécifie les clés d'éléments utilisées pour mettre en corrélation les séquences d'une opération de jointure.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_sort_order_for_columns_in_a_query_Can_be_followed_by_either_the_Ascending_or_the_Descending_keyword_If_neither_is_specified_Ascending_is_used">
<source>Specifies the sort order for columns in a query. Can be followed by either the Ascending or the Descending keyword. If neither is specified, Ascending is used.</source>
<target state="translated">Spécifie l'ordre de tri des colonnes dans une requête. Cette clause peut être suivie du mot clé Ascending ou Descending. Si aucun mot clé n'est spécifié, Ascending est utilisé.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_statements_to_run_when_the_event_is_raised_by_the_RaiseEvent_statement_RaiseEvent_delegateSignature_End_RaiseEvent">
<source>Specifies the statements to run when the event is raised by the RaiseEvent statement.
RaiseEvent(<delegateSignature>)...End RaiseEvent</source>
<target state="translated">Spécifie les instructions à exécuter lorsque l'événement est déclenché par l'instruction RaiseEvent.
RaiseEvent(<delegateSignature>)...End RaiseEvent</target>
<note />
</trans-unit>
<trans-unit id="Triggers_an_event_declared_at_module_level_within_a_class_form_or_document_RaiseEvent_eventName_bracket_argumentList_bracket">
<source>Triggers an event declared at module level within a class, form, or document.
RaiseEvent <eventName> [(<argumentList>)]</source>
<target state="translated">Déclenche un événement déclaré au niveau du module dans une classe, un formulaire ou un document.
RaiseEvent <eventName> [(<argumentList>)]</target>
<note />
</trans-unit>
<trans-unit id="Collapses_and_hides_sections_of_code_in_Visual_Basic_files">
<source>Collapses and hides sections of code in Visual Basic files.</source>
<target state="translated">Réduit et masque des sections de code dans des fichiers Visual Basic.</target>
<note />
</trans-unit>
<trans-unit id="Returns_execution_to_the_code_that_called_the_Function_Sub_Get_Set_or_Operator_procedure_Return_or_Return_expression">
<source>Returns execution to the code that called the Function, Sub, Get, Set, or Operator procedure.
Return -or- Return <expression></source>
<target state="translated">Retourne l'exécution au code qui a appelé la procédure Function, Sub, Get, Set ou Operator.
Return -ou- Return <expression></target>
<note />
</trans-unit>
<trans-unit id="Runs_one_of_several_groups_of_statements_depending_on_the_value_of_an_expression">
<source>Runs one of several groups of statements, depending on the value of an expression.</source>
<target state="translated">Exécute l'un des multiples groupes d'instructions, en fonction de la valeur d'une expression.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_which_columns_to_include_in_the_result_of_a_query">
<source>Specifies which columns to include in the result of a query.</source>
<target state="translated">Spécifie les colonnes à inclure dans le résultat d'une requête.</target>
<note />
</trans-unit>
<trans-unit id="Skips_elements_up_to_a_specified_position_in_the_collection">
<source>Skips elements up to a specified position in the collection.</source>
<target state="translated">Ignore des éléments jusqu'à une position spécifique dans la collection.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_how_much_to_increment_between_each_loop_iteration">
<source>Specifies how much to increment between each loop iteration.</source>
<target state="translated">Spécifie la valeur à ajouter à chaque itération de boucle.</target>
<note />
</trans-unit>
<trans-unit id="Suspends_program_execution">
<source>Suspends program execution.</source>
<target state="translated">Suspend l'exécution du programme.</target>
<note />
</trans-unit>
<trans-unit id="When_set_to_On_restricts_implicit_data_type_conversions_to_only_widening_conversions_Option_Strict_On_Off">
<source>When set to On, restricts implicit data type conversions to only widening conversions.
Option Strict {On | Off}</source>
<target state="translated">Lorsqu'il a la valeur On, il restreint les conversions de types de données implicites à des conversions étendues uniquement.
Option Strict {On | Off}</target>
<note />
</trans-unit>
<trans-unit id="Ensures_that_multiple_threads_do_not_execute_the_statement_block_at_the_same_time_SyncLock_object_End_Synclock">
<source>Ensures that multiple threads do not execute the statement block at the same time.
SyncLock <object>...End Synclock</source>
<target state="translated">S'assure que plusieurs threads n'exécutent pas le bloc d'instructions en même temps.
SyncLock <object>...End Synclock</target>
<note />
</trans-unit>
<trans-unit id="Includes_elements_up_to_a_specified_position_in_the_collection">
<source>Includes elements up to a specified position in the collection.</source>
<target state="translated">Inclut des éléments jusqu'à une position spécifique dans la collection.</target>
<note />
</trans-unit>
<trans-unit id="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_text_sort_order_that_is_not_case_sensitive">
<source>Sets the string comparison method specified in Option Compare to a text sort order that is not case sensitive.</source>
<target state="translated">Définit la méthode de comparaison de chaînes spécifiée dans Option Compare selon un ordre de tri alphabétique sans respect de la casse.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_statement_block_to_be_compiled_or_executed_if_a_tested_condition_is_true">
<source>Introduces a statement block to be compiled or executed if a tested condition is true.</source>
<target state="translated">Introduit un bloc d'instructions à compiler ou à exécuter si une condition testée a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Throws_an_exception_within_a_procedure_so_that_you_can_handle_it_with_structured_or_unstructured_exception_handling_code">
<source>Throws an exception within a procedure so that you can handle it with structured or unstructured exception-handling code.</source>
<target state="translated">Lève une exception dans une procédure de sorte que vous puissiez la gérer avec du code de gestion des exceptions structurée ou non structurée.</target>
<note />
</trans-unit>
<trans-unit id="Represents_a_Boolean_value_that_passes_a_conditional_test">
<source>Represents a Boolean value that passes a conditional test.</source>
<target state="translated">Représente une valeur Boolean qui réussit un test conditionnel.</target>
<note />
</trans-unit>
<trans-unit id="Provides_a_way_to_handle_some_or_all_possible_errors_that_might_occur_in_a_given_block_of_code_while_still_running_the_code_Try_bracket_Catch_bracket_Catch_Finally_End_Try">
<source>Provides a way to handle some or all possible errors that might occur in a given block of code, while still running the code.
Try...[Catch]...{Catch | Finally}...End Try</source>
<target state="translated">Permet de traiter une partie ou l'ensemble des erreurs possibles pouvant se produire dans un bloc de code donné, tout en continuant à exécuter le code.
Try...[Catch]...{Catch | Finally}...End Try</target>
<note />
</trans-unit>
<trans-unit id="A_Using_block_does_three_things_colon_it_creates_and_initializes_variables_in_the_resource_list_it_runs_the_code_in_the_block_and_it_disposes_of_the_variables_before_exiting_Resources_used_in_the_Using_block_must_implement_System_IDisposable_Using_resource1_bracket_resource2_bracket_End_Using">
<source>A Using block does three things: it creates and initializes variables in the resource list, it runs the code in the block, and it disposes of the variables before exiting. Resources used in the Using block must implement System.IDisposable.
Using <resource1>[, <resource2>]...End Using</source>
<target state="translated">Un bloc Using effectue trois actions : il crée et initialise des variables dans la liste des ressources, il exécute le code du bloc et supprime les variables avant de quitter. Les ressources utilisées dans le bloc Using doivent implémenter System.IDisposable.
Using <resource1>[, <resource2>]...End Using</target>
<note />
</trans-unit>
<trans-unit id="Adds_a_conditional_test_to_a_Catch_statement_Exceptions_are_caught_by_that_Catch_statement_only_when_the_conditional_test_that_follows_the_When_keyword_evaluates_to_True">
<source>Adds a conditional test to a Catch statement. Exceptions are caught by that Catch statement only when the conditional test that follows the When keyword evaluates to True.</source>
<target state="translated">Ajoute un test conditionnel à une instruction Catch. Les exceptions sont interceptées par cette instruction Catch uniquement lorsque le test conditionnel qui suit le mot clé When a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_filtering_condition_for_a_range_variable_in_a_query">
<source>Specifies the filtering condition for a range variable in a query.</source>
<target state="translated">Spécifie la condition de filtrage d'une variable de plage dans une requête.</target>
<note />
</trans-unit>
<trans-unit id="Runs_a_series_of_statements_as_long_as_a_given_condition_is_true">
<source>Runs a series of statements as long as a given condition is true.</source>
<target state="translated">Exécute une série d'instructions tant qu'une condition donnée a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_a_condition_for_Skip_and_Take_operations_Elements_will_be_bypassed_or_included_as_long_as_the_condition_is_true">
<source>Specifies a condition for Skip and Take operations. Elements will be bypassed or included as long as the condition is true.</source>
<target state="translated">Spécifie une condition pour les opérations Skip et Take. Les éléments sont ignorés ou inclus tant que la condition a la valeur True.</target>
<note />
</trans-unit>
<trans-unit id="Specifies_the_declaration_of_property_initializations_in_an_object_initializer_New_typeName_With_bracket_property_expression_bracket_bracket_bracket">
<source>Specifies the declaration of property initializations in an object initializer.
New <typeName> With {[.<property> = <expression>][,...]}</source>
<target state="translated">Spécifie la déclaration des initialisations de propriétés dans un initialiseur d'objet.
New <typeName> With {[.<property> = <expression>][,...]}</target>
<note />
</trans-unit>
<trans-unit id="Runs_a_series_of_statements_that_refer_to_a_single_object_or_structure_With_object_End_With">
<source>Runs a series of statements that refer to a single object or structure.
With <object>...End With</source>
<target state="translated">Exécute une série d'instructions qui font référence à un objet ou une structure unique.
With <object>...End With</target>
<note />
</trans-unit>
<trans-unit id="Produces_an_element_of_an_IEnumerable_or_IEnumerator">
<source>Produces an element of an IEnumerable or IEnumerator.</source>
<target state="translated">Produit un élément d'un IEnumerable ou IEnumerator.</target>
<note />
</trans-unit>
<trans-unit id="Defines_an_asynchronous_lambda_expression_that_can_use_the_Await_operator_Can_be_used_wherever_a_delegate_type_is_expected_Async_Sub_Function_parameterList_expression">
<source>Defines an asynchronous lambda expression that can use the Await operator. Can be used wherever a delegate type is expected.
Async Sub/Function(<parameterList>) <expression></source>
<target state="translated">Définit une expression lambda asynchrone pouvant utiliser l'opérateur Await. S'utilise lorsqu'un type délégué est attendu.
Async Sub/Function(<parameterList>) <expression></target>
<note />
</trans-unit>
<trans-unit id="Defines_a_lambda_expression_that_calculates_and_returns_a_single_value_Can_be_used_wherever_a_delegate_type_is_expected_Function_parameterList_expression">
<source>Defines a lambda expression that calculates and returns a single value. Can be used wherever a delegate type is expected.
Function(<parameterList>) <expression></source>
<target state="translated">Définit une expression lambda qui calcule et retourne une valeur unique. S'utilise lorsqu'un type délégué est attendu.
Function(<parameterList>) <expression></target>
<note />
</trans-unit>
<trans-unit id="Defines_a_lambda_expression_that_can_execute_statements_and_does_not_return_a_value_Can_be_used_wherever_a_delegate_type_is_expected_Sub_parameterList_statement">
<source>Defines a lambda expression that can execute statements and does not return a value. Can be used wherever a delegate type is expected.
Sub(<parameterList>) <statement></source>
<target state="translated">Définit une expression lambda qui exécute des instructions, mais qui ne retourne aucune valeur. S'utilise lorsqu'un type délégué est attendu.
Sub(<parameterList>) <statement></target>
<note />
</trans-unit>
<trans-unit id="Disables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line">
<source>Disables reporting of specified warnings in the portion of the source file below the current line.</source>
<target state="translated">Désactive la création de rapports des avertissements spécifiés dans la partie du fichier source en dessous de la ligne active.</target>
<note />
</trans-unit>
<trans-unit id="Enables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line">
<source>Enables reporting of specified warnings in the portion of the source file below the current line.</source>
<target state="translated">Active la création de rapports des avertissements spécifiés dans la partie du fichier source en dessous de la ligne active.</target>
<note />
</trans-unit>
<trans-unit id="Insert_Await">
<source>Insert 'Await'.</source>
<target state="translated">Insérez 'Await'.</target>
<note />
</trans-unit>
<trans-unit id="Make_0_an_Async_Function">
<source>Make {0} an Async Function.</source>
<target state="translated">Faire de {0} une fonction Async.</target>
<note />
</trans-unit>
<trans-unit id="Convert_0_to_Iterator">
<source>Convert {0} to Iterator</source>
<target state="translated">Convertir {0} en itérateur</target>
<note />
</trans-unit>
<trans-unit id="Replace_Return_with_Yield">
<source>Replace 'Return' with 'Yield</source>
<target state="translated">Remplacer 'Return' par 'Yield</target>
<note />
</trans-unit>
<trans-unit id="Use_the_correct_control_variable">
<source>Use the correct control variable</source>
<target state="translated">Utiliser la variable de contrôle correcte</target>
<note />
</trans-unit>
<trans-unit id="NameOf_function">
<source>NameOf function</source>
<target state="translated">Fonction NameOf</target>
<note />
</trans-unit>
<trans-unit id="Generate_narrowing_conversion_in_0">
<source>Generate narrowing conversion in '{0}'</source>
<target state="translated">Générer une conversion restrictive dans '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Generate_widening_conversion_in_0">
<source>Generate widening conversion in '{0}'</source>
<target state="translated">Générer une conversation étendue dans '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Try_block">
<source>Try block</source>
<target state="translated">Bloc Try</target>
<note>{Locked="Try"} "Try" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Catch_clause">
<source>Catch clause</source>
<target state="translated">Clause Catch</target>
<note>{Locked="Catch"} "Catch" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Finally_clause">
<source>Finally clause</source>
<target state="translated">Clause Finally</target>
<note>{Locked="Finally"} "Finally" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Using_statement">
<source>Using statement</source>
<target state="translated">Instruction Using</target>
<note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Using_block">
<source>Using block</source>
<target state="translated">Bloc Using</target>
<note>{Locked="Using"} "Using" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="With_statement">
<source>With statement</source>
<target state="translated">Instruction With</target>
<note>{Locked="With"} "With" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="With_block">
<source>With block</source>
<target state="translated">Bloc With</target>
<note>{Locked="With"} "With" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="SyncLock_statement">
<source>SyncLock statement</source>
<target state="translated">Instruction SyncLock</target>
<note>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="SyncLock_block">
<source>SyncLock block</source>
<target state="translated">Bloc SyncLock</target>
<note>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="For_Each_statement">
<source>For Each statement</source>
<target state="translated">Instruction For Each</target>
<note>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="For_Each_block">
<source>For Each block</source>
<target state="translated">Bloc For Each</target>
<note>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="On_Error_statement">
<source>On Error statement</source>
<target state="translated">Instruction On Error</target>
<note>{Locked="On Error"} "On Error" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Resume_statement">
<source>Resume statement</source>
<target state="translated">Instruction Resume</target>
<note>{Locked="Resume"} "Resume" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Yield_statement">
<source>Yield statement</source>
<target state="translated">Instruction Yield</target>
<note>{Locked="Yield"} "Yield" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Await_expression">
<source>Await expression</source>
<target state="translated">Expression Await</target>
<note>{Locked="Await"} "Await" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Lambda">
<source>Lambda</source>
<target state="translated">Lambda</target>
<note />
</trans-unit>
<trans-unit id="Where_clause">
<source>Where clause</source>
<target state="translated">Clause Where</target>
<note>{Locked="Where"} "Where" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Select_clause">
<source>Select clause</source>
<target state="translated">Clause Select</target>
<note>{Locked="Select"} "Select" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="From_clause">
<source>From clause</source>
<target state="translated">Clause From</target>
<note>{Locked="From"} "From" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Aggregate_clause">
<source>Aggregate clause</source>
<target state="translated">Clause Aggregate</target>
<note>{Locked="Aggregate"} "Aggregate" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Let_clause">
<source>Let clause</source>
<target state="translated">Clause Let</target>
<note>{Locked="Let"} "Let" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Join_clause">
<source>Join clause</source>
<target state="translated">Clause Join</target>
<note>{Locked="Join"} "Join" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Group_Join_clause">
<source>Group Join clause</source>
<target state="translated">Clause Group Join</target>
<note>{Locked="Group Join"} "Group Join" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Group_By_clause">
<source>Group By clause</source>
<target state="translated">Clause Group By</target>
<note>{Locked="Group By"} "Group By" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Function_aggregation">
<source>Function aggregation</source>
<target state="translated">Agrégation de fonction</target>
<note />
</trans-unit>
<trans-unit id="Take_While_clause">
<source>Take While clause</source>
<target state="translated">Clause Take While</target>
<note>{Locked="Take While"} "Take While" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Skip_While_clause">
<source>Skip While clause</source>
<target state="translated">Clause Skip While</target>
<note>{Locked="Skip While"} "Skip While" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Ordering_clause">
<source>Ordering clause</source>
<target state="translated">Clause Ordering</target>
<note>{Locked="Ordering"} "Ordering" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Join_condition">
<source>Join condition</source>
<target state="translated">Condition Join</target>
<note>{Locked="Join"} "Join" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="WithEvents_field">
<source>WithEvents field</source>
<target state="translated">Champ WithEvents</target>
<note>{Locked="WithEvents"} "WithEvents" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="as_clause">
<source>as clause</source>
<target state="translated">Clause as</target>
<note>{Locked="as"} "as" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="type_parameters">
<source>type parameters</source>
<target state="translated">paramètres de type</target>
<note />
</trans-unit>
<trans-unit id="parameters">
<source>parameters</source>
<target state="translated">paramètres</target>
<note />
</trans-unit>
<trans-unit id="attributes">
<source>attributes</source>
<target state="translated">attributs</target>
<note />
</trans-unit>
<trans-unit id="Too_many_arguments_to_0">
<source>Too many arguments to '{0}'.</source>
<target state="translated">Arguments trop nombreux pour '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Type_0_is_not_defined">
<source>Type '{0}' is not defined.</source>
<target state="translated">Le type '{0}' n'est pas défini.</target>
<note />
</trans-unit>
<trans-unit id="Add_Overloads">
<source>Add 'Overloads'</source>
<target state="translated">Ajouter 'Overloads'</target>
<note>{Locked="Overloads"} "Overloads" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Add_a_metadata_reference_to_specified_assembly_and_all_its_dependencies_e_g_Sharpr_myLib_dll">
<source>Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll".</source>
<target state="translated">Permet d'ajouter une référence de métadonnées à l'assembly spécifié et toutes ses dépendances. Exemple : #r "myLib.dll".</target>
<note />
</trans-unit>
<trans-unit id="Properties">
<source>Properties</source>
<target state="translated">Propriétés</target>
<note />
</trans-unit>
<trans-unit id="namespace_name">
<source><namespace name></source>
<target state="translated"><nom de l'espace de noms></target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_namespace">
<source>Type a name here to declare a namespace.</source>
<target state="translated">Tapez un nom ici pour déclarer un espace de noms.</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_class">
<source>Type a name here to declare a partial class.</source>
<target state="translated">Tapez un nom ici pour déclarer une classe partielle.</target>
<note />
</trans-unit>
<trans-unit id="class_name">
<source><class name></source>
<target state="translated"><nom de la classe></target>
<note />
</trans-unit>
<trans-unit id="interface_name">
<source><interface name></source>
<target state="translated"><nom de l'interface></target>
<note />
</trans-unit>
<trans-unit id="module_name">
<source><module name></source>
<target state="translated"><nom du module></target>
<note />
</trans-unit>
<trans-unit id="structure_name">
<source><structure name></source>
<target state="translated"><nom de la structure></target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_interface">
<source>Type a name here to declare a partial interface.</source>
<target state="translated">Tapez un nom ici pour déclarer une interface partielle.</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_module">
<source>Type a name here to declare a partial module.</source>
<target state="translated">Tapez un nom ici pour déclarer un module partiel.</target>
<note />
</trans-unit>
<trans-unit id="Type_a_name_here_to_declare_a_partial_structure">
<source>Type a name here to declare a partial structure.</source>
<target state="translated">Tapez un nom ici pour déclarer une structure partielle.</target>
<note />
</trans-unit>
<trans-unit id="Event_add_handler_name">
<source>{0}.add</source>
<target state="translated">{0}.add</target>
<note>The name of an event add handler where "{0}" is the event name.</note>
</trans-unit>
<trans-unit id="Event_remove_handler_name">
<source>{0}.remove</source>
<target state="translated">{0}.remove</target>
<note>The name of an event remove handler where "{0}" is the event name.</note>
</trans-unit>
<trans-unit id="Property_getter_name">
<source>{0}.get</source>
<target state="translated">{0}.get</target>
<note>The name of a property getter like "public int MyProperty { get; }" where "{0}" is the property name</note>
</trans-unit>
<trans-unit id="Property_setter_name">
<source>{0}.set</source>
<target state="translated">{0}.set</target>
<note>The name of a property setter like "public int MyProperty { set; }" where "{0}" is the property name</note>
</trans-unit>
<trans-unit id="Make_Async_Function">
<source>Make Async Function</source>
<target state="translated">Rendre la fonction asynchrone</target>
<note />
</trans-unit>
<trans-unit id="Make_Async_Sub">
<source>Make Async Sub</source>
<target state="translated">Rendre le Sub asynchrone</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_Select_Case">
<source>Convert to 'Select Case'</source>
<target state="translated">Convertir en 'Select Case'</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_For_Each">
<source>Convert to 'For Each'</source>
<target state="translated">Convertir en 'For Each'</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_For">
<source>Convert to 'For'</source>
<target state="translated">Convertir en 'For'</target>
<note />
</trans-unit>
<trans-unit id="Invert_If">
<source>Invert If</source>
<target state="translated">Inverser If</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/Core.Wpf/InlineRename/Dashboard/DashboardSeverity.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal enum DashboardSeverity
{
None,
Info,
Error
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal enum DashboardSeverity
{
None,
Info,
Error
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/CSharp/Portable/Indentation/CSharpIndentationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Indentation
{
[ExportLanguageService(typeof(IIndentationService), LanguageNames.CSharp), Shared]
internal sealed partial class CSharpIndentationService : AbstractIndentationService<CompilationUnitSyntax>
{
public static readonly CSharpIndentationService Instance = new();
private static readonly AbstractFormattingRule s_instance = new FormattingRule();
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")]
public CSharpIndentationService()
{
}
protected override AbstractFormattingRule GetSpecializedIndentationFormattingRule(FormattingOptions.IndentStyle indentStyle)
=> s_instance;
public static bool ShouldUseSmartTokenFormatterInsteadOfIndenter(
IEnumerable<AbstractFormattingRule> formattingRules,
CompilationUnitSyntax root,
TextLine line,
IOptionService optionService,
OptionSet optionSet,
out SyntaxToken token)
{
Contract.ThrowIfNull(formattingRules);
Contract.ThrowIfNull(root);
token = default;
if (!optionSet.GetOption(FormattingOptions.AutoFormattingOnReturn, LanguageNames.CSharp))
{
return false;
}
if (optionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) != FormattingOptions.IndentStyle.Smart)
{
return false;
}
var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition();
if (!firstNonWhitespacePosition.HasValue)
{
return false;
}
token = root.FindToken(firstNonWhitespacePosition.Value);
if (IsInvalidToken(token))
{
return false;
}
if (token.IsKind(SyntaxKind.None) ||
token.SpanStart != firstNonWhitespacePosition)
{
return false;
}
// first see whether there is a line operation for current token
var previousToken = token.GetPreviousToken(includeZeroWidth: true);
// only use smart token formatter when we have two visible tokens.
if (previousToken.Kind() == SyntaxKind.None || previousToken.IsMissing)
{
return false;
}
var lineOperation = FormattingOperations.GetAdjustNewLinesOperation(formattingRules, previousToken, token, optionSet.AsAnalyzerConfigOptions(optionService, LanguageNames.CSharp));
if (lineOperation == null || lineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine)
{
// no indentation operation, nothing to do for smart token formatter
return false;
}
// We're pressing enter between two tokens, have the formatter figure out hte appropriate
// indentation.
return true;
}
private static bool IsInvalidToken(SyntaxToken token)
{
// invalid token to be formatted
return token.IsKind(SyntaxKind.None) ||
token.IsKind(SyntaxKind.EndOfDirectiveToken) ||
token.IsKind(SyntaxKind.EndOfFileToken);
}
private class FormattingRule : AbstractFormattingRule
{
public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation)
{
// these nodes should be from syntax tree from ITextSnapshot.
Debug.Assert(node.SyntaxTree != null);
Debug.Assert(node.SyntaxTree.GetText() != null);
nextOperation.Invoke();
ReplaceCaseIndentationRules(list, node);
if (node is BaseParameterListSyntax ||
node is TypeArgumentListSyntax ||
node is TypeParameterListSyntax ||
node.IsKind(SyntaxKind.Interpolation))
{
AddIndentBlockOperations(list, node);
return;
}
if (node is BaseArgumentListSyntax argument &&
!argument.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) &&
!IsBracketedArgumentListMissingBrackets(argument as BracketedArgumentListSyntax))
{
AddIndentBlockOperations(list, argument);
return;
}
// only valid if the user has started to actually type a constructor initializer
if (node is ConstructorInitializerSyntax constructorInitializer &&
constructorInitializer.ArgumentList.OpenParenToken.Kind() != SyntaxKind.None &&
!constructorInitializer.ThisOrBaseKeyword.IsMissing)
{
var text = node.SyntaxTree.GetText();
// 3 different cases
// first case : this or base is the first token on line
// second case : colon is the first token on line
var colonIsFirstTokenOnLine = !constructorInitializer.ColonToken.IsMissing && constructorInitializer.ColonToken.IsFirstTokenOnLine(text);
var thisOrBaseIsFirstTokenOnLine = !constructorInitializer.ThisOrBaseKeyword.IsMissing && constructorInitializer.ThisOrBaseKeyword.IsFirstTokenOnLine(text);
if (colonIsFirstTokenOnLine || thisOrBaseIsFirstTokenOnLine)
{
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(
constructorInitializer.ThisOrBaseKeyword,
constructorInitializer.ArgumentList.OpenParenToken.GetNextToken(includeZeroWidth: true),
constructorInitializer.ArgumentList.CloseParenToken.GetPreviousToken(includeZeroWidth: true),
indentationDelta: 1,
option: IndentBlockOption.RelativePosition));
}
else
{
// third case : none of them are the first token on the line
AddIndentBlockOperations(list, constructorInitializer.ArgumentList);
}
}
}
private static bool IsBracketedArgumentListMissingBrackets(BracketedArgumentListSyntax? node)
=> node != null && node.OpenBracketToken.IsMissing && node.CloseBracketToken.IsMissing;
private static void ReplaceCaseIndentationRules(List<IndentBlockOperation> list, SyntaxNode node)
{
if (!(node is SwitchSectionSyntax section) || section.Statements.Count == 0)
{
return;
}
var startToken = section.Statements.First().GetFirstToken(includeZeroWidth: true);
var endToken = section.Statements.Last().GetLastToken(includeZeroWidth: true);
for (var i = 0; i < list.Count; i++)
{
var operation = list[i];
if (operation.StartToken == startToken && operation.EndToken == endToken)
{
// replace operation
list[i] = FormattingOperations.CreateIndentBlockOperation(startToken, endToken, indentationDelta: 1, option: IndentBlockOption.RelativePosition);
}
}
}
private static void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node)
{
RoslynDebug.AssertNotNull(node.Parent);
// only add indent block operation if the base token is the first token on line
var baseToken = node.Parent.GetFirstToken(includeZeroWidth: true);
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(
baseToken,
node.GetFirstToken(includeZeroWidth: true).GetNextToken(includeZeroWidth: true),
node.GetLastToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true),
indentationDelta: 1,
option: IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Indentation
{
[ExportLanguageService(typeof(IIndentationService), LanguageNames.CSharp), Shared]
internal sealed partial class CSharpIndentationService : AbstractIndentationService<CompilationUnitSyntax>
{
public static readonly CSharpIndentationService Instance = new();
private static readonly AbstractFormattingRule s_instance = new FormattingRule();
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")]
public CSharpIndentationService()
{
}
protected override AbstractFormattingRule GetSpecializedIndentationFormattingRule(FormattingOptions.IndentStyle indentStyle)
=> s_instance;
public static bool ShouldUseSmartTokenFormatterInsteadOfIndenter(
IEnumerable<AbstractFormattingRule> formattingRules,
CompilationUnitSyntax root,
TextLine line,
IOptionService optionService,
OptionSet optionSet,
out SyntaxToken token)
{
Contract.ThrowIfNull(formattingRules);
Contract.ThrowIfNull(root);
token = default;
if (!optionSet.GetOption(FormattingOptions.AutoFormattingOnReturn, LanguageNames.CSharp))
{
return false;
}
if (optionSet.GetOption(FormattingOptions.SmartIndent, LanguageNames.CSharp) != FormattingOptions.IndentStyle.Smart)
{
return false;
}
var firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition();
if (!firstNonWhitespacePosition.HasValue)
{
return false;
}
token = root.FindToken(firstNonWhitespacePosition.Value);
if (IsInvalidToken(token))
{
return false;
}
if (token.IsKind(SyntaxKind.None) ||
token.SpanStart != firstNonWhitespacePosition)
{
return false;
}
// first see whether there is a line operation for current token
var previousToken = token.GetPreviousToken(includeZeroWidth: true);
// only use smart token formatter when we have two visible tokens.
if (previousToken.Kind() == SyntaxKind.None || previousToken.IsMissing)
{
return false;
}
var lineOperation = FormattingOperations.GetAdjustNewLinesOperation(formattingRules, previousToken, token, optionSet.AsAnalyzerConfigOptions(optionService, LanguageNames.CSharp));
if (lineOperation == null || lineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine)
{
// no indentation operation, nothing to do for smart token formatter
return false;
}
// We're pressing enter between two tokens, have the formatter figure out hte appropriate
// indentation.
return true;
}
private static bool IsInvalidToken(SyntaxToken token)
{
// invalid token to be formatted
return token.IsKind(SyntaxKind.None) ||
token.IsKind(SyntaxKind.EndOfDirectiveToken) ||
token.IsKind(SyntaxKind.EndOfFileToken);
}
private class FormattingRule : AbstractFormattingRule
{
public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation)
{
// these nodes should be from syntax tree from ITextSnapshot.
Debug.Assert(node.SyntaxTree != null);
Debug.Assert(node.SyntaxTree.GetText() != null);
nextOperation.Invoke();
ReplaceCaseIndentationRules(list, node);
if (node is BaseParameterListSyntax ||
node is TypeArgumentListSyntax ||
node is TypeParameterListSyntax ||
node.IsKind(SyntaxKind.Interpolation))
{
AddIndentBlockOperations(list, node);
return;
}
if (node is BaseArgumentListSyntax argument &&
!argument.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) &&
!IsBracketedArgumentListMissingBrackets(argument as BracketedArgumentListSyntax))
{
AddIndentBlockOperations(list, argument);
return;
}
// only valid if the user has started to actually type a constructor initializer
if (node is ConstructorInitializerSyntax constructorInitializer &&
constructorInitializer.ArgumentList.OpenParenToken.Kind() != SyntaxKind.None &&
!constructorInitializer.ThisOrBaseKeyword.IsMissing)
{
var text = node.SyntaxTree.GetText();
// 3 different cases
// first case : this or base is the first token on line
// second case : colon is the first token on line
var colonIsFirstTokenOnLine = !constructorInitializer.ColonToken.IsMissing && constructorInitializer.ColonToken.IsFirstTokenOnLine(text);
var thisOrBaseIsFirstTokenOnLine = !constructorInitializer.ThisOrBaseKeyword.IsMissing && constructorInitializer.ThisOrBaseKeyword.IsFirstTokenOnLine(text);
if (colonIsFirstTokenOnLine || thisOrBaseIsFirstTokenOnLine)
{
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(
constructorInitializer.ThisOrBaseKeyword,
constructorInitializer.ArgumentList.OpenParenToken.GetNextToken(includeZeroWidth: true),
constructorInitializer.ArgumentList.CloseParenToken.GetPreviousToken(includeZeroWidth: true),
indentationDelta: 1,
option: IndentBlockOption.RelativePosition));
}
else
{
// third case : none of them are the first token on the line
AddIndentBlockOperations(list, constructorInitializer.ArgumentList);
}
}
}
private static bool IsBracketedArgumentListMissingBrackets(BracketedArgumentListSyntax? node)
=> node != null && node.OpenBracketToken.IsMissing && node.CloseBracketToken.IsMissing;
private static void ReplaceCaseIndentationRules(List<IndentBlockOperation> list, SyntaxNode node)
{
if (!(node is SwitchSectionSyntax section) || section.Statements.Count == 0)
{
return;
}
var startToken = section.Statements.First().GetFirstToken(includeZeroWidth: true);
var endToken = section.Statements.Last().GetLastToken(includeZeroWidth: true);
for (var i = 0; i < list.Count; i++)
{
var operation = list[i];
if (operation.StartToken == startToken && operation.EndToken == endToken)
{
// replace operation
list[i] = FormattingOperations.CreateIndentBlockOperation(startToken, endToken, indentationDelta: 1, option: IndentBlockOption.RelativePosition);
}
}
}
private static void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node)
{
RoslynDebug.AssertNotNull(node.Parent);
// only add indent block operation if the base token is the first token on line
var baseToken = node.Parent.GetFirstToken(includeZeroWidth: true);
list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(
baseToken,
node.GetFirstToken(includeZeroWidth: true).GetNextToken(includeZeroWidth: true),
node.GetLastToken(includeZeroWidth: true).GetPreviousToken(includeZeroWidth: true),
indentationDelta: 1,
option: IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine));
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspace.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
/// <summary>
/// Workspace created by the remote host that mirrors the corresponding client workspace.
/// </summary>
internal sealed partial class RemoteWorkspace : Workspace
{
private readonly ISolutionCrawlerRegistrationService? _registrationService;
/// <summary>
/// Guards updates to <see cref="_primaryBranchSolutionWithChecksum"/> and <see cref="_lastRequestedSolutionWithChecksum"/>.
/// </summary>
private readonly SemaphoreSlim _availableSolutionsGate = new(initialCount: 1);
/// <summary>
/// The last solution for the the primary branch fetched from the client.
/// </summary>
private volatile Tuple<Checksum, Solution>? _primaryBranchSolutionWithChecksum;
/// <summary>
/// The last solution requested by a service.
/// </summary>
private volatile Tuple<Checksum, Solution>? _lastRequestedSolutionWithChecksum;
/// <summary>
/// The last partial solution snapshot corresponding to a particular project-cone requested by a service.
/// </summary>
private readonly ConcurrentDictionary<ProjectId, StrongBox<(Checksum checksum, Solution solution)>> _lastRequestedProjectIdToSolutionWithChecksum = new();
/// <summary>
/// Guards setting current workspace solution.
/// </summary>
private readonly object _currentSolutionGate = new();
/// <summary>
/// Used to make sure we never move remote workspace backward.
/// this version is the WorkspaceVersion of primary solution in client (VS) we are
/// currently caching.
/// </summary>
private int _currentRemoteWorkspaceVersion = -1;
// internal for testing purposes.
internal RemoteWorkspace(HostServices hostServices, string? workspaceKind)
: base(hostServices, workspaceKind)
{
var exportProvider = (IMefHostExportProvider)Services.HostServices;
RegisterDocumentOptionProviders(exportProvider.GetExports<IDocumentOptionsProviderFactory, OrderableMetadata>());
SetOptions(Options.WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0));
_registrationService = Services.GetService<ISolutionCrawlerRegistrationService>();
_registrationService?.Register(this);
}
protected override void Dispose(bool finalize)
{
base.Dispose(finalize);
_registrationService?.Unregister(this);
}
public AssetProvider CreateAssetProvider(PinnedSolutionInfo solutionInfo, SolutionAssetCache assetCache, IAssetSource assetSource)
{
var serializerService = Services.GetRequiredService<ISerializerService>();
return new AssetProvider(solutionInfo.ScopeId, assetCache, assetSource, serializerService);
}
public async Task UpdatePrimaryBranchSolutionAsync(AssetProvider assetProvider, Checksum solutionChecksum, int workspaceVersion, CancellationToken cancellationToken)
{
var currentSolution = CurrentSolution;
var currentSolutionChecksum = await currentSolution.State.GetChecksumAsync(cancellationToken).ConfigureAwait(false);
if (currentSolutionChecksum == solutionChecksum)
{
return;
}
using (await _availableSolutionsGate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
var solution = await CreateFullSolution_NoLockAsync(assetProvider, solutionChecksum, fromPrimaryBranch: true, workspaceVersion, currentSolution, cancellationToken).ConfigureAwait(false);
_primaryBranchSolutionWithChecksum = Tuple.Create(solutionChecksum, solution);
}
}
public ValueTask<Solution> GetSolutionAsync(
AssetProvider assetProvider,
Checksum solutionChecksum,
bool fromPrimaryBranch,
int workspaceVersion,
ProjectId? projectId,
CancellationToken cancellationToken)
{
return projectId == null
? GetFullSolutionAsync(assetProvider, solutionChecksum, fromPrimaryBranch, workspaceVersion, cancellationToken)
: GetProjectSubsetSolutionAsync(assetProvider, solutionChecksum, projectId, cancellationToken);
}
private async ValueTask<Solution> GetFullSolutionAsync(AssetProvider assetProvider, Checksum solutionChecksum, bool fromPrimaryBranch, int workspaceVersion, CancellationToken cancellationToken)
{
var availableSolution = TryGetAvailableSolution(solutionChecksum);
if (availableSolution != null)
return availableSolution;
// make sure there is always only one that creates a new solution
using (await _availableSolutionsGate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
availableSolution = TryGetAvailableSolution(solutionChecksum);
if (availableSolution != null)
return availableSolution;
var solution = await CreateFullSolution_NoLockAsync(
assetProvider,
solutionChecksum,
fromPrimaryBranch,
workspaceVersion,
CurrentSolution,
cancellationToken).ConfigureAwait(false);
_lastRequestedSolutionWithChecksum = new(solutionChecksum, solution);
return solution;
}
}
/// <summary>
/// The workspace is designed to be stateless. If someone asks for a solution (through solution checksum),
/// it will create one and return the solution. The engine takes care of syncing required data and creating a solution
/// corresponding to the given checksum.
///
/// but doing that from scratch all the time will be expansive in terms of syncing data, compilation being cached, file being parsed
/// and etc. so even if the service itself is stateless, internally it has several caches to improve perf of various parts.
///
/// first, it holds onto last solution got built. this will take care of common cases where multiple services running off same solution.
/// second, it uses assets cache to hold onto data just synched (within 3 min) so that if it requires to build new solution,
/// it can save some time to re-sync data which might just used by other solution.
/// third, it holds onto solution from primary branch from Host. and it will try to see whether it can build new solution off the
/// primary solution it is holding onto. this will make many solution level cache to be re-used.
///
/// the primary solution can be updated in 2 ways.
/// first, host will keep track of primary solution changes in host, and call OOP to synch to latest time to time.
/// second, engine keeps track of whether a certain request is for primary solution or not, and if it is,
/// it let that request to update primary solution cache to latest.
///
/// these 2 are complimentary to each other. #1 makes OOP's primary solution to be ready for next call (push), #2 makes OOP's primary
/// solution be not stale as much as possible. (pull)
/// </summary>
private async Task<Solution> CreateFullSolution_NoLockAsync(
AssetProvider assetProvider,
Checksum solutionChecksum,
bool fromPrimaryBranch,
int workspaceVersion,
Solution baseSolution,
CancellationToken cancellationToken)
{
try
{
var updater = new SolutionCreator(Services.HostServices, assetProvider, baseSolution, cancellationToken);
// check whether solution is update to the given base solution
if (await updater.IsIncrementalUpdateAsync(solutionChecksum).ConfigureAwait(false))
{
// create updated solution off the baseSolution
var solution = await updater.CreateSolutionAsync(solutionChecksum).ConfigureAwait(false);
if (fromPrimaryBranch)
{
// if the solutionChecksum is for primary branch, update primary workspace cache with the solution
return UpdateSolutionIfPossible(solution, workspaceVersion);
}
// otherwise, just return the solution
return solution;
}
// we need new solution. bulk sync all asset for the solution first.
await assetProvider.SynchronizeSolutionAssetsAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);
// get new solution info and options
var (solutionInfo, options) = await assetProvider.CreateSolutionInfoAndOptionsAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);
if (fromPrimaryBranch)
{
// if the solutionChecksum is for primary branch, update primary workspace cache with new solution
if (TrySetCurrentSolution(solutionInfo, workspaceVersion, options, out var solution))
{
return solution;
}
}
// otherwise, just return new solution
var workspace = new TemporaryWorkspace(Services.HostServices, WorkspaceKind.RemoteTemporaryWorkspace, solutionInfo, options);
return workspace.CurrentSolution;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private Solution? TryGetAvailableSolution(Checksum solutionChecksum)
{
var currentSolution = _primaryBranchSolutionWithChecksum;
if (currentSolution?.Item1 == solutionChecksum)
{
// asked about primary solution
return currentSolution.Item2;
}
var lastSolution = _lastRequestedSolutionWithChecksum;
if (lastSolution?.Item1 == solutionChecksum)
{
// asked about last solution
return lastSolution.Item2;
}
return null;
}
private ValueTask<Solution> GetProjectSubsetSolutionAsync(
AssetProvider assetProvider,
Checksum solutionChecksum,
ProjectId projectId,
CancellationToken cancellationToken)
{
// Attempt to just read without incurring any other costs.
if (_lastRequestedProjectIdToSolutionWithChecksum.TryGetValue(projectId, out var box) &&
box.Value.checksum == solutionChecksum)
{
return new(box.Value.Item2);
}
return GetProjectSubsetSolutionSlowAsync(box?.Value.solution ?? CurrentSolution, assetProvider, solutionChecksum, projectId, cancellationToken);
async ValueTask<Solution> GetProjectSubsetSolutionSlowAsync(
Solution baseSolution,
AssetProvider assetProvider,
Checksum solutionChecksum,
ProjectId projectId,
CancellationToken cancellationToken)
{
try
{
var updater = new SolutionCreator(Services.HostServices, assetProvider, baseSolution, cancellationToken);
// check whether solution is update to the given base solution
Solution result;
if (await updater.IsIncrementalUpdateAsync(solutionChecksum).ConfigureAwait(false))
{
// create updated solution off the baseSolution
result = await updater.CreateSolutionAsync(solutionChecksum).ConfigureAwait(false);
}
else
{
// we need new solution. bulk sync all asset for the solution first.
await assetProvider.SynchronizeSolutionAssetsAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);
// get new solution info and options
var (solutionInfo, options) = await assetProvider.CreateSolutionInfoAndOptionsAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);
var workspace = new TemporaryWorkspace(Services.HostServices, WorkspaceKind.RemoteTemporaryWorkspace, solutionInfo, options);
result = workspace.CurrentSolution;
}
// Cache the result of our computation. Note: this is simply a last caller wins strategy. However,
// in general this should be fine as we're primarily storing this to make future calls to synchronize
// this project cone fast.
_lastRequestedProjectIdToSolutionWithChecksum[projectId] = new((solutionChecksum, result));
return result;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
}
/// <summary>
/// Adds an entire solution to the workspace, replacing any existing solution.
/// </summary>
internal bool TrySetCurrentSolution(SolutionInfo solutionInfo, int workspaceVersion, SerializableOptionSet options, [NotNullWhen(true)] out Solution? solution)
{
lock (_currentSolutionGate)
{
if (workspaceVersion <= _currentRemoteWorkspaceVersion)
{
// we never move workspace backward
solution = null;
return false;
}
// set initial solution version
_currentRemoteWorkspaceVersion = workspaceVersion;
// clear previous solution data if there is one
// it is required by OnSolutionAdded
ClearSolutionData();
OnSolutionAdded(solutionInfo);
SetOptions(options);
solution = CurrentSolution;
return true;
}
}
/// <summary>
/// update primary solution
/// </summary>
internal Solution UpdateSolutionIfPossible(Solution solution, int workspaceVersion)
{
lock (_currentSolutionGate)
{
if (workspaceVersion <= _currentRemoteWorkspaceVersion)
{
// we never move workspace backward
return solution;
}
// move version forward
_currentRemoteWorkspaceVersion = workspaceVersion;
var oldSolution = CurrentSolution;
Contract.ThrowIfFalse(oldSolution.Id == solution.Id && oldSolution.FilePath == solution.FilePath);
var newSolution = SetCurrentSolution(solution);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionChanged, oldSolution, newSolution);
SetOptions(newSolution.Options);
return this.CurrentSolution;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
/// <summary>
/// Workspace created by the remote host that mirrors the corresponding client workspace.
/// </summary>
internal sealed partial class RemoteWorkspace : Workspace
{
private readonly ISolutionCrawlerRegistrationService? _registrationService;
/// <summary>
/// Guards updates to <see cref="_primaryBranchSolutionWithChecksum"/> and <see cref="_lastRequestedSolutionWithChecksum"/>.
/// </summary>
private readonly SemaphoreSlim _availableSolutionsGate = new(initialCount: 1);
/// <summary>
/// The last solution for the the primary branch fetched from the client.
/// </summary>
private volatile Tuple<Checksum, Solution>? _primaryBranchSolutionWithChecksum;
/// <summary>
/// The last solution requested by a service.
/// </summary>
private volatile Tuple<Checksum, Solution>? _lastRequestedSolutionWithChecksum;
/// <summary>
/// The last partial solution snapshot corresponding to a particular project-cone requested by a service.
/// </summary>
private readonly ConcurrentDictionary<ProjectId, StrongBox<(Checksum checksum, Solution solution)>> _lastRequestedProjectIdToSolutionWithChecksum = new();
/// <summary>
/// Guards setting current workspace solution.
/// </summary>
private readonly object _currentSolutionGate = new();
/// <summary>
/// Used to make sure we never move remote workspace backward.
/// this version is the WorkspaceVersion of primary solution in client (VS) we are
/// currently caching.
/// </summary>
private int _currentRemoteWorkspaceVersion = -1;
// internal for testing purposes.
internal RemoteWorkspace(HostServices hostServices, string? workspaceKind)
: base(hostServices, workspaceKind)
{
var exportProvider = (IMefHostExportProvider)Services.HostServices;
RegisterDocumentOptionProviders(exportProvider.GetExports<IDocumentOptionsProviderFactory, OrderableMetadata>());
SetOptions(Options.WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0));
_registrationService = Services.GetService<ISolutionCrawlerRegistrationService>();
_registrationService?.Register(this);
}
protected override void Dispose(bool finalize)
{
base.Dispose(finalize);
_registrationService?.Unregister(this);
}
public AssetProvider CreateAssetProvider(PinnedSolutionInfo solutionInfo, SolutionAssetCache assetCache, IAssetSource assetSource)
{
var serializerService = Services.GetRequiredService<ISerializerService>();
return new AssetProvider(solutionInfo.ScopeId, assetCache, assetSource, serializerService);
}
public async Task UpdatePrimaryBranchSolutionAsync(AssetProvider assetProvider, Checksum solutionChecksum, int workspaceVersion, CancellationToken cancellationToken)
{
var currentSolution = CurrentSolution;
var currentSolutionChecksum = await currentSolution.State.GetChecksumAsync(cancellationToken).ConfigureAwait(false);
if (currentSolutionChecksum == solutionChecksum)
{
return;
}
using (await _availableSolutionsGate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
var solution = await CreateFullSolution_NoLockAsync(assetProvider, solutionChecksum, fromPrimaryBranch: true, workspaceVersion, currentSolution, cancellationToken).ConfigureAwait(false);
_primaryBranchSolutionWithChecksum = Tuple.Create(solutionChecksum, solution);
}
}
public ValueTask<Solution> GetSolutionAsync(
AssetProvider assetProvider,
Checksum solutionChecksum,
bool fromPrimaryBranch,
int workspaceVersion,
ProjectId? projectId,
CancellationToken cancellationToken)
{
return projectId == null
? GetFullSolutionAsync(assetProvider, solutionChecksum, fromPrimaryBranch, workspaceVersion, cancellationToken)
: GetProjectSubsetSolutionAsync(assetProvider, solutionChecksum, projectId, cancellationToken);
}
private async ValueTask<Solution> GetFullSolutionAsync(AssetProvider assetProvider, Checksum solutionChecksum, bool fromPrimaryBranch, int workspaceVersion, CancellationToken cancellationToken)
{
var availableSolution = TryGetAvailableSolution(solutionChecksum);
if (availableSolution != null)
return availableSolution;
// make sure there is always only one that creates a new solution
using (await _availableSolutionsGate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
availableSolution = TryGetAvailableSolution(solutionChecksum);
if (availableSolution != null)
return availableSolution;
var solution = await CreateFullSolution_NoLockAsync(
assetProvider,
solutionChecksum,
fromPrimaryBranch,
workspaceVersion,
CurrentSolution,
cancellationToken).ConfigureAwait(false);
_lastRequestedSolutionWithChecksum = new(solutionChecksum, solution);
return solution;
}
}
/// <summary>
/// The workspace is designed to be stateless. If someone asks for a solution (through solution checksum),
/// it will create one and return the solution. The engine takes care of syncing required data and creating a solution
/// corresponding to the given checksum.
///
/// but doing that from scratch all the time will be expansive in terms of syncing data, compilation being cached, file being parsed
/// and etc. so even if the service itself is stateless, internally it has several caches to improve perf of various parts.
///
/// first, it holds onto last solution got built. this will take care of common cases where multiple services running off same solution.
/// second, it uses assets cache to hold onto data just synched (within 3 min) so that if it requires to build new solution,
/// it can save some time to re-sync data which might just used by other solution.
/// third, it holds onto solution from primary branch from Host. and it will try to see whether it can build new solution off the
/// primary solution it is holding onto. this will make many solution level cache to be re-used.
///
/// the primary solution can be updated in 2 ways.
/// first, host will keep track of primary solution changes in host, and call OOP to synch to latest time to time.
/// second, engine keeps track of whether a certain request is for primary solution or not, and if it is,
/// it let that request to update primary solution cache to latest.
///
/// these 2 are complimentary to each other. #1 makes OOP's primary solution to be ready for next call (push), #2 makes OOP's primary
/// solution be not stale as much as possible. (pull)
/// </summary>
private async Task<Solution> CreateFullSolution_NoLockAsync(
AssetProvider assetProvider,
Checksum solutionChecksum,
bool fromPrimaryBranch,
int workspaceVersion,
Solution baseSolution,
CancellationToken cancellationToken)
{
try
{
var updater = new SolutionCreator(Services.HostServices, assetProvider, baseSolution, cancellationToken);
// check whether solution is update to the given base solution
if (await updater.IsIncrementalUpdateAsync(solutionChecksum).ConfigureAwait(false))
{
// create updated solution off the baseSolution
var solution = await updater.CreateSolutionAsync(solutionChecksum).ConfigureAwait(false);
if (fromPrimaryBranch)
{
// if the solutionChecksum is for primary branch, update primary workspace cache with the solution
return UpdateSolutionIfPossible(solution, workspaceVersion);
}
// otherwise, just return the solution
return solution;
}
// we need new solution. bulk sync all asset for the solution first.
await assetProvider.SynchronizeSolutionAssetsAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);
// get new solution info and options
var (solutionInfo, options) = await assetProvider.CreateSolutionInfoAndOptionsAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);
if (fromPrimaryBranch)
{
// if the solutionChecksum is for primary branch, update primary workspace cache with new solution
if (TrySetCurrentSolution(solutionInfo, workspaceVersion, options, out var solution))
{
return solution;
}
}
// otherwise, just return new solution
var workspace = new TemporaryWorkspace(Services.HostServices, WorkspaceKind.RemoteTemporaryWorkspace, solutionInfo, options);
return workspace.CurrentSolution;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private Solution? TryGetAvailableSolution(Checksum solutionChecksum)
{
var currentSolution = _primaryBranchSolutionWithChecksum;
if (currentSolution?.Item1 == solutionChecksum)
{
// asked about primary solution
return currentSolution.Item2;
}
var lastSolution = _lastRequestedSolutionWithChecksum;
if (lastSolution?.Item1 == solutionChecksum)
{
// asked about last solution
return lastSolution.Item2;
}
return null;
}
private ValueTask<Solution> GetProjectSubsetSolutionAsync(
AssetProvider assetProvider,
Checksum solutionChecksum,
ProjectId projectId,
CancellationToken cancellationToken)
{
// Attempt to just read without incurring any other costs.
if (_lastRequestedProjectIdToSolutionWithChecksum.TryGetValue(projectId, out var box) &&
box.Value.checksum == solutionChecksum)
{
return new(box.Value.Item2);
}
return GetProjectSubsetSolutionSlowAsync(box?.Value.solution ?? CurrentSolution, assetProvider, solutionChecksum, projectId, cancellationToken);
async ValueTask<Solution> GetProjectSubsetSolutionSlowAsync(
Solution baseSolution,
AssetProvider assetProvider,
Checksum solutionChecksum,
ProjectId projectId,
CancellationToken cancellationToken)
{
try
{
var updater = new SolutionCreator(Services.HostServices, assetProvider, baseSolution, cancellationToken);
// check whether solution is update to the given base solution
Solution result;
if (await updater.IsIncrementalUpdateAsync(solutionChecksum).ConfigureAwait(false))
{
// create updated solution off the baseSolution
result = await updater.CreateSolutionAsync(solutionChecksum).ConfigureAwait(false);
}
else
{
// we need new solution. bulk sync all asset for the solution first.
await assetProvider.SynchronizeSolutionAssetsAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);
// get new solution info and options
var (solutionInfo, options) = await assetProvider.CreateSolutionInfoAndOptionsAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);
var workspace = new TemporaryWorkspace(Services.HostServices, WorkspaceKind.RemoteTemporaryWorkspace, solutionInfo, options);
result = workspace.CurrentSolution;
}
// Cache the result of our computation. Note: this is simply a last caller wins strategy. However,
// in general this should be fine as we're primarily storing this to make future calls to synchronize
// this project cone fast.
_lastRequestedProjectIdToSolutionWithChecksum[projectId] = new((solutionChecksum, result));
return result;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
}
/// <summary>
/// Adds an entire solution to the workspace, replacing any existing solution.
/// </summary>
internal bool TrySetCurrentSolution(SolutionInfo solutionInfo, int workspaceVersion, SerializableOptionSet options, [NotNullWhen(true)] out Solution? solution)
{
lock (_currentSolutionGate)
{
if (workspaceVersion <= _currentRemoteWorkspaceVersion)
{
// we never move workspace backward
solution = null;
return false;
}
// set initial solution version
_currentRemoteWorkspaceVersion = workspaceVersion;
// clear previous solution data if there is one
// it is required by OnSolutionAdded
ClearSolutionData();
OnSolutionAdded(solutionInfo);
SetOptions(options);
solution = CurrentSolution;
return true;
}
}
/// <summary>
/// update primary solution
/// </summary>
internal Solution UpdateSolutionIfPossible(Solution solution, int workspaceVersion)
{
lock (_currentSolutionGate)
{
if (workspaceVersion <= _currentRemoteWorkspaceVersion)
{
// we never move workspace backward
return solution;
}
// move version forward
_currentRemoteWorkspaceVersion = workspaceVersion;
var oldSolution = CurrentSolution;
Contract.ThrowIfFalse(oldSolution.Id == solution.Id && oldSolution.FilePath == solution.FilePath);
var newSolution = SetCurrentSolution(solution);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionChanged, oldSolution, newSolution);
SetOptions(newSolution.Options);
return this.CurrentSolution;
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Test/Semantic/Semantics/LocalFunctionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using System;
using System.Collections.Immutable;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class LocalFunctionsTestBase : CSharpTestBase
{
internal static readonly CSharpParseOptions DefaultParseOptions = TestOptions.Regular;
internal static void VerifyDiagnostics(string source, params DiagnosticDescription[] expected)
{
var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseDll, parseOptions: DefaultParseOptions);
comp.VerifyDiagnostics(expected);
}
}
[CompilerTrait(CompilerFeature.LocalFunctions)]
public class LocalFunctionTests : LocalFunctionsTestBase
{
[Fact, WorkItem(29656, "https://github.com/dotnet/roslyn/issues/29656")]
public void RefReturningAsyncLocalFunction()
{
var source = @"
public class C
{
async ref System.Threading.Tasks.Task M() { }
public void M2()
{
_ = local();
async ref System.Threading.Tasks.Task local() { }
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,11): error CS1073: Unexpected token 'ref'
// async ref System.Threading.Tasks.Task M() { }
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(4, 11),
// (4,43): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async ref System.Threading.Tasks.Task M() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 43),
// (10,15): error CS1073: Unexpected token 'ref'
// async ref System.Threading.Tasks.Task local() { }
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(10, 15),
// (10,47): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async ref System.Threading.Tasks.Task local() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "local").WithLocation(10, 47)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void LocalFunctionResetsLockScopeFlag()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
static void Main()
{
lock (new Object())
{
async Task localFunc()
{
Console.Write(""localFunc"");
await Task.Yield();
}
localFunc();
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "localFunc");
}
[ConditionalFact(typeof(DesktopOnly))]
public void LocalFunctionResetsTryCatchFinallyScopeFlags()
{
var source = @"
using System;
using System.Collections.Generic;
class C
{
static void Main()
{
try
{
IEnumerable<int> localFunc()
{
yield return 1;
}
foreach (int i in localFunc())
{
Console.Write(i);
}
throw new Exception();
}
catch (Exception)
{
IEnumerable<int> localFunc()
{
yield return 2;
}
foreach (int i in localFunc())
{
Console.Write(i);
}
}
finally
{
IEnumerable<int> localFunc()
{
yield return 3;
}
foreach (int i in localFunc())
{
Console.Write(i);
}
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "123");
}
[ConditionalFact(typeof(DesktopOnly))]
public void LocalFunctionDoesNotOverwriteInnerLockScopeFlag()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class C
{
void M(List<Task> listOfTasks)
{
lock (new Object())
{
async Task localFunc()
{
lock (new Object())
{
await Task.Yield();
}
}
listOfTasks.Add(localFunc());
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source);
comp.VerifyDiagnostics(
// (16,21): error CS1996: Cannot await in the body of a lock statement
// await Task.Yield();
Diagnostic(ErrorCode.ERR_BadAwaitInLock, "await Task.Yield()").WithLocation(16, 21));
}
[ConditionalFact(typeof(DesktopOnly))]
public void LocalFunctionDoesNotOverwriteInnerTryCatchFinallyScopeFlags()
{
var source = @"
using System;
using System.Collections.Generic;
class C
{
void M()
{
try
{
IEnumerable<int> localFunc()
{
try
{
yield return 1;
}
catch (Exception) {}
}
localFunc();
}
catch (Exception)
{
IEnumerable<int> localFunc()
{
try {}
catch (Exception)
{
yield return 2;
}
}
localFunc();
}
finally
{
IEnumerable<int> localFunc()
{
try {}
finally
{
yield return 3;
}
}
localFunc();
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source);
comp.VerifyDiagnostics(
// (15,21): error CS1626: Cannot yield a value in the body of a try block with a catch clause
// yield return 1;
Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield").WithLocation(15, 21),
// (29,21): error CS1631: Cannot yield a value in the body of a catch clause
// yield return 2;
Diagnostic(ErrorCode.ERR_BadYieldInCatch, "yield").WithLocation(29, 21),
// (42,21): error CS1625: Cannot yield in the body of a finally clause
// yield return 3;
Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield").WithLocation(42, 21));
}
[ConditionalFact(typeof(DesktopOnly))]
public void RethrowingExceptionsInCatchInsideLocalFuncIsAllowed()
{
var source = @"
using System;
class C
{
static void Main()
{
try
{
throw new Exception();
}
catch (Exception)
{
void localFunc()
{
try
{
throw new Exception();
}
catch (Exception)
{
Console.Write(""localFunc"");
throw;
}
}
try
{
localFunc();
}
catch (Exception)
{
Console.Write(""_thrown"");
}
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "localFunc_thrown");
}
[ConditionalFact(typeof(DesktopOnly))]
public void RethrowingExceptionsInLocalFuncInsideCatchIsNotAllowed()
{
var source = @"
using System;
class C
{
static void Main()
{
try {}
catch (Exception)
{
void localFunc()
{
throw;
}
localFunc();
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source);
comp.VerifyDiagnostics(
// (13,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause
// throw;
Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(13, 17));
}
[Fact]
public void LocalFunctionTypeParametersUseCorrectBinder()
{
var text = @"
class C
{
static void M()
{
void local<[X]T>() {}
}
}";
var tree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Regular9);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree, ignoreAccessibility: true);
var newTree = SyntaxFactory.ParseSyntaxTree(text + " ");
var m = newTree.GetRoot()
.DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(m.Body.SpanStart, m, out model));
var x = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Single();
Assert.Equal("X", x.Identifier.Text);
// If we aren't using the right binder here, the compiler crashes going through the binder factory
var info = model.GetSymbolInfo(x);
Assert.Null(info.Symbol);
comp.VerifyDiagnostics(
// (6,21): error CS0246: The type or namespace name 'XAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void local<[X]T>() {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("XAttribute").WithLocation(6, 21),
// (6,21): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?)
// void local<[X]T>() {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 21),
// (6,14): warning CS8321: The local function 'local' is declared but never used
// void local<[X]T>() {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(6, 14));
}
[Theory]
[InlineData("[A] void local() { }")]
[InlineData("[return: A] void local() { }")]
[InlineData("void local([A] int i) { }")]
[InlineData("void local<[A]T>() {}")]
[InlineData("[A] int x = 123;")]
public void LocalFunctionAttribute_SpeculativeSemanticModel(string statement)
{
string text = $@"
using System;
class A : Attribute {{}}
class C
{{
static void M()
{{
{statement}
}}
}}";
var tree = SyntaxFactory.ParseSyntaxTree(text);
var comp = (Compilation)CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var a = tree.GetRoot().DescendantNodes()
.OfType<IdentifierNameSyntax>().ElementAt(2);
Assert.Equal("A", a.Identifier.Text);
var attrInfo = model.GetSymbolInfo(a);
var attrType = comp.GlobalNamespace.GetTypeMember("A");
var attrCtor = attrType.GetMember(".ctor");
Assert.Equal(attrCtor, attrInfo.Symbol);
// Assert that this is also true for the speculative semantic model
var newTree = SyntaxFactory.ParseSyntaxTree(text + " ");
var m = newTree.GetRoot()
.DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(m.Body.SpanStart, m, out model));
a = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().ElementAt(2);
Assert.Equal("A", a.Identifier.Text);
// If we aren't using the right binder here, the compiler crashes going through the binder factory
var info = model.GetSymbolInfo(a);
// This behavior is wrong. See https://github.com/dotnet/roslyn/issues/24135
Assert.Equal(attrType, info.Symbol);
}
[Theory]
[InlineData(@"[Attr(42, Name = ""hello"")] void local() { }")]
[InlineData(@"[return: Attr(42, Name = ""hello"")] void local() { }")]
[InlineData(@"void local([Attr(42, Name = ""hello"")] int i) { }")]
[InlineData(@"void local<[Attr(42, Name = ""hello"")]T>() {}")]
[InlineData(@"[Attr(42, Name = ""hello"")] int x = 123;")]
public void LocalFunctionAttribute_Argument_SemanticModel(string statement)
{
var text = $@"
class Attr
{{
public Attr(int id) {{ }}
public string Name {{ get; set; }}
}}
class C
{{
static void M()
{{
{statement}
}}
}}";
var tree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Regular9);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree, ignoreAccessibility: true);
validate(model, tree);
var newTree = SyntaxFactory.ParseSyntaxTree(text + " ", options: TestOptions.Regular9);
var mMethod = (MethodDeclarationSyntax)newTree.FindNodeOrTokenByKind(SyntaxKind.MethodDeclaration, occurrence: 1).AsNode();
Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(mMethod.Body.SpanStart, mMethod, out var newModel));
validate(newModel, newTree);
static void validate(SemanticModel model, SyntaxTree tree)
{
var attributeSyntax = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single();
var attrArgs = attributeSyntax.ArgumentList.Arguments;
var attrArg0 = attrArgs[0].Expression;
Assert.Null(model.GetSymbolInfo(attrArg0).Symbol);
var argType0 = model.GetTypeInfo(attrArg0).Type;
Assert.Equal(SpecialType.System_Int32, argType0.SpecialType);
var attrArg1 = attrArgs[1].Expression;
Assert.Null(model.GetSymbolInfo(attrArg1).Symbol);
var argType1 = model.GetTypeInfo(attrArg1).Type;
Assert.Equal(SpecialType.System_String, argType1.SpecialType);
}
}
[Fact]
public void LocalFunctionAttribute_OnFunction()
{
const string text = @"
using System;
class A : Attribute { }
class C
{
void M()
{
[A]
void local() { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,14): warning CS8321: The local function 'local' is declared but never used
// void local() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(10, 14));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var localFunction = tree.GetRoot().DescendantNodes()
.OfType<LocalFunctionStatementSyntax>()
.Single();
var attributeList = localFunction.AttributeLists.Single();
Assert.Null(attributeList.Target);
var attribute = attributeList.Attributes.Single();
Assert.Equal("A", ((SimpleNameSyntax)attribute.Name).Identifier.ValueText);
var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction);
Assert.NotNull(symbol);
var attributes = symbol.GetAttributes().As<CSharpAttributeData>();
Assert.Equal(new[] { "A" }, GetAttributeNames(attributes));
var returnAttributes = symbol.GetReturnTypeAttributes();
Assert.Empty(returnAttributes);
}
[Fact]
public void LocalFunctionAttribute_OnFunction_Argument()
{
const string text = @"
using System;
class A : Attribute
{
internal A(int i) { }
}
class C
{
void M()
{
[A(42)]
void local() { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (13,14): warning CS8321: The local function 'local' is declared but never used
// void local() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(13, 14));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var localFunction = tree.GetRoot().DescendantNodes()
.OfType<LocalFunctionStatementSyntax>()
.Single();
var attributeList = localFunction.AttributeLists.Single();
Assert.Null(attributeList.Target);
var attribute = attributeList.Attributes.Single();
Assert.Equal("A", ((SimpleNameSyntax)attribute.Name).Identifier.ValueText);
var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction);
Assert.NotNull(symbol);
var attributes = symbol.GetAttributes();
var attributeData = attributes.Single();
var aAttribute = comp.GetTypeByMetadataName("A");
Assert.Equal(aAttribute, attributeData.AttributeClass.GetSymbol());
Assert.Equal(aAttribute.InstanceConstructors.Single(), attributeData.AttributeConstructor.GetSymbol());
Assert.Equal(42, attributeData.ConstructorArguments.Single().Value);
var returnAttributes = symbol.GetReturnTypeAttributes();
Assert.Empty(returnAttributes);
}
[Fact]
public void LocalFunctionAttribute_OnFunction_LocalArgument()
{
const string text = @"
using System;
class A : Attribute
{
internal A(string s) { }
}
class C
{
void M()
{
#pragma warning disable 0219 // Unreferenced local variable
string s1 = ""hello"";
const string s2 = ""world"";
#pragma warning disable 8321 // Unreferenced local function
[A(s1)] // 1
void local1() { }
[A(nameof(s1))]
void local2() { }
[A(s2)]
void local3() { }
[A(s1.ToString())] // 2
void local4() { }
static string local5() => ""hello"";
[A(local5())] // 3
void local6() { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (17,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(s1)] // 1
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "s1").WithLocation(17, 12),
// (26,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(s1.ToString())] // 2
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "s1.ToString()").WithLocation(26, 12),
// (31,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(local5())] // 3
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "local5()").WithLocation(31, 12));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var arg1 = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 1).AsNode();
Assert.Equal("System.String s1", model.GetSymbolInfo(arg1.Expression).Symbol.ToTestDisplayString());
Assert.Equal(SpecialType.System_String, model.GetTypeInfo(arg1.Expression).Type.SpecialType);
var arg2 = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 2).AsNode();
Assert.Null(model.GetSymbolInfo(arg2.Expression).Symbol);
Assert.Equal(SpecialType.System_String, model.GetTypeInfo(arg2.Expression).Type.SpecialType);
var arg3 = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 3).AsNode();
Assert.Equal("System.String s2", model.GetSymbolInfo(arg3.Expression).Symbol.ToTestDisplayString());
Assert.Equal(SpecialType.System_String, model.GetTypeInfo(arg3.Expression).Type.SpecialType);
}
[Fact]
public void LocalFunctionAttribute_OnFunction_DeclarationPattern()
{
const string text = @"
using System;
class A : Attribute
{
internal A(bool b) { }
}
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[A(42 is int i)] // 1
void local1()
{
_ = i.ToString(); // 2
}
_ = i.ToString(); // 3
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (13,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(42 is int i)] // 1
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "42 is int i").WithLocation(13, 12),
// (16,17): error CS0103: The name 'i' does not exist in the current context
// _ = i.ToString(); // 2
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(16, 17),
// (19,13): error CS0103: The name 'i' does not exist in the current context
// _ = i.ToString(); // 3
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(19, 13));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var arg = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 1).AsNode();
Assert.Null(model.GetSymbolInfo(arg.Expression).Symbol);
Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(arg.Expression).Type.SpecialType);
var decl = (DeclarationPatternSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.DeclarationPattern, occurrence: 1).AsNode();
Assert.Equal("System.Int32 i", model.GetDeclaredSymbol(decl.Designation).ToTestDisplayString());
}
[Fact]
public void LocalFunctionAttribute_OnFunction_OutVarInCall()
{
const string text = @"
using System;
class A : Attribute
{
internal A(bool b) { }
}
class C
{
void M1()
{
#pragma warning disable 8321 // Unreferenced local function
[A(M2(out var i))] // 1
void local1()
{
_ = i.ToString(); // 2
}
_ = i.ToString(); // 3
}
static bool M2(out int x)
{
x = 0;
return false;
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (13,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(M2(out var i))] // 1
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "M2(out var i)").WithLocation(13, 12),
// (16,17): error CS0103: The name 'i' does not exist in the current context
// _ = i.ToString(); // 2
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(16, 17),
// (19,13): error CS0103: The name 'i' does not exist in the current context
// _ = i.ToString(); // 3
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(19, 13));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var arg = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 1).AsNode();
Assert.Equal("System.Boolean C.M2(out System.Int32 x)", model.GetSymbolInfo(arg.Expression).Symbol.ToTestDisplayString());
Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(arg.Expression).Type.SpecialType);
var decl = (DeclarationExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.DeclarationExpression, occurrence: 1).AsNode();
Assert.Equal("System.Int32 i", model.GetDeclaredSymbol(decl.Designation).ToTestDisplayString());
}
[Fact]
public void LocalFunctionAttribute_OutParam()
{
const string text = @"
using System;
class A : Attribute
{
internal A(out string s) { s = ""a""; }
}
class C
{
void M()
{
#pragma warning disable 8321, 0168 // Unreferenced local
string s;
[A(out s)]
void local1() { }
[A(out var s)]
void local2() { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (15,12): error CS1041: Identifier expected; 'out' is a keyword
// [A(out s)]
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(15, 12),
// (15,16): error CS1620: Argument 1 must be passed with the 'out' keyword
// [A(out s)]
Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(15, 16),
// (18,10): error CS1729: 'A' does not contain a constructor that takes 2 arguments
// [A(out var s)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "A(out var s)").WithArguments("A", "2").WithLocation(18, 10),
// (18,12): error CS1041: Identifier expected; 'out' is a keyword
// [A(out var s)]
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(18, 12),
// (18,16): error CS0103: The name 'var' does not exist in the current context
// [A(out var s)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(18, 16),
// (18,20): error CS1003: Syntax error, ',' expected
// [A(out var s)]
Diagnostic(ErrorCode.ERR_SyntaxError, "s").WithArguments(",", "").WithLocation(18, 20));
}
[Fact]
public void LocalFunctionAttribute_Return()
{
const string text = @"
using System;
class A : Attribute { }
class C
{
void M()
{
[return: A]
int local() => 42;
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,13): warning CS8321: The local function 'local' is declared but never used
// int local() => 42;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(10, 13));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var localFunction = tree.GetRoot().DescendantNodes()
.OfType<LocalFunctionStatementSyntax>()
.Single();
var attributeList = localFunction.AttributeLists.Single();
Assert.Equal(SyntaxKind.ReturnKeyword, attributeList.Target.Identifier.Kind());
var attribute = attributeList.Attributes.Single();
Assert.Equal("A", ((SimpleNameSyntax)attribute.Name).Identifier.ValueText);
var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction);
Assert.NotNull(symbol);
var returnAttributes = symbol.GetReturnTypeAttributes();
var attributeData = returnAttributes.Single();
var aAttribute = comp.GetTypeByMetadataName("A");
Assert.Equal(aAttribute, attributeData.AttributeClass.GetSymbol());
Assert.Equal(aAttribute.InstanceConstructors.Single(), attributeData.AttributeConstructor.GetSymbol());
var attributes = symbol.GetAttributes();
Assert.Empty(attributes);
}
[Fact]
public void LocalFunctionAttribute_Parameter()
{
var source = @"
using System;
class A : Attribute { }
class C
{
void M()
{
int local([A] int i) => i;
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (9,13): warning CS8321: The local function 'local' is declared but never used
// int local([A] int i) => i;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(9, 13));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var localFunction = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single();
var parameter = localFunction.ParameterList.Parameters.Single();
var paramSymbol = model.GetDeclaredSymbol(parameter);
var attrs = paramSymbol.GetAttributes();
var attr = attrs.Single();
Assert.Equal(comp.GetTypeByMetadataName("A"), attr.AttributeClass.GetSymbol());
}
[Fact]
public void LocalFunctionAttribute_LangVersionError()
{
const string text = @"
using System;
class A : Attribute { }
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[A]
void local1() { }
[return: A]
void local2() { }
void local3([A] int i) { }
void local4<[A] T>() { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (10,9): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater.
// [A]
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[A]").WithArguments("local function attributes", "9.0").WithLocation(10, 9),
// (13,9): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater.
// [return: A]
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[return: A]").WithArguments("local function attributes", "9.0").WithLocation(13, 9),
// (16,21): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater.
// void local3([A] int i) { }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[A]").WithArguments("local function attributes", "9.0").WithLocation(16, 21),
// (18,21): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater.
// void local4<[A] T>() { }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[A]").WithArguments("local function attributes", "9.0").WithLocation(18, 21));
comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void LocalFunctionAttribute_BadAttributeLocation()
{
const string text = @"
using System;
[AttributeUsage(AttributeTargets.Property)]
class PropAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
class MethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.ReturnValue)]
class ReturnAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter)]
class ParamAttribute : Attribute { }
[AttributeUsage(AttributeTargets.GenericParameter)]
class TypeParamAttribute : Attribute { }
public class C {
public void M() {
#pragma warning disable 8321 // Unreferenced local function
[Prop] // 1
[Return] // 2
[Method]
[return: Prop] // 3
[return: Return]
[return: Method] // 4
void local<
[Param] // 5
[TypeParam]
T>(
[Param]
[TypeParam] // 6
T t) { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (22,10): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations.
// [Prop] // 1
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(22, 10),
// (23,10): error CS0592: Attribute 'Return' is not valid on this declaration type. It is only valid on 'return' declarations.
// [Return] // 2
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Return").WithArguments("Return", "return").WithLocation(23, 10),
// (25,18): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations.
// [return: Prop] // 3
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(25, 18),
// (27,18): error CS0592: Attribute 'Method' is not valid on this declaration type. It is only valid on 'method' declarations.
// [return: Method] // 4
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Method").WithArguments("Method", "method").WithLocation(27, 18),
// (29,14): error CS0592: Attribute 'Param' is not valid on this declaration type. It is only valid on 'parameter' declarations.
// [Param] // 5
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Param").WithArguments("Param", "parameter").WithLocation(29, 14),
// (33,14): error CS0592: Attribute 'TypeParam' is not valid on this declaration type. It is only valid on 'type parameter' declarations.
// [TypeParam] // 6
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "TypeParam").WithArguments("TypeParam", "type parameter").WithLocation(33, 14));
var tree = comp.SyntaxTrees.Single();
var localFunction = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single();
var model = comp.GetSemanticModel(tree);
var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction);
Assert.NotNull(symbol);
var attributes = symbol.GetAttributes();
Assert.Equal(3, attributes.Length);
Assert.Equal(comp.GetTypeByMetadataName("PropAttribute"), attributes[0].AttributeClass.GetSymbol());
Assert.Equal(comp.GetTypeByMetadataName("ReturnAttribute"), attributes[1].AttributeClass.GetSymbol());
Assert.Equal(comp.GetTypeByMetadataName("MethodAttribute"), attributes[2].AttributeClass.GetSymbol());
var returnAttributes = symbol.GetReturnTypeAttributes();
Assert.Equal(3, returnAttributes.Length);
Assert.Equal(comp.GetTypeByMetadataName("PropAttribute"), returnAttributes[0].AttributeClass.GetSymbol());
Assert.Equal(comp.GetTypeByMetadataName("ReturnAttribute"), returnAttributes[1].AttributeClass.GetSymbol());
Assert.Equal(comp.GetTypeByMetadataName("MethodAttribute"), returnAttributes[2].AttributeClass.GetSymbol());
}
[Fact]
public void LocalFunctionAttribute_AttributeSemanticModel()
{
const string text = @"
using System;
class A : Attribute { }
class C
{
void M()
{
local1();
local2();
local3(0);
local4<object>();
[A]
void local1() { }
[return: A]
void local2() { }
void local3([A] int i) { }
void local4<[A] T>() { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var attributeSyntaxes = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().ToList();
Assert.Equal(4, attributeSyntaxes.Count);
var attributeConstructor = comp.GetTypeByMetadataName("A").InstanceConstructors.Single();
foreach (var attributeSyntax in attributeSyntaxes)
{
var symbol = model.GetSymbolInfo(attributeSyntax).Symbol.GetSymbol<MethodSymbol>();
Assert.Equal(attributeConstructor, symbol);
}
}
[Fact]
public void StatementAttributeSemanticModel()
{
const string text = @"
using System;
class A : Attribute { }
class C
{
void M()
{
#pragma warning disable 219 // The variable '{0}' is assigned but its value is never used
[A] int i = 0;
}
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (11,9): error CS7014: Attributes are not valid in this context.
// [A] int i = 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(11, 9));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var attrSyntax = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single();
var attrConstructor = (IMethodSymbol)model.GetSymbolInfo(attrSyntax).Symbol;
Assert.Equal(MethodKind.Constructor, attrConstructor.MethodKind);
Assert.Equal("A", attrConstructor.ContainingType.Name);
}
[Fact]
public void LocalFunctionNoBody()
{
const string text = @"
class C
{
void M()
{
local1();
void local1();
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (8,14): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'.
// void local1();
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(8, 14));
}
[Fact]
public void LocalFunctionExtern()
{
const string text = @"
using System.Runtime.InteropServices;
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[DllImport(""a"")] extern void local1(); // 1, 2
[DllImport(""a"")] extern void local2() { } // 3, 4
[DllImport(""a"")] extern int local3() => 0; // 5, 6
static void local4(); // 7
static void local5() { }
static int local6() => 0;
[DllImport(""a"")] static extern void local7();
[DllImport(""a"")] static extern void local8() { } // 8
[DllImport(""a"")] static extern int local9() => 0; // 9
[DllImport(""a"")] extern static void local10();
[DllImport(""a"")] extern static void local11() { } // 10
[DllImport(""a"")] extern static int local12() => 0; // 11
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern'
// [DllImport("a")] extern void local1(); // 1, 2
Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(10, 10),
// (10,38): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'.
// [DllImport("a")] extern void local1(); // 1, 2
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(10, 38),
// (11,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern'
// [DllImport("a")] extern void local2() { } // 3, 4
Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(11, 10),
// (11,38): error CS0179: 'local2()' cannot be extern and declare a body
// [DllImport("a")] extern void local2() { } // 3, 4
Diagnostic(ErrorCode.ERR_ExternHasBody, "local2").WithArguments("local2()").WithLocation(11, 38),
// (12,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern'
// [DllImport("a")] extern int local3() => 0; // 5, 6
Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(12, 10),
// (12,37): error CS0179: 'local3()' cannot be extern and declare a body
// [DllImport("a")] extern int local3() => 0; // 5, 6
Diagnostic(ErrorCode.ERR_ExternHasBody, "local3").WithArguments("local3()").WithLocation(12, 37),
// (14,21): error CS8112: Local function 'local4()' must either have a body or be marked 'static extern'.
// static void local4(); // 7
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local4").WithArguments("local4()").WithLocation(14, 21),
// (19,45): error CS0179: 'local8()' cannot be extern and declare a body
// [DllImport("a")] static extern void local8() { } // 8
Diagnostic(ErrorCode.ERR_ExternHasBody, "local8").WithArguments("local8()").WithLocation(19, 45),
// (20,44): error CS0179: 'local9()' cannot be extern and declare a body
// [DllImport("a")] static extern int local9() => 0; // 9
Diagnostic(ErrorCode.ERR_ExternHasBody, "local9").WithArguments("local9()").WithLocation(20, 44),
// (23,45): error CS0179: 'local11()' cannot be extern and declare a body
// [DllImport("a")] extern static void local11() { } // 10
Diagnostic(ErrorCode.ERR_ExternHasBody, "local11").WithArguments("local11()").WithLocation(23, 45),
// (24,44): error CS0179: 'local12()' cannot be extern and declare a body
// [DllImport("a")] extern static int local12() => 0; // 11
Diagnostic(ErrorCode.ERR_ExternHasBody, "local12").WithArguments("local12()").WithLocation(24, 44));
}
[Fact]
public void LocalFunctionExtern_Generic()
{
var source = @"
using System;
using System.Runtime.InteropServices;
class C
{
#pragma warning disable 8321 // Unreferenced local function
void M()
{
[DllImport(""a"")] extern static void local1();
[DllImport(""a"")] extern static void local2<T>(); // 1
void local3()
{
[DllImport(""a"")] extern static void local1();
[DllImport(""a"")] extern static void local2<T2>(); // 2
}
void local4<T4>()
{
[DllImport(""a"")] extern static void local1(); // 3
[DllImport(""a"")] extern static void local2<T2>(); // 4
}
Action a = () =>
{
[DllImport(""a"")] extern static void local1();
[DllImport(""a"")] extern static void local2<T>(); // 5
void local3()
{
[DllImport(""a"")] extern static void local1();
[DllImport(""a"")] extern static void local2<T2>(); // 6
}
void local4<T4>()
{
[DllImport(""a"")] extern static void local1(); // 7
[DllImport(""a"")] extern static void local2<T2>(); // 8
}
};
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (12,10): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T>(); // 1
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(12, 10),
// (17,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 2
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(17, 14),
// (22,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 3
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(22, 14),
// (23,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 4
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(23, 14),
// (29,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T>(); // 5
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(29, 14),
// (34,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 6
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(34, 18),
// (39,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 7
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(39, 18),
// (40,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 8
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(40, 18));
}
[Theory]
[InlineData("<CT>", "", "")]
[InlineData("", "<MT>", "")]
[InlineData("", "", "<LT>")]
public void LocalFunctionExtern_Generic_GenericMembers(string classTypeParams, string methodTypeParams, string localFunctionTypeParams)
{
var source = $@"
using System;
using System.Runtime.InteropServices;
class C{classTypeParams}
{{
#pragma warning disable 8321 // Unreferenced local function
void M{methodTypeParams}()
{{
void localOuter{localFunctionTypeParams}()
{{
[DllImport(""a"")] extern static void local1(); // 1
[DllImport(""a"")] extern static void local2<T>(); // 2
void local3()
{{
[DllImport(""a"")] extern static void local1(); // 3
[DllImport(""a"")] extern static void local2<T2>(); // 4
}}
void local4<T4>()
{{
[DllImport(""a"")] extern static void local1(); // 5
[DllImport(""a"")] extern static void local2<T2>(); // 6
}}
Action a = () =>
{{
[DllImport(""a"")] extern static void local1(); // 7
[DllImport(""a"")] extern static void local2<T>(); // 8
void local3()
{{
[DllImport(""a"")] extern static void local1(); // 9
[DllImport(""a"")] extern static void local2<T2>(); // 10
}}
void local4<T4>()
{{
[DllImport(""a"")] extern static void local1(); // 11
[DllImport(""a"")] extern static void local2<T2>(); // 12
}}
}};
}}
}}
}}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (13,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 1
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(13, 14),
// (14,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T>(); // 2
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(14, 14),
// (18,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 3
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(18, 18),
// (19,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 4
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(19, 18),
// (24,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 5
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(24, 18),
// (25,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 6
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(25, 18),
// (30,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 7
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(30, 18),
// (31,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T>(); // 8
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(31, 18),
// (35,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 9
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(35, 22),
// (36,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 10
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(36, 22),
// (41,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 11
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(41, 22),
// (42,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 12
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(42, 22));
}
[Fact]
public void LocalFunctionExtern_NoImplementationWarning_Attribute()
{
const string text = @"
using System.Runtime.InteropServices;
class Attr : System.Attribute { }
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
static extern void local1(); // 1
static extern void local2() { } // 2
[DllImport(""a"")]
static extern void local3();
[Attr]
static extern void local4();
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (12,28): warning CS0626: Method, operator, or accessor 'local1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation.
// static extern void local1(); // 1
Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "local1").WithArguments("local1()").WithLocation(12, 28),
// (13,28): error CS0179: 'local2()' cannot be extern and declare a body
// static extern void local2() { } // 2
Diagnostic(ErrorCode.ERR_ExternHasBody, "local2").WithArguments("local2()").WithLocation(13, 28));
}
[Fact]
public void LocalFunctionExtern_Errors()
{
const string text = @"
class C
{
#pragma warning disable 8321 // Unreferenced local function
void M1()
{
void local1(); // 1
static extern void local1(); // 2, 3
}
void M2()
{
void local1(); // 4
static extern void local1() { } // 5
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (8,14): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'.
// void local1(); // 1
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(8, 14),
// (9,28): error CS0128: A local variable or function named 'local1' is already defined in this scope
// static extern void local1(); // 2, 3
Diagnostic(ErrorCode.ERR_LocalDuplicate, "local1").WithArguments("local1").WithLocation(9, 28),
// (9,28): warning CS0626: Method, operator, or accessor 'local1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation.
// static extern void local1(); // 2, 3
Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "local1").WithArguments("local1()").WithLocation(9, 28),
// (14,14): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'.
// void local1(); // 4
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(14, 14),
// (15,28): error CS0128: A local variable or function named 'local1' is already defined in this scope
// static extern void local1() { } // 5
Diagnostic(ErrorCode.ERR_LocalDuplicate, "local1").WithArguments("local1").WithLocation(15, 28));
}
[Fact]
public void ComImport_Class()
{
const string text = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""00020813-0000-0000-c000-000000000046"")]
class C
{
void M() // 1
{
#pragma warning disable 8321 // Unreferenced local function
void local1() { }
}
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (8,10): error CS0423: Since 'C' has the ComImport attribute, 'C.M()' must be extern or abstract
// void M() // 1
Diagnostic(ErrorCode.ERR_ComImportWithImpl, "M").WithArguments("C.M()", "C").WithLocation(8, 10));
}
[Fact]
public void UnsafeLocal()
{
var source = @"
class C
{
void M()
{
var bytesA = local();
unsafe byte[] local()
{
var bytes = new byte[sizeof(int)];
fixed (byte* ptr = &bytes[0])
{
*(int*)ptr = sizeof(int);
}
return bytes;
}
}
}";
var comp = CreateCompilation(source);
Assert.Empty(comp.GetDeclarationDiagnostics());
comp.VerifyDiagnostics(
// (8,23): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe byte[] local()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "local").WithLocation(8, 23)
);
var compWithUnsafe = CreateCompilation(source, options: TestOptions.UnsafeDebugDll);
compWithUnsafe.VerifyDiagnostics();
}
[Fact]
public void LocalInUnsafeStruct()
{
var source = @"
unsafe struct C
{
void A()
{
var bytesA = local();
var bytesB = B();
byte[] local()
{
var bytes = new byte[sizeof(int)];
fixed (byte* ptr = &bytes[0])
{
*(int*)ptr = sizeof(int);
}
return bytes;
}
}
byte[] B()
{
var bytes = new byte[sizeof(long)];
fixed (byte* ptr = &bytes[0])
{
*(long*)ptr = sizeof(long);
}
return bytes;
}
}";
// no need to declare local function `local` or method `B` as unsafe
var compWithUnsafe = CreateCompilation(source, options: TestOptions.UnsafeDebugDll);
compWithUnsafe.VerifyDiagnostics();
}
[Fact]
public void LocalInUnsafeBlock()
{
var source = @"
struct C
{
void A()
{
unsafe
{
var bytesA = local();
byte[] local()
{
var bytes = new byte[sizeof(int)];
fixed (byte* ptr = &bytes[0])
{
*(int*)ptr = sizeof(int);
}
return bytes;
}
}
}
}";
// no need to declare local function `local` as unsafe
var compWithUnsafe = CreateCompilation(source, options: TestOptions.UnsafeDebugDll);
compWithUnsafe.VerifyDiagnostics();
}
[Fact]
public void ConstraintBinding()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
void Local<T, U>()
where T : U
where U : class
{ }
Local<object, object>();
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void ConstraintBinding2()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
void Local<T, U>(T t)
where T : U
where U : t
{ }
Local<object, object>(null);
}
}");
comp.VerifyDiagnostics(
// (8,23): error CS0246: The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?)
// where U : t
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "t").WithArguments("t").WithLocation(8, 23),
// (11,9): error CS0311: The type 'object' cannot be used as type parameter 'U' in the generic type or method 'Local<T, U>(T)'. There is no implicit reference conversion from 'object' to 't'.
// Local<object, object>(null);
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Local<object, object>").WithArguments("Local<T, U>(T)", "t", "U", "object").WithLocation(11, 9));
}
[Fact]
[WorkItem(17014, "https://github.com/dotnet/roslyn/pull/17014")]
public void RecursiveLocalFuncsAsParameterTypes()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
int L(L2 l2) => 0;
int L2(L l1) => 0;
}
}");
comp.VerifyDiagnostics(
// (6,15): error CS0246: The type or namespace name 'L2' could not be found (are you missing a using directive or an assembly reference?)
// int L(L2 l2) => 0;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L2").WithArguments("L2").WithLocation(6, 15),
// (7,16): error CS0246: The type or namespace name 'L' could not be found (are you missing a using directive or an assembly reference?)
// int L2(L l1) => 0;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L").WithArguments("L").WithLocation(7, 16),
// (6,13): warning CS8321: The local function 'L' is declared but never used
// int L(L2 l2) => 0;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L").WithArguments("L").WithLocation(6, 13),
// (7,13): warning CS8321: The local function 'L2' is declared but never used
// int L2(L l1) => 0;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L2").WithArguments("L2").WithLocation(7, 13));
}
[Fact]
[WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")]
public void BadGenericConstraint()
{
var comp = CreateCompilation(@"
class C
{
public void M<T>(T value) where T : class, object { }
}");
comp.VerifyDiagnostics(
// (4,48): error CS0702: Constraint cannot be special class 'object'
// public void M<T>(T value) where T : class, object { }
Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object").WithArguments("object").WithLocation(4, 48)
);
}
[Fact]
[WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")]
public void RecursiveDefaultParameter()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int Local(int j = Local()) => 0;
Local();
}
}");
comp.VerifyDiagnostics(
// (6,27): error CS1736: Default parameter value for 'j' must be a compile-time constant
// int Local(int j = Local()) => 0;
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local()").WithArguments("j").WithLocation(6, 27));
comp.DeclarationDiagnostics.Verify();
}
[Fact]
[WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")]
public void RecursiveDefaultParameter2()
{
var comp = CreateCompilation(@"
using System;
class C
{
void M()
{
int Local(Action a = Local) => 0;
Local();
}
}");
comp.VerifyDiagnostics(
// (7,30): error CS1736: Default parameter value for 'a' must be a compile-time constant
// int Local(Action a = Local) => 0;
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local").WithArguments("a").WithLocation(7, 30));
comp.DeclarationDiagnostics.Verify();
}
[Fact]
[WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")]
public void MutuallyRecursiveDefaultParameters()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
int Local1(int p = Local2()) => 0;
int Local2(int p = Local1()) => 0;
Local1();
Local2();
}
}");
comp.VerifyDiagnostics(
// (6,28): error CS1736: Default parameter value for 'p' must be a compile-time constant
// int Local1(int p = Local2()) => 0;
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local2()").WithArguments("p").WithLocation(6, 28),
// (7,28): error CS1736: Default parameter value for 'p' must be a compile-time constant
// int Local2(int p = Local1()) => 0;
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local1()").WithArguments("p").WithLocation(7, 28));
comp.DeclarationDiagnostics.Verify();
}
[Fact]
public void FetchLocalFunctionSymbolThroughLocal()
{
var tree = SyntaxFactory.ParseSyntaxTree(@"
using System;
class C
{
public void M()
{
void Local<[A, B, CLSCompliant, D]T>()
{
var x = new object();
}
Local<int>();
}
}");
var comp = CreateCompilation(tree);
comp.DeclarationDiagnostics.Verify();
comp.VerifyDiagnostics(
// (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21),
// (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21),
// (7,24): error CS0246: The type or namespace name 'BAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("BAttribute").WithLocation(7, 24),
// (7,24): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 24),
// (7,41): error CS0246: The type or namespace name 'DAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("DAttribute").WithLocation(7, 41),
// (7,41): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(7, 41),
// (7,27): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)'
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 27));
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.ValueText == "x").Single();
var localSymbol = model.GetDeclaredSymbol(x).ContainingSymbol.GetSymbol<LocalFunctionSymbol>();
var typeParam = localSymbol.TypeParameters.Single();
var attrs = typeParam.GetAttributes();
Assert.True(attrs[0].AttributeClass.IsErrorType());
Assert.True(attrs[1].AttributeClass.IsErrorType());
Assert.False(attrs[2].AttributeClass.IsErrorType());
Assert.Equal(comp.GlobalNamespace
.GetMember<NamespaceSymbol>("System")
.GetMember<NamedTypeSymbol>("CLSCompliantAttribute"),
attrs[2].AttributeClass);
Assert.True(attrs[3].AttributeClass.IsErrorType());
comp.DeclarationDiagnostics.Verify();
}
[Fact]
public void TypeParameterAttributesInSemanticModel()
{
var comp = (Compilation)CreateCompilation(@"
using System;
class C
{
public void M()
{
void Local<[A]T, [CLSCompliant]U>() { }
}
}", parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A]T, [CLSCompliant]U>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21),
// (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A]T, [CLSCompliant]U>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21),
// (7,27): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)'
// void Local<[A]T, [CLSCompliant]U>() { }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 27),
// (7,14): warning CS8321: The local function 'Local' is declared but never used
// void Local<[A]T, [CLSCompliant]U>() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(7, 14));
var tree = comp.SyntaxTrees.First();
var root = tree.GetRoot();
var model = comp.GetSemanticModel(tree);
var a = root.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(id => id.Identifier.ValueText == "A")
.Single();
Assert.Null(model.GetDeclaredSymbol(a));
var aSymbolInfo = model.GetSymbolInfo(a);
Assert.Equal(0, aSymbolInfo.CandidateSymbols.Length);
Assert.Null(aSymbolInfo.Symbol);
var aTypeInfo = model.GetTypeInfo(a);
Assert.Equal(TypeKind.Error, aTypeInfo.Type.TypeKind);
Assert.Null(model.GetAliasInfo(a));
Assert.Empty(model.LookupNamespacesAndTypes(a.SpanStart, name: "A"));
var clsCompliant = root.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(id => id.Identifier.ValueText == "CLSCompliant")
.Single();
var clsCompliantSymbol = comp.GlobalNamespace
.GetMember<INamespaceSymbol>("System")
.GetTypeMember("CLSCompliantAttribute");
Assert.Null(model.GetDeclaredSymbol(clsCompliant));
// This should be null because there is no CLSCompliant ctor with no args
var clsCompliantSymbolInfo = model.GetSymbolInfo(clsCompliant);
Assert.Null(clsCompliantSymbolInfo.Symbol);
Assert.Equal(clsCompliantSymbol.GetMember<IMethodSymbol>(".ctor"),
clsCompliantSymbolInfo.CandidateSymbols.Single());
Assert.Equal(CandidateReason.OverloadResolutionFailure, clsCompliantSymbolInfo.CandidateReason);
Assert.Equal(clsCompliantSymbol, model.GetTypeInfo(clsCompliant).Type);
Assert.Null(model.GetAliasInfo(clsCompliant));
Assert.Equal(clsCompliantSymbol,
model.LookupNamespacesAndTypes(clsCompliant.SpanStart, name: "CLSCompliantAttribute").Single());
((CSharpCompilation)comp).DeclarationDiagnostics.Verify();
}
[Fact]
public void ParameterAttributesInSemanticModel()
{
var comp = (Compilation)CreateCompilation(@"
using System;
class C
{
public void M()
{
void Local([A]int x, [CLSCompliant]int y) { }
}
}", parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local([A]int x, [CLSCompliant]int y) { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21),
// (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// void Local([A]int x, [CLSCompliant]int y) { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21),
// (7,31): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)'
// void Local([A]int x, [CLSCompliant]int y) { }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 31),
// (7,14): warning CS8321: The local function 'Local' is declared but never used
// void Local([A]int x, [CLSCompliant]int y) { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(7, 14));
var tree = comp.SyntaxTrees.First();
var root = tree.GetRoot();
var model = comp.GetSemanticModel(tree);
var a = root.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(id => id.Identifier.ValueText == "A")
.Single();
Assert.Null(model.GetDeclaredSymbol(a));
var aSymbolInfo = model.GetSymbolInfo(a);
Assert.Equal(0, aSymbolInfo.CandidateSymbols.Length);
Assert.Null(aSymbolInfo.Symbol);
var aTypeInfo = model.GetTypeInfo(a);
Assert.Equal(TypeKind.Error, aTypeInfo.Type.TypeKind);
Assert.Null(model.GetAliasInfo(a));
Assert.Empty(model.LookupNamespacesAndTypes(a.SpanStart, name: "A"));
var clsCompliant = root.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(id => id.Identifier.ValueText == "CLSCompliant")
.Single();
var clsCompliantSymbol = comp.GlobalNamespace
.GetMember<INamespaceSymbol>("System")
.GetTypeMember("CLSCompliantAttribute");
Assert.Null(model.GetDeclaredSymbol(clsCompliant));
// This should be null because there is no CLSCompliant ctor with no args
var clsCompliantSymbolInfo = model.GetSymbolInfo(clsCompliant);
Assert.Null(clsCompliantSymbolInfo.Symbol);
Assert.Equal(clsCompliantSymbol.GetMember<IMethodSymbol>(".ctor"),
clsCompliantSymbolInfo.CandidateSymbols.Single());
Assert.Equal(CandidateReason.OverloadResolutionFailure, clsCompliantSymbolInfo.CandidateReason);
Assert.Equal(clsCompliantSymbol, model.GetTypeInfo(clsCompliant).Type);
Assert.Null(model.GetAliasInfo(clsCompliant));
Assert.Equal(clsCompliantSymbol,
model.LookupNamespacesAndTypes(clsCompliant.SpanStart, name: "CLSCompliantAttribute").Single());
((CSharpCompilation)comp).DeclarationDiagnostics.Verify();
}
[Fact]
public void LocalFunctionAttribute_TypeParameter_Errors()
{
var tree = SyntaxFactory.ParseSyntaxTree(@"
using System;
class C
{
public void M()
{
void Local<[A, B, CLSCompliant, D]T>() { }
Local<int>();
}
}", options: TestOptions.Regular9);
var comp = CreateCompilation(tree);
comp.DeclarationDiagnostics.Verify();
comp.VerifyDiagnostics(
// (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21),
// (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21),
// (7,24): error CS0246: The type or namespace name 'BAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("BAttribute").WithLocation(7, 24),
// (7,24): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 24),
// (7,41): error CS0246: The type or namespace name 'DAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("DAttribute").WithLocation(7, 41),
// (7,41): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(7, 41),
// (7,27): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)'
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 27));
var localDecl = tree.FindNodeOrTokenByKind(SyntaxKind.LocalFunctionStatement);
var model = comp.GetSemanticModel(tree);
var localSymbol = Assert.IsType<LocalFunctionSymbol>(model.GetDeclaredSymbol(localDecl.AsNode()).GetSymbol());
var typeParam = localSymbol.TypeParameters.Single();
var attrs = typeParam.GetAttributes();
Assert.True(attrs[0].AttributeClass.IsErrorType());
Assert.True(attrs[1].AttributeClass.IsErrorType());
Assert.False(attrs[2].AttributeClass.IsErrorType());
Assert.Equal(comp.GlobalNamespace
.GetMember<NamespaceSymbol>("System")
.GetMember<NamedTypeSymbol>("CLSCompliantAttribute"),
attrs[2].AttributeClass);
Assert.True(attrs[3].AttributeClass.IsErrorType());
comp.DeclarationDiagnostics.Verify();
}
[Fact]
public void LocalFunctionAttribute_Parameter_Errors()
{
var tree = SyntaxFactory.ParseSyntaxTree(@"
using System;
class C
{
public void M()
{
void Local([A, B]int x, [CLSCompliant]string s = """") { }
Local(0);
}
}", options: TestOptions.Regular9);
var comp = CreateCompilation(tree);
comp.DeclarationDiagnostics.Verify();
comp.VerifyDiagnostics(
// (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local([A, B]int x, [CLSCompliant]string s = "") { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21),
// (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// void Local([A, B]int x, [CLSCompliant]string s = "") { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21),
// (7,24): error CS0246: The type or namespace name 'BAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local([A, B]int x, [CLSCompliant]string s = "") { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("BAttribute").WithLocation(7, 24),
// (7,24): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)
// void Local([A, B]int x, [CLSCompliant]string s = "") { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 24),
// (7,34): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)'
// void Local([A, B]int x, [CLSCompliant]string s = "") { }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 34));
var localDecl = tree.FindNodeOrTokenByKind(SyntaxKind.LocalFunctionStatement);
var model = comp.GetSemanticModel(tree);
var localSymbol = Assert.IsType<LocalFunctionSymbol>(model.GetDeclaredSymbol(localDecl.AsNode()).GetSymbol());
var param = localSymbol.Parameters[0];
var attrs = param.GetAttributes();
Assert.True(attrs[0].AttributeClass.IsErrorType());
Assert.True(attrs[1].AttributeClass.IsErrorType());
param = localSymbol.Parameters[1];
attrs = param.GetAttributes();
Assert.Equal(comp.GlobalNamespace
.GetMember<NamespaceSymbol>("System")
.GetMember<NamedTypeSymbol>("CLSCompliantAttribute"),
attrs[0].AttributeClass);
comp.DeclarationDiagnostics.Verify();
}
[Fact]
public void LocalFunctionDisallowedAttributes()
{
var source = @"
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
public class IsUnmanagedAttribute : System.Attribute { }
public class IsByRefLikeAttribute : System.Attribute { }
public class NullableContextAttribute : System.Attribute { public NullableContextAttribute(byte b) { } }
}
class C
{
void M()
{
local1();
[IsReadOnly] // 1
[IsUnmanaged] // 2
[IsByRefLike] // 3
[Extension] // 4
[NullableContext(0)] // 5
void local1()
{
}
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (18,10): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly] // 1
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(18, 10),
// (19,10): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage.
// [IsUnmanaged] // 2
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(19, 10),
// (20,10): error CS8335: Do not use 'System.Runtime.CompilerServices.IsByRefLikeAttribute'. This is reserved for compiler usage.
// [IsByRefLike] // 3
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsByRefLike").WithArguments("System.Runtime.CompilerServices.IsByRefLikeAttribute").WithLocation(20, 10),
// (21,10): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead.
// [Extension] // 4
Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension").WithLocation(21, 10),
// (22,10): error CS8335: Do not use 'System.Runtime.CompilerServices.NullableContextAttribute'. This is reserved for compiler usage.
// [NullableContext(0)] // 5
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullableContext(0)").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(22, 10));
}
[Fact]
public void LocalFunctionDisallowedSecurityAttributes()
{
var source = @"
using System.Security;
class C
{
void M()
{
local1();
[SecurityCritical] // 1
[SecuritySafeCriticalAttribute] // 2
async void local1() // 3
{
}
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,10): error CS4030: Security attribute 'SecurityCritical' cannot be applied to an Async method.
// [SecurityCritical] // 1
Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecurityCritical").WithArguments("SecurityCritical").WithLocation(10, 10),
// (11,10): error CS4030: Security attribute 'SecuritySafeCriticalAttribute' cannot be applied to an Async method.
// [SecuritySafeCriticalAttribute] // 2
Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecuritySafeCriticalAttribute").WithArguments("SecuritySafeCriticalAttribute").WithLocation(11, 10),
// (12,20): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async void local1() // 3
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "local1").WithLocation(12, 20));
}
[Fact]
public void TypeParameterBindingScope()
{
var src = @"
class C
{
public void M()
{
{
int T = 0; // Should not have error
int Local<T>() => 0; // Should conflict with above
Local<int>();
T++;
}
{
int T<T>() => 0;
T<int>();
}
{
int Local<T, T>() => 0;
Local<int, int>();
}
}
public void M2<T>()
{
{
int Local<T>() => 0;
Local<int>();
}
{
int Local1<V>()
{
int Local2<V>() => 0;
return Local2<int>();
}
Local1<int>();
}
{
int T() => 0;
T();
}
{
int Local1<V>()
{
int V() => 0;
return V();
}
Local1<int>();
}
{
int Local1<V>()
{
int Local2<U>()
{
// Conflicts with method type parameter
int T() => 0;
return T();
}
return Local2<int>();
}
Local1<int>();
}
{
int Local1<V>()
{
int Local2<U>()
{
// Shadows M.2<T>
int Local3<T>() => 0;
return Local3<int>();
}
return Local2<int>();
}
Local1<int>();
}
}
public void V<V>() { }
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,23): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int Local<T>() => 0; // Should conflict with above
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(9, 23),
// (14,19): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int T<T>() => 0;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(14, 19),
// (18,26): error CS0692: Duplicate type parameter 'T'
// int Local<T, T>() => 0;
Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T").WithLocation(18, 26),
// (25,23): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()'
// int Local<T>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(25, 23),
// (31,28): warning CS8387: Type parameter 'V' has the same name as the type parameter from outer method 'Local1<V>()'
// int Local2<V>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "V").WithArguments("V", "Local1<V>()").WithLocation(31, 28),
// (37,17): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// int T() => 0;
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(37, 17),
// (43,21): error CS0412: 'V': a parameter, local variable, or local function cannot have the same name as a method type parameter
// int V() => 0;
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "V").WithArguments("V").WithLocation(43, 21),
// (54,25): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// int T() => 0;
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(54, 25),
// (67,32): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()'
// int Local3<T>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(67, 32));
comp = CreateCompilation(src, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (18,26): error CS0692: Duplicate type parameter 'T'
// int Local<T, T>() => 0;
Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T").WithLocation(18, 26),
// (25,23): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()'
// int Local<T>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(25, 23),
// (31,28): warning CS8387: Type parameter 'V' has the same name as the type parameter from outer method 'Local1<V>()'
// int Local2<V>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "V").WithArguments("V", "Local1<V>()").WithLocation(31, 28),
// (37,17): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// int T() => 0;
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(37, 17),
// (43,21): error CS0412: 'V': a parameter, local variable, or local function cannot have the same name as a method type parameter
// int V() => 0;
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "V").WithArguments("V").WithLocation(43, 21),
// (67,32): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()'
// int Local3<T>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(67, 32));
}
[Fact]
public void LocalFuncAndTypeParameterOnType()
{
var comp = CreateCompilation(@"
class C2<T>
{
public void M()
{
{
int Local1()
{
int Local2<T>() => 0;
return Local2<int>();
}
Local1();
}
{
int Local1()
{
int Local2()
{
// Shadows type parameter
int T() => 0;
// Type parameter resolves in type only context
T t = default(T);
// Ambiguous context chooses local
T.M();
// Call chooses local
return T();
}
return Local2();
}
Local1();
}
}
}");
comp.VerifyDiagnostics(
// (9,28): warning CS0693: Type parameter 'T' has the same name as the type parameter from outer type 'C2<T>'
// int Local2<T>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "T").WithArguments("T", "C2<T>").WithLocation(9, 28),
// (26,21): error CS0119: 'T()' is a method, which is not valid in the given context
// T.M();
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T()", "method").WithLocation(26, 21),
// (23,23): warning CS0219: The variable 't' is assigned but its value is never used
// T t = default(T);
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t").WithArguments("t").WithLocation(23, 23));
}
[Fact]
public void RefArgsInIteratorLocalFuncs()
{
var src = @"
using System;
using System.Collections.Generic;
class C
{
public void M1()
{
IEnumerable<int> Local(ref int a) { yield break; }
int x = 0;
Local(ref x);
}
public void M2()
{
Action a = () =>
{
IEnumerable<int> Local(ref int x) { yield break; }
int y = 0;
Local(ref y);
return;
};
a();
}
public Func<int> M3() => (() =>
{
IEnumerable<int> Local(ref int a) { yield break; }
int x = 0;
Local(ref x);
return 0;
});
public IEnumerable<int> M4(ref int a)
{
yield return new Func<int>(() =>
{
IEnumerable<int> Local(ref int b) { yield break; }
int x = 0;
Local(ref x);
return 0;
})();
}
}";
VerifyDiagnostics(src,
// (8,40): error CS1623: Iterators cannot have ref, in or out parameters
// IEnumerable<int> Local(ref int a) { yield break; }
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "a").WithLocation(8, 40),
// (17,44): error CS1623: Iterators cannot have ref, in or out parameters
// IEnumerable<int> Local(ref int x) { yield break; }
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "x").WithLocation(17, 44),
// (27,40): error CS1623: Iterators cannot have ref, in or out parameters
// IEnumerable<int> Local(ref int a) { yield break; }
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "a").WithLocation(27, 40),
// (33,40): error CS1623: Iterators cannot have ref, in or out parameters
// public IEnumerable<int> M4(ref int a)
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "a").WithLocation(33, 40),
// (37,48): error CS1623: Iterators cannot have ref, in or out parameters
// IEnumerable<int> Local(ref int b) { yield break; }
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "b").WithLocation(37, 48));
}
[Fact]
public void UnsafeArgsInIteratorLocalFuncs()
{
var src = @"
using System;
using System.Collections.Generic;
class C
{
public unsafe void M1()
{
IEnumerable<int> Local(int* a) { yield break; }
int x = 0;
Local(&x);
}
public unsafe void M2()
{
Action a = () =>
{
IEnumerable<int> Local(int* x) { yield break; }
int y = 0;
Local(&y);
return;
};
a();
}
public unsafe Func<int> M3() => (() =>
{
IEnumerable<int> Local(int* a) { yield break; }
int x = 0;
Local(&x);
return 0;
});
public unsafe IEnumerable<int> M4(int* a)
{
yield return new Func<int>(() =>
{
IEnumerable<int> Local(int* b) { yield break; }
int x = 0;
Local(&x);
return 0;
})();
}
}";
CreateCompilation(src, options: TestOptions.UnsafeDebugDll)
.VerifyDiagnostics(
// (8,37): error CS1637: Iterators cannot have unsafe parameters or yield types
// IEnumerable<int> Local(int* a) { yield break; }
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "a").WithLocation(8, 37),
// (17,41): error CS1637: Iterators cannot have unsafe parameters or yield types
// IEnumerable<int> Local(int* x) { yield break; }
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "x").WithLocation(17, 41),
// (27,37): error CS1637: Iterators cannot have unsafe parameters or yield types
// IEnumerable<int> Local(int* a) { yield break; }
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "a").WithLocation(27, 37),
// (33,44): error CS1637: Iterators cannot have unsafe parameters or yield types
// public unsafe IEnumerable<int> M4(int* a)
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "a").WithLocation(33, 44),
// (33,36): error CS1629: Unsafe code may not appear in iterators
// public unsafe IEnumerable<int> M4(int* a)
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "M4").WithLocation(33, 36),
// (37,40): error CS1629: Unsafe code may not appear in iterators
// IEnumerable<int> Local(int* b) { yield break; }
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "int*").WithLocation(37, 40),
// (39,23): error CS1629: Unsafe code may not appear in iterators
// Local(&x);
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "&x").WithLocation(39, 23),
// (39,17): error CS1629: Unsafe code may not appear in iterators
// Local(&x);
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Local(&x)").WithLocation(39, 17),
// (37,45): error CS1637: Iterators cannot have unsafe parameters or yield types
// IEnumerable<int> Local(int* b) { yield break; }
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "b").WithLocation(37, 45));
}
[Fact]
[WorkItem(13193, "https://github.com/dotnet/roslyn/issues/13193")]
public void LocalFunctionConflictingName()
{
var comp = CreateCompilation(@"
class C
{
public void M<TLocal>()
{
void TLocal() { }
TLocal();
}
public void M(int Local)
{
void Local() { }
Local();
}
public void M()
{
int local = 0;
void local() { }
local();
}
}");
comp.VerifyDiagnostics(
// (6,14): error CS0412: 'TLocal': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void TLocal() { }
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "TLocal").WithArguments("TLocal").WithLocation(6, 14),
// (11,14): error CS0136: A local or parameter named 'Local' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void Local() { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "Local").WithArguments("Local").WithLocation(11, 14),
// (18,14): error CS0128: A local variable or function named 'local' is already defined in this scope
// void local() { }
Diagnostic(ErrorCode.ERR_LocalDuplicate, "local").WithArguments("local").WithLocation(18, 14),
// (16,13): warning CS0219: The variable 'local' is assigned but its value is never used
// int local = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "local").WithArguments("local").WithLocation(16, 13));
}
[Fact]
public void ForgotSemicolonLocalFunctionsMistake()
{
var src = @"
class C
{
public void M1()
{
// forget closing brace
public void BadLocal1()
{
this.BadLocal2();
}
public void BadLocal2()
{
}
public int P => 0;
}";
VerifyDiagnostics(src,
// (8,5): error CS0106: The modifier 'public' is not valid for this item
// public void BadLocal1()
Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(8, 5),
// (13,5): error CS0106: The modifier 'public' is not valid for this item
// public void BadLocal2()
Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(13, 5),
// (15,6): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(15, 6),
// (10,14): error CS1061: 'C' does not contain a definition for 'BadLocal2' and no extension method 'BadLocal2' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// this.BadLocal2();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BadLocal2").WithArguments("C", "BadLocal2").WithLocation(10, 14),
// (8,17): warning CS8321: The local function 'BadLocal1' is declared but never used
// public void BadLocal1()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "BadLocal1").WithArguments("BadLocal1").WithLocation(8, 17),
// (13,17): warning CS8321: The local function 'BadLocal2' is declared but never used
// public void BadLocal2()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "BadLocal2").WithArguments("BadLocal2").WithLocation(13, 17));
}
[Fact]
public void VarLocalFunction()
{
var src = @"
class C
{
void M()
{
var local() => 0;
int x = local();
}
}";
VerifyDiagnostics(src,
// (6,9): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// var local() => 0;
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(6, 9));
}
[Fact]
public void VarLocalFunction2()
{
var comp = CreateCompilation(@"
class C
{
private class var
{
}
void M()
{
var local() => new var();
var x = local();
}
}", parseOptions: DefaultParseOptions);
comp.VerifyDiagnostics();
}
[Fact]
[CompilerTrait(CompilerFeature.Params)]
public void BadParams()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
void Params(params int x)
{
Console.WriteLine(x);
}
Params(2);
}
}
";
VerifyDiagnostics(source,
// (8,21): error CS0225: The params parameter must be a single dimensional array
// void Params(params int x)
Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(8, 21)
);
}
[Fact]
public void BadRefWithDefault()
{
var source = @"
class Program
{
static void Main(string[] args)
{
void RefOut(ref int x = 2)
{
x++;
}
int y = 2;
RefOut(ref y);
}
}
";
VerifyDiagnostics(source,
// (6,21): error CS1741: A ref or out parameter cannot have a default value
// void RefOut(ref int x = 2)
Diagnostic(ErrorCode.ERR_RefOutDefaultValue, "ref").WithLocation(6, 21)
);
}
[Fact]
public void BadDefaultValueType()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
void NamedOptional(string x = 2)
{
Console.WriteLine(x);
}
NamedOptional(""2"");
}
}
";
VerifyDiagnostics(source,
// (8,35): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'string'
// void NamedOptional(string x = 2)
Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("int", "string").WithLocation(8, 35)
);
}
[Fact]
public void CallerMemberName()
{
var comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Runtime.CompilerServices;
class C
{
static void Main()
{
void CallerMemberName([CallerMemberName] string s = null)
{
Console.Write(s);
}
void LocalFuncName()
{
CallerMemberName();
}
LocalFuncName();
Console.Write(' ');
CallerMemberName();
}
}", parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void BadCallerMemberName()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main(string[] args)
{
void CallerMemberName([CallerMemberName] int s = 2) // 1
{
Console.WriteLine(s);
}
CallerMemberName(); // 2
}
}
";
CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics(
// (9,32): error CS4019: CallerMemberNameAttribute cannot be applied because there are no standard conversions from type 'string' to type 'int'
// void CallerMemberName([CallerMemberName] int s = 2) // 1
Diagnostic(ErrorCode.ERR_NoConversionForCallerMemberNameParam, "CallerMemberName").WithArguments("string", "int").WithLocation(9, 32),
// (13,9): error CS0029: Cannot implicitly convert type 'string' to 'int'
// CallerMemberName(); // 2
Diagnostic(ErrorCode.ERR_NoImplicitConv, "CallerMemberName()").WithArguments("string", "int").WithLocation(13, 9));
}
[WorkItem(10708, "https://github.com/dotnet/roslyn/issues/10708")]
[CompilerTrait(CompilerFeature.Dynamic, CompilerFeature.Params)]
[Fact]
public void DynamicArgumentToParams()
{
var src = @"
using System;
class C
{
static void Main()
{
void L1(int x = 0, params int[] ys) => Console.Write(x);
dynamic val = 2;
L1(val, val);
L1(ys: val, x: val);
L1(ys: val);
}
}";
VerifyDiagnostics(src,
// (10,9): error CS8106: Cannot pass argument with dynamic type to params parameter 'ys' of local function 'L1'.
// L1(val, val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "L1(val, val)").WithArguments("ys", "L1").WithLocation(10, 9),
// (11,9): error CS8106: Cannot pass argument with dynamic type to params parameter 'ys' of local function 'L1'.
// L1(ys: val, x: val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "L1(ys: val, x: val)").WithArguments("ys", "L1").WithLocation(11, 9),
// (12,9): error CS8106: Cannot pass argument with dynamic type to params parameter 'ys' of local function 'L1'.
// L1(ys: val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "L1(ys: val)").WithArguments("ys", "L1").WithLocation(12, 9));
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicArgOverload()
{
var src = @"
using System;
class C
{
static void Main()
{
void Overload(int i) => Console.Write(i);
void Overload(string s) => Console.Write(s);
dynamic val = 2;
Overload(val);
}
}";
VerifyDiagnostics(src,
// (8,14): error CS0128: A local variable named 'Overload' is already defined in this scope
// void Overload(string s) => Console.Write(s);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "Overload").WithArguments("Overload").WithLocation(8, 14),
// (8,14): warning CS8321: The local function 'Overload' is declared but never used
// void Overload(string s) => Console.Write(s);
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Overload").WithArguments("Overload").WithLocation(8, 14));
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicArgWrongArity()
{
var src = @"
using System;
class C
{
static void Main()
{
void Local(int i) => Console.Write(i);
dynamic val = 2;
Local(val, val);
}
}";
VerifyDiagnostics(src,
// (10,9): error CS1501: No overload for method 'Local' takes 2 arguments
// Local(val, val);
Diagnostic(ErrorCode.ERR_BadArgCount, "Local").WithArguments("Local", "2").WithLocation(10, 9));
}
[WorkItem(3923, "https://github.com/dotnet/roslyn/issues/3923")]
[Fact]
public void ExpressionTreeLocalFunctionUsage_01()
{
var source = @"
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
T Id<T>(T x)
{
return x;
}
Expression<Func<T>> Local<T>(Expression<Func<T>> f)
{
return f;
}
Console.Write(Local(() => Id(2)));
Console.Write(Local<Func<int, int>>(() => Id));
Console.Write(Local(() => new Func<int, int>(Id)));
Console.Write(Local(() => nameof(Id)));
}
}
";
VerifyDiagnostics(source,
// (16,35): error CS8096: An expression tree may not contain a reference to a local function
// Console.Write(Local(() => Id(2)));
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id(2)").WithLocation(16, 35),
// (17,51): error CS8096: An expression tree may not contain a reference to a local function
// Console.Write(Local<Func<int, int>>(() => Id));
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(17, 51),
// (18,35): error CS8096: An expression tree may not contain a reference to a local function
// Console.Write(Local(() => new Func<int, int>(Id)));
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(18, 54)
);
}
[Fact]
public void ExpressionTreeLocalFunctionUsage_02()
{
var source = @"
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
static T Id<T>(T x)
{
return x;
}
static Expression<Func<T>> Local<T>(Expression<Func<T>> f)
{
return f;
}
Console.Write(Local(() => Id(2)));
Console.Write(Local<Func<int, int>>(() => Id));
Console.Write(Local(() => new Func<int, int>(Id)));
Console.Write(Local(() => nameof(Id)));
}
}
";
VerifyDiagnostics(source,
// (16,35): error CS8096: An expression tree may not contain a reference to a local function
// Console.Write(Local(() => Id(2)));
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id(2)").WithLocation(16, 35),
// (17,51): error CS8096: An expression tree may not contain a reference to a local function
// Console.Write(Local<Func<int, int>>(() => Id));
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(17, 51),
// (18,35): error CS8096: An expression tree may not contain a reference to a local function
// Console.Write(Local(() => new Func<int, int>(Id)));
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(18, 54)
);
}
[Fact]
public void ExpressionTreeLocalFunctionInside()
{
var source = @"
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<int, int>> f = x =>
{
int Local(int y) => y;
return Local(x);
};
Console.Write(f);
}
}
";
VerifyDiagnostics(source,
// (8,40): error CS0834: A lambda expression with a statement body cannot be converted to an expression tree
// Expression<Func<int, int>> f = x =>
Diagnostic(ErrorCode.ERR_StatementLambdaToExpressionTree, @"x =>
{
int Local(int y) => y;
return Local(x);
}").WithLocation(8, 40),
// (11,20): error CS8096: An expression tree may not contain a local function or a reference to a local function
// return Local(x);
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Local(x)").WithLocation(11, 20)
);
}
[Fact]
public void BadScoping()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
if (true)
{
void Local()
{
Console.WriteLine(2);
}
Local();
}
Local();
Local2();
void Local2()
{
Console.WriteLine(2);
}
}
}
";
VerifyDiagnostics(source,
// (16,9): error CS0103: The name 'Local' does not exist in the current context
// Local();
Diagnostic(ErrorCode.ERR_NameNotInContext, "Local").WithArguments("Local").WithLocation(16, 9)
);
}
[Fact]
public void NameConflictDuplicate()
{
var source = @"
class Program
{
static void Main(string[] args)
{
void Duplicate() { }
void Duplicate() { }
Duplicate();
}
}
";
VerifyDiagnostics(source,
// (7,14): error CS0128: A local variable named 'Duplicate' is already defined in this scope
// void Duplicate() { }
Diagnostic(ErrorCode.ERR_LocalDuplicate, "Duplicate").WithArguments("Duplicate").WithLocation(7, 14),
// (7,14): warning CS8321: The local function 'Duplicate' is declared but never used
// void Duplicate() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Duplicate").WithArguments("Duplicate").WithLocation(7, 14)
);
}
[Fact]
public void NameConflictParameter()
{
var source = @"
class Program
{
static void Main(string[] args)
{
int x = 2;
void Param(int x) { }
Param(x);
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (7,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void Param(int x) { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(7, 24));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
}
[Fact]
public void NameConflictTypeParameter()
{
var source = @"
class Program
{
static void Main(string[] args)
{
int T;
void Generic<T>() { }
Generic<int>();
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (7,22): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void Generic<T>() { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(7, 22),
// (6,13): warning CS0168: The variable 'T' is declared but never used
// int T;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "T").WithArguments("T").WithLocation(6, 13));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (6,13): warning CS0168: The variable 'T' is declared but never used
// int T;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "T").WithArguments("T").WithLocation(6, 13));
}
[Fact]
public void NameConflictNestedTypeParameter()
{
var source = @"
class Program
{
static void Main(string[] args)
{
T Outer<T>()
{
T Inner<T>()
{
return default(T);
}
return Inner<T>();
}
System.Console.Write(Outer<int>());
}
}
";
VerifyDiagnostics(source,
// (8,21): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Outer<T>()'
// T Inner<T>()
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Outer<T>()").WithLocation(8, 21)
);
}
[Fact]
public void NameConflictLocalVarFirst()
{
var source = @"
class Program
{
static void Main(string[] args)
{
int Conflict;
void Conflict() { }
}
}
";
VerifyDiagnostics(source,
// (7,14): error CS0128: A local variable named 'Conflict' is already defined in this scope
// void Conflict() { }
Diagnostic(ErrorCode.ERR_LocalDuplicate, "Conflict").WithArguments("Conflict").WithLocation(7, 14),
// (6,13): warning CS0168: The variable 'Conflict' is declared but never used
// int Conflict;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "Conflict").WithArguments("Conflict").WithLocation(6, 13),
// (7,14): warning CS8321: The local function 'Conflict' is declared but never used
// void Conflict() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Conflict").WithArguments("Conflict").WithLocation(7, 14)
);
}
[Fact]
public void NameConflictLocalVarLast()
{
var source = @"
class Program
{
static void Main(string[] args)
{
void Conflict() { }
int Conflict;
}
}
";
// TODO: This is strange. Probably has to do with the fact that local variables are preferred over functions.
VerifyDiagnostics(source,
// (6,14): error CS0136: A local or parameter named 'Conflict' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void Conflict() { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "Conflict").WithArguments("Conflict").WithLocation(6, 14),
// (7,13): warning CS0168: The variable 'Conflict' is declared but never used
// int Conflict;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "Conflict").WithArguments("Conflict").WithLocation(7, 13),
// (6,14): warning CS8321: The local function 'Conflict' is declared but never used
// void Conflict() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Conflict").WithArguments("Conflict").WithLocation(6, 14)
);
}
[Fact]
public void BadUnsafeNoKeyword()
{
var source = @"
using System;
class Program
{
static void A()
{
void Local()
{
int x = 2;
Console.WriteLine(*&x);
}
Local();
}
static void Main(string[] args)
{
A();
}
}
";
VerifyDiagnostics(source,
// (11,32): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Console.WriteLine(*&x);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "&x").WithLocation(11, 32)
);
}
[Fact]
public void BadUnsafeKeywordDoesntApply()
{
var source = @"
using System;
class Program
{
static unsafe void B()
{
void Local()
{
int x = 2;
Console.WriteLine(*&x);
}
Local();
}
static void Main(string[] args)
{
B();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(true));
comp.VerifyDiagnostics();
}
[Fact]
public void BadEmptyBody()
{
var source = @"
class Program
{
static void Main(string[] args)
{
void Local(int x);
Local(2);
}
}";
VerifyDiagnostics(source,
// (6,14): error CS8112: 'Local(int)' is a local function and must therefore always have a body.
// void Local(int x);
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Local").WithArguments("Local(int)").WithLocation(6, 14)
);
}
[Fact]
public void BadGotoInto()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
goto A;
void Local()
{
A: Console.Write(2);
}
Local();
}
}";
VerifyDiagnostics(source,
// (8,14): error CS0159: No such label 'A' within the scope of the goto statement
// goto A;
Diagnostic(ErrorCode.ERR_LabelNotFound, "A").WithArguments("A").WithLocation(8, 14),
// (11,9): warning CS0164: This label has not been referenced
// A: Console.Write(2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "A").WithLocation(11, 9)
);
}
[Fact]
public void BadGotoOutOf()
{
var source = @"
class Program
{
static void Main(string[] args)
{
void Local()
{
goto A;
}
A: Local();
}
}";
VerifyDiagnostics(source,
// (8,13): error CS0159: No such label 'A' within the scope of the goto statement
// goto A;
Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("A").WithLocation(8, 13)
);
}
[Fact]
public void BadDefiniteAssignmentCall()
{
var source = @"
using System;
class Program
{
static void A()
{
goto Label;
int x = 2;
void Local()
{
Console.Write(x);
}
Label:
Local();
}
static void Main(string[] args)
{
A();
}
}";
VerifyDiagnostics(source,
// (9,9): warning CS0162: Unreachable code detected
// int x = 2;
Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(9, 9),
// (15,9): error CS0165: Use of unassigned local variable 'x'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local()").WithArguments("x").WithLocation(15, 9)
);
}
[Fact]
public void BadDefiniteAssignmentDelegateConversion()
{
var source = @"
using System;
class Program
{
static void A()
{
goto Label;
int x = 2;
void Local()
{
Console.Write(x);
}
Label:
Action goo = Local;
}
static void Main(string[] args)
{
A();
}
}";
VerifyDiagnostics(source,
// (9,9): warning CS0162: Unreachable code detected
// int x = 2;
Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(9, 9),
// (15,22): error CS0165: Use of unassigned local variable 'x'
// Action goo = Local;
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local").WithArguments("x").WithLocation(15, 22)
);
}
[Fact]
public void BadDefiniteAssignmentDelegateConstruction()
{
var source = @"
using System;
class Program
{
static void A()
{
goto Label;
int x = 2;
void Local()
{
Console.Write(x);
}
Label:
var bar = new Action(Local);
}
static void Main(string[] args)
{
A();
}
}";
VerifyDiagnostics(source,
// (9,9): warning CS0162: Unreachable code detected
// int x = 2;
Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(9, 9),
// (15,19): error CS0165: Use of unassigned local variable 'x'
// var bar = new Action(Local);
Diagnostic(ErrorCode.ERR_UseDefViolation, "new Action(Local)").WithArguments("x").WithLocation(15, 19)
);
}
[Fact]
public void BadNotUsed()
{
var source = @"
class Program
{
static void A()
{
void Local()
{
}
}
static void Main(string[] args)
{
A();
}
}";
VerifyDiagnostics(source,
// (6,14): warning CS8321: The local function 'Local' is declared but never used
// void Local()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(6, 14)
);
}
[Fact]
public void BadNotUsedSwitch()
{
var source = @"
class Program
{
static void A()
{
switch (0)
{
case 0:
void Local()
{
}
break;
}
}
static void Main(string[] args)
{
A();
}
}";
VerifyDiagnostics(source,
// (9,18): warning CS8321: The local function 'Local' is declared but never used
// void Local()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(9, 18)
);
}
[Fact]
public void BadByRefClosure()
{
var source = @"
using System;
class Program
{
static void A(ref int x)
{
void Local()
{
Console.WriteLine(x);
}
Local();
}
static void Main()
{
}
}";
VerifyDiagnostics(source,
// (10,31): error CS1628: Cannot use ref or out parameter 'x' inside an anonymous method, lambda expression, query expression, or local function
// Console.WriteLine(x);
Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "x").WithArguments("x").WithLocation(10, 31)
);
}
[Fact]
public void BadInClosure()
{
var source = @"
using System;
class Program
{
static void A(in int x)
{
void Local()
{
Console.WriteLine(x);
}
Local();
}
static void Main()
{
}
}";
VerifyDiagnostics(source,
// (10,31): error CS1628: Cannot use ref, out, or in parameter 'x' inside an anonymous method, lambda expression, query expression, or local function
// Console.WriteLine(x);
Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "x").WithArguments("x").WithLocation(10, 31)
);
}
[Fact]
public void BadArglistUse()
{
var source = @"
using System;
class Program
{
static void A()
{
void Local()
{
Console.WriteLine(__arglist);
}
Local();
}
static void B(__arglist)
{
void Local()
{
Console.WriteLine(__arglist);
}
Local();
}
static void C() // C and D produce different errors
{
void Local(__arglist)
{
Console.WriteLine(__arglist);
}
Local(__arglist());
}
static void D(__arglist)
{
void Local(__arglist)
{
Console.WriteLine(__arglist);
}
Local(__arglist());
}
static void Main()
{
}
}
";
VerifyDiagnostics(source,
// (10,31): error CS0190: The __arglist construct is valid only within a variable argument method
// Console.WriteLine(__arglist);
Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist").WithLocation(10, 31),
// (18,31): error CS4013: Instance of type 'RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method
// Console.WriteLine(__arglist);
Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(18, 31),
// (24,20): error CS1669: __arglist is not valid in this context
// void Local(__arglist)
Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(24, 20),
// (26,31): error CS0190: The __arglist construct is valid only within a variable argument method
// Console.WriteLine(__arglist);
Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist").WithLocation(26, 31),
// (32,20): error CS1669: __arglist is not valid in this context
// void Local(__arglist)
Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(32, 20),
// (34,31): error CS4013: Instance of type 'RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method
// Console.WriteLine(__arglist);
Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(34, 31)
);
}
[Fact]
public void BadClosureStaticRefInstance()
{
var source = @"
using System;
class Program
{
int _a = 0;
static void A()
{
void Local()
{
Console.WriteLine(_a);
}
Local();
}
static void Main()
{
}
}
";
VerifyDiagnostics(source,
// (11,31): error CS0120: An object reference is required for the non-static field, method, or property 'Program._a'
// Console.WriteLine(_a);
Diagnostic(ErrorCode.ERR_ObjectRequired, "_a").WithArguments("Program._a").WithLocation(11, 31)
);
}
[Fact]
public void BadRefIterator()
{
var source = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
IEnumerable<int> RefEnumerable(ref int x)
{
yield return x;
}
int y = 0;
RefEnumerable(ref y);
}
}
";
VerifyDiagnostics(source,
// (8,48): error CS1623: Iterators cannot have ref, in or out parameters
// IEnumerable<int> RefEnumerable(ref int x)
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "x").WithLocation(8, 48)
);
}
[Fact]
public void BadRefAsync()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
async Task<int> RefAsync(ref int x)
{
return await Task.FromResult(x);
}
int y = 2;
Console.Write(RefAsync(ref y).Result);
}
}
";
VerifyDiagnostics(source,
// (9,42): error CS1988: Async methods cannot have ref, in or out parameters
// async Task<int> RefAsync(ref int x)
Diagnostic(ErrorCode.ERR_BadAsyncArgType, "x").WithLocation(9, 42)
);
}
[Fact]
public void Extension_01()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int Local(this int x)
{
return x;
}
Console.WriteLine(Local(2));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (8,13): error CS1106: Extension method must be defined in a non-generic static class
// int Local(this int x)
Diagnostic(ErrorCode.ERR_BadExtensionAgg, "Local").WithLocation(8, 13)
);
}
[Fact]
public void Extension_02()
{
var source =
@"#pragma warning disable 8321
static class E
{
static void M()
{
void F1(this string s) { }
static void F2(this string s) { }
}
}";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (6,14): error CS1106: Extension method must be defined in a non-generic static class
// void F1(this string s) { }
Diagnostic(ErrorCode.ERR_BadExtensionAgg, "F1").WithLocation(6, 14),
// (7,21): error CS1106: Extension method must be defined in a non-generic static class
// static void F2(this string s) { }
Diagnostic(ErrorCode.ERR_BadExtensionAgg, "F2").WithLocation(7, 21));
}
[Fact]
public void BadModifiers()
{
var source = @"
class Program
{
static void Main(string[] args)
{
const void LocalConst()
{
}
static void LocalStatic()
{
}
readonly void LocalReadonly()
{
}
volatile void LocalVolatile()
{
}
LocalConst();
LocalStatic();
LocalReadonly();
LocalVolatile();
}
}
";
var baseExpected = new[]
{
// (6,9): error CS0106: The modifier 'const' is not valid for this item
// const void LocalConst()
Diagnostic(ErrorCode.ERR_BadMemberFlag, "const").WithArguments("const").WithLocation(6, 9),
// (12,9): error CS0106: The modifier 'readonly' is not valid for this item
// readonly void LocalReadonly()
Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(12, 9),
// (15,9): error CS0106: The modifier 'volatile' is not valid for this item
// volatile void LocalVolatile()
Diagnostic(ErrorCode.ERR_BadMemberFlag, "volatile").WithArguments("volatile").WithLocation(15, 9)
};
var extra = new[]
{
// (9,9): error CS8652: The feature 'static local functions' is not available in C# 7.3. Please use language version 8.0 or greater.
// static void LocalStatic()
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "static").WithArguments("static local functions", "8.0").WithLocation(9, 9),
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
baseExpected.Concat(extra).ToArray());
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(baseExpected);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(baseExpected);
}
[Fact]
public void ArglistIterator()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
IEnumerable<int> Local(__arglist)
{
yield return 2;
}
Console.WriteLine(string.Join("","", Local(__arglist())));
}
}
";
VerifyDiagnostics(source,
// (9,26): error CS1636: __arglist is not allowed in the parameter list of iterators
// IEnumerable<int> Local(__arglist)
Diagnostic(ErrorCode.ERR_VarargsIterator, "Local").WithLocation(9, 26),
// (9,32): error CS1669: __arglist is not valid in this context
// IEnumerable<int> Local(__arglist)
Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(9, 32));
}
[Fact]
public void ForwardReference()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Local());
int Local() => 2;
}
}
";
CompileAndVerify(source, expectedOutput: "2");
}
[Fact]
public void ForwardReferenceCapture()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int x = 2;
Console.WriteLine(Local());
int Local() => x;
}
}
";
CompileAndVerify(source, expectedOutput: "2");
}
[Fact]
public void ForwardRefInLocalFunc()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int x = 2;
Console.WriteLine(Local());
int Local()
{
x = 3;
return Local2();
}
int Local2() => x;
}
}
";
CompileAndVerify(source, expectedOutput: "3");
}
[Fact]
public void LocalFuncMutualRecursion()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 0;
Console.WriteLine(Local1());
int Local1()
{
x -= 1;
return Local2(y++);
}
int Local2(int z)
{
if (x == 0)
{
return z;
}
else
{
return Local1();
}
}
}
}
";
CompileAndVerify(source, expectedOutput: "4");
}
[Fact]
public void OtherSwitchBlock()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
var x = int.Parse(Console.ReadLine());
switch (x)
{
case 0:
void Local()
{
}
break;
default:
Local();
break;
}
}
}
";
VerifyDiagnostics(source);
}
[Fact]
public void NoOperator()
{
var source = @"
class Program
{
static void Main(string[] args)
{
Program operator +(Program left, Program right)
{
return left;
}
}
}
";
VerifyDiagnostics(source,
// (6,17): error CS1002: ; expected
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "operator").WithLocation(6, 17),
// (6,17): error CS1513: } expected
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_RbraceExpected, "operator").WithLocation(6, 17),
// (6,56): error CS1002: ; expected
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 56),
// (6,9): error CS0119: 'Program' is a type, which is not valid in the given context
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(6, 9),
// (6,28): error CS8185: A declaration is not allowed in this context.
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "Program left").WithLocation(6, 28),
// (6,42): error CS8185: A declaration is not allowed in this context.
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "Program right").WithLocation(6, 42),
// (6,27): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(Program left, Program right)").WithArguments("System.ValueTuple`2").WithLocation(6, 27),
// (8,13): error CS0127: Since 'Program.Main(string[])' returns void, a return keyword must not be followed by an object expression
// return left;
Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("Program.Main(string[])").WithLocation(8, 13),
// (6,28): error CS0165: Use of unassigned local variable 'left'
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_UseDefViolation, "Program left").WithArguments("left").WithLocation(6, 28),
// (6,42): error CS0165: Use of unassigned local variable 'right'
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_UseDefViolation, "Program right").WithArguments("right").WithLocation(6, 42)
);
}
[Fact]
public void NoProperty()
{
var source = @"
class Program
{
static void Main(string[] args)
{
int Goo
{
get
{
return 2;
}
}
int Bar => 2;
}
}
";
VerifyDiagnostics(source,
// (6,16): error CS1002: ; expected
// int Goo
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 16),
// (8,16): error CS1002: ; expected
// get
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 16),
// (13,17): error CS1003: Syntax error, ',' expected
// int Bar => 2;
Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(13, 17),
// (13,20): error CS1002: ; expected
// int Bar => 2;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "2").WithLocation(13, 20),
// (8,13): error CS0103: The name 'get' does not exist in the current context
// get
Diagnostic(ErrorCode.ERR_NameNotInContext, "get").WithArguments("get").WithLocation(8, 13),
// (10,17): error CS0127: Since 'Program.Main(string[])' returns void, a return keyword must not be followed by an object expression
// return 2;
Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("Program.Main(string[])").WithLocation(10, 17),
// (13,20): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// int Bar => 2;
Diagnostic(ErrorCode.ERR_IllegalStatement, "2").WithLocation(13, 20),
// (13,9): warning CS0162: Unreachable code detected
// int Bar => 2;
Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(13, 9),
// (6,13): warning CS0168: The variable 'Goo' is declared but never used
// int Goo
Diagnostic(ErrorCode.WRN_UnreferencedVar, "Goo").WithArguments("Goo").WithLocation(6, 13),
// (13,13): warning CS0168: The variable 'Bar' is declared but never used
// int Bar => 2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "Bar").WithArguments("Bar").WithLocation(13, 13)
);
}
[Fact]
public void NoFeatureSwitch()
{
var source = @"
class Program
{
static void Main(string[] args)
{
void Local() { }
Local();
}
}
";
var option = TestOptions.ReleaseExe;
CreateCompilation(source, options: option, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics(
// (6,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater.
// void Local() { }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "Local").WithArguments("local functions", "7.0").WithLocation(6, 14)
);
}
[Fact, WorkItem(10521, "https://github.com/dotnet/roslyn/issues/10521")]
public void LocalFunctionInIf()
{
var source = @"
class Program
{
static void Main(string[] args)
{
if () // typing at this point
int Add(int x, int y) => x + y;
}
}
";
VerifyDiagnostics(source,
// (6,13): error CS1525: Invalid expression term ')'
// if () // typing at this point
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 13),
// (7,9): error CS1023: Embedded statement cannot be a declaration or labeled statement
// int Add(int x, int y) => x + y;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "int Add(int x, int y) => x + y;").WithLocation(7, 9),
// (7,13): warning CS8321: The local function 'Add' is declared but never used
// int Add(int x, int y) => x + y;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Add").WithArguments("Add").WithLocation(7, 13)
);
}
[Fact, WorkItem(10521, "https://github.com/dotnet/roslyn/issues/10521")]
public void LabeledLocalFunctionInIf()
{
var source = @"
class Program
{
static void Main(string[] args)
{
if () // typing at this point
a: int Add(int x, int y) => x + y;
}
}
";
VerifyDiagnostics(source,
// (6,13): error CS1525: Invalid expression term ')'
// if () // typing at this point
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 13),
// (7,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: int Add(int x, int y) => x + y;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: int Add(int x, int y) => x + y;").WithLocation(7, 1),
// (7,1): warning CS0164: This label has not been referenced
// a: int Add(int x, int y) => x + y;
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(7, 1),
// (7,13): warning CS8321: The local function 'Add' is declared but never used
// a: int Add(int x, int y) => x + y;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Add").WithArguments("Add").WithLocation(7, 13)
);
}
[CompilerTrait(CompilerFeature.LocalFunctions, CompilerFeature.Var)]
public sealed class VarTests : LocalFunctionsTestBase
{
[Fact]
public void IllegalAsReturn()
{
var source = @"
using System;
class Program
{
static void Main()
{
var f() => 42;
Console.WriteLine(f());
}
}";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: DefaultParseOptions);
comp.VerifyDiagnostics(
// (7,9): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// var f() => 42;
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(7, 9));
}
[Fact]
public void RealTypeAsReturn()
{
var source = @"
using System;
class var
{
public override string ToString() => ""dog"";
}
class Program
{
static void Main()
{
var f() => new var();
Console.WriteLine(f());
}
}";
CompileAndVerify(
source,
parseOptions: DefaultParseOptions,
expectedOutput: "dog");
}
[Fact]
public void RealTypeParameterAsReturn()
{
var source = @"
using System;
class test
{
public override string ToString() => ""dog"";
}
class Program
{
static void Test<var>(var x)
{
var f() => x;
Console.WriteLine(f());
}
static void Main()
{
Test(new test());
}
}";
CompileAndVerify(
source,
parseOptions: DefaultParseOptions,
expectedOutput: "dog");
}
[Fact]
public void IdentifierAndTypeNamedVar()
{
var source = @"
using System;
class var
{
public override string ToString() => ""dog"";
}
class Program
{
static void Main()
{
int var = 42;
var f() => new var();
Console.WriteLine($""{f()}-{var}"");
}
}";
CompileAndVerify(
source,
parseOptions: DefaultParseOptions,
expectedOutput: "dog-42");
}
}
[CompilerTrait(CompilerFeature.LocalFunctions, CompilerFeature.Async)]
public sealed class AsyncTests : LocalFunctionsTestBase
{
[Fact]
public void RealTypeAsReturn()
{
var source = @"
using System;
class async
{
public override string ToString() => ""dog"";
}
class Program
{
static void Main()
{
async f() => new async();
Console.WriteLine(f());
}
}";
CompileAndVerify(
source,
parseOptions: DefaultParseOptions,
expectedOutput: "dog");
}
[Fact]
public void RealTypeParameterAsReturn()
{
var source = @"
using System;
class test
{
public override string ToString() => ""dog"";
}
class Program
{
static void Test<async>(async x)
{
async f() => x;
Console.WriteLine(f());
}
static void Main()
{
Test(new test());
}
}";
CompileAndVerify(
source,
parseOptions: DefaultParseOptions,
expectedOutput: "dog");
}
[Fact]
public void ManyMeaningsType()
{
var source = @"
using System;
using System.Threading;
using System.Threading.Tasks;
class async
{
public override string ToString() => ""async"";
}
class Program
{
static void Main()
{
async Task<async> Test(Task<async> t)
{
async local = await t;
Console.WriteLine(local);
return local;
}
Test(Task.FromResult<async>(new async())).Wait();
}
}";
var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe);
CompileAndVerify(
comp,
expectedOutput: "async");
}
}
[Fact]
[WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")]
public void ParamUnassigned_01()
{
var src = @"
class C
{
public void M1()
{
void TakeOutParam1(out int x)
{
}
int y;
TakeOutParam1(out y);
}
void TakeOutParam2(out int x)
{
}
}";
VerifyDiagnostics(src,
// (6,14): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// void TakeOutParam1(out int x)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam1").WithArguments("x").WithLocation(6, 14),
// (14,14): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// void TakeOutParam2(out int x)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam2").WithArguments("x").WithLocation(14, 14)
);
}
[Fact]
[WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")]
public void ParamUnassigned_02()
{
var src = @"
class C
{
public void M1()
{
void TakeOutParam1(out int x)
{
return; // 1
}
int y;
TakeOutParam1(out y);
}
void TakeOutParam2(out int x)
{
return; // 2
}
}";
VerifyDiagnostics(src,
// (8,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// return; // 1
Diagnostic(ErrorCode.ERR_ParamUnassigned, "return;").WithArguments("x").WithLocation(8, 13),
// (17,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// return; // 2
Diagnostic(ErrorCode.ERR_ParamUnassigned, "return;").WithArguments("x").WithLocation(17, 13)
);
}
[Fact]
[WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")]
public void ParamUnassigned_03()
{
var src = @"
class C
{
public void M1()
{
int TakeOutParam1(out int x)
{
}
int y;
TakeOutParam1(out y);
}
int TakeOutParam2(out int x)
{
}
}";
VerifyDiagnostics(src,
// (6,13): error CS0161: 'TakeOutParam1(out int)': not all code paths return a value
// int TakeOutParam1(out int x)
Diagnostic(ErrorCode.ERR_ReturnExpected, "TakeOutParam1").WithArguments("TakeOutParam1(out int)").WithLocation(6, 13),
// (6,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// int TakeOutParam1(out int x)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam1").WithArguments("x").WithLocation(6, 13),
// (14,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// int TakeOutParam2(out int x)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam2").WithArguments("x").WithLocation(14, 13),
// (14,13): error CS0161: 'C.TakeOutParam2(out int)': not all code paths return a value
// int TakeOutParam2(out int x)
Diagnostic(ErrorCode.ERR_ReturnExpected, "TakeOutParam2").WithArguments("C.TakeOutParam2(out int)").WithLocation(14, 13)
);
}
[Fact]
[WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")]
public void ParamUnassigned_04()
{
var src = @"
class C
{
public void M1()
{
int TakeOutParam1(out int x)
{
return 1;
}
int y;
TakeOutParam1(out y);
}
int TakeOutParam2(out int x)
{
return 2;
}
}";
VerifyDiagnostics(src,
// (8,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// return 1;
Diagnostic(ErrorCode.ERR_ParamUnassigned, "return 1;").WithArguments("x").WithLocation(8, 13),
// (17,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// return 2;
Diagnostic(ErrorCode.ERR_ParamUnassigned, "return 2;").WithArguments("x").WithLocation(17, 13)
);
}
[Fact]
[WorkItem(49500, "https://github.com/dotnet/roslyn/issues/49500")]
public void OutParam_Extern_01()
{
var src = @"
using System.Runtime.InteropServices;
class C
{
void M()
{
int x;
local(out x);
x.ToString();
[DllImport(""a"")]
static extern void local(out int x);
}
[DllImport(""a"")]
static extern void Method(out int x);
}";
VerifyDiagnostics(src);
}
[Fact]
[WorkItem(49500, "https://github.com/dotnet/roslyn/issues/49500")]
public void OutParam_Extern_02()
{
var src = @"
using System.Runtime.InteropServices;
class C
{
void M()
{
local1(out _);
local2(out _);
local3(out _);
[DllImport(""a"")]
static extern void local1(out int x) { } // 1
static void local2(out int x) { } // 2
static void local3(out int x); // 3, 4
}
[DllImport(""a"")]
static extern void Method(out int x);
}";
VerifyDiagnostics(src,
// (13,28): error CS0179: 'local1(out int)' cannot be extern and declare a body
// static extern void local1(out int x) { } // 1
Diagnostic(ErrorCode.ERR_ExternHasBody, "local1").WithArguments("local1(out int)").WithLocation(13, 28),
// (15,21): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// static void local2(out int x) { } // 2
Diagnostic(ErrorCode.ERR_ParamUnassigned, "local2").WithArguments("x").WithLocation(15, 21),
// (17,21): error CS8112: Local function 'local3(out int)' must declare a body because it is not marked 'static extern'.
// static void local3(out int x); // 3, 4
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local3").WithArguments("local3(out int)").WithLocation(17, 21),
// (17,21): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// static void local3(out int x); // 3, 4
Diagnostic(ErrorCode.ERR_ParamUnassigned, "local3").WithArguments("x").WithLocation(17, 21));
}
[Fact]
[WorkItem(13172, "https://github.com/dotnet/roslyn/issues/13172")]
public void InheritUnsafeContext()
{
var comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
async Task<IntPtr> Local()
{
await Task.Delay(0);
return (IntPtr)(void*)null;
}
var _ = Local();
}
public void M2()
{
unsafe
{
async Task<IntPtr> Local()
{
await Task.Delay(1);
return (IntPtr)(void*)null;
}
var _ = Local();
}
}
public unsafe void M3()
{
async Task<IntPtr> Local()
{
await Task.Delay(2);
return (IntPtr)(void*)null;
}
var _ = Local();
}
}
unsafe class D
{
int* p = null;
public void M()
{
async Task<IntPtr> Local()
{
await Task.Delay(3);
return (IntPtr)p;
}
var _ = Local();
}
public unsafe void M2()
{
unsafe
{
async Task<IntPtr> Local()
{
await Task.Delay(4);
return (IntPtr)(void*)null;
}
var _ = Local();
}
}
}", options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (11,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// return (IntPtr)(void*)null;
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*").WithLocation(11, 29),
// (11,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// return (IntPtr)(void*)null;
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(void*)null").WithLocation(11, 28),
// (47,13): error CS4004: Cannot await in an unsafe context
// await Task.Delay(3);
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(3)").WithLocation(47, 13),
// (22,17): error CS4004: Cannot await in an unsafe context
// await Task.Delay(1);
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(1)").WithLocation(22, 17),
// (59,17): error CS4004: Cannot await in an unsafe context
// await Task.Delay(4);
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(4)").WithLocation(59, 17),
// (33,13): error CS4004: Cannot await in an unsafe context
// await Task.Delay(2);
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(2)").WithLocation(33, 13));
}
[Fact, WorkItem(16167, "https://github.com/dotnet/roslyn/issues/16167")]
public void DeclarationInLocalFunctionParameterDefault()
{
var text = @"
class C
{
public static void Main(int arg)
{
void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {}
void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {}
void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {}
void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {}
void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {}
void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {}
int t = z1 + z2 + z3 + z4 + z5 + z6;
}
static bool M(out int z) // needed to infer type of z5
{
z = 1;
return true;
}
static bool M(params object[] args) => true;
}
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
Item1 = item1;
Item2 = item2;
}
}
}
";
// the scope of an expression variable introduced in the default expression
// of a local function parameter is that default expression.
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(arg is int z1, z1)").WithArguments("b").WithLocation(6, 30),
// (6,61): error CS0103: The name 'z1' does not exist in the current context
// void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 61),
// (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out int z2), z2)").WithArguments("b").WithLocation(7, 30),
// (7,61): error CS0103: The name 'z2' does not exist in the current context
// void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 61),
// (8,35): error CS8185: A declaration is not allowed in this context.
// void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {}
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int z3").WithLocation(8, 35),
// (8,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M((int z3, int a2) = (1, 2)), z3)").WithArguments("b").WithLocation(8, 30),
// (8,76): error CS0103: The name 'z3' does not exist in the current context
// void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(8, 76),
// (10,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(arg is var z4, z4)").WithArguments("b").WithLocation(10, 30),
// (10,61): error CS0103: The name 'z4' does not exist in the current context
// void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "z4").WithArguments("z4").WithLocation(10, 61),
// (11,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out var z5), z5)").WithArguments("b").WithLocation(11, 30),
// (11,61): error CS0103: The name 'z5' does not exist in the current context
// void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "z5").WithArguments("z5").WithLocation(11, 61),
// (12,35): error CS8185: A declaration is not allowed in this context.
// void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {}
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var z6").WithLocation(12, 35),
// (12,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M((var z6, int a2) = (1, 2)), z6)").WithArguments("b").WithLocation(12, 30),
// (12,76): error CS0103: The name 'z6' does not exist in the current context
// void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(12, 76),
// (14,17): error CS0103: The name 'z1' does not exist in the current context
// int t = z1 + z2 + z3 + z4 + z5 + z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(14, 17),
// (14,22): error CS0103: The name 'z2' does not exist in the current context
// int t = z1 + z2 + z3 + z4 + z5 + z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 22),
// (14,27): error CS0103: The name 'z3' does not exist in the current context
// int t = z1 + z2 + z3 + z4 + z5 + z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(14, 27),
// (14,32): error CS0103: The name 'z4' does not exist in the current context
// int t = z1 + z2 + z3 + z4 + z5 + z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z4").WithArguments("z4").WithLocation(14, 32),
// (14,37): error CS0103: The name 'z5' does not exist in the current context
// int t = z1 + z2 + z3 + z4 + z5 + z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z5").WithArguments("z5").WithLocation(14, 37),
// (14,42): error CS0103: The name 'z6' does not exist in the current context
// int t = z1 + z2 + z3 + z4 + z5 + z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(14, 42),
// (6,14): warning CS8321: The local function 'Local1' is declared but never used
// void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local1").WithArguments("Local1").WithLocation(6, 14),
// (7,14): warning CS8321: The local function 'Local2' is declared but never used
// void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(7, 14),
// (8,14): warning CS8321: The local function 'Local3' is declared but never used
// void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local3").WithArguments("Local3").WithLocation(8, 14),
// (10,14): warning CS8321: The local function 'Local4' is declared but never used
// void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local4").WithArguments("Local4").WithLocation(10, 14),
// (11,14): warning CS8321: The local function 'Local5' is declared but never used
// void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(11, 14),
// (12,14): warning CS8321: The local function 'Local6' is declared but never used
// void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local6").WithArguments("Local6").WithLocation(12, 14)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var descendents = tree.GetRoot().DescendantNodes();
for (int i = 1; i <= 6; i++)
{
var name = $"z{i}";
var designation = descendents.OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == name).Single();
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(designation);
Assert.NotNull(symbol);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
var refs = descendents.OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == name).ToArray();
Assert.Equal(3, refs.Length);
Assert.Equal(symbol, model.GetSymbolInfo(refs[0]).Symbol);
Assert.Null(model.GetSymbolInfo(refs[1]).Symbol);
Assert.Null(model.GetSymbolInfo(refs[2]).Symbol);
}
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/16451")]
public void RecursiveParameterDefault()
{
var text = @"
class C
{
public static void Main(int arg)
{
int Local(int x = Local()) => 2;
}
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
);
}
[Fact]
[WorkItem(16757, "https://github.com/dotnet/roslyn/issues/16757")]
public void LocalFunctionParameterDefaultUsingConst()
{
var source = @"
class C
{
public static void Main()
{
const int N = 2;
void Local1(int n = N) { System.Console.Write(n); }
Local1();
Local1(3);
}
}
";
CompileAndVerify(source, expectedOutput: "23", sourceSymbolValidator: m =>
{
var compilation = m.DeclaringCompilation;
// See https://github.com/dotnet/roslyn/issues/16454; this should actually produce no errors
compilation.VerifyDiagnostics(
// (6,19): warning CS0219: The variable 'N' is assigned but its value is never used
// const int N = 2;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "N").WithArguments("N").WithLocation(6, 19)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var descendents = tree.GetRoot().DescendantNodes();
var parameter = descendents.OfType<ParameterSyntax>().Single();
Assert.Equal("int n = N", parameter.ToString());
Assert.Equal("[System.Int32 n = 2]", model.GetDeclaredSymbol(parameter).ToTestDisplayString());
var name = "N";
var declarator = descendents.OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == name).Single();
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(declarator);
Assert.NotNull(symbol);
Assert.Equal("System.Int32 N", symbol.ToTestDisplayString());
var refs = descendents.OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == name).ToArray();
Assert.Equal(1, refs.Length);
Assert.Same(symbol, model.GetSymbolInfo(refs[0]).Symbol);
});
}
[Fact]
[WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")]
public void CallFromDifferentSwitchSection_01()
{
var source = @"
class Program
{
static void Main()
{
Test(string.Empty);
}
static void Test(object o)
{
switch (o)
{
case string x:
Assign();
Print();
break;
case int x:
void Assign() { x = 5; }
void Print() => System.Console.WriteLine(x);
break;
}
}
}";
var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "5");
}
[Fact]
[WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")]
public void CallFromDifferentSwitchSection_02()
{
var source = @"
class Program
{
static void Main()
{
Test(string.Empty);
}
static void Test(object o)
{
switch (o)
{
case int x:
void Assign() { x = 5; }
void Print() => System.Console.WriteLine(x);
break;
case string x:
Assign();
Print();
break;
}
}
}";
var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "5");
}
[Fact]
[WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")]
public void CallFromDifferentSwitchSection_03()
{
var source = @"
class Program
{
static void Main()
{
Test(string.Empty);
}
static void Test(object o)
{
switch (o)
{
case string x:
Assign();
System.Action p = Print;
p();
break;
case int x:
void Assign() { x = 5; }
void Print() => System.Console.WriteLine(x);
break;
}
}
}";
var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "5");
}
[Fact]
[WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")]
public void CallFromDifferentSwitchSection_04()
{
var source = @"
class Program
{
static void Main()
{
Test(string.Empty);
}
static void Test(object o)
{
switch (o)
{
case int x:
void Assign() { x = 5; }
void Print() => System.Console.WriteLine(x);
break;
case string x:
Assign();
System.Action p = Print;
p();
break;
}
}
}";
var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "5");
}
[Fact]
[WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")]
public void CallFromDifferentSwitchSection_05()
{
var source = @"
class Program
{
static void Main()
{
Test(string.Empty);
}
static void Test(object o)
{
switch (o)
{
case string x:
Local1();
break;
case int x:
void Local1() => Local2(x = 5);
break;
case char x:
void Local2(int y)
{
System.Console.WriteLine(x = 'a');
System.Console.WriteLine(y);
}
break;
}
}
}";
var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput:
@"a
5");
}
[Fact]
[WorkItem(16751, "https://github.com/dotnet/roslyn/issues/16751")]
public void SemanticModelInAttribute_01()
{
var source =
@"
public class X
{
public static void Main()
{
const bool b1 = true;
void Local1(
[Test(p = b1)]
[Test(p = b2)]
int p1)
{
}
Local1(1);
}
}
class b1 {}
class Test : System.Attribute
{
public bool p {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (10,23): error CS0103: The name 'b2' does not exist in the current context
// [Test(p = b2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "b2").WithArguments("b2").WithLocation(10, 23),
// (6,20): warning CS0219: The variable 'b1' is assigned but its value is never used
// const bool b1 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b1").WithArguments("b1").WithLocation(6, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var b2 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b2").Single();
Assert.Null(model.GetSymbolInfo(b2).Symbol);
var b1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b1").Single();
var b1Symbol = model.GetSymbolInfo(b1).Symbol;
Assert.Equal("System.Boolean b1", b1Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, b1Symbol.Kind);
}
[Fact]
[WorkItem(19778, "https://github.com/dotnet/roslyn/issues/19778")]
public void BindDynamicInvocation()
{
var source =
@"using System;
class C
{
static void M()
{
dynamic L<T>(Func<dynamic, T> t, object p) => p;
L(m => L(d => d, null), null);
L(m => L(d => d, m), null);
}
}";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef, CSharpRef });
comp.VerifyEmitDiagnostics(
// (8,18): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
// L(m => L(d => d, m), null);
Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "d => d").WithLocation(8, 18),
// (8,16): error CS8322: Cannot pass argument with dynamic type to generic local function 'L' with inferred type arguments.
// L(m => L(d => d, m), null);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L(d => d, m)").WithArguments("L").WithLocation(8, 16));
}
[Fact]
[WorkItem(19778, "https://github.com/dotnet/roslyn/issues/19778")]
public void BindDynamicInvocation_Async()
{
var source =
@"using System;
using System.Threading.Tasks;
class C
{
static void M()
{
async Task<dynamic> L<T>(Func<dynamic, T> t, object p)
=> await L(async m => L(async d => await d, m), p);
}
}";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef, CSharpRef });
comp.VerifyEmitDiagnostics(
// (8,37): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
// => await L(async m => L(async d => await d, m), p);
Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "async d => await d").WithLocation(8, 37),
// (8,35): error CS8322: Cannot pass argument with dynamic type to generic local function 'L' with inferred type arguments.
// => await L(async m => L(async d => await d, m), p);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L(async d => await d, m)").WithArguments("L").WithLocation(8, 35),
// (8,32): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// => await L(async m => L(async d => await d, m), p);
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(8, 32));
}
[Fact]
[WorkItem(21317, "https://github.com/dotnet/roslyn/issues/21317")]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicGenericArg()
{
var src = @"
using System.Collections.Generic;
class C
{
static void M()
{
dynamic val = 2;
dynamic dynamicList = new List<int>();
void L1<T>(T x) { }
L1(val);
void L2<T>(int x, T y) { }
L2(1, val);
L2(val, 3.0f);
void L3<T>(List<T> x) { }
L3(dynamicList);
void L4<T>(int x, params T[] y) { }
L4(1, 2, val);
L4(val, 3, 4);
void L5<T>(T x, params int[] y) { }
L5(val, 1, 2);
L5(1, 3, val);
}
}
";
VerifyDiagnostics(src,
// (11,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L1'. Try specifying the type arguments explicitly.
// L1(val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L1(val)").WithArguments("L1").WithLocation(11, 9),
// (14,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L2'. Try specifying the type arguments explicitly.
// L2(1, val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L2(1, val)").WithArguments("L2").WithLocation(14, 9),
// (15,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L2'. Try specifying the type arguments explicitly.
// L2(val, 3.0f);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L2(val, 3.0f)").WithArguments("L2").WithLocation(15, 9),
// (18,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L3'. Try specifying the type arguments explicitly.
// L3(dynamicList);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L3(dynamicList)").WithArguments("L3").WithLocation(18, 9),
// (21,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L4'. Try specifying the type arguments explicitly.
// L4(1, 2, val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L4(1, 2, val)").WithArguments("L4").WithLocation(21, 9),
// (22,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L4'. Try specifying the type arguments explicitly.
// L4(val, 3, 4);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L4(val, 3, 4)").WithArguments("L4").WithLocation(22, 9),
// (25,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L5'. Try specifying the type arguments explicitly.
// L5(val, 1, 2);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L5(val, 1, 2)").WithArguments("L5").WithLocation(25, 9),
// (26,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L5'. Try specifying the type arguments explicitly.
// L5(1, 3, val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L5(1, 3, val)").WithArguments("L5").WithLocation(26, 9)
);
}
[Fact]
[WorkItem(23699, "https://github.com/dotnet/roslyn/issues/23699")]
public void GetDeclaredSymbolOnTypeParameter()
{
var src = @"
class C<T>
{
void M<U>()
{
void LocalFunction<T, U, V>(T p1, U p2, V p3)
{
}
}
}
";
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var localDecl = (LocalFunctionStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.LocalFunctionStatement).AsNode();
var typeParameters = localDecl.TypeParameterList.Parameters;
var parameters = localDecl.ParameterList.Parameters;
verifyTypeParameterAndParameter(typeParameters[0], parameters[0], "T");
verifyTypeParameterAndParameter(typeParameters[1], parameters[1], "U");
verifyTypeParameterAndParameter(typeParameters[2], parameters[2], "V");
void verifyTypeParameterAndParameter(TypeParameterSyntax typeParameter, ParameterSyntax parameter, string expected)
{
var symbol = model.GetDeclaredSymbol(typeParameter);
Assert.Equal(expected, symbol.ToTestDisplayString());
var parameterSymbol = model.GetDeclaredSymbol(parameter);
Assert.Equal(expected, parameterSymbol.Type.ToTestDisplayString());
Assert.Same(symbol, parameterSymbol.Type);
}
}
public sealed class ScriptGlobals
{
public int SomeGlobal => 42;
}
[ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28001")]
public void CanAccessScriptGlobalsFromInsideMethod()
{
var source = @"
void Method()
{
LocalFunction();
void LocalFunction()
{
_ = SomeGlobal;
}
}";
CreateSubmission(source, new[] { ScriptTestFixtures.HostRef }, hostObjectType: typeof(ScriptGlobals))
.VerifyEmitDiagnostics();
}
[ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28001")]
public void CanAccessScriptGlobalsFromInsideLambda()
{
var source = @"
var lambda = new System.Action(() =>
{
LocalFunction();
void LocalFunction()
{
_ = SomeGlobal;
}
});";
CreateSubmission(source, new[] { ScriptTestFixtures.HostRef }, hostObjectType: typeof(ScriptGlobals))
.VerifyEmitDiagnostics();
}
[Fact]
public void CanAccessPreviousSubmissionVariablesFromInsideMethod()
{
var previous = CreateSubmission("int previousSubmissionVariable = 42;")
.VerifyEmitDiagnostics();
var source = @"
void Method()
{
LocalFunction();
void LocalFunction()
{
_ = previousSubmissionVariable;
}
}";
CreateSubmission(source, previous: previous)
.VerifyEmitDiagnostics();
}
[Fact]
public void CanAccessPreviousSubmissionVariablesFromInsideLambda()
{
var previous = CreateSubmission("int previousSubmissionVariable = 42;")
.VerifyEmitDiagnostics();
var source = @"
var lambda = new System.Action(() =>
{
LocalFunction();
void LocalFunction()
{
_ = previousSubmissionVariable;
}
});";
CreateSubmission(source, previous: previous)
.VerifyEmitDiagnostics();
}
[Fact]
public void CanAccessPreviousSubmissionMethodsFromInsideMethod()
{
var previous = CreateSubmission("void PreviousSubmissionMethod() { }")
.VerifyEmitDiagnostics();
var source = @"
void Method()
{
LocalFunction();
void LocalFunction()
{
PreviousSubmissionMethod();
}
}";
CreateSubmission(source, previous: previous)
.VerifyEmitDiagnostics();
}
[Fact]
public void CanAccessPreviousSubmissionMethodsFromInsideLambda()
{
var previous = CreateSubmission("void PreviousSubmissionMethod() { }")
.VerifyEmitDiagnostics();
var source = @"
var lambda = new System.Action(() =>
{
LocalFunction();
void LocalFunction()
{
PreviousSubmissionMethod();
}
});";
CreateSubmission(source, previous: previous)
.VerifyEmitDiagnostics();
}
[Fact]
public void ShadowNames_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
class Program
{
static void M()
{
void F1(object x) { string x = null; } // local
void F2(object x, string y, int x) { } // parameter
void F3(object x) { void x() { } } // method
void F4<x, y>(object x) { void y() { } } // type parameter
void F5(object M, string Program) { }
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
verifyDiagnostics();
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
verifyDiagnostics();
comp = CreateCompilation(source);
verifyDiagnostics();
void verifyDiagnostics()
{
comp.VerifyDiagnostics(
// (7,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1(object x) { string x = null; } // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(7, 36),
// (8,41): error CS0100: The parameter name 'x' is a duplicate
// void F2(object x, string y, int x) { } // parameter
Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x").WithLocation(8, 41),
// (9,34): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F3(object x) { void x() { } } // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 34),
// (10,30): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void F4<x, y>(object x) { void y() { } } // type parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 30),
// (10,40): error CS0412: 'y': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void F4<x, y>(object x) { void y() { } } // type parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "y").WithArguments("y").WithLocation(10, 40));
}
}
[Fact]
public void ShadowNames_Local_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M()
{
object x = null;
void F1() { object x = 0; } // local
void F2(string x) { } // parameter
void F3() { void x() { } } // method
void F4<x>() { } // type parameter
void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1() { object x = 0; } // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 28),
// (10,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F2(string x) { } // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 24),
// (11,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F3() { void x() { } } // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 26),
// (12,17): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F4<x>() { } // type parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 17),
// (13,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 30));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Local_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M()
{
void F1() { object x = 0; } // local
void F2(string x) { } // parameter
void F3() { void x() { } } // method
void F4<x>() { } // type parameter
void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
object x = null;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1() { object x = 0; } // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 28),
// (9,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F2(string x) { } // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 24),
// (10,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F3() { void x() { } } // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 26),
// (11,17): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F4<x>() { } // type parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 17),
// (12,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 30));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Local_03()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M()
{
static void F1() { object x = 0; } // local
static void F2(string x) { } // parameter
static void F3() { void x() { } } // method
static void F4<x>() { } // type parameter
static void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
object x = null;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Parameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M(object x)
{
void F1() { object x = 0; } // local
void F2(string x) { } // parameter
void F3() { void x() { } } // method
void F4<x>() { } // type parameter
void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
// The conflict between the type parameter in F4<x>() and the parameter
// in M(object x) is not reported, for backwards compatibility.
comp.VerifyDiagnostics(
// (8,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1() { object x = 0; } // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 28),
// (9,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F2(string x) { } // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 24),
// (10,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F3() { void x() { } } // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 26),
// (12,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 30));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_TypeParameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M<x>()
{
void F1() { object x = 0; } // local
void F2(string x) { } // parameter
void F3() { void x() { } } // method
void F4<x>() { } // type parameter
void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,28): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void F1() { object x = 0; } // local
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(8, 28),
// (9,24): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void F2(string x) { } // parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 24),
// (10,26): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void F3() { void x() { } } // method
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 26),
// (11,17): warning CS8387: Type parameter 'x' has the same name as the type parameter from outer method 'Program.M<x>()'
// void F4<x>() { } // type parameter
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "x").WithArguments("x", "Program.M<x>()").WithLocation(11, 17),
// (12,30): error CS1948: The range variable 'x' cannot have the same name as a method type parameter
// void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(12, 30));
comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,17): warning CS8387: Type parameter 'x' has the same name as the type parameter from outer method 'Program.M<x>()'
// void F4<x>() { } // type parameter
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "x").WithArguments("x", "Program.M<x>()").WithLocation(11, 17));
}
[Fact]
public void ShadowNames_LocalFunction_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M()
{
void x() { }
void F1() { object x = 0; } // local
void F2(string x) { } // parameter
void F3() { void x() { } } // method
void F4<x>() { } // type parameter
void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1() { object x = 0; } // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 28),
// (10,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F2(string x) { } // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 24),
// (11,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F3() { void x() { } } // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 26),
// (12,17): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F4<x>() { } // type parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 17),
// (13,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 30));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LocalFunction_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
class Program
{
static void M1()
{
void M1() { }
}
static void M2(object x)
{
void x() { }
}
static void M3()
{
object x = null;
void x() { }
}
static void M4<T>()
{
void T() { }
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
verifyDiagnostics();
comp = CreateCompilation(source);
verifyDiagnostics();
void verifyDiagnostics()
{
comp.VerifyDiagnostics(
// (11,14): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void x() { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 14),
// (16,14): error CS0128: A local variable or function named 'x' is already defined in this scope
// void x() { }
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(16, 14),
// (20,14): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void T() { }
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(20, 14));
}
}
[Fact]
public void ShadowNames_ThisLocalFunction()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M()
{
void F1() { object F1 = 0; } // local
void F2(string F2) { } // parameter
void F3() { void F3() { } } // method
void F4<F4>() { } // type parameter
void F5() { _ = from F5 in new[] { 1, 2, 3 } select F5; } // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,28): error CS0136: A local or parameter named 'F1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1() { object F1 = 0; } // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F1").WithArguments("F1").WithLocation(8, 28),
// (9,24): error CS0136: A local or parameter named 'F2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F2(string F2) { } // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F2").WithArguments("F2").WithLocation(9, 24),
// (10,26): error CS0136: A local or parameter named 'F3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F3() { void F3() { } } // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F3").WithArguments("F3").WithLocation(10, 26),
// (11,17): error CS0136: A local or parameter named 'F4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F4<F4>() { } // type parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F4").WithArguments("F4").WithLocation(11, 17),
// (12,30): error CS1931: The range variable 'F5' conflicts with a previous declaration of 'F5'
// void F5() { _ = from F5 in new[] { 1, 2, 3 } select F5; } // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "F5").WithArguments("F5").WithLocation(12, 30));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LocalFunctionInsideLocalFunction_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
class Program
{
static void M<T>(object x)
{
void F()
{
void G1(int x) { }
void G2() { int T = 0; }
void G3<T>() { }
}
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,25): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void G1(int x) { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 25),
// (10,29): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void G2() { int T = 0; }
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(10, 29),
// (11,21): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Program.M<T>(object)'
// void G3<T>() { }
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Program.M<T>(object)").WithLocation(11, 21));
comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,21): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Program.M<T>(object)'
// void G3<T>() { }
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Program.M<T>(object)").WithLocation(11, 21));
}
[Fact]
public void ShadowNames_LocalFunctionInsideLocalFunction_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
class Program
{
static void M<T>(object x)
{
static void F1()
{
void G1(int x) { }
}
void F2()
{
static void G2() { int T = 0; }
}
static void F3()
{
static void G3<T>() { }
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (17,28): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Program.M<T>(object)'
// static void G3<T>() { }
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Program.M<T>(object)").WithLocation(17, 28));
}
[Fact]
public void ShadowNames_LocalFunctionInsideLambda_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
Action a1 = () =>
{
int x = 0;
void F1() { object x = null; }
};
Action a2 = () =>
{
int T = 0;
void F2<T>() { }
};
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (11,32): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1() { object x = null; }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 32),
// (16,21): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F2<T>() { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(16, 21));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LocalFunctionInsideLambda_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
Action<int> a1 = x =>
{
void F1(object x) { }
};
Action<int> a2 = (int T) =>
{
void F2<T>() { }
};
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
// The conflict between the type parameter in F2<T>() and the parameter
// in a2 is not reported, for backwards compatibility.
comp.VerifyDiagnostics(
// (10,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1(object x) { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 28));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LocalFunctionInsideLambda_03()
{
var source =
@"using System;
class Program
{
static void M()
{
Action<int> a = x =>
{
void x() { }
x();
};
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
// The conflict between the local function and the parameter is not reported,
// for backwards compatibility.
comp.VerifyDiagnostics();
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void StaticWithThisReference()
{
var source =
@"#pragma warning disable 8321
class C
{
void M()
{
static object F1() => this.GetHashCode();
static object F2() => base.GetHashCode();
static void F3()
{
object G3() => ToString();
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,31): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// static object F1() => this.GetHashCode();
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(6, 31),
// (7,31): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// static object F2() => base.GetHashCode();
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(7, 31),
// (10,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// object G3() => ToString();
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "ToString").WithLocation(10, 28));
}
[Fact]
public void StaticWithVariableReference()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M(object x)
{
object y = null;
static object F1() => x;
static object F2() => y;
static void F3()
{
object G3() => x;
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,31): error CS8421: A static local function cannot contain a reference to 'x'.
// static object F1() => x;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(7, 31),
// (8,31): error CS8421: A static local function cannot contain a reference to 'y'.
// static object F2() => y;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "y").WithArguments("y").WithLocation(8, 31),
// (11,28): error CS8421: A static local function cannot contain a reference to 'x'.
// object G3() => x;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(11, 28));
}
[Fact]
public void StaticWithLocalFunctionVariableReference_01()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M()
{
static void F(object x)
{
object y = null;
object G1() => x ?? y;
static object G2() => x ?? y;
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (10,35): error CS8421: A static local function cannot contain a reference to 'x'.
// static object G2() => x ?? y;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(10, 35),
// (10,40): error CS8421: A static local function cannot contain a reference to 'y'.
// static object G2() => x ?? y;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "y").WithArguments("y").WithLocation(10, 40));
}
[Fact]
public void StaticWithLocalFunctionVariableReference_02()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M(int x)
{
static void F1(int y)
{
int F2() => x + y;
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,25): error CS8421: A static local function cannot contain a reference to 'x'.
// int F2() => x + y;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(8, 25));
}
/// <summary>
/// Can reference type parameters from enclosing scope.
/// </summary>
[Fact]
public void StaticWithTypeParameterReferences()
{
var source =
@"using static System.Console;
class A<T>
{
internal string F1()
{
static string L1() => typeof(T).FullName;
return L1();
}
}
class B
{
internal string F2<T>()
{
static string L2() => typeof(T).FullName;
return L2();
}
internal static string F3()
{
static string L3<T>()
{
static string L4() => typeof(T).FullName;
return L4();
}
return L3<byte>();
}
}
class Program
{
static void Main()
{
WriteLine(new A<int>().F1());
WriteLine(new B().F2<string>());
WriteLine(B.F3());
}
}";
CompileAndVerify(source, expectedOutput:
@"System.Int32
System.String
System.Byte");
}
[Fact]
public void Conditional_ThisReferenceInStatic()
{
var source =
@"#pragma warning disable 0649
#pragma warning disable 8321
using System.Diagnostics;
class A
{
internal object _f;
}
class B : A
{
[Conditional(""MyDefine"")]
static void F(object o)
{
}
void M()
{
static void F1() { F(this); }
static void F2() { F(base._f); }
static void F3() { F(_f); }
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithPreprocessorSymbols("MyDefine"));
verifyDiagnostics();
comp = CreateCompilation(source, parseOptions: TestOptions.Regular);
verifyDiagnostics();
void verifyDiagnostics()
{
comp.VerifyDiagnostics(
// (16,30): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// static void F1() { F(this); }
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(16, 30),
// (17,30): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// static void F2() { F(base._f); }
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(17, 30),
// (18,30): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// static void F3() { F(_f); }
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "_f").WithLocation(18, 30));
}
}
[Fact]
public void LocalFunctionConditional_Errors()
{
var source = @"
using System.Diagnostics;
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[Conditional(""DEBUG"")] // 1
int local1() => 42;
[Conditional(""DEBUG"")] // 2
void local2(out int i) { i = 42; }
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,10): error CS0578: The Conditional attribute is not valid on 'local1()' because its return type is not void
// [Conditional("DEBUG")] // 1
Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"Conditional(""DEBUG"")").WithArguments("local1()").WithLocation(10, 10),
// (13,10): error CS0685: Conditional member 'local2(out int)' cannot have an out parameter
// [Conditional("DEBUG")] // 2
Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""DEBUG"")").WithArguments("local2(out int)").WithLocation(13, 10));
}
[Fact]
public void LocalFunctionObsolete()
{
var source = @"
using System;
class C
{
void M1()
{
local1(); // 1
local2(); // 2
[Obsolete]
void local1() { }
[Obsolete(""hello"", true)]
void local2() { }
#pragma warning disable 8321 // Unreferenced local function
[Obsolete]
void local3()
{
// no diagnostics expected when calling an Obsolete method within an Obsolete method
local1();
local2();
}
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (8,9): warning CS0612: 'local1()' is obsolete
// local1(); // 1
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "local1()").WithArguments("local1()").WithLocation(8, 9),
// (9,9): error CS0619: 'local2()' is obsolete: 'hello'
// local2(); // 2
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "local2()").WithArguments("local2()", "hello").WithLocation(9, 9));
}
[Fact]
public void LocalFunction_AttributeMarkedObsolete()
{
var source = @"
using System;
[Obsolete]
class Attr : Attribute { }
class C
{
void M1()
{
#pragma warning disable 8321
[Attr] void local1() { } // 1
[return: Attr] void local2() { } // 2
void local3([Attr] int i) { } // 3
void local4<[Attr] T>(T t) { } // 4
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (12,10): warning CS0612: 'Attr' is obsolete
// [Attr] void local1() { } // 1
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(12, 10),
// (13,18): warning CS0612: 'Attr' is obsolete
// [return: Attr] void local2() { } // 2
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(13, 18),
// (14,22): warning CS0612: 'Attr' is obsolete
// void local3([Attr] int i) { } // 3
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(14, 22),
// (15,22): warning CS0612: 'Attr' is obsolete
// void local4<[Attr] T>(T t) { } // 4
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(15, 22));
}
[Fact]
public void LocalFunction_NotNullIfNotNullAttribute()
{
var source = @"
using System.Diagnostics.CodeAnalysis;
#nullable enable
class C
{
void M()
{
_ = local1(null).ToString(); // 1
_ = local1(""hello"").ToString();
[return: NotNullIfNotNull(""s1"")]
string? local1(string? s1) => s1;
}
}
";
var comp = CreateCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,13): warning CS8602: Dereference of a possibly null reference.
// _ = local1(null).ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "local1(null)").WithLocation(10, 13));
}
[Fact]
public void LocalFunction_MaybeNullWhenAttribute()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M()
{
_ = tryGetValue(true, out var s)
? s.ToString()
: s.ToString(); // 1
bool tryGetValue(bool b, [MaybeNullWhen(false)] out string s1)
{
s1 = b ? ""abc"" : null;
return b;
}
}
}
";
var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (12,15): warning CS8602: Dereference of a possibly null reference.
// : s.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 15));
}
[Fact]
public void LocalFunction_MaybeNullWhenAttribute_CheckUsage()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M()
{
var s = ""abc"";
local1();
tryGetValue(""a"", out s);
local1();
void local1()
{
_ = s.ToString(); // 1
}
bool tryGetValue(string key, [MaybeNullWhen(false)] out string s1)
{
s1 = key;
return true;
}
}
}
";
var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (18,17): warning CS8602: Dereference of a possibly null reference.
// _ = s.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17));
}
[Fact]
public void LocalFunction_AllowNullAttribute()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M<T>([AllowNull] T t1, T t2)
{
local1(t1);
local1(t2);
local2(t1); // 1
local2(t2);
void local1([AllowNull] T t) { }
void local2(T t) { }
}
}
";
var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (13,16): warning CS8604: Possible null reference argument for parameter 't' in 'void local2(T t)'.
// local2(t1); // 1
Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t1").WithArguments("t", "void local2(T t)").WithLocation(13, 16));
}
[Fact]
public void LocalFunction_MaybeNullAttribute()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M<TOuter>()
{
getDefault<string>().ToString(); // 1
getDefault<string?>().ToString(); // 2
getDefault<int>().ToString();
getDefault<int?>().Value.ToString(); // 3
getDefault<TOuter>().ToString(); // 4
[return: MaybeNull] T getDefault<T>() => default(T);
}
}
";
var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,9): warning CS8602: Dereference of a possibly null reference.
// getDefault<string>().ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "getDefault<string>()").WithLocation(10, 9),
// (11,9): warning CS8602: Dereference of a possibly null reference.
// getDefault<string?>().ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "getDefault<string?>()").WithLocation(11, 9),
// (13,9): warning CS8629: Nullable value type may be null.
// getDefault<int?>().Value.ToString(); // 3
Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "getDefault<int?>()").WithLocation(13, 9),
// (14,9): warning CS8602: Dereference of a possibly null reference.
// getDefault<TOuter>().ToString(); // 4
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "getDefault<TOuter>()").WithLocation(14, 9));
}
[Fact]
public void LocalFunction_Nullable_CheckUsage_DoesNotUsePostconditions()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M()
{
var s0 = ""hello"";
local1(out s0);
bool local1([MaybeNullWhen(false)] out string s1)
{
s0.ToString();
s1 = ""world"";
return true;
}
}
}
";
var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void LocalFunction_DoesNotReturn()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M(string? s)
{
local1();
s.ToString();
[DoesNotReturn]
void local1()
{
throw null!;
}
}
}
";
var comp = CreateCompilation(new[] { DoesNotReturnAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void LocalFunction_DoesNotReturnIf()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M(string? s1, string? s2)
{
local1(s1 != null);
s1.ToString();
local1(false);
s2.ToString();
void local1([DoesNotReturnIf(false)] bool b)
{
throw null!;
}
}
}
";
var comp = CreateCompilation(new[] { DoesNotReturnIfAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void NameOf_ThisReferenceInStatic()
{
var source =
@"#pragma warning disable 8321
class C
{
void M()
{
static object F1() => nameof(this.ToString);
static object F2() => nameof(base.GetHashCode);
static object F3() => nameof(M);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void NameOf_InstanceMemberInStatic()
{
var source =
@"#pragma warning disable 0649
#pragma warning disable 8321
class C
{
object _f;
static void M()
{
_ = nameof(_f);
static object F() => nameof(_f);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = GetNameOfExpressions(tree)[1];
var symbol = model.GetSymbolInfo(expr).Symbol;
Assert.Equal("System.Object C._f", symbol.ToTestDisplayString());
}
[Fact]
public void NameOf_CapturedVariableInStatic()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M(object x)
{
static object F() => nameof(x);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = GetNameOfExpressions(tree)[0];
var symbol = model.GetSymbolInfo(expr).Symbol;
Assert.Equal("System.Object x", symbol.ToTestDisplayString());
}
/// <summary>
/// nameof(x) should bind to shadowing symbol.
/// </summary>
[Fact]
public void NameOf_ShadowedVariable()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M(object x)
{
object F()
{
int x = 0;
return nameof(x);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = GetNameOfExpressions(tree)[0];
var symbol = model.GetSymbolInfo(expr).Symbol;
Assert.Equal(SymbolKind.Local, symbol.Kind);
Assert.Equal("System.Int32 x", symbol.ToTestDisplayString());
}
/// <summary>
/// nameof(T) should bind to shadowing symbol.
/// </summary>
[Fact]
public void NameOf_ShadowedTypeParameter()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M<T>()
{
object F1()
{
int T = 0;
return nameof(T);
}
object F2<T>()
{
return nameof(T);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,19): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M<T>()'
// object F2<T>()
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M<T>()").WithLocation(11, 19));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = GetNameOfExpressions(tree);
var symbol = model.GetSymbolInfo(exprs[0]).Symbol;
Assert.Equal(SymbolKind.Local, symbol.Kind);
Assert.Equal("System.Int32 T", symbol.ToTestDisplayString());
symbol = model.GetSymbolInfo(exprs[1]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("System.Object F2<T>()", symbol.ContainingSymbol.ToTestDisplayString());
}
/// <summary>
/// typeof(T) should bind to nearest type.
/// </summary>
[Fact]
public void TypeOf_ShadowedTypeParameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
class C
{
static void M<T>()
{
object F1()
{
int T = 0;
return typeof(T);
}
object F2<T>()
{
return typeof(T);
}
object F3<U>()
{
return typeof(U);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (12,19): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M<T>()'
// object F2<T>()
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M<T>()").WithLocation(12, 19));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<TypeOfExpressionSyntax>().Select(n => n.Type).ToImmutableArray();
var symbol = model.GetSymbolInfo(exprs[0]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("void C.M<T>()", symbol.ContainingSymbol.ToTestDisplayString());
symbol = model.GetSymbolInfo(exprs[1]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("System.Object F2<T>()", symbol.ContainingSymbol.ToTestDisplayString());
symbol = model.GetSymbolInfo(exprs[2]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("System.Object F3<U>()", symbol.ContainingSymbol.ToTestDisplayString());
}
/// <summary>
/// sizeof(T) should bind to nearest type.
/// </summary>
[Fact]
public void SizeOf_ShadowedTypeParameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
unsafe class C
{
static void M<T>() where T : unmanaged
{
object F1()
{
int T = 0;
return sizeof(T);
}
object F2<T>() where T : unmanaged
{
return sizeof(T);
}
object F3<U>() where U : unmanaged
{
return sizeof(U);
}
}
}";
var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (12,19): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M<T>()'
// object F2<T>()
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M<T>()").WithLocation(12, 19));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>().Select(n => n.Type).ToImmutableArray();
var symbol = model.GetSymbolInfo(exprs[0]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("void C.M<T>()", symbol.ContainingSymbol.ToTestDisplayString());
symbol = model.GetSymbolInfo(exprs[1]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("System.Object F2<T>()", symbol.ContainingSymbol.ToTestDisplayString());
symbol = model.GetSymbolInfo(exprs[2]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("System.Object F3<U>()", symbol.ContainingSymbol.ToTestDisplayString());
}
private static ImmutableArray<ExpressionSyntax> GetNameOfExpressions(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().
OfType<InvocationExpressionSyntax>().
Where(n => n.Expression.ToString() == "nameof").
Select(n => n.ArgumentList.Arguments[0].Expression).
ToImmutableArray();
}
[Fact]
public void ShadowWithSelfReferencingLocal()
{
var source =
@"using System;
class Program
{
static void Main()
{
int x = 13;
void Local()
{
int x = (x = 0) + 42;
Console.WriteLine(x);
}
Local();
Console.WriteLine(x);
}
}";
CompileAndVerify(source, expectedOutput:
@"42
13");
}
[Fact, WorkItem(38129, "https://github.com/dotnet/roslyn/issues/38129")]
public void StaticLocalFunctionLocalFunctionReference_01()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M()
{
void F1() {}
static void F2() {}
static void F3()
{
F1();
F2();
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,13): error CS8421: A static local function cannot contain a reference to 'F1'.
// F1();
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "F1()").WithArguments("F1").WithLocation(11, 13));
}
[Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")]
public void StaticLocalFunctionLocalFunctionReference_02()
{
var source =
@"#pragma warning disable 8321
class Program
{
static void Method()
{
void Local<T>() {}
static void StaticLocal()
{
Local<int>();
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,13): error CS8421: A static local function cannot contain a reference to 'Local'.
// Local<int>();
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>()").WithArguments("Local").WithLocation(9, 13));
}
[Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")]
public void StaticLocalFunctionLocalFunctionReference_03()
{
var source =
@"using System;
class Program
{
static void Method()
{
int i = 0;
void Local<T>()
{
i = 0;
}
Action a = () => i++;
static void StaticLocal()
{
Local<int>();
}
StaticLocal();
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (14,13): error CS8421: A static local function cannot contain a reference to 'Local'.
// Local<int>();
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>()").WithArguments("Local").WithLocation(14, 13));
}
[Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")]
public void StaticLocalFunctionLocalFunctionDelegateReference_01()
{
var source =
@"#pragma warning disable 8321
using System;
class C
{
static void M()
{
void F1() {}
static void F2()
{
Action a = F1;
_ = new Action(F1);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,24): error CS8421: A static local function cannot contain a reference to 'F1'.
// Action a = F1;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "F1").WithArguments("F1").WithLocation(11, 24),
// (12,28): error CS8421: A static local function cannot contain a reference to 'F1'.
// _ = new Action(F1);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "F1").WithArguments("F1").WithLocation(12, 28));
}
[Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")]
public void StaticLocalFunctionLocalFunctionDelegateReference_02()
{
var source =
@"#pragma warning disable 8321
using System;
class Program
{
static void Method()
{
void Local<T>() {}
static void StaticLocal()
{
Action a;
a = Local<int>;
a = new Action(Local<string>);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,17): error CS8421: A static local function cannot contain a reference to 'Local'.
// a = Local<int>;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>").WithArguments("Local").WithLocation(11, 17),
// (12,28): error CS8421: A static local function cannot contain a reference to 'Local'.
// a = new Action(Local<string>);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<string>").WithArguments("Local").WithLocation(12, 28));
}
[Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")]
public void StaticLocalFunctionLocalFunctionDelegateReference_03()
{
var source =
@"using System;
class Program
{
static void Method()
{
int i = 0;
void Local<T>()
{
i = 0;
}
Action a = () => i++;
a = StaticLocal();
static Action StaticLocal()
{
return Local<int>;
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (15,20): error CS8421: A static local function cannot contain a reference to 'Local'.
// return Local<int>;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>").WithArguments("Local").WithLocation(15, 20));
}
[Fact]
public void StaticLocalFunctionGenericStaticLocalFunction()
{
var source =
@"using System;
class Program
{
static void Main()
{
static void F1<T>()
{
Console.WriteLine(typeof(T));
}
static void F2()
{
F1<int>();
Action a = F1<string>;
a();
}
F2();
}
}";
CompileAndVerify(source, expectedOutput:
@"System.Int32
System.String");
}
[Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")]
public void StaticLocalFunctionStaticFunctionsDelegateReference()
{
var source =
@"#pragma warning disable 8321
using System;
class C
{
static void M()
{
static void F1() {}
static void F2()
{
Action m = M;
Action f1 = F1;
_ = new Action(M);
_ = new Action(F1);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")]
public void StaticLocalFunctionThisAndBaseDelegateReference()
{
var source =
@"#pragma warning disable 8321
using System;
class B
{
public virtual void M() {}
}
class C : B
{
public override void M()
{
static void F()
{
Action a1 = base.M;
Action a2 = this.M;
Action a3 = M;
_ = new Action(base.M);
_ = new Action(this.M);
_ = new Action(M);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (14,25): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// Action a1 = base.M;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(14, 25),
// (15,25): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// Action a2 = this.M;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(15, 25),
// (16,25): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// Action a3 = M;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "M").WithLocation(16, 25),
// (17,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// _ = new Action(base.M);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(17, 28),
// (18,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// _ = new Action(this.M);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(18, 28),
// (19,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// _ = new Action(M);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "M").WithLocation(19, 28));
}
[Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")]
public void StaticLocalFunctionDelegateReferenceWithReceiver()
{
var source =
@"#pragma warning disable 649
#pragma warning disable 8321
using System;
class C
{
object f;
void M()
{
object l;
static void F1()
{
_ = new Func<int>(f.GetHashCode);
_ = new Func<int>(l.GetHashCode);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (14,31): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// _ = new Func<int>(f.GetHashCode);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "f").WithLocation(14, 31),
// (15,31): error CS8421: A static local function cannot contain a reference to 'l'.
// _ = new Func<int>(l.GetHashCode);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "l").WithArguments("l").WithLocation(15, 31));
}
[Fact]
[WorkItem(38143, "https://github.com/dotnet/roslyn/issues/38143")]
public void EmittedAsStatic_01()
{
var source =
@"class Program
{
static void M()
{
static void local() { }
System.Action action = local;
}
}";
CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: m =>
{
var method = (MethodSymbol)m.GlobalNamespace.GetMember("Program.<M>g__local|0_0");
Assert.True(method.IsStatic);
});
}
[Fact]
[WorkItem(38143, "https://github.com/dotnet/roslyn/issues/38143")]
public void EmittedAsStatic_02()
{
var source =
@"class Program
{
static void M<T>()
{
static void local(T t) { System.Console.Write(t.GetType().FullName); }
System.Action<T> action = local;
action(default(T));
}
static void Main()
{
M<int>();
}
}";
CompileAndVerify(source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "System.Int32", symbolValidator: m =>
{
var method = (MethodSymbol)m.GlobalNamespace.GetMember("Program.<M>g__local|0_0");
Assert.True(method.IsStatic);
Assert.True(method.IsGenericMethod);
Assert.Equal("void Program.<M>g__local|0_0<T>(T t)", method.ToTestDisplayString());
});
}
/// <summary>
/// Local function in generic method is emitted as a generic
/// method even if no references to type parameters.
/// </summary>
[Fact]
[WorkItem(38143, "https://github.com/dotnet/roslyn/issues/38143")]
public void EmittedAsStatic_03()
{
var source =
@"class Program
{
static void M<T>() where T : new()
{
static void local(object o) { System.Console.Write(o.GetType().FullName); }
local(new T());
}
static void Main()
{
M<int>();
}
}";
CompileAndVerify(source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "System.Int32", symbolValidator: m =>
{
var method = (MethodSymbol)m.GlobalNamespace.GetMember("Program.<M>g__local|0_0");
Assert.True(method.IsStatic);
Assert.True(method.IsGenericMethod);
Assert.Equal("void Program.<M>g__local|0_0<T>(System.Object o)", method.ToTestDisplayString());
});
}
/// <summary>
/// Emit 'call' rather than 'callvirt' for local functions regardless of whether
/// the local function is static.
/// </summary>
[Fact]
public void EmitCallInstruction()
{
var source =
@"using static System.Console;
class Program
{
static void Main()
{
int i;
void L1() => WriteLine(i++);
static void L2(int i) => WriteLine(i);
i = 1;
L1();
L2(i);
}
}";
var verifier = CompileAndVerify(source, expectedOutput:
@"1
2");
verifier.VerifyIL("Program.Main",
@"{
// Code size 27 (0x1b)
.maxstack 2
.locals init (Program.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: stfld ""int Program.<>c__DisplayClass0_0.i""
IL_0008: ldloca.s V_0
IL_000a: call ""void Program.<Main>g__L1|0_0(ref Program.<>c__DisplayClass0_0)""
IL_000f: ldloc.0
IL_0010: ldfld ""int Program.<>c__DisplayClass0_0.i""
IL_0015: call ""void Program.<Main>g__L2|0_1(int)""
IL_001a: ret
}");
}
/// <summary>
/// '_' should bind to '_' symbol in outer scope even in static local function.
/// </summary>
[Fact]
public void UnderscoreInOuterScope()
{
var source =
@"#pragma warning disable 8321
class C1
{
object _;
void F1()
{
void A1(object x) => _ = x;
static void B1(object y) => _ = y;
}
}
class C2
{
static void F2()
{
object _;
void A2(object x) => _ = x;
static void B2(object y) => _ = y;
}
static void F3()
{
void A3(object x) => _ = x;
static void B3(object y) => _ = y;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,37): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// static void B1(object y) => _ = y;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "_").WithLocation(8, 37),
// (17,37): error CS8421: A static local function cannot contain a reference to '_'.
// static void B2(object y) => _ = y;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "_").WithArguments("_").WithLocation(17, 37));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>();
var actualSymbols = nodes.Select(n => model.GetSymbolInfo(n.Left).Symbol).Select(s => $"{s.Kind}: {s.ToTestDisplayString()}").ToArray();
var expectedSymbols = new[]
{
"Field: System.Object C1._",
"Field: System.Object C1._",
"Local: System.Object _",
"Local: System.Object _",
"Discard: System.Object _",
"Discard: System.Object _",
};
AssertEx.Equal(expectedSymbols, actualSymbols);
}
/// <summary>
/// 'var' should bind to 'var' symbol in outer scope even in static local function.
/// </summary>
[Fact]
public void VarInOuterScope()
{
var source =
@"#pragma warning disable 8321
class C1
{
class var { }
static void F1()
{
void A1(object x) { var y = x; }
static void B1(object x) { var y = x; }
}
}
namespace N
{
using var = System.String;
class C2
{
static void F2()
{
void A2(object x) { var y = x; }
static void B3(object x) { var y = x; }
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,37): error CS0266: Cannot implicitly convert type 'object' to 'C1.var'. An explicit conversion exists (are you missing a cast?)
// void A1(object x) { var y = x; }
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "C1.var").WithLocation(7, 37),
// (8,44): error CS0266: Cannot implicitly convert type 'object' to 'C1.var'. An explicit conversion exists (are you missing a cast?)
// static void B1(object x) { var y = x; }
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "C1.var").WithLocation(8, 44),
// (18,41): error CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
// void A2(object x) { var y = x; }
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "string").WithLocation(18, 41),
// (19,48): error CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
// static void B3(object x) { var y = x; }
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "string").WithLocation(19, 48));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>();
var actualSymbols = nodes.Select(n => model.GetDeclaredSymbol(n)).ToTestDisplayStrings();
var expectedSymbols = new[]
{
"C1.var y",
"C1.var y",
"System.String y",
"System.String y",
};
AssertEx.Equal(expectedSymbols, actualSymbols);
}
[Fact]
public void AwaitWithinAsyncOuterScope_01()
{
var source =
@"#pragma warning disable 1998
#pragma warning disable 8321
using System.Threading.Tasks;
class Program
{
void F1()
{
void A1() { await Task.Yield(); }
static void B1() { await Task.Yield(); }
}
void F2()
{
async void A2() { await Task.Yield(); }
async static void B2() { await Task.Yield(); }
}
async void F3()
{
void A3() { await Task.Yield(); }
static void B3() { await Task.Yield(); }
}
async void F4()
{
async void A4() { await Task.Yield(); }
async static void B4() { await Task.Yield(); }
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,21): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// void A1() { await Task.Yield(); }
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(8, 21),
// (9,28): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// static void B1() { await Task.Yield(); }
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(9, 28),
// (18,21): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// void A3() { await Task.Yield(); }
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(18, 21),
// (19,28): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// static void B3() { await Task.Yield(); }
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(19, 28));
}
/// <summary>
/// 'await' should be a contextual keyword in the same way,
/// regardless of whether local function is static.
/// </summary>
[Fact]
public void AwaitWithinAsyncOuterScope_02()
{
var source =
@"#pragma warning disable 1998
#pragma warning disable 8321
class Program
{
void F1()
{
void A1<await>() { }
static void B1<await>() { }
}
void F2()
{
async void A2<await>() { }
async static void B2<await>() { }
}
async void F3()
{
void A3<await>() { }
static void B3<await>() { }
}
async void F4()
{
async void A4<await>() { }
async static void B4<await>() { }
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (12,23): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// async void A2<await>() { }
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(12, 23),
// (13,30): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// async static void B2<await>() { }
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(13, 30),
// (22,23): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// async void A4<await>() { }
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(22, 23),
// (23,30): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// async static void B4<await>() { }
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(23, 30));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using System;
using System.Collections.Immutable;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class LocalFunctionsTestBase : CSharpTestBase
{
internal static readonly CSharpParseOptions DefaultParseOptions = TestOptions.Regular;
internal static void VerifyDiagnostics(string source, params DiagnosticDescription[] expected)
{
var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseDll, parseOptions: DefaultParseOptions);
comp.VerifyDiagnostics(expected);
}
}
[CompilerTrait(CompilerFeature.LocalFunctions)]
public class LocalFunctionTests : LocalFunctionsTestBase
{
[Fact, WorkItem(29656, "https://github.com/dotnet/roslyn/issues/29656")]
public void RefReturningAsyncLocalFunction()
{
var source = @"
public class C
{
async ref System.Threading.Tasks.Task M() { }
public void M2()
{
_ = local();
async ref System.Threading.Tasks.Task local() { }
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,11): error CS1073: Unexpected token 'ref'
// async ref System.Threading.Tasks.Task M() { }
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(4, 11),
// (4,43): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async ref System.Threading.Tasks.Task M() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 43),
// (10,15): error CS1073: Unexpected token 'ref'
// async ref System.Threading.Tasks.Task local() { }
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(10, 15),
// (10,47): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async ref System.Threading.Tasks.Task local() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "local").WithLocation(10, 47)
);
}
[ConditionalFact(typeof(DesktopOnly))]
public void LocalFunctionResetsLockScopeFlag()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
static void Main()
{
lock (new Object())
{
async Task localFunc()
{
Console.Write(""localFunc"");
await Task.Yield();
}
localFunc();
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "localFunc");
}
[ConditionalFact(typeof(DesktopOnly))]
public void LocalFunctionResetsTryCatchFinallyScopeFlags()
{
var source = @"
using System;
using System.Collections.Generic;
class C
{
static void Main()
{
try
{
IEnumerable<int> localFunc()
{
yield return 1;
}
foreach (int i in localFunc())
{
Console.Write(i);
}
throw new Exception();
}
catch (Exception)
{
IEnumerable<int> localFunc()
{
yield return 2;
}
foreach (int i in localFunc())
{
Console.Write(i);
}
}
finally
{
IEnumerable<int> localFunc()
{
yield return 3;
}
foreach (int i in localFunc())
{
Console.Write(i);
}
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "123");
}
[ConditionalFact(typeof(DesktopOnly))]
public void LocalFunctionDoesNotOverwriteInnerLockScopeFlag()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class C
{
void M(List<Task> listOfTasks)
{
lock (new Object())
{
async Task localFunc()
{
lock (new Object())
{
await Task.Yield();
}
}
listOfTasks.Add(localFunc());
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source);
comp.VerifyDiagnostics(
// (16,21): error CS1996: Cannot await in the body of a lock statement
// await Task.Yield();
Diagnostic(ErrorCode.ERR_BadAwaitInLock, "await Task.Yield()").WithLocation(16, 21));
}
[ConditionalFact(typeof(DesktopOnly))]
public void LocalFunctionDoesNotOverwriteInnerTryCatchFinallyScopeFlags()
{
var source = @"
using System;
using System.Collections.Generic;
class C
{
void M()
{
try
{
IEnumerable<int> localFunc()
{
try
{
yield return 1;
}
catch (Exception) {}
}
localFunc();
}
catch (Exception)
{
IEnumerable<int> localFunc()
{
try {}
catch (Exception)
{
yield return 2;
}
}
localFunc();
}
finally
{
IEnumerable<int> localFunc()
{
try {}
finally
{
yield return 3;
}
}
localFunc();
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source);
comp.VerifyDiagnostics(
// (15,21): error CS1626: Cannot yield a value in the body of a try block with a catch clause
// yield return 1;
Diagnostic(ErrorCode.ERR_BadYieldInTryOfCatch, "yield").WithLocation(15, 21),
// (29,21): error CS1631: Cannot yield a value in the body of a catch clause
// yield return 2;
Diagnostic(ErrorCode.ERR_BadYieldInCatch, "yield").WithLocation(29, 21),
// (42,21): error CS1625: Cannot yield in the body of a finally clause
// yield return 3;
Diagnostic(ErrorCode.ERR_BadYieldInFinally, "yield").WithLocation(42, 21));
}
[ConditionalFact(typeof(DesktopOnly))]
public void RethrowingExceptionsInCatchInsideLocalFuncIsAllowed()
{
var source = @"
using System;
class C
{
static void Main()
{
try
{
throw new Exception();
}
catch (Exception)
{
void localFunc()
{
try
{
throw new Exception();
}
catch (Exception)
{
Console.Write(""localFunc"");
throw;
}
}
try
{
localFunc();
}
catch (Exception)
{
Console.Write(""_thrown"");
}
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "localFunc_thrown");
}
[ConditionalFact(typeof(DesktopOnly))]
public void RethrowingExceptionsInLocalFuncInsideCatchIsNotAllowed()
{
var source = @"
using System;
class C
{
static void Main()
{
try {}
catch (Exception)
{
void localFunc()
{
throw;
}
localFunc();
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source);
comp.VerifyDiagnostics(
// (13,17): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause
// throw;
Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(13, 17));
}
[Fact]
public void LocalFunctionTypeParametersUseCorrectBinder()
{
var text = @"
class C
{
static void M()
{
void local<[X]T>() {}
}
}";
var tree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Regular9);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree, ignoreAccessibility: true);
var newTree = SyntaxFactory.ParseSyntaxTree(text + " ");
var m = newTree.GetRoot()
.DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(m.Body.SpanStart, m, out model));
var x = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Single();
Assert.Equal("X", x.Identifier.Text);
// If we aren't using the right binder here, the compiler crashes going through the binder factory
var info = model.GetSymbolInfo(x);
Assert.Null(info.Symbol);
comp.VerifyDiagnostics(
// (6,21): error CS0246: The type or namespace name 'XAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void local<[X]T>() {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("XAttribute").WithLocation(6, 21),
// (6,21): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?)
// void local<[X]T>() {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 21),
// (6,14): warning CS8321: The local function 'local' is declared but never used
// void local<[X]T>() {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(6, 14));
}
[Theory]
[InlineData("[A] void local() { }")]
[InlineData("[return: A] void local() { }")]
[InlineData("void local([A] int i) { }")]
[InlineData("void local<[A]T>() {}")]
[InlineData("[A] int x = 123;")]
public void LocalFunctionAttribute_SpeculativeSemanticModel(string statement)
{
string text = $@"
using System;
class A : Attribute {{}}
class C
{{
static void M()
{{
{statement}
}}
}}";
var tree = SyntaxFactory.ParseSyntaxTree(text);
var comp = (Compilation)CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var a = tree.GetRoot().DescendantNodes()
.OfType<IdentifierNameSyntax>().ElementAt(2);
Assert.Equal("A", a.Identifier.Text);
var attrInfo = model.GetSymbolInfo(a);
var attrType = comp.GlobalNamespace.GetTypeMember("A");
var attrCtor = attrType.GetMember(".ctor");
Assert.Equal(attrCtor, attrInfo.Symbol);
// Assert that this is also true for the speculative semantic model
var newTree = SyntaxFactory.ParseSyntaxTree(text + " ");
var m = newTree.GetRoot()
.DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(m.Body.SpanStart, m, out model));
a = newTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().ElementAt(2);
Assert.Equal("A", a.Identifier.Text);
// If we aren't using the right binder here, the compiler crashes going through the binder factory
var info = model.GetSymbolInfo(a);
// This behavior is wrong. See https://github.com/dotnet/roslyn/issues/24135
Assert.Equal(attrType, info.Symbol);
}
[Theory]
[InlineData(@"[Attr(42, Name = ""hello"")] void local() { }")]
[InlineData(@"[return: Attr(42, Name = ""hello"")] void local() { }")]
[InlineData(@"void local([Attr(42, Name = ""hello"")] int i) { }")]
[InlineData(@"void local<[Attr(42, Name = ""hello"")]T>() {}")]
[InlineData(@"[Attr(42, Name = ""hello"")] int x = 123;")]
public void LocalFunctionAttribute_Argument_SemanticModel(string statement)
{
var text = $@"
class Attr
{{
public Attr(int id) {{ }}
public string Name {{ get; set; }}
}}
class C
{{
static void M()
{{
{statement}
}}
}}";
var tree = SyntaxFactory.ParseSyntaxTree(text, options: TestOptions.Regular9);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree, ignoreAccessibility: true);
validate(model, tree);
var newTree = SyntaxFactory.ParseSyntaxTree(text + " ", options: TestOptions.Regular9);
var mMethod = (MethodDeclarationSyntax)newTree.FindNodeOrTokenByKind(SyntaxKind.MethodDeclaration, occurrence: 1).AsNode();
Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(mMethod.Body.SpanStart, mMethod, out var newModel));
validate(newModel, newTree);
static void validate(SemanticModel model, SyntaxTree tree)
{
var attributeSyntax = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single();
var attrArgs = attributeSyntax.ArgumentList.Arguments;
var attrArg0 = attrArgs[0].Expression;
Assert.Null(model.GetSymbolInfo(attrArg0).Symbol);
var argType0 = model.GetTypeInfo(attrArg0).Type;
Assert.Equal(SpecialType.System_Int32, argType0.SpecialType);
var attrArg1 = attrArgs[1].Expression;
Assert.Null(model.GetSymbolInfo(attrArg1).Symbol);
var argType1 = model.GetTypeInfo(attrArg1).Type;
Assert.Equal(SpecialType.System_String, argType1.SpecialType);
}
}
[Fact]
public void LocalFunctionAttribute_OnFunction()
{
const string text = @"
using System;
class A : Attribute { }
class C
{
void M()
{
[A]
void local() { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,14): warning CS8321: The local function 'local' is declared but never used
// void local() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(10, 14));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var localFunction = tree.GetRoot().DescendantNodes()
.OfType<LocalFunctionStatementSyntax>()
.Single();
var attributeList = localFunction.AttributeLists.Single();
Assert.Null(attributeList.Target);
var attribute = attributeList.Attributes.Single();
Assert.Equal("A", ((SimpleNameSyntax)attribute.Name).Identifier.ValueText);
var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction);
Assert.NotNull(symbol);
var attributes = symbol.GetAttributes().As<CSharpAttributeData>();
Assert.Equal(new[] { "A" }, GetAttributeNames(attributes));
var returnAttributes = symbol.GetReturnTypeAttributes();
Assert.Empty(returnAttributes);
}
[Fact]
public void LocalFunctionAttribute_OnFunction_Argument()
{
const string text = @"
using System;
class A : Attribute
{
internal A(int i) { }
}
class C
{
void M()
{
[A(42)]
void local() { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (13,14): warning CS8321: The local function 'local' is declared but never used
// void local() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(13, 14));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var localFunction = tree.GetRoot().DescendantNodes()
.OfType<LocalFunctionStatementSyntax>()
.Single();
var attributeList = localFunction.AttributeLists.Single();
Assert.Null(attributeList.Target);
var attribute = attributeList.Attributes.Single();
Assert.Equal("A", ((SimpleNameSyntax)attribute.Name).Identifier.ValueText);
var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction);
Assert.NotNull(symbol);
var attributes = symbol.GetAttributes();
var attributeData = attributes.Single();
var aAttribute = comp.GetTypeByMetadataName("A");
Assert.Equal(aAttribute, attributeData.AttributeClass.GetSymbol());
Assert.Equal(aAttribute.InstanceConstructors.Single(), attributeData.AttributeConstructor.GetSymbol());
Assert.Equal(42, attributeData.ConstructorArguments.Single().Value);
var returnAttributes = symbol.GetReturnTypeAttributes();
Assert.Empty(returnAttributes);
}
[Fact]
public void LocalFunctionAttribute_OnFunction_LocalArgument()
{
const string text = @"
using System;
class A : Attribute
{
internal A(string s) { }
}
class C
{
void M()
{
#pragma warning disable 0219 // Unreferenced local variable
string s1 = ""hello"";
const string s2 = ""world"";
#pragma warning disable 8321 // Unreferenced local function
[A(s1)] // 1
void local1() { }
[A(nameof(s1))]
void local2() { }
[A(s2)]
void local3() { }
[A(s1.ToString())] // 2
void local4() { }
static string local5() => ""hello"";
[A(local5())] // 3
void local6() { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (17,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(s1)] // 1
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "s1").WithLocation(17, 12),
// (26,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(s1.ToString())] // 2
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "s1.ToString()").WithLocation(26, 12),
// (31,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(local5())] // 3
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "local5()").WithLocation(31, 12));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var arg1 = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 1).AsNode();
Assert.Equal("System.String s1", model.GetSymbolInfo(arg1.Expression).Symbol.ToTestDisplayString());
Assert.Equal(SpecialType.System_String, model.GetTypeInfo(arg1.Expression).Type.SpecialType);
var arg2 = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 2).AsNode();
Assert.Null(model.GetSymbolInfo(arg2.Expression).Symbol);
Assert.Equal(SpecialType.System_String, model.GetTypeInfo(arg2.Expression).Type.SpecialType);
var arg3 = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 3).AsNode();
Assert.Equal("System.String s2", model.GetSymbolInfo(arg3.Expression).Symbol.ToTestDisplayString());
Assert.Equal(SpecialType.System_String, model.GetTypeInfo(arg3.Expression).Type.SpecialType);
}
[Fact]
public void LocalFunctionAttribute_OnFunction_DeclarationPattern()
{
const string text = @"
using System;
class A : Attribute
{
internal A(bool b) { }
}
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[A(42 is int i)] // 1
void local1()
{
_ = i.ToString(); // 2
}
_ = i.ToString(); // 3
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (13,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(42 is int i)] // 1
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "42 is int i").WithLocation(13, 12),
// (16,17): error CS0103: The name 'i' does not exist in the current context
// _ = i.ToString(); // 2
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(16, 17),
// (19,13): error CS0103: The name 'i' does not exist in the current context
// _ = i.ToString(); // 3
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(19, 13));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var arg = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 1).AsNode();
Assert.Null(model.GetSymbolInfo(arg.Expression).Symbol);
Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(arg.Expression).Type.SpecialType);
var decl = (DeclarationPatternSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.DeclarationPattern, occurrence: 1).AsNode();
Assert.Equal("System.Int32 i", model.GetDeclaredSymbol(decl.Designation).ToTestDisplayString());
}
[Fact]
public void LocalFunctionAttribute_OnFunction_OutVarInCall()
{
const string text = @"
using System;
class A : Attribute
{
internal A(bool b) { }
}
class C
{
void M1()
{
#pragma warning disable 8321 // Unreferenced local function
[A(M2(out var i))] // 1
void local1()
{
_ = i.ToString(); // 2
}
_ = i.ToString(); // 3
}
static bool M2(out int x)
{
x = 0;
return false;
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (13,12): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(M2(out var i))] // 1
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "M2(out var i)").WithLocation(13, 12),
// (16,17): error CS0103: The name 'i' does not exist in the current context
// _ = i.ToString(); // 2
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(16, 17),
// (19,13): error CS0103: The name 'i' does not exist in the current context
// _ = i.ToString(); // 3
Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(19, 13));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var arg = (AttributeArgumentSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.AttributeArgument, occurrence: 1).AsNode();
Assert.Equal("System.Boolean C.M2(out System.Int32 x)", model.GetSymbolInfo(arg.Expression).Symbol.ToTestDisplayString());
Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(arg.Expression).Type.SpecialType);
var decl = (DeclarationExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.DeclarationExpression, occurrence: 1).AsNode();
Assert.Equal("System.Int32 i", model.GetDeclaredSymbol(decl.Designation).ToTestDisplayString());
}
[Fact]
public void LocalFunctionAttribute_OutParam()
{
const string text = @"
using System;
class A : Attribute
{
internal A(out string s) { s = ""a""; }
}
class C
{
void M()
{
#pragma warning disable 8321, 0168 // Unreferenced local
string s;
[A(out s)]
void local1() { }
[A(out var s)]
void local2() { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (15,12): error CS1041: Identifier expected; 'out' is a keyword
// [A(out s)]
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(15, 12),
// (15,16): error CS1620: Argument 1 must be passed with the 'out' keyword
// [A(out s)]
Diagnostic(ErrorCode.ERR_BadArgRef, "s").WithArguments("1", "out").WithLocation(15, 16),
// (18,10): error CS1729: 'A' does not contain a constructor that takes 2 arguments
// [A(out var s)]
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "A(out var s)").WithArguments("A", "2").WithLocation(18, 10),
// (18,12): error CS1041: Identifier expected; 'out' is a keyword
// [A(out var s)]
Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(18, 12),
// (18,16): error CS0103: The name 'var' does not exist in the current context
// [A(out var s)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(18, 16),
// (18,20): error CS1003: Syntax error, ',' expected
// [A(out var s)]
Diagnostic(ErrorCode.ERR_SyntaxError, "s").WithArguments(",", "").WithLocation(18, 20));
}
[Fact]
public void LocalFunctionAttribute_Return()
{
const string text = @"
using System;
class A : Attribute { }
class C
{
void M()
{
[return: A]
int local() => 42;
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,13): warning CS8321: The local function 'local' is declared but never used
// int local() => 42;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(10, 13));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var localFunction = tree.GetRoot().DescendantNodes()
.OfType<LocalFunctionStatementSyntax>()
.Single();
var attributeList = localFunction.AttributeLists.Single();
Assert.Equal(SyntaxKind.ReturnKeyword, attributeList.Target.Identifier.Kind());
var attribute = attributeList.Attributes.Single();
Assert.Equal("A", ((SimpleNameSyntax)attribute.Name).Identifier.ValueText);
var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction);
Assert.NotNull(symbol);
var returnAttributes = symbol.GetReturnTypeAttributes();
var attributeData = returnAttributes.Single();
var aAttribute = comp.GetTypeByMetadataName("A");
Assert.Equal(aAttribute, attributeData.AttributeClass.GetSymbol());
Assert.Equal(aAttribute.InstanceConstructors.Single(), attributeData.AttributeConstructor.GetSymbol());
var attributes = symbol.GetAttributes();
Assert.Empty(attributes);
}
[Fact]
public void LocalFunctionAttribute_Parameter()
{
var source = @"
using System;
class A : Attribute { }
class C
{
void M()
{
int local([A] int i) => i;
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (9,13): warning CS8321: The local function 'local' is declared but never used
// int local([A] int i) => i;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(9, 13));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var localFunction = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single();
var parameter = localFunction.ParameterList.Parameters.Single();
var paramSymbol = model.GetDeclaredSymbol(parameter);
var attrs = paramSymbol.GetAttributes();
var attr = attrs.Single();
Assert.Equal(comp.GetTypeByMetadataName("A"), attr.AttributeClass.GetSymbol());
}
[Fact]
public void LocalFunctionAttribute_LangVersionError()
{
const string text = @"
using System;
class A : Attribute { }
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[A]
void local1() { }
[return: A]
void local2() { }
void local3([A] int i) { }
void local4<[A] T>() { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (10,9): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater.
// [A]
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[A]").WithArguments("local function attributes", "9.0").WithLocation(10, 9),
// (13,9): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater.
// [return: A]
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[return: A]").WithArguments("local function attributes", "9.0").WithLocation(13, 9),
// (16,21): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater.
// void local3([A] int i) { }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[A]").WithArguments("local function attributes", "9.0").WithLocation(16, 21),
// (18,21): error CS8400: Feature 'local function attributes' is not available in C# 8.0. Please use language version 9.0 or greater.
// void local4<[A] T>() { }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "[A]").WithArguments("local function attributes", "9.0").WithLocation(18, 21));
comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void LocalFunctionAttribute_BadAttributeLocation()
{
const string text = @"
using System;
[AttributeUsage(AttributeTargets.Property)]
class PropAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
class MethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.ReturnValue)]
class ReturnAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter)]
class ParamAttribute : Attribute { }
[AttributeUsage(AttributeTargets.GenericParameter)]
class TypeParamAttribute : Attribute { }
public class C {
public void M() {
#pragma warning disable 8321 // Unreferenced local function
[Prop] // 1
[Return] // 2
[Method]
[return: Prop] // 3
[return: Return]
[return: Method] // 4
void local<
[Param] // 5
[TypeParam]
T>(
[Param]
[TypeParam] // 6
T t) { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (22,10): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations.
// [Prop] // 1
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(22, 10),
// (23,10): error CS0592: Attribute 'Return' is not valid on this declaration type. It is only valid on 'return' declarations.
// [Return] // 2
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Return").WithArguments("Return", "return").WithLocation(23, 10),
// (25,18): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations.
// [return: Prop] // 3
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(25, 18),
// (27,18): error CS0592: Attribute 'Method' is not valid on this declaration type. It is only valid on 'method' declarations.
// [return: Method] // 4
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Method").WithArguments("Method", "method").WithLocation(27, 18),
// (29,14): error CS0592: Attribute 'Param' is not valid on this declaration type. It is only valid on 'parameter' declarations.
// [Param] // 5
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Param").WithArguments("Param", "parameter").WithLocation(29, 14),
// (33,14): error CS0592: Attribute 'TypeParam' is not valid on this declaration type. It is only valid on 'type parameter' declarations.
// [TypeParam] // 6
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "TypeParam").WithArguments("TypeParam", "type parameter").WithLocation(33, 14));
var tree = comp.SyntaxTrees.Single();
var localFunction = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single();
var model = comp.GetSemanticModel(tree);
var symbol = (IMethodSymbol)model.GetDeclaredSymbol(localFunction);
Assert.NotNull(symbol);
var attributes = symbol.GetAttributes();
Assert.Equal(3, attributes.Length);
Assert.Equal(comp.GetTypeByMetadataName("PropAttribute"), attributes[0].AttributeClass.GetSymbol());
Assert.Equal(comp.GetTypeByMetadataName("ReturnAttribute"), attributes[1].AttributeClass.GetSymbol());
Assert.Equal(comp.GetTypeByMetadataName("MethodAttribute"), attributes[2].AttributeClass.GetSymbol());
var returnAttributes = symbol.GetReturnTypeAttributes();
Assert.Equal(3, returnAttributes.Length);
Assert.Equal(comp.GetTypeByMetadataName("PropAttribute"), returnAttributes[0].AttributeClass.GetSymbol());
Assert.Equal(comp.GetTypeByMetadataName("ReturnAttribute"), returnAttributes[1].AttributeClass.GetSymbol());
Assert.Equal(comp.GetTypeByMetadataName("MethodAttribute"), returnAttributes[2].AttributeClass.GetSymbol());
}
[Fact]
public void LocalFunctionAttribute_AttributeSemanticModel()
{
const string text = @"
using System;
class A : Attribute { }
class C
{
void M()
{
local1();
local2();
local3(0);
local4<object>();
[A]
void local1() { }
[return: A]
void local2() { }
void local3([A] int i) { }
void local4<[A] T>() { }
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var attributeSyntaxes = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().ToList();
Assert.Equal(4, attributeSyntaxes.Count);
var attributeConstructor = comp.GetTypeByMetadataName("A").InstanceConstructors.Single();
foreach (var attributeSyntax in attributeSyntaxes)
{
var symbol = model.GetSymbolInfo(attributeSyntax).Symbol.GetSymbol<MethodSymbol>();
Assert.Equal(attributeConstructor, symbol);
}
}
[Fact]
public void StatementAttributeSemanticModel()
{
const string text = @"
using System;
class A : Attribute { }
class C
{
void M()
{
#pragma warning disable 219 // The variable '{0}' is assigned but its value is never used
[A] int i = 0;
}
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (11,9): error CS7014: Attributes are not valid in this context.
// [A] int i = 0;
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(11, 9));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var attrSyntax = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single();
var attrConstructor = (IMethodSymbol)model.GetSymbolInfo(attrSyntax).Symbol;
Assert.Equal(MethodKind.Constructor, attrConstructor.MethodKind);
Assert.Equal("A", attrConstructor.ContainingType.Name);
}
[Fact]
public void LocalFunctionNoBody()
{
const string text = @"
class C
{
void M()
{
local1();
void local1();
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (8,14): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'.
// void local1();
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(8, 14));
}
[Fact]
public void LocalFunctionExtern()
{
const string text = @"
using System.Runtime.InteropServices;
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[DllImport(""a"")] extern void local1(); // 1, 2
[DllImport(""a"")] extern void local2() { } // 3, 4
[DllImport(""a"")] extern int local3() => 0; // 5, 6
static void local4(); // 7
static void local5() { }
static int local6() => 0;
[DllImport(""a"")] static extern void local7();
[DllImport(""a"")] static extern void local8() { } // 8
[DllImport(""a"")] static extern int local9() => 0; // 9
[DllImport(""a"")] extern static void local10();
[DllImport(""a"")] extern static void local11() { } // 10
[DllImport(""a"")] extern static int local12() => 0; // 11
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern'
// [DllImport("a")] extern void local1(); // 1, 2
Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(10, 10),
// (10,38): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'.
// [DllImport("a")] extern void local1(); // 1, 2
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(10, 38),
// (11,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern'
// [DllImport("a")] extern void local2() { } // 3, 4
Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(11, 10),
// (11,38): error CS0179: 'local2()' cannot be extern and declare a body
// [DllImport("a")] extern void local2() { } // 3, 4
Diagnostic(ErrorCode.ERR_ExternHasBody, "local2").WithArguments("local2()").WithLocation(11, 38),
// (12,10): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern'
// [DllImport("a")] extern int local3() => 0; // 5, 6
Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(12, 10),
// (12,37): error CS0179: 'local3()' cannot be extern and declare a body
// [DllImport("a")] extern int local3() => 0; // 5, 6
Diagnostic(ErrorCode.ERR_ExternHasBody, "local3").WithArguments("local3()").WithLocation(12, 37),
// (14,21): error CS8112: Local function 'local4()' must either have a body or be marked 'static extern'.
// static void local4(); // 7
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local4").WithArguments("local4()").WithLocation(14, 21),
// (19,45): error CS0179: 'local8()' cannot be extern and declare a body
// [DllImport("a")] static extern void local8() { } // 8
Diagnostic(ErrorCode.ERR_ExternHasBody, "local8").WithArguments("local8()").WithLocation(19, 45),
// (20,44): error CS0179: 'local9()' cannot be extern and declare a body
// [DllImport("a")] static extern int local9() => 0; // 9
Diagnostic(ErrorCode.ERR_ExternHasBody, "local9").WithArguments("local9()").WithLocation(20, 44),
// (23,45): error CS0179: 'local11()' cannot be extern and declare a body
// [DllImport("a")] extern static void local11() { } // 10
Diagnostic(ErrorCode.ERR_ExternHasBody, "local11").WithArguments("local11()").WithLocation(23, 45),
// (24,44): error CS0179: 'local12()' cannot be extern and declare a body
// [DllImport("a")] extern static int local12() => 0; // 11
Diagnostic(ErrorCode.ERR_ExternHasBody, "local12").WithArguments("local12()").WithLocation(24, 44));
}
[Fact]
public void LocalFunctionExtern_Generic()
{
var source = @"
using System;
using System.Runtime.InteropServices;
class C
{
#pragma warning disable 8321 // Unreferenced local function
void M()
{
[DllImport(""a"")] extern static void local1();
[DllImport(""a"")] extern static void local2<T>(); // 1
void local3()
{
[DllImport(""a"")] extern static void local1();
[DllImport(""a"")] extern static void local2<T2>(); // 2
}
void local4<T4>()
{
[DllImport(""a"")] extern static void local1(); // 3
[DllImport(""a"")] extern static void local2<T2>(); // 4
}
Action a = () =>
{
[DllImport(""a"")] extern static void local1();
[DllImport(""a"")] extern static void local2<T>(); // 5
void local3()
{
[DllImport(""a"")] extern static void local1();
[DllImport(""a"")] extern static void local2<T2>(); // 6
}
void local4<T4>()
{
[DllImport(""a"")] extern static void local1(); // 7
[DllImport(""a"")] extern static void local2<T2>(); // 8
}
};
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (12,10): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T>(); // 1
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(12, 10),
// (17,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 2
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(17, 14),
// (22,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 3
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(22, 14),
// (23,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 4
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(23, 14),
// (29,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T>(); // 5
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(29, 14),
// (34,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 6
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(34, 18),
// (39,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 7
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(39, 18),
// (40,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 8
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(40, 18));
}
[Theory]
[InlineData("<CT>", "", "")]
[InlineData("", "<MT>", "")]
[InlineData("", "", "<LT>")]
public void LocalFunctionExtern_Generic_GenericMembers(string classTypeParams, string methodTypeParams, string localFunctionTypeParams)
{
var source = $@"
using System;
using System.Runtime.InteropServices;
class C{classTypeParams}
{{
#pragma warning disable 8321 // Unreferenced local function
void M{methodTypeParams}()
{{
void localOuter{localFunctionTypeParams}()
{{
[DllImport(""a"")] extern static void local1(); // 1
[DllImport(""a"")] extern static void local2<T>(); // 2
void local3()
{{
[DllImport(""a"")] extern static void local1(); // 3
[DllImport(""a"")] extern static void local2<T2>(); // 4
}}
void local4<T4>()
{{
[DllImport(""a"")] extern static void local1(); // 5
[DllImport(""a"")] extern static void local2<T2>(); // 6
}}
Action a = () =>
{{
[DllImport(""a"")] extern static void local1(); // 7
[DllImport(""a"")] extern static void local2<T>(); // 8
void local3()
{{
[DllImport(""a"")] extern static void local1(); // 9
[DllImport(""a"")] extern static void local2<T2>(); // 10
}}
void local4<T4>()
{{
[DllImport(""a"")] extern static void local1(); // 11
[DllImport(""a"")] extern static void local2<T2>(); // 12
}}
}};
}}
}}
}}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (13,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 1
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(13, 14),
// (14,14): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T>(); // 2
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(14, 14),
// (18,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 3
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(18, 18),
// (19,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 4
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(19, 18),
// (24,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 5
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(24, 18),
// (25,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 6
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(25, 18),
// (30,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 7
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(30, 18),
// (31,18): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T>(); // 8
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(31, 18),
// (35,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 9
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(35, 22),
// (36,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 10
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(36, 22),
// (41,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local1(); // 11
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(41, 22),
// (42,22): error CS7042: The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.
// [DllImport("a")] extern static void local2<T2>(); // 12
Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport").WithLocation(42, 22));
}
[Fact]
public void LocalFunctionExtern_NoImplementationWarning_Attribute()
{
const string text = @"
using System.Runtime.InteropServices;
class Attr : System.Attribute { }
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
static extern void local1(); // 1
static extern void local2() { } // 2
[DllImport(""a"")]
static extern void local3();
[Attr]
static extern void local4();
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (12,28): warning CS0626: Method, operator, or accessor 'local1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation.
// static extern void local1(); // 1
Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "local1").WithArguments("local1()").WithLocation(12, 28),
// (13,28): error CS0179: 'local2()' cannot be extern and declare a body
// static extern void local2() { } // 2
Diagnostic(ErrorCode.ERR_ExternHasBody, "local2").WithArguments("local2()").WithLocation(13, 28));
}
[Fact]
public void LocalFunctionExtern_Errors()
{
const string text = @"
class C
{
#pragma warning disable 8321 // Unreferenced local function
void M1()
{
void local1(); // 1
static extern void local1(); // 2, 3
}
void M2()
{
void local1(); // 4
static extern void local1() { } // 5
}
}
";
var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (8,14): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'.
// void local1(); // 1
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(8, 14),
// (9,28): error CS0128: A local variable or function named 'local1' is already defined in this scope
// static extern void local1(); // 2, 3
Diagnostic(ErrorCode.ERR_LocalDuplicate, "local1").WithArguments("local1").WithLocation(9, 28),
// (9,28): warning CS0626: Method, operator, or accessor 'local1()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation.
// static extern void local1(); // 2, 3
Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "local1").WithArguments("local1()").WithLocation(9, 28),
// (14,14): error CS8112: Local function 'local1()' must either have a body or be marked 'static extern'.
// void local1(); // 4
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local1").WithArguments("local1()").WithLocation(14, 14),
// (15,28): error CS0128: A local variable or function named 'local1' is already defined in this scope
// static extern void local1() { } // 5
Diagnostic(ErrorCode.ERR_LocalDuplicate, "local1").WithArguments("local1").WithLocation(15, 28));
}
[Fact]
public void ComImport_Class()
{
const string text = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""00020813-0000-0000-c000-000000000046"")]
class C
{
void M() // 1
{
#pragma warning disable 8321 // Unreferenced local function
void local1() { }
}
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (8,10): error CS0423: Since 'C' has the ComImport attribute, 'C.M()' must be extern or abstract
// void M() // 1
Diagnostic(ErrorCode.ERR_ComImportWithImpl, "M").WithArguments("C.M()", "C").WithLocation(8, 10));
}
[Fact]
public void UnsafeLocal()
{
var source = @"
class C
{
void M()
{
var bytesA = local();
unsafe byte[] local()
{
var bytes = new byte[sizeof(int)];
fixed (byte* ptr = &bytes[0])
{
*(int*)ptr = sizeof(int);
}
return bytes;
}
}
}";
var comp = CreateCompilation(source);
Assert.Empty(comp.GetDeclarationDiagnostics());
comp.VerifyDiagnostics(
// (8,23): error CS0227: Unsafe code may only appear if compiling with /unsafe
// unsafe byte[] local()
Diagnostic(ErrorCode.ERR_IllegalUnsafe, "local").WithLocation(8, 23)
);
var compWithUnsafe = CreateCompilation(source, options: TestOptions.UnsafeDebugDll);
compWithUnsafe.VerifyDiagnostics();
}
[Fact]
public void LocalInUnsafeStruct()
{
var source = @"
unsafe struct C
{
void A()
{
var bytesA = local();
var bytesB = B();
byte[] local()
{
var bytes = new byte[sizeof(int)];
fixed (byte* ptr = &bytes[0])
{
*(int*)ptr = sizeof(int);
}
return bytes;
}
}
byte[] B()
{
var bytes = new byte[sizeof(long)];
fixed (byte* ptr = &bytes[0])
{
*(long*)ptr = sizeof(long);
}
return bytes;
}
}";
// no need to declare local function `local` or method `B` as unsafe
var compWithUnsafe = CreateCompilation(source, options: TestOptions.UnsafeDebugDll);
compWithUnsafe.VerifyDiagnostics();
}
[Fact]
public void LocalInUnsafeBlock()
{
var source = @"
struct C
{
void A()
{
unsafe
{
var bytesA = local();
byte[] local()
{
var bytes = new byte[sizeof(int)];
fixed (byte* ptr = &bytes[0])
{
*(int*)ptr = sizeof(int);
}
return bytes;
}
}
}
}";
// no need to declare local function `local` as unsafe
var compWithUnsafe = CreateCompilation(source, options: TestOptions.UnsafeDebugDll);
compWithUnsafe.VerifyDiagnostics();
}
[Fact]
public void ConstraintBinding()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
void Local<T, U>()
where T : U
where U : class
{ }
Local<object, object>();
}
}");
comp.VerifyDiagnostics();
}
[Fact]
public void ConstraintBinding2()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
void Local<T, U>(T t)
where T : U
where U : t
{ }
Local<object, object>(null);
}
}");
comp.VerifyDiagnostics(
// (8,23): error CS0246: The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?)
// where U : t
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "t").WithArguments("t").WithLocation(8, 23),
// (11,9): error CS0311: The type 'object' cannot be used as type parameter 'U' in the generic type or method 'Local<T, U>(T)'. There is no implicit reference conversion from 'object' to 't'.
// Local<object, object>(null);
Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Local<object, object>").WithArguments("Local<T, U>(T)", "t", "U", "object").WithLocation(11, 9));
}
[Fact]
[WorkItem(17014, "https://github.com/dotnet/roslyn/pull/17014")]
public void RecursiveLocalFuncsAsParameterTypes()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
int L(L2 l2) => 0;
int L2(L l1) => 0;
}
}");
comp.VerifyDiagnostics(
// (6,15): error CS0246: The type or namespace name 'L2' could not be found (are you missing a using directive or an assembly reference?)
// int L(L2 l2) => 0;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L2").WithArguments("L2").WithLocation(6, 15),
// (7,16): error CS0246: The type or namespace name 'L' could not be found (are you missing a using directive or an assembly reference?)
// int L2(L l1) => 0;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "L").WithArguments("L").WithLocation(7, 16),
// (6,13): warning CS8321: The local function 'L' is declared but never used
// int L(L2 l2) => 0;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L").WithArguments("L").WithLocation(6, 13),
// (7,13): warning CS8321: The local function 'L2' is declared but never used
// int L2(L l1) => 0;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "L2").WithArguments("L2").WithLocation(7, 13));
}
[Fact]
[WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")]
public void BadGenericConstraint()
{
var comp = CreateCompilation(@"
class C
{
public void M<T>(T value) where T : class, object { }
}");
comp.VerifyDiagnostics(
// (4,48): error CS0702: Constraint cannot be special class 'object'
// public void M<T>(T value) where T : class, object { }
Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object").WithArguments("object").WithLocation(4, 48)
);
}
[Fact]
[WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")]
public void RecursiveDefaultParameter()
{
var comp = CreateCompilation(@"
class C
{
public static void Main()
{
int Local(int j = Local()) => 0;
Local();
}
}");
comp.VerifyDiagnostics(
// (6,27): error CS1736: Default parameter value for 'j' must be a compile-time constant
// int Local(int j = Local()) => 0;
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local()").WithArguments("j").WithLocation(6, 27));
comp.DeclarationDiagnostics.Verify();
}
[Fact]
[WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")]
public void RecursiveDefaultParameter2()
{
var comp = CreateCompilation(@"
using System;
class C
{
void M()
{
int Local(Action a = Local) => 0;
Local();
}
}");
comp.VerifyDiagnostics(
// (7,30): error CS1736: Default parameter value for 'a' must be a compile-time constant
// int Local(Action a = Local) => 0;
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local").WithArguments("a").WithLocation(7, 30));
comp.DeclarationDiagnostics.Verify();
}
[Fact]
[WorkItem(16451, "https://github.com/dotnet/roslyn/issues/16451")]
public void MutuallyRecursiveDefaultParameters()
{
var comp = CreateCompilation(@"
class C
{
void M()
{
int Local1(int p = Local2()) => 0;
int Local2(int p = Local1()) => 0;
Local1();
Local2();
}
}");
comp.VerifyDiagnostics(
// (6,28): error CS1736: Default parameter value for 'p' must be a compile-time constant
// int Local1(int p = Local2()) => 0;
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local2()").WithArguments("p").WithLocation(6, 28),
// (7,28): error CS1736: Default parameter value for 'p' must be a compile-time constant
// int Local2(int p = Local1()) => 0;
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Local1()").WithArguments("p").WithLocation(7, 28));
comp.DeclarationDiagnostics.Verify();
}
[Fact]
public void FetchLocalFunctionSymbolThroughLocal()
{
var tree = SyntaxFactory.ParseSyntaxTree(@"
using System;
class C
{
public void M()
{
void Local<[A, B, CLSCompliant, D]T>()
{
var x = new object();
}
Local<int>();
}
}");
var comp = CreateCompilation(tree);
comp.DeclarationDiagnostics.Verify();
comp.VerifyDiagnostics(
// (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21),
// (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21),
// (7,24): error CS0246: The type or namespace name 'BAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("BAttribute").WithLocation(7, 24),
// (7,24): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 24),
// (7,41): error CS0246: The type or namespace name 'DAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("DAttribute").WithLocation(7, 41),
// (7,41): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(7, 41),
// (7,27): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)'
// void Local<[A, B, CLSCompliant, D]T>()
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 27));
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(v => v.Identifier.ValueText == "x").Single();
var localSymbol = model.GetDeclaredSymbol(x).ContainingSymbol.GetSymbol<LocalFunctionSymbol>();
var typeParam = localSymbol.TypeParameters.Single();
var attrs = typeParam.GetAttributes();
Assert.True(attrs[0].AttributeClass.IsErrorType());
Assert.True(attrs[1].AttributeClass.IsErrorType());
Assert.False(attrs[2].AttributeClass.IsErrorType());
Assert.Equal(comp.GlobalNamespace
.GetMember<NamespaceSymbol>("System")
.GetMember<NamedTypeSymbol>("CLSCompliantAttribute"),
attrs[2].AttributeClass);
Assert.True(attrs[3].AttributeClass.IsErrorType());
comp.DeclarationDiagnostics.Verify();
}
[Fact]
public void TypeParameterAttributesInSemanticModel()
{
var comp = (Compilation)CreateCompilation(@"
using System;
class C
{
public void M()
{
void Local<[A]T, [CLSCompliant]U>() { }
}
}", parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A]T, [CLSCompliant]U>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21),
// (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A]T, [CLSCompliant]U>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21),
// (7,27): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)'
// void Local<[A]T, [CLSCompliant]U>() { }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 27),
// (7,14): warning CS8321: The local function 'Local' is declared but never used
// void Local<[A]T, [CLSCompliant]U>() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(7, 14));
var tree = comp.SyntaxTrees.First();
var root = tree.GetRoot();
var model = comp.GetSemanticModel(tree);
var a = root.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(id => id.Identifier.ValueText == "A")
.Single();
Assert.Null(model.GetDeclaredSymbol(a));
var aSymbolInfo = model.GetSymbolInfo(a);
Assert.Equal(0, aSymbolInfo.CandidateSymbols.Length);
Assert.Null(aSymbolInfo.Symbol);
var aTypeInfo = model.GetTypeInfo(a);
Assert.Equal(TypeKind.Error, aTypeInfo.Type.TypeKind);
Assert.Null(model.GetAliasInfo(a));
Assert.Empty(model.LookupNamespacesAndTypes(a.SpanStart, name: "A"));
var clsCompliant = root.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(id => id.Identifier.ValueText == "CLSCompliant")
.Single();
var clsCompliantSymbol = comp.GlobalNamespace
.GetMember<INamespaceSymbol>("System")
.GetTypeMember("CLSCompliantAttribute");
Assert.Null(model.GetDeclaredSymbol(clsCompliant));
// This should be null because there is no CLSCompliant ctor with no args
var clsCompliantSymbolInfo = model.GetSymbolInfo(clsCompliant);
Assert.Null(clsCompliantSymbolInfo.Symbol);
Assert.Equal(clsCompliantSymbol.GetMember<IMethodSymbol>(".ctor"),
clsCompliantSymbolInfo.CandidateSymbols.Single());
Assert.Equal(CandidateReason.OverloadResolutionFailure, clsCompliantSymbolInfo.CandidateReason);
Assert.Equal(clsCompliantSymbol, model.GetTypeInfo(clsCompliant).Type);
Assert.Null(model.GetAliasInfo(clsCompliant));
Assert.Equal(clsCompliantSymbol,
model.LookupNamespacesAndTypes(clsCompliant.SpanStart, name: "CLSCompliantAttribute").Single());
((CSharpCompilation)comp).DeclarationDiagnostics.Verify();
}
[Fact]
public void ParameterAttributesInSemanticModel()
{
var comp = (Compilation)CreateCompilation(@"
using System;
class C
{
public void M()
{
void Local([A]int x, [CLSCompliant]int y) { }
}
}", parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local([A]int x, [CLSCompliant]int y) { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21),
// (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// void Local([A]int x, [CLSCompliant]int y) { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21),
// (7,31): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)'
// void Local([A]int x, [CLSCompliant]int y) { }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 31),
// (7,14): warning CS8321: The local function 'Local' is declared but never used
// void Local([A]int x, [CLSCompliant]int y) { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(7, 14));
var tree = comp.SyntaxTrees.First();
var root = tree.GetRoot();
var model = comp.GetSemanticModel(tree);
var a = root.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(id => id.Identifier.ValueText == "A")
.Single();
Assert.Null(model.GetDeclaredSymbol(a));
var aSymbolInfo = model.GetSymbolInfo(a);
Assert.Equal(0, aSymbolInfo.CandidateSymbols.Length);
Assert.Null(aSymbolInfo.Symbol);
var aTypeInfo = model.GetTypeInfo(a);
Assert.Equal(TypeKind.Error, aTypeInfo.Type.TypeKind);
Assert.Null(model.GetAliasInfo(a));
Assert.Empty(model.LookupNamespacesAndTypes(a.SpanStart, name: "A"));
var clsCompliant = root.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(id => id.Identifier.ValueText == "CLSCompliant")
.Single();
var clsCompliantSymbol = comp.GlobalNamespace
.GetMember<INamespaceSymbol>("System")
.GetTypeMember("CLSCompliantAttribute");
Assert.Null(model.GetDeclaredSymbol(clsCompliant));
// This should be null because there is no CLSCompliant ctor with no args
var clsCompliantSymbolInfo = model.GetSymbolInfo(clsCompliant);
Assert.Null(clsCompliantSymbolInfo.Symbol);
Assert.Equal(clsCompliantSymbol.GetMember<IMethodSymbol>(".ctor"),
clsCompliantSymbolInfo.CandidateSymbols.Single());
Assert.Equal(CandidateReason.OverloadResolutionFailure, clsCompliantSymbolInfo.CandidateReason);
Assert.Equal(clsCompliantSymbol, model.GetTypeInfo(clsCompliant).Type);
Assert.Null(model.GetAliasInfo(clsCompliant));
Assert.Equal(clsCompliantSymbol,
model.LookupNamespacesAndTypes(clsCompliant.SpanStart, name: "CLSCompliantAttribute").Single());
((CSharpCompilation)comp).DeclarationDiagnostics.Verify();
}
[Fact]
public void LocalFunctionAttribute_TypeParameter_Errors()
{
var tree = SyntaxFactory.ParseSyntaxTree(@"
using System;
class C
{
public void M()
{
void Local<[A, B, CLSCompliant, D]T>() { }
Local<int>();
}
}", options: TestOptions.Regular9);
var comp = CreateCompilation(tree);
comp.DeclarationDiagnostics.Verify();
comp.VerifyDiagnostics(
// (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21),
// (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21),
// (7,24): error CS0246: The type or namespace name 'BAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("BAttribute").WithLocation(7, 24),
// (7,24): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 24),
// (7,41): error CS0246: The type or namespace name 'DAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("DAttribute").WithLocation(7, 41),
// (7,41): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(7, 41),
// (7,27): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)'
// void Local<[A, B, CLSCompliant, D]T>() { }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 27));
var localDecl = tree.FindNodeOrTokenByKind(SyntaxKind.LocalFunctionStatement);
var model = comp.GetSemanticModel(tree);
var localSymbol = Assert.IsType<LocalFunctionSymbol>(model.GetDeclaredSymbol(localDecl.AsNode()).GetSymbol());
var typeParam = localSymbol.TypeParameters.Single();
var attrs = typeParam.GetAttributes();
Assert.True(attrs[0].AttributeClass.IsErrorType());
Assert.True(attrs[1].AttributeClass.IsErrorType());
Assert.False(attrs[2].AttributeClass.IsErrorType());
Assert.Equal(comp.GlobalNamespace
.GetMember<NamespaceSymbol>("System")
.GetMember<NamedTypeSymbol>("CLSCompliantAttribute"),
attrs[2].AttributeClass);
Assert.True(attrs[3].AttributeClass.IsErrorType());
comp.DeclarationDiagnostics.Verify();
}
[Fact]
public void LocalFunctionAttribute_Parameter_Errors()
{
var tree = SyntaxFactory.ParseSyntaxTree(@"
using System;
class C
{
public void M()
{
void Local([A, B]int x, [CLSCompliant]string s = """") { }
Local(0);
}
}", options: TestOptions.Regular9);
var comp = CreateCompilation(tree);
comp.DeclarationDiagnostics.Verify();
comp.VerifyDiagnostics(
// (7,21): error CS0246: The type or namespace name 'AAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local([A, B]int x, [CLSCompliant]string s = "") { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("AAttribute").WithLocation(7, 21),
// (7,21): error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)
// void Local([A, B]int x, [CLSCompliant]string s = "") { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A").WithArguments("A").WithLocation(7, 21),
// (7,24): error CS0246: The type or namespace name 'BAttribute' could not be found (are you missing a using directive or an assembly reference?)
// void Local([A, B]int x, [CLSCompliant]string s = "") { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("BAttribute").WithLocation(7, 24),
// (7,24): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)
// void Local([A, B]int x, [CLSCompliant]string s = "") { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 24),
// (7,34): error CS7036: There is no argument given that corresponds to the required formal parameter 'isCompliant' of 'CLSCompliantAttribute.CLSCompliantAttribute(bool)'
// void Local([A, B]int x, [CLSCompliant]string s = "") { }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CLSCompliant").WithArguments("isCompliant", "System.CLSCompliantAttribute.CLSCompliantAttribute(bool)").WithLocation(7, 34));
var localDecl = tree.FindNodeOrTokenByKind(SyntaxKind.LocalFunctionStatement);
var model = comp.GetSemanticModel(tree);
var localSymbol = Assert.IsType<LocalFunctionSymbol>(model.GetDeclaredSymbol(localDecl.AsNode()).GetSymbol());
var param = localSymbol.Parameters[0];
var attrs = param.GetAttributes();
Assert.True(attrs[0].AttributeClass.IsErrorType());
Assert.True(attrs[1].AttributeClass.IsErrorType());
param = localSymbol.Parameters[1];
attrs = param.GetAttributes();
Assert.Equal(comp.GlobalNamespace
.GetMember<NamespaceSymbol>("System")
.GetMember<NamedTypeSymbol>("CLSCompliantAttribute"),
attrs[0].AttributeClass);
comp.DeclarationDiagnostics.Verify();
}
[Fact]
public void LocalFunctionDisallowedAttributes()
{
var source = @"
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
public class IsUnmanagedAttribute : System.Attribute { }
public class IsByRefLikeAttribute : System.Attribute { }
public class NullableContextAttribute : System.Attribute { public NullableContextAttribute(byte b) { } }
}
class C
{
void M()
{
local1();
[IsReadOnly] // 1
[IsUnmanaged] // 2
[IsByRefLike] // 3
[Extension] // 4
[NullableContext(0)] // 5
void local1()
{
}
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (18,10): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly] // 1
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(18, 10),
// (19,10): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage.
// [IsUnmanaged] // 2
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(19, 10),
// (20,10): error CS8335: Do not use 'System.Runtime.CompilerServices.IsByRefLikeAttribute'. This is reserved for compiler usage.
// [IsByRefLike] // 3
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsByRefLike").WithArguments("System.Runtime.CompilerServices.IsByRefLikeAttribute").WithLocation(20, 10),
// (21,10): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead.
// [Extension] // 4
Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension").WithLocation(21, 10),
// (22,10): error CS8335: Do not use 'System.Runtime.CompilerServices.NullableContextAttribute'. This is reserved for compiler usage.
// [NullableContext(0)] // 5
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullableContext(0)").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(22, 10));
}
[Fact]
public void LocalFunctionDisallowedSecurityAttributes()
{
var source = @"
using System.Security;
class C
{
void M()
{
local1();
[SecurityCritical] // 1
[SecuritySafeCriticalAttribute] // 2
async void local1() // 3
{
}
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,10): error CS4030: Security attribute 'SecurityCritical' cannot be applied to an Async method.
// [SecurityCritical] // 1
Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecurityCritical").WithArguments("SecurityCritical").WithLocation(10, 10),
// (11,10): error CS4030: Security attribute 'SecuritySafeCriticalAttribute' cannot be applied to an Async method.
// [SecuritySafeCriticalAttribute] // 2
Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecuritySafeCriticalAttribute").WithArguments("SecuritySafeCriticalAttribute").WithLocation(11, 10),
// (12,20): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async void local1() // 3
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "local1").WithLocation(12, 20));
}
[Fact]
public void TypeParameterBindingScope()
{
var src = @"
class C
{
public void M()
{
{
int T = 0; // Should not have error
int Local<T>() => 0; // Should conflict with above
Local<int>();
T++;
}
{
int T<T>() => 0;
T<int>();
}
{
int Local<T, T>() => 0;
Local<int, int>();
}
}
public void M2<T>()
{
{
int Local<T>() => 0;
Local<int>();
}
{
int Local1<V>()
{
int Local2<V>() => 0;
return Local2<int>();
}
Local1<int>();
}
{
int T() => 0;
T();
}
{
int Local1<V>()
{
int V() => 0;
return V();
}
Local1<int>();
}
{
int Local1<V>()
{
int Local2<U>()
{
// Conflicts with method type parameter
int T() => 0;
return T();
}
return Local2<int>();
}
Local1<int>();
}
{
int Local1<V>()
{
int Local2<U>()
{
// Shadows M.2<T>
int Local3<T>() => 0;
return Local3<int>();
}
return Local2<int>();
}
Local1<int>();
}
}
public void V<V>() { }
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,23): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int Local<T>() => 0; // Should conflict with above
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(9, 23),
// (14,19): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int T<T>() => 0;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(14, 19),
// (18,26): error CS0692: Duplicate type parameter 'T'
// int Local<T, T>() => 0;
Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T").WithLocation(18, 26),
// (25,23): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()'
// int Local<T>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(25, 23),
// (31,28): warning CS8387: Type parameter 'V' has the same name as the type parameter from outer method 'Local1<V>()'
// int Local2<V>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "V").WithArguments("V", "Local1<V>()").WithLocation(31, 28),
// (37,17): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// int T() => 0;
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(37, 17),
// (43,21): error CS0412: 'V': a parameter, local variable, or local function cannot have the same name as a method type parameter
// int V() => 0;
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "V").WithArguments("V").WithLocation(43, 21),
// (54,25): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// int T() => 0;
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(54, 25),
// (67,32): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()'
// int Local3<T>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(67, 32));
comp = CreateCompilation(src, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (18,26): error CS0692: Duplicate type parameter 'T'
// int Local<T, T>() => 0;
Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T").WithLocation(18, 26),
// (25,23): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()'
// int Local<T>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(25, 23),
// (31,28): warning CS8387: Type parameter 'V' has the same name as the type parameter from outer method 'Local1<V>()'
// int Local2<V>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "V").WithArguments("V", "Local1<V>()").WithLocation(31, 28),
// (37,17): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// int T() => 0;
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(37, 17),
// (43,21): error CS0412: 'V': a parameter, local variable, or local function cannot have the same name as a method type parameter
// int V() => 0;
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "V").WithArguments("V").WithLocation(43, 21),
// (67,32): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M2<T>()'
// int Local3<T>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M2<T>()").WithLocation(67, 32));
}
[Fact]
public void LocalFuncAndTypeParameterOnType()
{
var comp = CreateCompilation(@"
class C2<T>
{
public void M()
{
{
int Local1()
{
int Local2<T>() => 0;
return Local2<int>();
}
Local1();
}
{
int Local1()
{
int Local2()
{
// Shadows type parameter
int T() => 0;
// Type parameter resolves in type only context
T t = default(T);
// Ambiguous context chooses local
T.M();
// Call chooses local
return T();
}
return Local2();
}
Local1();
}
}
}");
comp.VerifyDiagnostics(
// (9,28): warning CS0693: Type parameter 'T' has the same name as the type parameter from outer type 'C2<T>'
// int Local2<T>() => 0;
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "T").WithArguments("T", "C2<T>").WithLocation(9, 28),
// (26,21): error CS0119: 'T()' is a method, which is not valid in the given context
// T.M();
Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T()", "method").WithLocation(26, 21),
// (23,23): warning CS0219: The variable 't' is assigned but its value is never used
// T t = default(T);
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t").WithArguments("t").WithLocation(23, 23));
}
[Fact]
public void RefArgsInIteratorLocalFuncs()
{
var src = @"
using System;
using System.Collections.Generic;
class C
{
public void M1()
{
IEnumerable<int> Local(ref int a) { yield break; }
int x = 0;
Local(ref x);
}
public void M2()
{
Action a = () =>
{
IEnumerable<int> Local(ref int x) { yield break; }
int y = 0;
Local(ref y);
return;
};
a();
}
public Func<int> M3() => (() =>
{
IEnumerable<int> Local(ref int a) { yield break; }
int x = 0;
Local(ref x);
return 0;
});
public IEnumerable<int> M4(ref int a)
{
yield return new Func<int>(() =>
{
IEnumerable<int> Local(ref int b) { yield break; }
int x = 0;
Local(ref x);
return 0;
})();
}
}";
VerifyDiagnostics(src,
// (8,40): error CS1623: Iterators cannot have ref, in or out parameters
// IEnumerable<int> Local(ref int a) { yield break; }
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "a").WithLocation(8, 40),
// (17,44): error CS1623: Iterators cannot have ref, in or out parameters
// IEnumerable<int> Local(ref int x) { yield break; }
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "x").WithLocation(17, 44),
// (27,40): error CS1623: Iterators cannot have ref, in or out parameters
// IEnumerable<int> Local(ref int a) { yield break; }
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "a").WithLocation(27, 40),
// (33,40): error CS1623: Iterators cannot have ref, in or out parameters
// public IEnumerable<int> M4(ref int a)
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "a").WithLocation(33, 40),
// (37,48): error CS1623: Iterators cannot have ref, in or out parameters
// IEnumerable<int> Local(ref int b) { yield break; }
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "b").WithLocation(37, 48));
}
[Fact]
public void UnsafeArgsInIteratorLocalFuncs()
{
var src = @"
using System;
using System.Collections.Generic;
class C
{
public unsafe void M1()
{
IEnumerable<int> Local(int* a) { yield break; }
int x = 0;
Local(&x);
}
public unsafe void M2()
{
Action a = () =>
{
IEnumerable<int> Local(int* x) { yield break; }
int y = 0;
Local(&y);
return;
};
a();
}
public unsafe Func<int> M3() => (() =>
{
IEnumerable<int> Local(int* a) { yield break; }
int x = 0;
Local(&x);
return 0;
});
public unsafe IEnumerable<int> M4(int* a)
{
yield return new Func<int>(() =>
{
IEnumerable<int> Local(int* b) { yield break; }
int x = 0;
Local(&x);
return 0;
})();
}
}";
CreateCompilation(src, options: TestOptions.UnsafeDebugDll)
.VerifyDiagnostics(
// (8,37): error CS1637: Iterators cannot have unsafe parameters or yield types
// IEnumerable<int> Local(int* a) { yield break; }
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "a").WithLocation(8, 37),
// (17,41): error CS1637: Iterators cannot have unsafe parameters or yield types
// IEnumerable<int> Local(int* x) { yield break; }
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "x").WithLocation(17, 41),
// (27,37): error CS1637: Iterators cannot have unsafe parameters or yield types
// IEnumerable<int> Local(int* a) { yield break; }
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "a").WithLocation(27, 37),
// (33,44): error CS1637: Iterators cannot have unsafe parameters or yield types
// public unsafe IEnumerable<int> M4(int* a)
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "a").WithLocation(33, 44),
// (33,36): error CS1629: Unsafe code may not appear in iterators
// public unsafe IEnumerable<int> M4(int* a)
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "M4").WithLocation(33, 36),
// (37,40): error CS1629: Unsafe code may not appear in iterators
// IEnumerable<int> Local(int* b) { yield break; }
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "int*").WithLocation(37, 40),
// (39,23): error CS1629: Unsafe code may not appear in iterators
// Local(&x);
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "&x").WithLocation(39, 23),
// (39,17): error CS1629: Unsafe code may not appear in iterators
// Local(&x);
Diagnostic(ErrorCode.ERR_IllegalInnerUnsafe, "Local(&x)").WithLocation(39, 17),
// (37,45): error CS1637: Iterators cannot have unsafe parameters or yield types
// IEnumerable<int> Local(int* b) { yield break; }
Diagnostic(ErrorCode.ERR_UnsafeIteratorArgType, "b").WithLocation(37, 45));
}
[Fact]
[WorkItem(13193, "https://github.com/dotnet/roslyn/issues/13193")]
public void LocalFunctionConflictingName()
{
var comp = CreateCompilation(@"
class C
{
public void M<TLocal>()
{
void TLocal() { }
TLocal();
}
public void M(int Local)
{
void Local() { }
Local();
}
public void M()
{
int local = 0;
void local() { }
local();
}
}");
comp.VerifyDiagnostics(
// (6,14): error CS0412: 'TLocal': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void TLocal() { }
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "TLocal").WithArguments("TLocal").WithLocation(6, 14),
// (11,14): error CS0136: A local or parameter named 'Local' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void Local() { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "Local").WithArguments("Local").WithLocation(11, 14),
// (18,14): error CS0128: A local variable or function named 'local' is already defined in this scope
// void local() { }
Diagnostic(ErrorCode.ERR_LocalDuplicate, "local").WithArguments("local").WithLocation(18, 14),
// (16,13): warning CS0219: The variable 'local' is assigned but its value is never used
// int local = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "local").WithArguments("local").WithLocation(16, 13));
}
[Fact]
public void ForgotSemicolonLocalFunctionsMistake()
{
var src = @"
class C
{
public void M1()
{
// forget closing brace
public void BadLocal1()
{
this.BadLocal2();
}
public void BadLocal2()
{
}
public int P => 0;
}";
VerifyDiagnostics(src,
// (8,5): error CS0106: The modifier 'public' is not valid for this item
// public void BadLocal1()
Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(8, 5),
// (13,5): error CS0106: The modifier 'public' is not valid for this item
// public void BadLocal2()
Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(13, 5),
// (15,6): error CS1513: } expected
// }
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(15, 6),
// (10,14): error CS1061: 'C' does not contain a definition for 'BadLocal2' and no extension method 'BadLocal2' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// this.BadLocal2();
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BadLocal2").WithArguments("C", "BadLocal2").WithLocation(10, 14),
// (8,17): warning CS8321: The local function 'BadLocal1' is declared but never used
// public void BadLocal1()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "BadLocal1").WithArguments("BadLocal1").WithLocation(8, 17),
// (13,17): warning CS8321: The local function 'BadLocal2' is declared but never used
// public void BadLocal2()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "BadLocal2").WithArguments("BadLocal2").WithLocation(13, 17));
}
[Fact]
public void VarLocalFunction()
{
var src = @"
class C
{
void M()
{
var local() => 0;
int x = local();
}
}";
VerifyDiagnostics(src,
// (6,9): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// var local() => 0;
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(6, 9));
}
[Fact]
public void VarLocalFunction2()
{
var comp = CreateCompilation(@"
class C
{
private class var
{
}
void M()
{
var local() => new var();
var x = local();
}
}", parseOptions: DefaultParseOptions);
comp.VerifyDiagnostics();
}
[Fact]
[CompilerTrait(CompilerFeature.Params)]
public void BadParams()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
void Params(params int x)
{
Console.WriteLine(x);
}
Params(2);
}
}
";
VerifyDiagnostics(source,
// (8,21): error CS0225: The params parameter must be a single dimensional array
// void Params(params int x)
Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(8, 21)
);
}
[Fact]
public void BadRefWithDefault()
{
var source = @"
class Program
{
static void Main(string[] args)
{
void RefOut(ref int x = 2)
{
x++;
}
int y = 2;
RefOut(ref y);
}
}
";
VerifyDiagnostics(source,
// (6,21): error CS1741: A ref or out parameter cannot have a default value
// void RefOut(ref int x = 2)
Diagnostic(ErrorCode.ERR_RefOutDefaultValue, "ref").WithLocation(6, 21)
);
}
[Fact]
public void BadDefaultValueType()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
void NamedOptional(string x = 2)
{
Console.WriteLine(x);
}
NamedOptional(""2"");
}
}
";
VerifyDiagnostics(source,
// (8,35): error CS1750: A value of type 'int' cannot be used as a default parameter because there are no standard conversions to type 'string'
// void NamedOptional(string x = 2)
Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "x").WithArguments("int", "string").WithLocation(8, 35)
);
}
[Fact]
public void CallerMemberName()
{
var comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Runtime.CompilerServices;
class C
{
static void Main()
{
void CallerMemberName([CallerMemberName] string s = null)
{
Console.Write(s);
}
void LocalFuncName()
{
CallerMemberName();
}
LocalFuncName();
Console.Write(' ');
CallerMemberName();
}
}", parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void BadCallerMemberName()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main(string[] args)
{
void CallerMemberName([CallerMemberName] int s = 2) // 1
{
Console.WriteLine(s);
}
CallerMemberName(); // 2
}
}
";
CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics(
// (9,32): error CS4019: CallerMemberNameAttribute cannot be applied because there are no standard conversions from type 'string' to type 'int'
// void CallerMemberName([CallerMemberName] int s = 2) // 1
Diagnostic(ErrorCode.ERR_NoConversionForCallerMemberNameParam, "CallerMemberName").WithArguments("string", "int").WithLocation(9, 32),
// (13,9): error CS0029: Cannot implicitly convert type 'string' to 'int'
// CallerMemberName(); // 2
Diagnostic(ErrorCode.ERR_NoImplicitConv, "CallerMemberName()").WithArguments("string", "int").WithLocation(13, 9));
}
[WorkItem(10708, "https://github.com/dotnet/roslyn/issues/10708")]
[CompilerTrait(CompilerFeature.Dynamic, CompilerFeature.Params)]
[Fact]
public void DynamicArgumentToParams()
{
var src = @"
using System;
class C
{
static void Main()
{
void L1(int x = 0, params int[] ys) => Console.Write(x);
dynamic val = 2;
L1(val, val);
L1(ys: val, x: val);
L1(ys: val);
}
}";
VerifyDiagnostics(src,
// (10,9): error CS8106: Cannot pass argument with dynamic type to params parameter 'ys' of local function 'L1'.
// L1(val, val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "L1(val, val)").WithArguments("ys", "L1").WithLocation(10, 9),
// (11,9): error CS8106: Cannot pass argument with dynamic type to params parameter 'ys' of local function 'L1'.
// L1(ys: val, x: val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "L1(ys: val, x: val)").WithArguments("ys", "L1").WithLocation(11, 9),
// (12,9): error CS8106: Cannot pass argument with dynamic type to params parameter 'ys' of local function 'L1'.
// L1(ys: val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionParamsParameter, "L1(ys: val)").WithArguments("ys", "L1").WithLocation(12, 9));
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicArgOverload()
{
var src = @"
using System;
class C
{
static void Main()
{
void Overload(int i) => Console.Write(i);
void Overload(string s) => Console.Write(s);
dynamic val = 2;
Overload(val);
}
}";
VerifyDiagnostics(src,
// (8,14): error CS0128: A local variable named 'Overload' is already defined in this scope
// void Overload(string s) => Console.Write(s);
Diagnostic(ErrorCode.ERR_LocalDuplicate, "Overload").WithArguments("Overload").WithLocation(8, 14),
// (8,14): warning CS8321: The local function 'Overload' is declared but never used
// void Overload(string s) => Console.Write(s);
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Overload").WithArguments("Overload").WithLocation(8, 14));
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicArgWrongArity()
{
var src = @"
using System;
class C
{
static void Main()
{
void Local(int i) => Console.Write(i);
dynamic val = 2;
Local(val, val);
}
}";
VerifyDiagnostics(src,
// (10,9): error CS1501: No overload for method 'Local' takes 2 arguments
// Local(val, val);
Diagnostic(ErrorCode.ERR_BadArgCount, "Local").WithArguments("Local", "2").WithLocation(10, 9));
}
[WorkItem(3923, "https://github.com/dotnet/roslyn/issues/3923")]
[Fact]
public void ExpressionTreeLocalFunctionUsage_01()
{
var source = @"
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
T Id<T>(T x)
{
return x;
}
Expression<Func<T>> Local<T>(Expression<Func<T>> f)
{
return f;
}
Console.Write(Local(() => Id(2)));
Console.Write(Local<Func<int, int>>(() => Id));
Console.Write(Local(() => new Func<int, int>(Id)));
Console.Write(Local(() => nameof(Id)));
}
}
";
VerifyDiagnostics(source,
// (16,35): error CS8096: An expression tree may not contain a reference to a local function
// Console.Write(Local(() => Id(2)));
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id(2)").WithLocation(16, 35),
// (17,51): error CS8096: An expression tree may not contain a reference to a local function
// Console.Write(Local<Func<int, int>>(() => Id));
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(17, 51),
// (18,35): error CS8096: An expression tree may not contain a reference to a local function
// Console.Write(Local(() => new Func<int, int>(Id)));
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(18, 54)
);
}
[Fact]
public void ExpressionTreeLocalFunctionUsage_02()
{
var source = @"
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
static T Id<T>(T x)
{
return x;
}
static Expression<Func<T>> Local<T>(Expression<Func<T>> f)
{
return f;
}
Console.Write(Local(() => Id(2)));
Console.Write(Local<Func<int, int>>(() => Id));
Console.Write(Local(() => new Func<int, int>(Id)));
Console.Write(Local(() => nameof(Id)));
}
}
";
VerifyDiagnostics(source,
// (16,35): error CS8096: An expression tree may not contain a reference to a local function
// Console.Write(Local(() => Id(2)));
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id(2)").WithLocation(16, 35),
// (17,51): error CS8096: An expression tree may not contain a reference to a local function
// Console.Write(Local<Func<int, int>>(() => Id));
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(17, 51),
// (18,35): error CS8096: An expression tree may not contain a reference to a local function
// Console.Write(Local(() => new Func<int, int>(Id)));
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Id").WithLocation(18, 54)
);
}
[Fact]
public void ExpressionTreeLocalFunctionInside()
{
var source = @"
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<int, int>> f = x =>
{
int Local(int y) => y;
return Local(x);
};
Console.Write(f);
}
}
";
VerifyDiagnostics(source,
// (8,40): error CS0834: A lambda expression with a statement body cannot be converted to an expression tree
// Expression<Func<int, int>> f = x =>
Diagnostic(ErrorCode.ERR_StatementLambdaToExpressionTree, @"x =>
{
int Local(int y) => y;
return Local(x);
}").WithLocation(8, 40),
// (11,20): error CS8096: An expression tree may not contain a local function or a reference to a local function
// return Local(x);
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsLocalFunction, "Local(x)").WithLocation(11, 20)
);
}
[Fact]
public void BadScoping()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
if (true)
{
void Local()
{
Console.WriteLine(2);
}
Local();
}
Local();
Local2();
void Local2()
{
Console.WriteLine(2);
}
}
}
";
VerifyDiagnostics(source,
// (16,9): error CS0103: The name 'Local' does not exist in the current context
// Local();
Diagnostic(ErrorCode.ERR_NameNotInContext, "Local").WithArguments("Local").WithLocation(16, 9)
);
}
[Fact]
public void NameConflictDuplicate()
{
var source = @"
class Program
{
static void Main(string[] args)
{
void Duplicate() { }
void Duplicate() { }
Duplicate();
}
}
";
VerifyDiagnostics(source,
// (7,14): error CS0128: A local variable named 'Duplicate' is already defined in this scope
// void Duplicate() { }
Diagnostic(ErrorCode.ERR_LocalDuplicate, "Duplicate").WithArguments("Duplicate").WithLocation(7, 14),
// (7,14): warning CS8321: The local function 'Duplicate' is declared but never used
// void Duplicate() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Duplicate").WithArguments("Duplicate").WithLocation(7, 14)
);
}
[Fact]
public void NameConflictParameter()
{
var source = @"
class Program
{
static void Main(string[] args)
{
int x = 2;
void Param(int x) { }
Param(x);
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (7,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void Param(int x) { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(7, 24));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
}
[Fact]
public void NameConflictTypeParameter()
{
var source = @"
class Program
{
static void Main(string[] args)
{
int T;
void Generic<T>() { }
Generic<int>();
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (7,22): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void Generic<T>() { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(7, 22),
// (6,13): warning CS0168: The variable 'T' is declared but never used
// int T;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "T").WithArguments("T").WithLocation(6, 13));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (6,13): warning CS0168: The variable 'T' is declared but never used
// int T;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "T").WithArguments("T").WithLocation(6, 13));
}
[Fact]
public void NameConflictNestedTypeParameter()
{
var source = @"
class Program
{
static void Main(string[] args)
{
T Outer<T>()
{
T Inner<T>()
{
return default(T);
}
return Inner<T>();
}
System.Console.Write(Outer<int>());
}
}
";
VerifyDiagnostics(source,
// (8,21): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Outer<T>()'
// T Inner<T>()
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Outer<T>()").WithLocation(8, 21)
);
}
[Fact]
public void NameConflictLocalVarFirst()
{
var source = @"
class Program
{
static void Main(string[] args)
{
int Conflict;
void Conflict() { }
}
}
";
VerifyDiagnostics(source,
// (7,14): error CS0128: A local variable named 'Conflict' is already defined in this scope
// void Conflict() { }
Diagnostic(ErrorCode.ERR_LocalDuplicate, "Conflict").WithArguments("Conflict").WithLocation(7, 14),
// (6,13): warning CS0168: The variable 'Conflict' is declared but never used
// int Conflict;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "Conflict").WithArguments("Conflict").WithLocation(6, 13),
// (7,14): warning CS8321: The local function 'Conflict' is declared but never used
// void Conflict() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Conflict").WithArguments("Conflict").WithLocation(7, 14)
);
}
[Fact]
public void NameConflictLocalVarLast()
{
var source = @"
class Program
{
static void Main(string[] args)
{
void Conflict() { }
int Conflict;
}
}
";
// TODO: This is strange. Probably has to do with the fact that local variables are preferred over functions.
VerifyDiagnostics(source,
// (6,14): error CS0136: A local or parameter named 'Conflict' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void Conflict() { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "Conflict").WithArguments("Conflict").WithLocation(6, 14),
// (7,13): warning CS0168: The variable 'Conflict' is declared but never used
// int Conflict;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "Conflict").WithArguments("Conflict").WithLocation(7, 13),
// (6,14): warning CS8321: The local function 'Conflict' is declared but never used
// void Conflict() { }
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Conflict").WithArguments("Conflict").WithLocation(6, 14)
);
}
[Fact]
public void BadUnsafeNoKeyword()
{
var source = @"
using System;
class Program
{
static void A()
{
void Local()
{
int x = 2;
Console.WriteLine(*&x);
}
Local();
}
static void Main(string[] args)
{
A();
}
}
";
VerifyDiagnostics(source,
// (11,32): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// Console.WriteLine(*&x);
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "&x").WithLocation(11, 32)
);
}
[Fact]
public void BadUnsafeKeywordDoesntApply()
{
var source = @"
using System;
class Program
{
static unsafe void B()
{
void Local()
{
int x = 2;
Console.WriteLine(*&x);
}
Local();
}
static void Main(string[] args)
{
B();
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(true));
comp.VerifyDiagnostics();
}
[Fact]
public void BadEmptyBody()
{
var source = @"
class Program
{
static void Main(string[] args)
{
void Local(int x);
Local(2);
}
}";
VerifyDiagnostics(source,
// (6,14): error CS8112: 'Local(int)' is a local function and must therefore always have a body.
// void Local(int x);
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Local").WithArguments("Local(int)").WithLocation(6, 14)
);
}
[Fact]
public void BadGotoInto()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
goto A;
void Local()
{
A: Console.Write(2);
}
Local();
}
}";
VerifyDiagnostics(source,
// (8,14): error CS0159: No such label 'A' within the scope of the goto statement
// goto A;
Diagnostic(ErrorCode.ERR_LabelNotFound, "A").WithArguments("A").WithLocation(8, 14),
// (11,9): warning CS0164: This label has not been referenced
// A: Console.Write(2);
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "A").WithLocation(11, 9)
);
}
[Fact]
public void BadGotoOutOf()
{
var source = @"
class Program
{
static void Main(string[] args)
{
void Local()
{
goto A;
}
A: Local();
}
}";
VerifyDiagnostics(source,
// (8,13): error CS0159: No such label 'A' within the scope of the goto statement
// goto A;
Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("A").WithLocation(8, 13)
);
}
[Fact]
public void BadDefiniteAssignmentCall()
{
var source = @"
using System;
class Program
{
static void A()
{
goto Label;
int x = 2;
void Local()
{
Console.Write(x);
}
Label:
Local();
}
static void Main(string[] args)
{
A();
}
}";
VerifyDiagnostics(source,
// (9,9): warning CS0162: Unreachable code detected
// int x = 2;
Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(9, 9),
// (15,9): error CS0165: Use of unassigned local variable 'x'
// Local();
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local()").WithArguments("x").WithLocation(15, 9)
);
}
[Fact]
public void BadDefiniteAssignmentDelegateConversion()
{
var source = @"
using System;
class Program
{
static void A()
{
goto Label;
int x = 2;
void Local()
{
Console.Write(x);
}
Label:
Action goo = Local;
}
static void Main(string[] args)
{
A();
}
}";
VerifyDiagnostics(source,
// (9,9): warning CS0162: Unreachable code detected
// int x = 2;
Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(9, 9),
// (15,22): error CS0165: Use of unassigned local variable 'x'
// Action goo = Local;
Diagnostic(ErrorCode.ERR_UseDefViolation, "Local").WithArguments("x").WithLocation(15, 22)
);
}
[Fact]
public void BadDefiniteAssignmentDelegateConstruction()
{
var source = @"
using System;
class Program
{
static void A()
{
goto Label;
int x = 2;
void Local()
{
Console.Write(x);
}
Label:
var bar = new Action(Local);
}
static void Main(string[] args)
{
A();
}
}";
VerifyDiagnostics(source,
// (9,9): warning CS0162: Unreachable code detected
// int x = 2;
Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(9, 9),
// (15,19): error CS0165: Use of unassigned local variable 'x'
// var bar = new Action(Local);
Diagnostic(ErrorCode.ERR_UseDefViolation, "new Action(Local)").WithArguments("x").WithLocation(15, 19)
);
}
[Fact]
public void BadNotUsed()
{
var source = @"
class Program
{
static void A()
{
void Local()
{
}
}
static void Main(string[] args)
{
A();
}
}";
VerifyDiagnostics(source,
// (6,14): warning CS8321: The local function 'Local' is declared but never used
// void Local()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(6, 14)
);
}
[Fact]
public void BadNotUsedSwitch()
{
var source = @"
class Program
{
static void A()
{
switch (0)
{
case 0:
void Local()
{
}
break;
}
}
static void Main(string[] args)
{
A();
}
}";
VerifyDiagnostics(source,
// (9,18): warning CS8321: The local function 'Local' is declared but never used
// void Local()
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local").WithArguments("Local").WithLocation(9, 18)
);
}
[Fact]
public void BadByRefClosure()
{
var source = @"
using System;
class Program
{
static void A(ref int x)
{
void Local()
{
Console.WriteLine(x);
}
Local();
}
static void Main()
{
}
}";
VerifyDiagnostics(source,
// (10,31): error CS1628: Cannot use ref or out parameter 'x' inside an anonymous method, lambda expression, query expression, or local function
// Console.WriteLine(x);
Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "x").WithArguments("x").WithLocation(10, 31)
);
}
[Fact]
public void BadInClosure()
{
var source = @"
using System;
class Program
{
static void A(in int x)
{
void Local()
{
Console.WriteLine(x);
}
Local();
}
static void Main()
{
}
}";
VerifyDiagnostics(source,
// (10,31): error CS1628: Cannot use ref, out, or in parameter 'x' inside an anonymous method, lambda expression, query expression, or local function
// Console.WriteLine(x);
Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "x").WithArguments("x").WithLocation(10, 31)
);
}
[Fact]
public void BadArglistUse()
{
var source = @"
using System;
class Program
{
static void A()
{
void Local()
{
Console.WriteLine(__arglist);
}
Local();
}
static void B(__arglist)
{
void Local()
{
Console.WriteLine(__arglist);
}
Local();
}
static void C() // C and D produce different errors
{
void Local(__arglist)
{
Console.WriteLine(__arglist);
}
Local(__arglist());
}
static void D(__arglist)
{
void Local(__arglist)
{
Console.WriteLine(__arglist);
}
Local(__arglist());
}
static void Main()
{
}
}
";
VerifyDiagnostics(source,
// (10,31): error CS0190: The __arglist construct is valid only within a variable argument method
// Console.WriteLine(__arglist);
Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist").WithLocation(10, 31),
// (18,31): error CS4013: Instance of type 'RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method
// Console.WriteLine(__arglist);
Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(18, 31),
// (24,20): error CS1669: __arglist is not valid in this context
// void Local(__arglist)
Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(24, 20),
// (26,31): error CS0190: The __arglist construct is valid only within a variable argument method
// Console.WriteLine(__arglist);
Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist").WithLocation(26, 31),
// (32,20): error CS1669: __arglist is not valid in this context
// void Local(__arglist)
Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(32, 20),
// (34,31): error CS4013: Instance of type 'RuntimeArgumentHandle' cannot be used inside an anonymous function, query expression, iterator block or async method
// Console.WriteLine(__arglist);
Diagnostic(ErrorCode.ERR_SpecialByRefInLambda, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(34, 31)
);
}
[Fact]
public void BadClosureStaticRefInstance()
{
var source = @"
using System;
class Program
{
int _a = 0;
static void A()
{
void Local()
{
Console.WriteLine(_a);
}
Local();
}
static void Main()
{
}
}
";
VerifyDiagnostics(source,
// (11,31): error CS0120: An object reference is required for the non-static field, method, or property 'Program._a'
// Console.WriteLine(_a);
Diagnostic(ErrorCode.ERR_ObjectRequired, "_a").WithArguments("Program._a").WithLocation(11, 31)
);
}
[Fact]
public void BadRefIterator()
{
var source = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
IEnumerable<int> RefEnumerable(ref int x)
{
yield return x;
}
int y = 0;
RefEnumerable(ref y);
}
}
";
VerifyDiagnostics(source,
// (8,48): error CS1623: Iterators cannot have ref, in or out parameters
// IEnumerable<int> RefEnumerable(ref int x)
Diagnostic(ErrorCode.ERR_BadIteratorArgType, "x").WithLocation(8, 48)
);
}
[Fact]
public void BadRefAsync()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
async Task<int> RefAsync(ref int x)
{
return await Task.FromResult(x);
}
int y = 2;
Console.Write(RefAsync(ref y).Result);
}
}
";
VerifyDiagnostics(source,
// (9,42): error CS1988: Async methods cannot have ref, in or out parameters
// async Task<int> RefAsync(ref int x)
Diagnostic(ErrorCode.ERR_BadAsyncArgType, "x").WithLocation(9, 42)
);
}
[Fact]
public void Extension_01()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int Local(this int x)
{
return x;
}
Console.WriteLine(Local(2));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (8,13): error CS1106: Extension method must be defined in a non-generic static class
// int Local(this int x)
Diagnostic(ErrorCode.ERR_BadExtensionAgg, "Local").WithLocation(8, 13)
);
}
[Fact]
public void Extension_02()
{
var source =
@"#pragma warning disable 8321
static class E
{
static void M()
{
void F1(this string s) { }
static void F2(this string s) { }
}
}";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (6,14): error CS1106: Extension method must be defined in a non-generic static class
// void F1(this string s) { }
Diagnostic(ErrorCode.ERR_BadExtensionAgg, "F1").WithLocation(6, 14),
// (7,21): error CS1106: Extension method must be defined in a non-generic static class
// static void F2(this string s) { }
Diagnostic(ErrorCode.ERR_BadExtensionAgg, "F2").WithLocation(7, 21));
}
[Fact]
public void BadModifiers()
{
var source = @"
class Program
{
static void Main(string[] args)
{
const void LocalConst()
{
}
static void LocalStatic()
{
}
readonly void LocalReadonly()
{
}
volatile void LocalVolatile()
{
}
LocalConst();
LocalStatic();
LocalReadonly();
LocalVolatile();
}
}
";
var baseExpected = new[]
{
// (6,9): error CS0106: The modifier 'const' is not valid for this item
// const void LocalConst()
Diagnostic(ErrorCode.ERR_BadMemberFlag, "const").WithArguments("const").WithLocation(6, 9),
// (12,9): error CS0106: The modifier 'readonly' is not valid for this item
// readonly void LocalReadonly()
Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(12, 9),
// (15,9): error CS0106: The modifier 'volatile' is not valid for this item
// volatile void LocalVolatile()
Diagnostic(ErrorCode.ERR_BadMemberFlag, "volatile").WithArguments("volatile").WithLocation(15, 9)
};
var extra = new[]
{
// (9,9): error CS8652: The feature 'static local functions' is not available in C# 7.3. Please use language version 8.0 or greater.
// static void LocalStatic()
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "static").WithArguments("static local functions", "8.0").WithLocation(9, 9),
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
baseExpected.Concat(extra).ToArray());
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(baseExpected);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(baseExpected);
}
[Fact]
public void ArglistIterator()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
IEnumerable<int> Local(__arglist)
{
yield return 2;
}
Console.WriteLine(string.Join("","", Local(__arglist())));
}
}
";
VerifyDiagnostics(source,
// (9,26): error CS1636: __arglist is not allowed in the parameter list of iterators
// IEnumerable<int> Local(__arglist)
Diagnostic(ErrorCode.ERR_VarargsIterator, "Local").WithLocation(9, 26),
// (9,32): error CS1669: __arglist is not valid in this context
// IEnumerable<int> Local(__arglist)
Diagnostic(ErrorCode.ERR_IllegalVarArgs, "__arglist").WithLocation(9, 32));
}
[Fact]
public void ForwardReference()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Local());
int Local() => 2;
}
}
";
CompileAndVerify(source, expectedOutput: "2");
}
[Fact]
public void ForwardReferenceCapture()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int x = 2;
Console.WriteLine(Local());
int Local() => x;
}
}
";
CompileAndVerify(source, expectedOutput: "2");
}
[Fact]
public void ForwardRefInLocalFunc()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int x = 2;
Console.WriteLine(Local());
int Local()
{
x = 3;
return Local2();
}
int Local2() => x;
}
}
";
CompileAndVerify(source, expectedOutput: "3");
}
[Fact]
public void LocalFuncMutualRecursion()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 0;
Console.WriteLine(Local1());
int Local1()
{
x -= 1;
return Local2(y++);
}
int Local2(int z)
{
if (x == 0)
{
return z;
}
else
{
return Local1();
}
}
}
}
";
CompileAndVerify(source, expectedOutput: "4");
}
[Fact]
public void OtherSwitchBlock()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
var x = int.Parse(Console.ReadLine());
switch (x)
{
case 0:
void Local()
{
}
break;
default:
Local();
break;
}
}
}
";
VerifyDiagnostics(source);
}
[Fact]
public void NoOperator()
{
var source = @"
class Program
{
static void Main(string[] args)
{
Program operator +(Program left, Program right)
{
return left;
}
}
}
";
VerifyDiagnostics(source,
// (6,17): error CS1002: ; expected
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "operator").WithLocation(6, 17),
// (6,17): error CS1513: } expected
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_RbraceExpected, "operator").WithLocation(6, 17),
// (6,56): error CS1002: ; expected
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 56),
// (6,9): error CS0119: 'Program' is a type, which is not valid in the given context
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(6, 9),
// (6,28): error CS8185: A declaration is not allowed in this context.
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "Program left").WithLocation(6, 28),
// (6,42): error CS8185: A declaration is not allowed in this context.
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "Program right").WithLocation(6, 42),
// (6,27): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(Program left, Program right)").WithArguments("System.ValueTuple`2").WithLocation(6, 27),
// (8,13): error CS0127: Since 'Program.Main(string[])' returns void, a return keyword must not be followed by an object expression
// return left;
Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("Program.Main(string[])").WithLocation(8, 13),
// (6,28): error CS0165: Use of unassigned local variable 'left'
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_UseDefViolation, "Program left").WithArguments("left").WithLocation(6, 28),
// (6,42): error CS0165: Use of unassigned local variable 'right'
// Program operator +(Program left, Program right)
Diagnostic(ErrorCode.ERR_UseDefViolation, "Program right").WithArguments("right").WithLocation(6, 42)
);
}
[Fact]
public void NoProperty()
{
var source = @"
class Program
{
static void Main(string[] args)
{
int Goo
{
get
{
return 2;
}
}
int Bar => 2;
}
}
";
VerifyDiagnostics(source,
// (6,16): error CS1002: ; expected
// int Goo
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 16),
// (8,16): error CS1002: ; expected
// get
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 16),
// (13,17): error CS1003: Syntax error, ',' expected
// int Bar => 2;
Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(13, 17),
// (13,20): error CS1002: ; expected
// int Bar => 2;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "2").WithLocation(13, 20),
// (8,13): error CS0103: The name 'get' does not exist in the current context
// get
Diagnostic(ErrorCode.ERR_NameNotInContext, "get").WithArguments("get").WithLocation(8, 13),
// (10,17): error CS0127: Since 'Program.Main(string[])' returns void, a return keyword must not be followed by an object expression
// return 2;
Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("Program.Main(string[])").WithLocation(10, 17),
// (13,20): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// int Bar => 2;
Diagnostic(ErrorCode.ERR_IllegalStatement, "2").WithLocation(13, 20),
// (13,9): warning CS0162: Unreachable code detected
// int Bar => 2;
Diagnostic(ErrorCode.WRN_UnreachableCode, "int").WithLocation(13, 9),
// (6,13): warning CS0168: The variable 'Goo' is declared but never used
// int Goo
Diagnostic(ErrorCode.WRN_UnreferencedVar, "Goo").WithArguments("Goo").WithLocation(6, 13),
// (13,13): warning CS0168: The variable 'Bar' is declared but never used
// int Bar => 2;
Diagnostic(ErrorCode.WRN_UnreferencedVar, "Bar").WithArguments("Bar").WithLocation(13, 13)
);
}
[Fact]
public void NoFeatureSwitch()
{
var source = @"
class Program
{
static void Main(string[] args)
{
void Local() { }
Local();
}
}
";
var option = TestOptions.ReleaseExe;
CreateCompilation(source, options: option, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics(
// (6,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater.
// void Local() { }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "Local").WithArguments("local functions", "7.0").WithLocation(6, 14)
);
}
[Fact, WorkItem(10521, "https://github.com/dotnet/roslyn/issues/10521")]
public void LocalFunctionInIf()
{
var source = @"
class Program
{
static void Main(string[] args)
{
if () // typing at this point
int Add(int x, int y) => x + y;
}
}
";
VerifyDiagnostics(source,
// (6,13): error CS1525: Invalid expression term ')'
// if () // typing at this point
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 13),
// (7,9): error CS1023: Embedded statement cannot be a declaration or labeled statement
// int Add(int x, int y) => x + y;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "int Add(int x, int y) => x + y;").WithLocation(7, 9),
// (7,13): warning CS8321: The local function 'Add' is declared but never used
// int Add(int x, int y) => x + y;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Add").WithArguments("Add").WithLocation(7, 13)
);
}
[Fact, WorkItem(10521, "https://github.com/dotnet/roslyn/issues/10521")]
public void LabeledLocalFunctionInIf()
{
var source = @"
class Program
{
static void Main(string[] args)
{
if () // typing at this point
a: int Add(int x, int y) => x + y;
}
}
";
VerifyDiagnostics(source,
// (6,13): error CS1525: Invalid expression term ')'
// if () // typing at this point
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 13),
// (7,1): error CS1023: Embedded statement cannot be a declaration or labeled statement
// a: int Add(int x, int y) => x + y;
Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: int Add(int x, int y) => x + y;").WithLocation(7, 1),
// (7,1): warning CS0164: This label has not been referenced
// a: int Add(int x, int y) => x + y;
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(7, 1),
// (7,13): warning CS8321: The local function 'Add' is declared but never used
// a: int Add(int x, int y) => x + y;
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Add").WithArguments("Add").WithLocation(7, 13)
);
}
[CompilerTrait(CompilerFeature.LocalFunctions, CompilerFeature.Var)]
public sealed class VarTests : LocalFunctionsTestBase
{
[Fact]
public void IllegalAsReturn()
{
var source = @"
using System;
class Program
{
static void Main()
{
var f() => 42;
Console.WriteLine(f());
}
}";
var comp = CreateCompilationWithMscorlib45(source, parseOptions: DefaultParseOptions);
comp.VerifyDiagnostics(
// (7,9): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// var f() => 42;
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(7, 9));
}
[Fact]
public void RealTypeAsReturn()
{
var source = @"
using System;
class var
{
public override string ToString() => ""dog"";
}
class Program
{
static void Main()
{
var f() => new var();
Console.WriteLine(f());
}
}";
CompileAndVerify(
source,
parseOptions: DefaultParseOptions,
expectedOutput: "dog");
}
[Fact]
public void RealTypeParameterAsReturn()
{
var source = @"
using System;
class test
{
public override string ToString() => ""dog"";
}
class Program
{
static void Test<var>(var x)
{
var f() => x;
Console.WriteLine(f());
}
static void Main()
{
Test(new test());
}
}";
CompileAndVerify(
source,
parseOptions: DefaultParseOptions,
expectedOutput: "dog");
}
[Fact]
public void IdentifierAndTypeNamedVar()
{
var source = @"
using System;
class var
{
public override string ToString() => ""dog"";
}
class Program
{
static void Main()
{
int var = 42;
var f() => new var();
Console.WriteLine($""{f()}-{var}"");
}
}";
CompileAndVerify(
source,
parseOptions: DefaultParseOptions,
expectedOutput: "dog-42");
}
}
[CompilerTrait(CompilerFeature.LocalFunctions, CompilerFeature.Async)]
public sealed class AsyncTests : LocalFunctionsTestBase
{
[Fact]
public void RealTypeAsReturn()
{
var source = @"
using System;
class async
{
public override string ToString() => ""dog"";
}
class Program
{
static void Main()
{
async f() => new async();
Console.WriteLine(f());
}
}";
CompileAndVerify(
source,
parseOptions: DefaultParseOptions,
expectedOutput: "dog");
}
[Fact]
public void RealTypeParameterAsReturn()
{
var source = @"
using System;
class test
{
public override string ToString() => ""dog"";
}
class Program
{
static void Test<async>(async x)
{
async f() => x;
Console.WriteLine(f());
}
static void Main()
{
Test(new test());
}
}";
CompileAndVerify(
source,
parseOptions: DefaultParseOptions,
expectedOutput: "dog");
}
[Fact]
public void ManyMeaningsType()
{
var source = @"
using System;
using System.Threading;
using System.Threading.Tasks;
class async
{
public override string ToString() => ""async"";
}
class Program
{
static void Main()
{
async Task<async> Test(Task<async> t)
{
async local = await t;
Console.WriteLine(local);
return local;
}
Test(Task.FromResult<async>(new async())).Wait();
}
}";
var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe);
CompileAndVerify(
comp,
expectedOutput: "async");
}
}
[Fact]
[WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")]
public void ParamUnassigned_01()
{
var src = @"
class C
{
public void M1()
{
void TakeOutParam1(out int x)
{
}
int y;
TakeOutParam1(out y);
}
void TakeOutParam2(out int x)
{
}
}";
VerifyDiagnostics(src,
// (6,14): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// void TakeOutParam1(out int x)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam1").WithArguments("x").WithLocation(6, 14),
// (14,14): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// void TakeOutParam2(out int x)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam2").WithArguments("x").WithLocation(14, 14)
);
}
[Fact]
[WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")]
public void ParamUnassigned_02()
{
var src = @"
class C
{
public void M1()
{
void TakeOutParam1(out int x)
{
return; // 1
}
int y;
TakeOutParam1(out y);
}
void TakeOutParam2(out int x)
{
return; // 2
}
}";
VerifyDiagnostics(src,
// (8,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// return; // 1
Diagnostic(ErrorCode.ERR_ParamUnassigned, "return;").WithArguments("x").WithLocation(8, 13),
// (17,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// return; // 2
Diagnostic(ErrorCode.ERR_ParamUnassigned, "return;").WithArguments("x").WithLocation(17, 13)
);
}
[Fact]
[WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")]
public void ParamUnassigned_03()
{
var src = @"
class C
{
public void M1()
{
int TakeOutParam1(out int x)
{
}
int y;
TakeOutParam1(out y);
}
int TakeOutParam2(out int x)
{
}
}";
VerifyDiagnostics(src,
// (6,13): error CS0161: 'TakeOutParam1(out int)': not all code paths return a value
// int TakeOutParam1(out int x)
Diagnostic(ErrorCode.ERR_ReturnExpected, "TakeOutParam1").WithArguments("TakeOutParam1(out int)").WithLocation(6, 13),
// (6,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// int TakeOutParam1(out int x)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam1").WithArguments("x").WithLocation(6, 13),
// (14,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// int TakeOutParam2(out int x)
Diagnostic(ErrorCode.ERR_ParamUnassigned, "TakeOutParam2").WithArguments("x").WithLocation(14, 13),
// (14,13): error CS0161: 'C.TakeOutParam2(out int)': not all code paths return a value
// int TakeOutParam2(out int x)
Diagnostic(ErrorCode.ERR_ReturnExpected, "TakeOutParam2").WithArguments("C.TakeOutParam2(out int)").WithLocation(14, 13)
);
}
[Fact]
[WorkItem(12467, "https://github.com/dotnet/roslyn/issues/12467")]
public void ParamUnassigned_04()
{
var src = @"
class C
{
public void M1()
{
int TakeOutParam1(out int x)
{
return 1;
}
int y;
TakeOutParam1(out y);
}
int TakeOutParam2(out int x)
{
return 2;
}
}";
VerifyDiagnostics(src,
// (8,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// return 1;
Diagnostic(ErrorCode.ERR_ParamUnassigned, "return 1;").WithArguments("x").WithLocation(8, 13),
// (17,13): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// return 2;
Diagnostic(ErrorCode.ERR_ParamUnassigned, "return 2;").WithArguments("x").WithLocation(17, 13)
);
}
[Fact]
[WorkItem(49500, "https://github.com/dotnet/roslyn/issues/49500")]
public void OutParam_Extern_01()
{
var src = @"
using System.Runtime.InteropServices;
class C
{
void M()
{
int x;
local(out x);
x.ToString();
[DllImport(""a"")]
static extern void local(out int x);
}
[DllImport(""a"")]
static extern void Method(out int x);
}";
VerifyDiagnostics(src);
}
[Fact]
[WorkItem(49500, "https://github.com/dotnet/roslyn/issues/49500")]
public void OutParam_Extern_02()
{
var src = @"
using System.Runtime.InteropServices;
class C
{
void M()
{
local1(out _);
local2(out _);
local3(out _);
[DllImport(""a"")]
static extern void local1(out int x) { } // 1
static void local2(out int x) { } // 2
static void local3(out int x); // 3, 4
}
[DllImport(""a"")]
static extern void Method(out int x);
}";
VerifyDiagnostics(src,
// (13,28): error CS0179: 'local1(out int)' cannot be extern and declare a body
// static extern void local1(out int x) { } // 1
Diagnostic(ErrorCode.ERR_ExternHasBody, "local1").WithArguments("local1(out int)").WithLocation(13, 28),
// (15,21): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// static void local2(out int x) { } // 2
Diagnostic(ErrorCode.ERR_ParamUnassigned, "local2").WithArguments("x").WithLocation(15, 21),
// (17,21): error CS8112: Local function 'local3(out int)' must declare a body because it is not marked 'static extern'.
// static void local3(out int x); // 3, 4
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local3").WithArguments("local3(out int)").WithLocation(17, 21),
// (17,21): error CS0177: The out parameter 'x' must be assigned to before control leaves the current method
// static void local3(out int x); // 3, 4
Diagnostic(ErrorCode.ERR_ParamUnassigned, "local3").WithArguments("x").WithLocation(17, 21));
}
[Fact]
[WorkItem(13172, "https://github.com/dotnet/roslyn/issues/13172")]
public void InheritUnsafeContext()
{
var comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
async Task<IntPtr> Local()
{
await Task.Delay(0);
return (IntPtr)(void*)null;
}
var _ = Local();
}
public void M2()
{
unsafe
{
async Task<IntPtr> Local()
{
await Task.Delay(1);
return (IntPtr)(void*)null;
}
var _ = Local();
}
}
public unsafe void M3()
{
async Task<IntPtr> Local()
{
await Task.Delay(2);
return (IntPtr)(void*)null;
}
var _ = Local();
}
}
unsafe class D
{
int* p = null;
public void M()
{
async Task<IntPtr> Local()
{
await Task.Delay(3);
return (IntPtr)p;
}
var _ = Local();
}
public unsafe void M2()
{
unsafe
{
async Task<IntPtr> Local()
{
await Task.Delay(4);
return (IntPtr)(void*)null;
}
var _ = Local();
}
}
}", options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (11,29): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// return (IntPtr)(void*)null;
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "void*").WithLocation(11, 29),
// (11,28): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// return (IntPtr)(void*)null;
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "(void*)null").WithLocation(11, 28),
// (47,13): error CS4004: Cannot await in an unsafe context
// await Task.Delay(3);
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(3)").WithLocation(47, 13),
// (22,17): error CS4004: Cannot await in an unsafe context
// await Task.Delay(1);
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(1)").WithLocation(22, 17),
// (59,17): error CS4004: Cannot await in an unsafe context
// await Task.Delay(4);
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(4)").WithLocation(59, 17),
// (33,13): error CS4004: Cannot await in an unsafe context
// await Task.Delay(2);
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.Delay(2)").WithLocation(33, 13));
}
[Fact, WorkItem(16167, "https://github.com/dotnet/roslyn/issues/16167")]
public void DeclarationInLocalFunctionParameterDefault()
{
var text = @"
class C
{
public static void Main(int arg)
{
void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {}
void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {}
void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {}
void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {}
void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {}
void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {}
int t = z1 + z2 + z3 + z4 + z5 + z6;
}
static bool M(out int z) // needed to infer type of z5
{
z = 1;
return true;
}
static bool M(params object[] args) => true;
}
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
Item1 = item1;
Item2 = item2;
}
}
}
";
// the scope of an expression variable introduced in the default expression
// of a local function parameter is that default expression.
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
// (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(arg is int z1, z1)").WithArguments("b").WithLocation(6, 30),
// (6,61): error CS0103: The name 'z1' does not exist in the current context
// void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 61),
// (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out int z2), z2)").WithArguments("b").WithLocation(7, 30),
// (7,61): error CS0103: The name 'z2' does not exist in the current context
// void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 61),
// (8,35): error CS8185: A declaration is not allowed in this context.
// void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {}
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int z3").WithLocation(8, 35),
// (8,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M((int z3, int a2) = (1, 2)), z3)").WithArguments("b").WithLocation(8, 30),
// (8,76): error CS0103: The name 'z3' does not exist in the current context
// void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(8, 76),
// (10,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(arg is var z4, z4)").WithArguments("b").WithLocation(10, 30),
// (10,61): error CS0103: The name 'z4' does not exist in the current context
// void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "z4").WithArguments("z4").WithLocation(10, 61),
// (11,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out var z5), z5)").WithArguments("b").WithLocation(11, 30),
// (11,61): error CS0103: The name 'z5' does not exist in the current context
// void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "z5").WithArguments("z5").WithLocation(11, 61),
// (12,35): error CS8185: A declaration is not allowed in this context.
// void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {}
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var z6").WithLocation(12, 35),
// (12,30): error CS1736: Default parameter value for 'b' must be a compile-time constant
// void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M((var z6, int a2) = (1, 2)), z6)").WithArguments("b").WithLocation(12, 30),
// (12,76): error CS0103: The name 'z6' does not exist in the current context
// void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {}
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(12, 76),
// (14,17): error CS0103: The name 'z1' does not exist in the current context
// int t = z1 + z2 + z3 + z4 + z5 + z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(14, 17),
// (14,22): error CS0103: The name 'z2' does not exist in the current context
// int t = z1 + z2 + z3 + z4 + z5 + z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 22),
// (14,27): error CS0103: The name 'z3' does not exist in the current context
// int t = z1 + z2 + z3 + z4 + z5 + z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(14, 27),
// (14,32): error CS0103: The name 'z4' does not exist in the current context
// int t = z1 + z2 + z3 + z4 + z5 + z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z4").WithArguments("z4").WithLocation(14, 32),
// (14,37): error CS0103: The name 'z5' does not exist in the current context
// int t = z1 + z2 + z3 + z4 + z5 + z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z5").WithArguments("z5").WithLocation(14, 37),
// (14,42): error CS0103: The name 'z6' does not exist in the current context
// int t = z1 + z2 + z3 + z4 + z5 + z6;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(14, 42),
// (6,14): warning CS8321: The local function 'Local1' is declared but never used
// void Local1(bool b = M(arg is int z1, z1), int s1 = z1) {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local1").WithArguments("Local1").WithLocation(6, 14),
// (7,14): warning CS8321: The local function 'Local2' is declared but never used
// void Local2(bool b = M(M(out int z2), z2), int s2 = z2) {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(7, 14),
// (8,14): warning CS8321: The local function 'Local3' is declared but never used
// void Local3(bool b = M(M((int z3, int a2) = (1, 2)), z3), int a3 = z3) {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local3").WithArguments("Local3").WithLocation(8, 14),
// (10,14): warning CS8321: The local function 'Local4' is declared but never used
// void Local4(bool b = M(arg is var z4, z4), int s1 = z4) {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local4").WithArguments("Local4").WithLocation(10, 14),
// (11,14): warning CS8321: The local function 'Local5' is declared but never used
// void Local5(bool b = M(M(out var z5), z5), int s2 = z5) {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(11, 14),
// (12,14): warning CS8321: The local function 'Local6' is declared but never used
// void Local6(bool b = M(M((var z6, int a2) = (1, 2)), z6), int a3 = z6) {}
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local6").WithArguments("Local6").WithLocation(12, 14)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var descendents = tree.GetRoot().DescendantNodes();
for (int i = 1; i <= 6; i++)
{
var name = $"z{i}";
var designation = descendents.OfType<SingleVariableDesignationSyntax>().Where(d => d.Identifier.ValueText == name).Single();
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(designation);
Assert.NotNull(symbol);
Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString());
var refs = descendents.OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == name).ToArray();
Assert.Equal(3, refs.Length);
Assert.Equal(symbol, model.GetSymbolInfo(refs[0]).Symbol);
Assert.Null(model.GetSymbolInfo(refs[1]).Symbol);
Assert.Null(model.GetSymbolInfo(refs[2]).Symbol);
}
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/16451")]
public void RecursiveParameterDefault()
{
var text = @"
class C
{
public static void Main(int arg)
{
int Local(int x = Local()) => 2;
}
}
";
var compilation = CreateCompilationWithMscorlib45(text);
compilation.VerifyDiagnostics(
);
}
[Fact]
[WorkItem(16757, "https://github.com/dotnet/roslyn/issues/16757")]
public void LocalFunctionParameterDefaultUsingConst()
{
var source = @"
class C
{
public static void Main()
{
const int N = 2;
void Local1(int n = N) { System.Console.Write(n); }
Local1();
Local1(3);
}
}
";
CompileAndVerify(source, expectedOutput: "23", sourceSymbolValidator: m =>
{
var compilation = m.DeclaringCompilation;
// See https://github.com/dotnet/roslyn/issues/16454; this should actually produce no errors
compilation.VerifyDiagnostics(
// (6,19): warning CS0219: The variable 'N' is assigned but its value is never used
// const int N = 2;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "N").WithArguments("N").WithLocation(6, 19)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var descendents = tree.GetRoot().DescendantNodes();
var parameter = descendents.OfType<ParameterSyntax>().Single();
Assert.Equal("int n = N", parameter.ToString());
Assert.Equal("[System.Int32 n = 2]", model.GetDeclaredSymbol(parameter).ToTestDisplayString());
var name = "N";
var declarator = descendents.OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == name).Single();
var symbol = (ILocalSymbol)model.GetDeclaredSymbol(declarator);
Assert.NotNull(symbol);
Assert.Equal("System.Int32 N", symbol.ToTestDisplayString());
var refs = descendents.OfType<IdentifierNameSyntax>().Where(n => n.Identifier.ValueText == name).ToArray();
Assert.Equal(1, refs.Length);
Assert.Same(symbol, model.GetSymbolInfo(refs[0]).Symbol);
});
}
[Fact]
[WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")]
public void CallFromDifferentSwitchSection_01()
{
var source = @"
class Program
{
static void Main()
{
Test(string.Empty);
}
static void Test(object o)
{
switch (o)
{
case string x:
Assign();
Print();
break;
case int x:
void Assign() { x = 5; }
void Print() => System.Console.WriteLine(x);
break;
}
}
}";
var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "5");
}
[Fact]
[WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")]
public void CallFromDifferentSwitchSection_02()
{
var source = @"
class Program
{
static void Main()
{
Test(string.Empty);
}
static void Test(object o)
{
switch (o)
{
case int x:
void Assign() { x = 5; }
void Print() => System.Console.WriteLine(x);
break;
case string x:
Assign();
Print();
break;
}
}
}";
var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "5");
}
[Fact]
[WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")]
public void CallFromDifferentSwitchSection_03()
{
var source = @"
class Program
{
static void Main()
{
Test(string.Empty);
}
static void Test(object o)
{
switch (o)
{
case string x:
Assign();
System.Action p = Print;
p();
break;
case int x:
void Assign() { x = 5; }
void Print() => System.Console.WriteLine(x);
break;
}
}
}";
var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "5");
}
[Fact]
[WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")]
public void CallFromDifferentSwitchSection_04()
{
var source = @"
class Program
{
static void Main()
{
Test(string.Empty);
}
static void Test(object o)
{
switch (o)
{
case int x:
void Assign() { x = 5; }
void Print() => System.Console.WriteLine(x);
break;
case string x:
Assign();
System.Action p = Print;
p();
break;
}
}
}";
var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "5");
}
[Fact]
[WorkItem(15536, "https://github.com/dotnet/roslyn/issues/15536")]
public void CallFromDifferentSwitchSection_05()
{
var source = @"
class Program
{
static void Main()
{
Test(string.Empty);
}
static void Test(object o)
{
switch (o)
{
case string x:
Local1();
break;
case int x:
void Local1() => Local2(x = 5);
break;
case char x:
void Local2(int y)
{
System.Console.WriteLine(x = 'a');
System.Console.WriteLine(y);
}
break;
}
}
}";
var comp = CreateCompilationWithMscorlib46(source, parseOptions: DefaultParseOptions, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput:
@"a
5");
}
[Fact]
[WorkItem(16751, "https://github.com/dotnet/roslyn/issues/16751")]
public void SemanticModelInAttribute_01()
{
var source =
@"
public class X
{
public static void Main()
{
const bool b1 = true;
void Local1(
[Test(p = b1)]
[Test(p = b2)]
int p1)
{
}
Local1(1);
}
}
class b1 {}
class Test : System.Attribute
{
public bool p {get; set;}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
compilation.VerifyDiagnostics(
// (10,23): error CS0103: The name 'b2' does not exist in the current context
// [Test(p = b2)]
Diagnostic(ErrorCode.ERR_NameNotInContext, "b2").WithArguments("b2").WithLocation(10, 23),
// (6,20): warning CS0219: The variable 'b1' is assigned but its value is never used
// const bool b1 = true;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b1").WithArguments("b1").WithLocation(6, 20)
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var b2 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b2").Single();
Assert.Null(model.GetSymbolInfo(b2).Symbol);
var b1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b1").Single();
var b1Symbol = model.GetSymbolInfo(b1).Symbol;
Assert.Equal("System.Boolean b1", b1Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, b1Symbol.Kind);
}
[Fact]
[WorkItem(19778, "https://github.com/dotnet/roslyn/issues/19778")]
public void BindDynamicInvocation()
{
var source =
@"using System;
class C
{
static void M()
{
dynamic L<T>(Func<dynamic, T> t, object p) => p;
L(m => L(d => d, null), null);
L(m => L(d => d, m), null);
}
}";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef, CSharpRef });
comp.VerifyEmitDiagnostics(
// (8,18): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
// L(m => L(d => d, m), null);
Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "d => d").WithLocation(8, 18),
// (8,16): error CS8322: Cannot pass argument with dynamic type to generic local function 'L' with inferred type arguments.
// L(m => L(d => d, m), null);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L(d => d, m)").WithArguments("L").WithLocation(8, 16));
}
[Fact]
[WorkItem(19778, "https://github.com/dotnet/roslyn/issues/19778")]
public void BindDynamicInvocation_Async()
{
var source =
@"using System;
using System.Threading.Tasks;
class C
{
static void M()
{
async Task<dynamic> L<T>(Func<dynamic, T> t, object p)
=> await L(async m => L(async d => await d, m), p);
}
}";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { SystemCoreRef, CSharpRef });
comp.VerifyEmitDiagnostics(
// (8,37): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
// => await L(async m => L(async d => await d, m), p);
Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "async d => await d").WithLocation(8, 37),
// (8,35): error CS8322: Cannot pass argument with dynamic type to generic local function 'L' with inferred type arguments.
// => await L(async m => L(async d => await d, m), p);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L(async d => await d, m)").WithArguments("L").WithLocation(8, 35),
// (8,32): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// => await L(async m => L(async d => await d, m), p);
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(8, 32));
}
[Fact]
[WorkItem(21317, "https://github.com/dotnet/roslyn/issues/21317")]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicGenericArg()
{
var src = @"
using System.Collections.Generic;
class C
{
static void M()
{
dynamic val = 2;
dynamic dynamicList = new List<int>();
void L1<T>(T x) { }
L1(val);
void L2<T>(int x, T y) { }
L2(1, val);
L2(val, 3.0f);
void L3<T>(List<T> x) { }
L3(dynamicList);
void L4<T>(int x, params T[] y) { }
L4(1, 2, val);
L4(val, 3, 4);
void L5<T>(T x, params int[] y) { }
L5(val, 1, 2);
L5(1, 3, val);
}
}
";
VerifyDiagnostics(src,
// (11,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L1'. Try specifying the type arguments explicitly.
// L1(val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L1(val)").WithArguments("L1").WithLocation(11, 9),
// (14,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L2'. Try specifying the type arguments explicitly.
// L2(1, val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L2(1, val)").WithArguments("L2").WithLocation(14, 9),
// (15,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L2'. Try specifying the type arguments explicitly.
// L2(val, 3.0f);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L2(val, 3.0f)").WithArguments("L2").WithLocation(15, 9),
// (18,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L3'. Try specifying the type arguments explicitly.
// L3(dynamicList);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L3(dynamicList)").WithArguments("L3").WithLocation(18, 9),
// (21,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L4'. Try specifying the type arguments explicitly.
// L4(1, 2, val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L4(1, 2, val)").WithArguments("L4").WithLocation(21, 9),
// (22,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L4'. Try specifying the type arguments explicitly.
// L4(val, 3, 4);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L4(val, 3, 4)").WithArguments("L4").WithLocation(22, 9),
// (25,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L5'. Try specifying the type arguments explicitly.
// L5(val, 1, 2);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L5(val, 1, 2)").WithArguments("L5").WithLocation(25, 9),
// (26,9): error CS8322: Cannot pass argument with dynamic type to generic local function 'L5'. Try specifying the type arguments explicitly.
// L5(1, 3, val);
Diagnostic(ErrorCode.ERR_DynamicLocalFunctionTypeParameter, "L5(1, 3, val)").WithArguments("L5").WithLocation(26, 9)
);
}
[Fact]
[WorkItem(23699, "https://github.com/dotnet/roslyn/issues/23699")]
public void GetDeclaredSymbolOnTypeParameter()
{
var src = @"
class C<T>
{
void M<U>()
{
void LocalFunction<T, U, V>(T p1, U p2, V p3)
{
}
}
}
";
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var localDecl = (LocalFunctionStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.LocalFunctionStatement).AsNode();
var typeParameters = localDecl.TypeParameterList.Parameters;
var parameters = localDecl.ParameterList.Parameters;
verifyTypeParameterAndParameter(typeParameters[0], parameters[0], "T");
verifyTypeParameterAndParameter(typeParameters[1], parameters[1], "U");
verifyTypeParameterAndParameter(typeParameters[2], parameters[2], "V");
void verifyTypeParameterAndParameter(TypeParameterSyntax typeParameter, ParameterSyntax parameter, string expected)
{
var symbol = model.GetDeclaredSymbol(typeParameter);
Assert.Equal(expected, symbol.ToTestDisplayString());
var parameterSymbol = model.GetDeclaredSymbol(parameter);
Assert.Equal(expected, parameterSymbol.Type.ToTestDisplayString());
Assert.Same(symbol, parameterSymbol.Type);
}
}
public sealed class ScriptGlobals
{
public int SomeGlobal => 42;
}
[ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28001")]
public void CanAccessScriptGlobalsFromInsideMethod()
{
var source = @"
void Method()
{
LocalFunction();
void LocalFunction()
{
_ = SomeGlobal;
}
}";
CreateSubmission(source, new[] { ScriptTestFixtures.HostRef }, hostObjectType: typeof(ScriptGlobals))
.VerifyEmitDiagnostics();
}
[ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28001")]
public void CanAccessScriptGlobalsFromInsideLambda()
{
var source = @"
var lambda = new System.Action(() =>
{
LocalFunction();
void LocalFunction()
{
_ = SomeGlobal;
}
});";
CreateSubmission(source, new[] { ScriptTestFixtures.HostRef }, hostObjectType: typeof(ScriptGlobals))
.VerifyEmitDiagnostics();
}
[Fact]
public void CanAccessPreviousSubmissionVariablesFromInsideMethod()
{
var previous = CreateSubmission("int previousSubmissionVariable = 42;")
.VerifyEmitDiagnostics();
var source = @"
void Method()
{
LocalFunction();
void LocalFunction()
{
_ = previousSubmissionVariable;
}
}";
CreateSubmission(source, previous: previous)
.VerifyEmitDiagnostics();
}
[Fact]
public void CanAccessPreviousSubmissionVariablesFromInsideLambda()
{
var previous = CreateSubmission("int previousSubmissionVariable = 42;")
.VerifyEmitDiagnostics();
var source = @"
var lambda = new System.Action(() =>
{
LocalFunction();
void LocalFunction()
{
_ = previousSubmissionVariable;
}
});";
CreateSubmission(source, previous: previous)
.VerifyEmitDiagnostics();
}
[Fact]
public void CanAccessPreviousSubmissionMethodsFromInsideMethod()
{
var previous = CreateSubmission("void PreviousSubmissionMethod() { }")
.VerifyEmitDiagnostics();
var source = @"
void Method()
{
LocalFunction();
void LocalFunction()
{
PreviousSubmissionMethod();
}
}";
CreateSubmission(source, previous: previous)
.VerifyEmitDiagnostics();
}
[Fact]
public void CanAccessPreviousSubmissionMethodsFromInsideLambda()
{
var previous = CreateSubmission("void PreviousSubmissionMethod() { }")
.VerifyEmitDiagnostics();
var source = @"
var lambda = new System.Action(() =>
{
LocalFunction();
void LocalFunction()
{
PreviousSubmissionMethod();
}
});";
CreateSubmission(source, previous: previous)
.VerifyEmitDiagnostics();
}
[Fact]
public void ShadowNames_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
class Program
{
static void M()
{
void F1(object x) { string x = null; } // local
void F2(object x, string y, int x) { } // parameter
void F3(object x) { void x() { } } // method
void F4<x, y>(object x) { void y() { } } // type parameter
void F5(object M, string Program) { }
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
verifyDiagnostics();
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
verifyDiagnostics();
comp = CreateCompilation(source);
verifyDiagnostics();
void verifyDiagnostics()
{
comp.VerifyDiagnostics(
// (7,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1(object x) { string x = null; } // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(7, 36),
// (8,41): error CS0100: The parameter name 'x' is a duplicate
// void F2(object x, string y, int x) { } // parameter
Diagnostic(ErrorCode.ERR_DuplicateParamName, "x").WithArguments("x").WithLocation(8, 41),
// (9,34): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F3(object x) { void x() { } } // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 34),
// (10,30): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void F4<x, y>(object x) { void y() { } } // type parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 30),
// (10,40): error CS0412: 'y': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void F4<x, y>(object x) { void y() { } } // type parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "y").WithArguments("y").WithLocation(10, 40));
}
}
[Fact]
public void ShadowNames_Local_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M()
{
object x = null;
void F1() { object x = 0; } // local
void F2(string x) { } // parameter
void F3() { void x() { } } // method
void F4<x>() { } // type parameter
void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1() { object x = 0; } // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 28),
// (10,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F2(string x) { } // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 24),
// (11,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F3() { void x() { } } // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 26),
// (12,17): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F4<x>() { } // type parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 17),
// (13,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 30));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Local_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M()
{
void F1() { object x = 0; } // local
void F2(string x) { } // parameter
void F3() { void x() { } } // method
void F4<x>() { } // type parameter
void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
object x = null;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1() { object x = 0; } // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 28),
// (9,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F2(string x) { } // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 24),
// (10,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F3() { void x() { } } // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 26),
// (11,17): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F4<x>() { } // type parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 17),
// (12,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 30));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Local_03()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M()
{
static void F1() { object x = 0; } // local
static void F2(string x) { } // parameter
static void F3() { void x() { } } // method
static void F4<x>() { } // type parameter
static void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
object x = null;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Parameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M(object x)
{
void F1() { object x = 0; } // local
void F2(string x) { } // parameter
void F3() { void x() { } } // method
void F4<x>() { } // type parameter
void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
// The conflict between the type parameter in F4<x>() and the parameter
// in M(object x) is not reported, for backwards compatibility.
comp.VerifyDiagnostics(
// (8,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1() { object x = 0; } // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 28),
// (9,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F2(string x) { } // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 24),
// (10,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F3() { void x() { } } // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 26),
// (12,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 30));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_TypeParameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M<x>()
{
void F1() { object x = 0; } // local
void F2(string x) { } // parameter
void F3() { void x() { } } // method
void F4<x>() { } // type parameter
void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,28): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void F1() { object x = 0; } // local
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(8, 28),
// (9,24): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void F2(string x) { } // parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 24),
// (10,26): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void F3() { void x() { } } // method
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 26),
// (11,17): warning CS8387: Type parameter 'x' has the same name as the type parameter from outer method 'Program.M<x>()'
// void F4<x>() { } // type parameter
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "x").WithArguments("x", "Program.M<x>()").WithLocation(11, 17),
// (12,30): error CS1948: The range variable 'x' cannot have the same name as a method type parameter
// void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(12, 30));
comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,17): warning CS8387: Type parameter 'x' has the same name as the type parameter from outer method 'Program.M<x>()'
// void F4<x>() { } // type parameter
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "x").WithArguments("x", "Program.M<x>()").WithLocation(11, 17));
}
[Fact]
public void ShadowNames_LocalFunction_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M()
{
void x() { }
void F1() { object x = 0; } // local
void F2(string x) { } // parameter
void F3() { void x() { } } // method
void F4<x>() { } // type parameter
void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1() { object x = 0; } // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 28),
// (10,24): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F2(string x) { } // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 24),
// (11,26): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F3() { void x() { } } // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 26),
// (12,17): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F4<x>() { } // type parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 17),
// (13,30): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// void F5() { _ = from x in new[] { 1, 2, 3 } select x; } // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 30));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LocalFunction_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
class Program
{
static void M1()
{
void M1() { }
}
static void M2(object x)
{
void x() { }
}
static void M3()
{
object x = null;
void x() { }
}
static void M4<T>()
{
void T() { }
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
verifyDiagnostics();
comp = CreateCompilation(source);
verifyDiagnostics();
void verifyDiagnostics()
{
comp.VerifyDiagnostics(
// (11,14): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void x() { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 14),
// (16,14): error CS0128: A local variable or function named 'x' is already defined in this scope
// void x() { }
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(16, 14),
// (20,14): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void T() { }
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(20, 14));
}
}
[Fact]
public void ShadowNames_ThisLocalFunction()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System.Linq;
class Program
{
static void M()
{
void F1() { object F1 = 0; } // local
void F2(string F2) { } // parameter
void F3() { void F3() { } } // method
void F4<F4>() { } // type parameter
void F5() { _ = from F5 in new[] { 1, 2, 3 } select F5; } // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,28): error CS0136: A local or parameter named 'F1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1() { object F1 = 0; } // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F1").WithArguments("F1").WithLocation(8, 28),
// (9,24): error CS0136: A local or parameter named 'F2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F2(string F2) { } // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F2").WithArguments("F2").WithLocation(9, 24),
// (10,26): error CS0136: A local or parameter named 'F3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F3() { void F3() { } } // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F3").WithArguments("F3").WithLocation(10, 26),
// (11,17): error CS0136: A local or parameter named 'F4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F4<F4>() { } // type parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "F4").WithArguments("F4").WithLocation(11, 17),
// (12,30): error CS1931: The range variable 'F5' conflicts with a previous declaration of 'F5'
// void F5() { _ = from F5 in new[] { 1, 2, 3 } select F5; } // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "F5").WithArguments("F5").WithLocation(12, 30));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LocalFunctionInsideLocalFunction_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
class Program
{
static void M<T>(object x)
{
void F()
{
void G1(int x) { }
void G2() { int T = 0; }
void G3<T>() { }
}
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,25): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void G1(int x) { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 25),
// (10,29): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// void G2() { int T = 0; }
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(10, 29),
// (11,21): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Program.M<T>(object)'
// void G3<T>() { }
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Program.M<T>(object)").WithLocation(11, 21));
comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,21): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Program.M<T>(object)'
// void G3<T>() { }
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Program.M<T>(object)").WithLocation(11, 21));
}
[Fact]
public void ShadowNames_LocalFunctionInsideLocalFunction_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
class Program
{
static void M<T>(object x)
{
static void F1()
{
void G1(int x) { }
}
void F2()
{
static void G2() { int T = 0; }
}
static void F3()
{
static void G3<T>() { }
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (17,28): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'Program.M<T>(object)'
// static void G3<T>() { }
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "Program.M<T>(object)").WithLocation(17, 28));
}
[Fact]
public void ShadowNames_LocalFunctionInsideLambda_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
Action a1 = () =>
{
int x = 0;
void F1() { object x = null; }
};
Action a2 = () =>
{
int T = 0;
void F2<T>() { }
};
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (11,32): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1() { object x = null; }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 32),
// (16,21): error CS0136: A local or parameter named 'T' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F2<T>() { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "T").WithArguments("T").WithLocation(16, 21));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LocalFunctionInsideLambda_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
Action<int> a1 = x =>
{
void F1(object x) { }
};
Action<int> a2 = (int T) =>
{
void F2<T>() { }
};
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
// The conflict between the type parameter in F2<T>() and the parameter
// in a2 is not reported, for backwards compatibility.
comp.VerifyDiagnostics(
// (10,28): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// void F1(object x) { }
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 28));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LocalFunctionInsideLambda_03()
{
var source =
@"using System;
class Program
{
static void M()
{
Action<int> a = x =>
{
void x() { }
x();
};
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
// The conflict between the local function and the parameter is not reported,
// for backwards compatibility.
comp.VerifyDiagnostics();
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void StaticWithThisReference()
{
var source =
@"#pragma warning disable 8321
class C
{
void M()
{
static object F1() => this.GetHashCode();
static object F2() => base.GetHashCode();
static void F3()
{
object G3() => ToString();
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,31): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// static object F1() => this.GetHashCode();
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(6, 31),
// (7,31): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// static object F2() => base.GetHashCode();
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(7, 31),
// (10,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// object G3() => ToString();
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "ToString").WithLocation(10, 28));
}
[Fact]
public void StaticWithVariableReference()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M(object x)
{
object y = null;
static object F1() => x;
static object F2() => y;
static void F3()
{
object G3() => x;
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,31): error CS8421: A static local function cannot contain a reference to 'x'.
// static object F1() => x;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(7, 31),
// (8,31): error CS8421: A static local function cannot contain a reference to 'y'.
// static object F2() => y;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "y").WithArguments("y").WithLocation(8, 31),
// (11,28): error CS8421: A static local function cannot contain a reference to 'x'.
// object G3() => x;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(11, 28));
}
[Fact]
public void StaticWithLocalFunctionVariableReference_01()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M()
{
static void F(object x)
{
object y = null;
object G1() => x ?? y;
static object G2() => x ?? y;
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (10,35): error CS8421: A static local function cannot contain a reference to 'x'.
// static object G2() => x ?? y;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(10, 35),
// (10,40): error CS8421: A static local function cannot contain a reference to 'y'.
// static object G2() => x ?? y;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "y").WithArguments("y").WithLocation(10, 40));
}
[Fact]
public void StaticWithLocalFunctionVariableReference_02()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M(int x)
{
static void F1(int y)
{
int F2() => x + y;
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,25): error CS8421: A static local function cannot contain a reference to 'x'.
// int F2() => x + y;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(8, 25));
}
/// <summary>
/// Can reference type parameters from enclosing scope.
/// </summary>
[Fact]
public void StaticWithTypeParameterReferences()
{
var source =
@"using static System.Console;
class A<T>
{
internal string F1()
{
static string L1() => typeof(T).FullName;
return L1();
}
}
class B
{
internal string F2<T>()
{
static string L2() => typeof(T).FullName;
return L2();
}
internal static string F3()
{
static string L3<T>()
{
static string L4() => typeof(T).FullName;
return L4();
}
return L3<byte>();
}
}
class Program
{
static void Main()
{
WriteLine(new A<int>().F1());
WriteLine(new B().F2<string>());
WriteLine(B.F3());
}
}";
CompileAndVerify(source, expectedOutput:
@"System.Int32
System.String
System.Byte");
}
[Fact]
public void Conditional_ThisReferenceInStatic()
{
var source =
@"#pragma warning disable 0649
#pragma warning disable 8321
using System.Diagnostics;
class A
{
internal object _f;
}
class B : A
{
[Conditional(""MyDefine"")]
static void F(object o)
{
}
void M()
{
static void F1() { F(this); }
static void F2() { F(base._f); }
static void F3() { F(_f); }
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithPreprocessorSymbols("MyDefine"));
verifyDiagnostics();
comp = CreateCompilation(source, parseOptions: TestOptions.Regular);
verifyDiagnostics();
void verifyDiagnostics()
{
comp.VerifyDiagnostics(
// (16,30): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// static void F1() { F(this); }
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(16, 30),
// (17,30): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// static void F2() { F(base._f); }
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(17, 30),
// (18,30): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// static void F3() { F(_f); }
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "_f").WithLocation(18, 30));
}
}
[Fact]
public void LocalFunctionConditional_Errors()
{
var source = @"
using System.Diagnostics;
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[Conditional(""DEBUG"")] // 1
int local1() => 42;
[Conditional(""DEBUG"")] // 2
void local2(out int i) { i = 42; }
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,10): error CS0578: The Conditional attribute is not valid on 'local1()' because its return type is not void
// [Conditional("DEBUG")] // 1
Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"Conditional(""DEBUG"")").WithArguments("local1()").WithLocation(10, 10),
// (13,10): error CS0685: Conditional member 'local2(out int)' cannot have an out parameter
// [Conditional("DEBUG")] // 2
Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""DEBUG"")").WithArguments("local2(out int)").WithLocation(13, 10));
}
[Fact]
public void LocalFunctionObsolete()
{
var source = @"
using System;
class C
{
void M1()
{
local1(); // 1
local2(); // 2
[Obsolete]
void local1() { }
[Obsolete(""hello"", true)]
void local2() { }
#pragma warning disable 8321 // Unreferenced local function
[Obsolete]
void local3()
{
// no diagnostics expected when calling an Obsolete method within an Obsolete method
local1();
local2();
}
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (8,9): warning CS0612: 'local1()' is obsolete
// local1(); // 1
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "local1()").WithArguments("local1()").WithLocation(8, 9),
// (9,9): error CS0619: 'local2()' is obsolete: 'hello'
// local2(); // 2
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "local2()").WithArguments("local2()", "hello").WithLocation(9, 9));
}
[Fact]
public void LocalFunction_AttributeMarkedObsolete()
{
var source = @"
using System;
[Obsolete]
class Attr : Attribute { }
class C
{
void M1()
{
#pragma warning disable 8321
[Attr] void local1() { } // 1
[return: Attr] void local2() { } // 2
void local3([Attr] int i) { } // 3
void local4<[Attr] T>(T t) { } // 4
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (12,10): warning CS0612: 'Attr' is obsolete
// [Attr] void local1() { } // 1
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(12, 10),
// (13,18): warning CS0612: 'Attr' is obsolete
// [return: Attr] void local2() { } // 2
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(13, 18),
// (14,22): warning CS0612: 'Attr' is obsolete
// void local3([Attr] int i) { } // 3
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(14, 22),
// (15,22): warning CS0612: 'Attr' is obsolete
// void local4<[Attr] T>(T t) { } // 4
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Attr").WithArguments("Attr").WithLocation(15, 22));
}
[Fact]
public void LocalFunction_NotNullIfNotNullAttribute()
{
var source = @"
using System.Diagnostics.CodeAnalysis;
#nullable enable
class C
{
void M()
{
_ = local1(null).ToString(); // 1
_ = local1(""hello"").ToString();
[return: NotNullIfNotNull(""s1"")]
string? local1(string? s1) => s1;
}
}
";
var comp = CreateCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,13): warning CS8602: Dereference of a possibly null reference.
// _ = local1(null).ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "local1(null)").WithLocation(10, 13));
}
[Fact]
public void LocalFunction_MaybeNullWhenAttribute()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M()
{
_ = tryGetValue(true, out var s)
? s.ToString()
: s.ToString(); // 1
bool tryGetValue(bool b, [MaybeNullWhen(false)] out string s1)
{
s1 = b ? ""abc"" : null;
return b;
}
}
}
";
var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (12,15): warning CS8602: Dereference of a possibly null reference.
// : s.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 15));
}
[Fact]
public void LocalFunction_MaybeNullWhenAttribute_CheckUsage()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M()
{
var s = ""abc"";
local1();
tryGetValue(""a"", out s);
local1();
void local1()
{
_ = s.ToString(); // 1
}
bool tryGetValue(string key, [MaybeNullWhen(false)] out string s1)
{
s1 = key;
return true;
}
}
}
";
var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (18,17): warning CS8602: Dereference of a possibly null reference.
// _ = s.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17));
}
[Fact]
public void LocalFunction_AllowNullAttribute()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M<T>([AllowNull] T t1, T t2)
{
local1(t1);
local1(t2);
local2(t1); // 1
local2(t2);
void local1([AllowNull] T t) { }
void local2(T t) { }
}
}
";
var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (13,16): warning CS8604: Possible null reference argument for parameter 't' in 'void local2(T t)'.
// local2(t1); // 1
Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t1").WithArguments("t", "void local2(T t)").WithLocation(13, 16));
}
[Fact]
public void LocalFunction_MaybeNullAttribute()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M<TOuter>()
{
getDefault<string>().ToString(); // 1
getDefault<string?>().ToString(); // 2
getDefault<int>().ToString();
getDefault<int?>().Value.ToString(); // 3
getDefault<TOuter>().ToString(); // 4
[return: MaybeNull] T getDefault<T>() => default(T);
}
}
";
var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (10,9): warning CS8602: Dereference of a possibly null reference.
// getDefault<string>().ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "getDefault<string>()").WithLocation(10, 9),
// (11,9): warning CS8602: Dereference of a possibly null reference.
// getDefault<string?>().ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "getDefault<string?>()").WithLocation(11, 9),
// (13,9): warning CS8629: Nullable value type may be null.
// getDefault<int?>().Value.ToString(); // 3
Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "getDefault<int?>()").WithLocation(13, 9),
// (14,9): warning CS8602: Dereference of a possibly null reference.
// getDefault<TOuter>().ToString(); // 4
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "getDefault<TOuter>()").WithLocation(14, 9));
}
[Fact]
public void LocalFunction_Nullable_CheckUsage_DoesNotUsePostconditions()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M()
{
var s0 = ""hello"";
local1(out s0);
bool local1([MaybeNullWhen(false)] out string s1)
{
s0.ToString();
s1 = ""world"";
return true;
}
}
}
";
var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void LocalFunction_DoesNotReturn()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M(string? s)
{
local1();
s.ToString();
[DoesNotReturn]
void local1()
{
throw null!;
}
}
}
";
var comp = CreateCompilation(new[] { DoesNotReturnAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void LocalFunction_DoesNotReturnIf()
{
var source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
class C
{
void M(string? s1, string? s2)
{
local1(s1 != null);
s1.ToString();
local1(false);
s2.ToString();
void local1([DoesNotReturnIf(false)] bool b)
{
throw null!;
}
}
}
";
var comp = CreateCompilation(new[] { DoesNotReturnIfAttributeDefinition, source }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
public void NameOf_ThisReferenceInStatic()
{
var source =
@"#pragma warning disable 8321
class C
{
void M()
{
static object F1() => nameof(this.ToString);
static object F2() => nameof(base.GetHashCode);
static object F3() => nameof(M);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void NameOf_InstanceMemberInStatic()
{
var source =
@"#pragma warning disable 0649
#pragma warning disable 8321
class C
{
object _f;
static void M()
{
_ = nameof(_f);
static object F() => nameof(_f);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = GetNameOfExpressions(tree)[1];
var symbol = model.GetSymbolInfo(expr).Symbol;
Assert.Equal("System.Object C._f", symbol.ToTestDisplayString());
}
[Fact]
public void NameOf_CapturedVariableInStatic()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M(object x)
{
static object F() => nameof(x);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = GetNameOfExpressions(tree)[0];
var symbol = model.GetSymbolInfo(expr).Symbol;
Assert.Equal("System.Object x", symbol.ToTestDisplayString());
}
/// <summary>
/// nameof(x) should bind to shadowing symbol.
/// </summary>
[Fact]
public void NameOf_ShadowedVariable()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M(object x)
{
object F()
{
int x = 0;
return nameof(x);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = GetNameOfExpressions(tree)[0];
var symbol = model.GetSymbolInfo(expr).Symbol;
Assert.Equal(SymbolKind.Local, symbol.Kind);
Assert.Equal("System.Int32 x", symbol.ToTestDisplayString());
}
/// <summary>
/// nameof(T) should bind to shadowing symbol.
/// </summary>
[Fact]
public void NameOf_ShadowedTypeParameter()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M<T>()
{
object F1()
{
int T = 0;
return nameof(T);
}
object F2<T>()
{
return nameof(T);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,19): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M<T>()'
// object F2<T>()
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M<T>()").WithLocation(11, 19));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = GetNameOfExpressions(tree);
var symbol = model.GetSymbolInfo(exprs[0]).Symbol;
Assert.Equal(SymbolKind.Local, symbol.Kind);
Assert.Equal("System.Int32 T", symbol.ToTestDisplayString());
symbol = model.GetSymbolInfo(exprs[1]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("System.Object F2<T>()", symbol.ContainingSymbol.ToTestDisplayString());
}
/// <summary>
/// typeof(T) should bind to nearest type.
/// </summary>
[Fact]
public void TypeOf_ShadowedTypeParameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
class C
{
static void M<T>()
{
object F1()
{
int T = 0;
return typeof(T);
}
object F2<T>()
{
return typeof(T);
}
object F3<U>()
{
return typeof(U);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (12,19): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M<T>()'
// object F2<T>()
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M<T>()").WithLocation(12, 19));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<TypeOfExpressionSyntax>().Select(n => n.Type).ToImmutableArray();
var symbol = model.GetSymbolInfo(exprs[0]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("void C.M<T>()", symbol.ContainingSymbol.ToTestDisplayString());
symbol = model.GetSymbolInfo(exprs[1]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("System.Object F2<T>()", symbol.ContainingSymbol.ToTestDisplayString());
symbol = model.GetSymbolInfo(exprs[2]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("System.Object F3<U>()", symbol.ContainingSymbol.ToTestDisplayString());
}
/// <summary>
/// sizeof(T) should bind to nearest type.
/// </summary>
[Fact]
public void SizeOf_ShadowedTypeParameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
unsafe class C
{
static void M<T>() where T : unmanaged
{
object F1()
{
int T = 0;
return sizeof(T);
}
object F2<T>() where T : unmanaged
{
return sizeof(T);
}
object F3<U>() where U : unmanaged
{
return sizeof(U);
}
}
}";
var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (12,19): warning CS8387: Type parameter 'T' has the same name as the type parameter from outer method 'C.M<T>()'
// object F2<T>()
Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter, "T").WithArguments("T", "C.M<T>()").WithLocation(12, 19));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<SizeOfExpressionSyntax>().Select(n => n.Type).ToImmutableArray();
var symbol = model.GetSymbolInfo(exprs[0]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("void C.M<T>()", symbol.ContainingSymbol.ToTestDisplayString());
symbol = model.GetSymbolInfo(exprs[1]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("System.Object F2<T>()", symbol.ContainingSymbol.ToTestDisplayString());
symbol = model.GetSymbolInfo(exprs[2]).Symbol;
Assert.Equal(SymbolKind.TypeParameter, symbol.Kind);
Assert.Equal("System.Object F3<U>()", symbol.ContainingSymbol.ToTestDisplayString());
}
private static ImmutableArray<ExpressionSyntax> GetNameOfExpressions(SyntaxTree tree)
{
return tree.GetRoot().DescendantNodes().
OfType<InvocationExpressionSyntax>().
Where(n => n.Expression.ToString() == "nameof").
Select(n => n.ArgumentList.Arguments[0].Expression).
ToImmutableArray();
}
[Fact]
public void ShadowWithSelfReferencingLocal()
{
var source =
@"using System;
class Program
{
static void Main()
{
int x = 13;
void Local()
{
int x = (x = 0) + 42;
Console.WriteLine(x);
}
Local();
Console.WriteLine(x);
}
}";
CompileAndVerify(source, expectedOutput:
@"42
13");
}
[Fact, WorkItem(38129, "https://github.com/dotnet/roslyn/issues/38129")]
public void StaticLocalFunctionLocalFunctionReference_01()
{
var source =
@"#pragma warning disable 8321
class C
{
static void M()
{
void F1() {}
static void F2() {}
static void F3()
{
F1();
F2();
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,13): error CS8421: A static local function cannot contain a reference to 'F1'.
// F1();
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "F1()").WithArguments("F1").WithLocation(11, 13));
}
[Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")]
public void StaticLocalFunctionLocalFunctionReference_02()
{
var source =
@"#pragma warning disable 8321
class Program
{
static void Method()
{
void Local<T>() {}
static void StaticLocal()
{
Local<int>();
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,13): error CS8421: A static local function cannot contain a reference to 'Local'.
// Local<int>();
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>()").WithArguments("Local").WithLocation(9, 13));
}
[Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")]
public void StaticLocalFunctionLocalFunctionReference_03()
{
var source =
@"using System;
class Program
{
static void Method()
{
int i = 0;
void Local<T>()
{
i = 0;
}
Action a = () => i++;
static void StaticLocal()
{
Local<int>();
}
StaticLocal();
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (14,13): error CS8421: A static local function cannot contain a reference to 'Local'.
// Local<int>();
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>()").WithArguments("Local").WithLocation(14, 13));
}
[Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")]
public void StaticLocalFunctionLocalFunctionDelegateReference_01()
{
var source =
@"#pragma warning disable 8321
using System;
class C
{
static void M()
{
void F1() {}
static void F2()
{
Action a = F1;
_ = new Action(F1);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,24): error CS8421: A static local function cannot contain a reference to 'F1'.
// Action a = F1;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "F1").WithArguments("F1").WithLocation(11, 24),
// (12,28): error CS8421: A static local function cannot contain a reference to 'F1'.
// _ = new Action(F1);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "F1").WithArguments("F1").WithLocation(12, 28));
}
[Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")]
public void StaticLocalFunctionLocalFunctionDelegateReference_02()
{
var source =
@"#pragma warning disable 8321
using System;
class Program
{
static void Method()
{
void Local<T>() {}
static void StaticLocal()
{
Action a;
a = Local<int>;
a = new Action(Local<string>);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,17): error CS8421: A static local function cannot contain a reference to 'Local'.
// a = Local<int>;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>").WithArguments("Local").WithLocation(11, 17),
// (12,28): error CS8421: A static local function cannot contain a reference to 'Local'.
// a = new Action(Local<string>);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<string>").WithArguments("Local").WithLocation(12, 28));
}
[Fact, WorkItem(39706, "https://github.com/dotnet/roslyn/issues/39706")]
public void StaticLocalFunctionLocalFunctionDelegateReference_03()
{
var source =
@"using System;
class Program
{
static void Method()
{
int i = 0;
void Local<T>()
{
i = 0;
}
Action a = () => i++;
a = StaticLocal();
static Action StaticLocal()
{
return Local<int>;
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (15,20): error CS8421: A static local function cannot contain a reference to 'Local'.
// return Local<int>;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "Local<int>").WithArguments("Local").WithLocation(15, 20));
}
[Fact]
public void StaticLocalFunctionGenericStaticLocalFunction()
{
var source =
@"using System;
class Program
{
static void Main()
{
static void F1<T>()
{
Console.WriteLine(typeof(T));
}
static void F2()
{
F1<int>();
Action a = F1<string>;
a();
}
F2();
}
}";
CompileAndVerify(source, expectedOutput:
@"System.Int32
System.String");
}
[Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")]
public void StaticLocalFunctionStaticFunctionsDelegateReference()
{
var source =
@"#pragma warning disable 8321
using System;
class C
{
static void M()
{
static void F1() {}
static void F2()
{
Action m = M;
Action f1 = F1;
_ = new Action(M);
_ = new Action(F1);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")]
public void StaticLocalFunctionThisAndBaseDelegateReference()
{
var source =
@"#pragma warning disable 8321
using System;
class B
{
public virtual void M() {}
}
class C : B
{
public override void M()
{
static void F()
{
Action a1 = base.M;
Action a2 = this.M;
Action a3 = M;
_ = new Action(base.M);
_ = new Action(this.M);
_ = new Action(M);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (14,25): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// Action a1 = base.M;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(14, 25),
// (15,25): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// Action a2 = this.M;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(15, 25),
// (16,25): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// Action a3 = M;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "M").WithLocation(16, 25),
// (17,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// _ = new Action(base.M);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(17, 28),
// (18,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// _ = new Action(this.M);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(18, 28),
// (19,28): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// _ = new Action(M);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "M").WithLocation(19, 28));
}
[Fact, WorkItem(38240, "https://github.com/dotnet/roslyn/issues/38240")]
public void StaticLocalFunctionDelegateReferenceWithReceiver()
{
var source =
@"#pragma warning disable 649
#pragma warning disable 8321
using System;
class C
{
object f;
void M()
{
object l;
static void F1()
{
_ = new Func<int>(f.GetHashCode);
_ = new Func<int>(l.GetHashCode);
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (14,31): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// _ = new Func<int>(f.GetHashCode);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "f").WithLocation(14, 31),
// (15,31): error CS8421: A static local function cannot contain a reference to 'l'.
// _ = new Func<int>(l.GetHashCode);
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "l").WithArguments("l").WithLocation(15, 31));
}
[Fact]
[WorkItem(38143, "https://github.com/dotnet/roslyn/issues/38143")]
public void EmittedAsStatic_01()
{
var source =
@"class Program
{
static void M()
{
static void local() { }
System.Action action = local;
}
}";
CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: m =>
{
var method = (MethodSymbol)m.GlobalNamespace.GetMember("Program.<M>g__local|0_0");
Assert.True(method.IsStatic);
});
}
[Fact]
[WorkItem(38143, "https://github.com/dotnet/roslyn/issues/38143")]
public void EmittedAsStatic_02()
{
var source =
@"class Program
{
static void M<T>()
{
static void local(T t) { System.Console.Write(t.GetType().FullName); }
System.Action<T> action = local;
action(default(T));
}
static void Main()
{
M<int>();
}
}";
CompileAndVerify(source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "System.Int32", symbolValidator: m =>
{
var method = (MethodSymbol)m.GlobalNamespace.GetMember("Program.<M>g__local|0_0");
Assert.True(method.IsStatic);
Assert.True(method.IsGenericMethod);
Assert.Equal("void Program.<M>g__local|0_0<T>(T t)", method.ToTestDisplayString());
});
}
/// <summary>
/// Local function in generic method is emitted as a generic
/// method even if no references to type parameters.
/// </summary>
[Fact]
[WorkItem(38143, "https://github.com/dotnet/roslyn/issues/38143")]
public void EmittedAsStatic_03()
{
var source =
@"class Program
{
static void M<T>() where T : new()
{
static void local(object o) { System.Console.Write(o.GetType().FullName); }
local(new T());
}
static void Main()
{
M<int>();
}
}";
CompileAndVerify(source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), expectedOutput: "System.Int32", symbolValidator: m =>
{
var method = (MethodSymbol)m.GlobalNamespace.GetMember("Program.<M>g__local|0_0");
Assert.True(method.IsStatic);
Assert.True(method.IsGenericMethod);
Assert.Equal("void Program.<M>g__local|0_0<T>(System.Object o)", method.ToTestDisplayString());
});
}
/// <summary>
/// Emit 'call' rather than 'callvirt' for local functions regardless of whether
/// the local function is static.
/// </summary>
[Fact]
public void EmitCallInstruction()
{
var source =
@"using static System.Console;
class Program
{
static void Main()
{
int i;
void L1() => WriteLine(i++);
static void L2(int i) => WriteLine(i);
i = 1;
L1();
L2(i);
}
}";
var verifier = CompileAndVerify(source, expectedOutput:
@"1
2");
verifier.VerifyIL("Program.Main",
@"{
// Code size 27 (0x1b)
.maxstack 2
.locals init (Program.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: stfld ""int Program.<>c__DisplayClass0_0.i""
IL_0008: ldloca.s V_0
IL_000a: call ""void Program.<Main>g__L1|0_0(ref Program.<>c__DisplayClass0_0)""
IL_000f: ldloc.0
IL_0010: ldfld ""int Program.<>c__DisplayClass0_0.i""
IL_0015: call ""void Program.<Main>g__L2|0_1(int)""
IL_001a: ret
}");
}
/// <summary>
/// '_' should bind to '_' symbol in outer scope even in static local function.
/// </summary>
[Fact]
public void UnderscoreInOuterScope()
{
var source =
@"#pragma warning disable 8321
class C1
{
object _;
void F1()
{
void A1(object x) => _ = x;
static void B1(object y) => _ = y;
}
}
class C2
{
static void F2()
{
object _;
void A2(object x) => _ = x;
static void B2(object y) => _ = y;
}
static void F3()
{
void A3(object x) => _ = x;
static void B3(object y) => _ = y;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,37): error CS8422: A static local function cannot contain a reference to 'this' or 'base'.
// static void B1(object y) => _ = y;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "_").WithLocation(8, 37),
// (17,37): error CS8421: A static local function cannot contain a reference to '_'.
// static void B2(object y) => _ = y;
Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "_").WithArguments("_").WithLocation(17, 37));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>();
var actualSymbols = nodes.Select(n => model.GetSymbolInfo(n.Left).Symbol).Select(s => $"{s.Kind}: {s.ToTestDisplayString()}").ToArray();
var expectedSymbols = new[]
{
"Field: System.Object C1._",
"Field: System.Object C1._",
"Local: System.Object _",
"Local: System.Object _",
"Discard: System.Object _",
"Discard: System.Object _",
};
AssertEx.Equal(expectedSymbols, actualSymbols);
}
/// <summary>
/// 'var' should bind to 'var' symbol in outer scope even in static local function.
/// </summary>
[Fact]
public void VarInOuterScope()
{
var source =
@"#pragma warning disable 8321
class C1
{
class var { }
static void F1()
{
void A1(object x) { var y = x; }
static void B1(object x) { var y = x; }
}
}
namespace N
{
using var = System.String;
class C2
{
static void F2()
{
void A2(object x) { var y = x; }
static void B3(object x) { var y = x; }
}
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,37): error CS0266: Cannot implicitly convert type 'object' to 'C1.var'. An explicit conversion exists (are you missing a cast?)
// void A1(object x) { var y = x; }
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "C1.var").WithLocation(7, 37),
// (8,44): error CS0266: Cannot implicitly convert type 'object' to 'C1.var'. An explicit conversion exists (are you missing a cast?)
// static void B1(object x) { var y = x; }
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "C1.var").WithLocation(8, 44),
// (18,41): error CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
// void A2(object x) { var y = x; }
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "string").WithLocation(18, 41),
// (19,48): error CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
// static void B3(object x) { var y = x; }
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "string").WithLocation(19, 48));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var nodes = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>();
var actualSymbols = nodes.Select(n => model.GetDeclaredSymbol(n)).ToTestDisplayStrings();
var expectedSymbols = new[]
{
"C1.var y",
"C1.var y",
"System.String y",
"System.String y",
};
AssertEx.Equal(expectedSymbols, actualSymbols);
}
[Fact]
public void AwaitWithinAsyncOuterScope_01()
{
var source =
@"#pragma warning disable 1998
#pragma warning disable 8321
using System.Threading.Tasks;
class Program
{
void F1()
{
void A1() { await Task.Yield(); }
static void B1() { await Task.Yield(); }
}
void F2()
{
async void A2() { await Task.Yield(); }
async static void B2() { await Task.Yield(); }
}
async void F3()
{
void A3() { await Task.Yield(); }
static void B3() { await Task.Yield(); }
}
async void F4()
{
async void A4() { await Task.Yield(); }
async static void B4() { await Task.Yield(); }
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,21): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// void A1() { await Task.Yield(); }
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(8, 21),
// (9,28): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// static void B1() { await Task.Yield(); }
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(9, 28),
// (18,21): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// void A3() { await Task.Yield(); }
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(18, 21),
// (19,28): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// static void B3() { await Task.Yield(); }
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Yield()").WithLocation(19, 28));
}
/// <summary>
/// 'await' should be a contextual keyword in the same way,
/// regardless of whether local function is static.
/// </summary>
[Fact]
public void AwaitWithinAsyncOuterScope_02()
{
var source =
@"#pragma warning disable 1998
#pragma warning disable 8321
class Program
{
void F1()
{
void A1<await>() { }
static void B1<await>() { }
}
void F2()
{
async void A2<await>() { }
async static void B2<await>() { }
}
async void F3()
{
void A3<await>() { }
static void B3<await>() { }
}
async void F4()
{
async void A4<await>() { }
async static void B4<await>() { }
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (12,23): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// async void A2<await>() { }
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(12, 23),
// (13,30): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// async static void B2<await>() { }
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(13, 30),
// (22,23): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// async void A4<await>() { }
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(22, 23),
// (23,30): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// async static void B4<await>() { }
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(23, 30));
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpRenameFileToMatchTypeRefactoring.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpRenameFileToMatchTypeRefactoring : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpRenameFileToMatchTypeRefactoring(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpGenerateFromUsage))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public void RenameFileToMatchType_ExistingCode()
{
var project = new ProjectUtils.Project(ProjectName);
SetUpEditor(@"class $$MismatchedClassName { }");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Rename file to MismatchedClassName.cs", applyFix: true);
// Ensure the file is still open in the editor, and that the file name change was made & saved
VisualStudio.Editor.Verify.TextContains("class MismatchedClassName { }");
VisualStudio.SolutionExplorer.Verify.FileContents(project, "MismatchedClassName.cs", @"class MismatchedClassName { }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public void RenameFileToMatchType_InSubfolder()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, @"folder1\folder2\test.cs", open: true);
SetUpEditor(@"class $$MismatchedClassName { }");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Rename file to MismatchedClassName.cs", applyFix: true);
// Ensure the file is still open in the editor, and that the file name change was made & saved
VisualStudio.Editor.Verify.TextContains("class MismatchedClassName { }");
VisualStudio.SolutionExplorer.Verify.FileContents(project, @"folder1\folder2\MismatchedClassName.cs", @"class MismatchedClassName { }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public void RenameFileToMatchType_UndoStackPreserved()
{
var project = new ProjectUtils.Project(ProjectName);
SetUpEditor(@"$$class MismatchedClassName { }");
VisualStudio.Editor.SendKeys("public ");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Rename file to MismatchedClassName.cs", applyFix: true);
// Ensure the file is still open in the editor, and that the file name change was made & saved
VisualStudio.Editor.Verify.CurrentLineText("public class MismatchedClassName { }");
VisualStudio.SolutionExplorer.Verify.FileContents(project, "MismatchedClassName.cs", @"public class MismatchedClassName { }");
// The first undo is for the file rename.
VisualStudio.Editor.Undo();
VisualStudio.Editor.Verify.CurrentLineText("public class MismatchedClassName { }");
VisualStudio.SolutionExplorer.Verify.FileContents(project, "Class1.cs", @"public class MismatchedClassName { }");
// The second undo is for the text changes.
VisualStudio.Editor.Undo();
VisualStudio.Editor.Verify.CurrentLineText("class MismatchedClassName { }");
// Redo the text changes
VisualStudio.Editor.Redo();
VisualStudio.Editor.Verify.CurrentLineText("public class MismatchedClassName { }");
// Redo the file rename
VisualStudio.Editor.Redo();
VisualStudio.SolutionExplorer.Verify.FileContents(project, "MismatchedClassName.cs", @"public class MismatchedClassName { }");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpRenameFileToMatchTypeRefactoring : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpRenameFileToMatchTypeRefactoring(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpGenerateFromUsage))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public void RenameFileToMatchType_ExistingCode()
{
var project = new ProjectUtils.Project(ProjectName);
SetUpEditor(@"class $$MismatchedClassName { }");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Rename file to MismatchedClassName.cs", applyFix: true);
// Ensure the file is still open in the editor, and that the file name change was made & saved
VisualStudio.Editor.Verify.TextContains("class MismatchedClassName { }");
VisualStudio.SolutionExplorer.Verify.FileContents(project, "MismatchedClassName.cs", @"class MismatchedClassName { }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public void RenameFileToMatchType_InSubfolder()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, @"folder1\folder2\test.cs", open: true);
SetUpEditor(@"class $$MismatchedClassName { }");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Rename file to MismatchedClassName.cs", applyFix: true);
// Ensure the file is still open in the editor, and that the file name change was made & saved
VisualStudio.Editor.Verify.TextContains("class MismatchedClassName { }");
VisualStudio.SolutionExplorer.Verify.FileContents(project, @"folder1\folder2\MismatchedClassName.cs", @"class MismatchedClassName { }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)]
public void RenameFileToMatchType_UndoStackPreserved()
{
var project = new ProjectUtils.Project(ProjectName);
SetUpEditor(@"$$class MismatchedClassName { }");
VisualStudio.Editor.SendKeys("public ");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Rename file to MismatchedClassName.cs", applyFix: true);
// Ensure the file is still open in the editor, and that the file name change was made & saved
VisualStudio.Editor.Verify.CurrentLineText("public class MismatchedClassName { }");
VisualStudio.SolutionExplorer.Verify.FileContents(project, "MismatchedClassName.cs", @"public class MismatchedClassName { }");
// The first undo is for the file rename.
VisualStudio.Editor.Undo();
VisualStudio.Editor.Verify.CurrentLineText("public class MismatchedClassName { }");
VisualStudio.SolutionExplorer.Verify.FileContents(project, "Class1.cs", @"public class MismatchedClassName { }");
// The second undo is for the text changes.
VisualStudio.Editor.Undo();
VisualStudio.Editor.Verify.CurrentLineText("class MismatchedClassName { }");
// Redo the text changes
VisualStudio.Editor.Redo();
VisualStudio.Editor.Verify.CurrentLineText("public class MismatchedClassName { }");
// Redo the file rename
VisualStudio.Editor.Redo();
VisualStudio.SolutionExplorer.Verify.FileContents(project, "MismatchedClassName.cs", @"public class MismatchedClassName { }");
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/Core/Implementation/Interactive/Completion/InteractiveCommandCompletionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Interactive;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Completion
{
[ExportLanguageServiceFactory(typeof(CompletionService), InteractiveLanguageNames.InteractiveCommand), Shared]
internal class InteractiveCommandCompletionServiceFactory : ILanguageServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InteractiveCommandCompletionServiceFactory()
{
}
public ILanguageService CreateLanguageService(HostLanguageServices languageServices)
=> new InteractiveCommandCompletionService(languageServices.WorkspaceServices.Workspace);
}
internal class InteractiveCommandCompletionService : CompletionServiceWithProviders
{
public InteractiveCommandCompletionService(Workspace workspace)
: base(workspace)
{
}
public override string Language
{
get { return InteractiveLanguageNames.InteractiveCommand; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Interactive;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Completion
{
[ExportLanguageServiceFactory(typeof(CompletionService), InteractiveLanguageNames.InteractiveCommand), Shared]
internal class InteractiveCommandCompletionServiceFactory : ILanguageServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public InteractiveCommandCompletionServiceFactory()
{
}
public ILanguageService CreateLanguageService(HostLanguageServices languageServices)
=> new InteractiveCommandCompletionService(languageServices.WorkspaceServices.Workspace);
}
internal class InteractiveCommandCompletionService : CompletionServiceWithProviders
{
public InteractiveCommandCompletionService(Workspace workspace)
: base(workspace)
{
}
public override string Language
{
get { return InteractiveLanguageNames.InteractiveCommand; }
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/CSharp/Impl/CodeModel/CSharpCodeModelService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders;
using Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.MethodXml;
using Microsoft.VisualStudio.LanguageServices.CSharp.Utilities;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel
{
internal partial class CSharpCodeModelService : AbstractCodeModelService
{
internal CSharpCodeModelService(
HostLanguageServices languageServiceProvider,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
IThreadingContext threadingContext)
: base(languageServiceProvider,
editorOptionsFactoryService,
refactorNotifyServices,
BlankLineInGeneratedMethodFormattingRule.Instance,
EndRegionFormattingRule.Instance,
threadingContext)
{
}
private static readonly SymbolDisplayFormat s_codeTypeRefAsFullNameFormat =
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.ExpandNullable);
private static readonly SymbolDisplayFormat s_codeTypeRefAsStringFormat =
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
private static readonly SymbolDisplayFormat s_externalNameFormat =
new(
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
parameterOptions: SymbolDisplayParameterOptions.IncludeName);
private static readonly SymbolDisplayFormat s_externalFullNameFormat =
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
parameterOptions: SymbolDisplayParameterOptions.IncludeName);
private static readonly SymbolDisplayFormat s_setTypeFormat =
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
private static bool IsNameableNode(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMemberDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.RecordStructDeclaration:
return true;
case SyntaxKind.VariableDeclarator:
// Could be a regular field or an event field.
return node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>() != null;
default:
return false;
}
}
public override EnvDTE.vsCMElement GetElementKind(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return EnvDTE.vsCMElement.vsCMElementClass;
default:
Debug.Fail("Unsupported element kind: " + node.Kind());
throw Exceptions.ThrowEInvalidArg();
}
}
public override bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope)
{
switch (node.Kind())
{
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementNamespace &&
node.Parent != null)
{
return true;
}
break;
case SyntaxKind.ClassDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementClass)
{
return true;
}
break;
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementFunction)
{
return true;
}
break;
case SyntaxKind.EnumMemberDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementVariable)
{
return true;
}
break;
case SyntaxKind.FieldDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementVariable)
{
return true;
}
break;
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementEvent)
{
return true;
}
break;
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementProperty)
{
return true;
}
break;
case SyntaxKind.Attribute:
if (scope == EnvDTE.vsCMElement.vsCMElementAttribute)
{
return true;
}
break;
case SyntaxKind.InterfaceDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementInterface)
{
return true;
}
break;
case SyntaxKind.DelegateDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementDelegate)
{
return true;
}
break;
case SyntaxKind.EnumDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementEnum)
{
return true;
}
break;
case SyntaxKind.StructDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementStruct)
{
return true;
}
break;
case SyntaxKind.UsingDirective:
if (scope == EnvDTE.vsCMElement.vsCMElementImportStmt &&
((UsingDirectiveSyntax)node).Name != null)
{
return true;
}
break;
case SyntaxKind.VariableDeclaration:
case SyntaxKind.VariableDeclarator:
// The parent of a VariableDeclarator might be an event or
// a field declaration. If the parent matches the desired
// scope, then this node matches the scope as well.
return MatchesScope(node.Parent, scope);
case SyntaxKind.Parameter:
if (scope == EnvDTE.vsCMElement.vsCMElementParameter)
{
return true;
}
break;
default:
return false;
}
return false;
}
public override IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent)
{
// Only VB has Option statements
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
public override IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent)
=> parent switch
{
CompilationUnitSyntax compilationUnit => compilationUnit.Usings,
BaseNamespaceDeclarationSyntax baseNamespace => baseNamespace.Usings,
_ => SpecializedCollections.EmptyEnumerable<SyntaxNode>(),
};
private static IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxList<AttributeListSyntax> attributeDeclarationList)
{
foreach (var attributeDeclaration in attributeDeclarationList)
{
foreach (var attribute in attributeDeclaration.Attributes)
{
yield return attribute;
}
}
}
public override IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent)
{
if (parent is CompilationUnitSyntax compilationUnit)
{
return GetAttributeNodes(compilationUnit.AttributeLists);
}
else if (parent is BaseTypeDeclarationSyntax baseType)
{
return GetAttributeNodes(baseType.AttributeLists);
}
else if (parent is BaseMethodDeclarationSyntax baseMethod)
{
return GetAttributeNodes(baseMethod.AttributeLists);
}
else if (parent is BasePropertyDeclarationSyntax baseProperty)
{
return GetAttributeNodes(baseProperty.AttributeLists);
}
else if (parent is BaseFieldDeclarationSyntax baseField)
{
return GetAttributeNodes(baseField.AttributeLists);
}
else if (parent is DelegateDeclarationSyntax delegateDecl)
{
return GetAttributeNodes(delegateDecl.AttributeLists);
}
else if (parent is EnumMemberDeclarationSyntax enumMember)
{
return GetAttributeNodes(enumMember.AttributeLists);
}
else if (parent is ParameterSyntax parameter)
{
return GetAttributeNodes(parameter.AttributeLists);
}
else if (parent is VariableDeclaratorSyntax ||
parent is VariableDeclarationSyntax)
{
return GetAttributeNodes(parent.Parent);
}
else if (parent is AccessorDeclarationSyntax accessor)
{
return GetAttributeNodes(accessor.AttributeLists);
}
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
public override IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent)
{
if (parent is AttributeSyntax attribute)
{
if (attribute.ArgumentList == null)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
return attribute.ArgumentList.Arguments;
}
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
public override IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent)
{
// Only VB has Inherits statements
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
public override IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent)
{
// Only VB has Implements statements
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
private static bool IsContainerNode(SyntaxNode container) =>
container is CompilationUnitSyntax ||
container is BaseNamespaceDeclarationSyntax ||
container is BaseTypeDeclarationSyntax;
private static bool IsNamespaceOrTypeDeclaration(SyntaxNode node) =>
node is BaseNamespaceDeclarationSyntax ||
node is BaseTypeDeclarationSyntax ||
node is DelegateDeclarationSyntax;
private static IEnumerable<MemberDeclarationSyntax> GetChildMemberNodes(SyntaxNode container)
{
if (container is CompilationUnitSyntax compilationUnit)
{
foreach (var member in compilationUnit.Members)
{
if (IsNamespaceOrTypeDeclaration(member))
{
yield return member;
}
}
}
else if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
{
foreach (var member in namespaceDecl.Members)
{
if (IsNamespaceOrTypeDeclaration(member))
{
yield return member;
}
}
}
else if (container is TypeDeclarationSyntax typeDecl)
{
foreach (var member in typeDecl.Members)
{
if (member.Kind() != SyntaxKind.NamespaceDeclaration)
{
yield return member;
}
}
}
else if (container is EnumDeclarationSyntax enumDecl)
{
foreach (var member in enumDecl.Members)
{
yield return member;
}
}
}
private static bool NodeIsSupported(bool test, SyntaxNode node)
=> !test || IsNameableNode(node);
/// <summary>
/// Retrieves the members of a specified <paramref name="container"/> node. The members that are
/// returned can be controlled by passing various parameters.
/// </summary>
/// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param>
/// <param name="includeSelf">If true, the container is returned as well.</param>
/// <param name="recursive">If true, members are recursed to return descendant members as well
/// as immediate children. For example, a namespace would return the namespaces and types within.
/// However, if <paramref name="recursive"/> is true, members with the namespaces and types would
/// also be returned.</param>
/// <param name="logicalFields">If true, field declarations are broken into their respective declarators.
/// For example, the field "int x, y" would return two declarators, one for x and one for y in place
/// of the field.</param>
/// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param>
public override IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes)
{
// Filter out all records from code model, they are not supported at all.
return GetMemberNodesWorker(container, includeSelf, recursive, logicalFields, onlySupportedNodes).Where(t => t is not RecordDeclarationSyntax);
}
private IEnumerable<SyntaxNode> GetMemberNodesWorker(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes)
{
if (!IsContainerNode(container))
{
yield break;
}
if (includeSelf && NodeIsSupported(onlySupportedNodes, container))
{
yield return container;
}
foreach (var member in GetChildMemberNodes(container))
{
if (member is BaseFieldDeclarationSyntax baseField)
{
// For fields, the 'logical' and 'supported' flags are intrinsically tied.
// * If 'logical' is true, only declarators should be returned, regardless of the value of 'supported'.
// * If 'logical' is false, the field should only be returned if 'supported' is also false.
if (logicalFields)
{
foreach (var declarator in baseField.Declaration.Variables)
{
// We know that variable declarators are supported, so there's no need to check them here.
yield return declarator;
}
}
else if (!onlySupportedNodes)
{
// Only return field declarations if the supported flag is false.
yield return member;
}
}
else if (NodeIsSupported(onlySupportedNodes, member))
{
yield return member;
}
if (recursive && IsContainerNode(member))
{
foreach (var innerMember in GetMemberNodes(member, includeSelf: false, recursive: true, logicalFields: logicalFields, onlySupportedNodes: onlySupportedNodes))
{
yield return innerMember;
}
}
}
}
public override string Language
{
get { return EnvDTE.CodeModelLanguageConstants.vsCMLanguageCSharp; }
}
public override string AssemblyAttributeString
{
get
{
return "assembly";
}
}
/// <summary>
/// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/>
/// </summary>
public override EnvDTE.CodeElement CreateInternalCodeElement(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNode node)
{
// Attributes, attribute arguments, parameters, imports directives, and
// accessor functions do not have their own node keys. Rather, they are
// based off their parents node keys and other data.
switch (node.Kind())
{
case SyntaxKind.Attribute:
return (EnvDTE.CodeElement)CreateInternalCodeAttribute(state, fileCodeModel, node);
case SyntaxKind.AttributeArgument:
return (EnvDTE.CodeElement)CreateInternalCodeAttributeArgument(state, fileCodeModel, (AttributeArgumentSyntax)node);
case SyntaxKind.Parameter:
return (EnvDTE.CodeElement)CreateInternalCodeParameter(state, fileCodeModel, (ParameterSyntax)node);
case SyntaxKind.UsingDirective:
return CreateInternalCodeImport(state, fileCodeModel, (UsingDirectiveSyntax)node);
}
if (IsAccessorNode(node))
{
return (EnvDTE.CodeElement)CreateInternalCodeAccessorFunction(state, fileCodeModel, node);
}
var nodeKey = GetNodeKey(node);
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return (EnvDTE.CodeElement)CodeClass.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.InterfaceDeclaration:
return (EnvDTE.CodeElement)CodeInterface.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.StructDeclaration:
return (EnvDTE.CodeElement)CodeStruct.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.EnumDeclaration:
return (EnvDTE.CodeElement)CodeEnum.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.EnumMemberDeclaration:
return (EnvDTE.CodeElement)CodeVariable.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.DelegateDeclaration:
return (EnvDTE.CodeElement)CodeDelegate.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
return (EnvDTE.CodeElement)CodeFunction.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return (EnvDTE.CodeElement)CodeNamespace.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
return (EnvDTE.CodeElement)CodeProperty.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.EventDeclaration:
return (EnvDTE.CodeElement)CodeEvent.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.VariableDeclarator:
var baseFieldDeclaration = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>();
if (baseFieldDeclaration != null)
{
if (baseFieldDeclaration.Kind() == SyntaxKind.FieldDeclaration)
{
return (EnvDTE.CodeElement)CodeVariable.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
}
else if (baseFieldDeclaration.Kind() == SyntaxKind.EventFieldDeclaration)
{
return (EnvDTE.CodeElement)CodeEvent.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
}
}
throw Exceptions.ThrowEUnexpected();
default:
throw new InvalidOperationException();
}
}
public override EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return (EnvDTE.CodeElement)CodeNamespace.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.ClassDeclaration:
return (EnvDTE.CodeElement)CodeClass.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.InterfaceDeclaration:
return (EnvDTE.CodeElement)CodeInterface.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.StructDeclaration:
return (EnvDTE.CodeElement)CodeStruct.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.EnumDeclaration:
return (EnvDTE.CodeElement)CodeEnum.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.DelegateDeclaration:
return (EnvDTE.CodeElement)CodeDelegate.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
return (EnvDTE.CodeElement)CodeFunction.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
return (EnvDTE.CodeElement)CodeProperty.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.EventDeclaration:
return (EnvDTE.CodeElement)CodeEvent.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.VariableDeclarator:
var eventFieldDeclaration = node.FirstAncestorOrSelf<EventFieldDeclarationSyntax>();
if (eventFieldDeclaration != null)
{
return (EnvDTE.CodeElement)CodeEvent.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
}
goto case SyntaxKind.EnumMemberDeclaration;
case SyntaxKind.EnumMemberDeclaration:
return (EnvDTE.CodeElement)CodeVariable.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
default:
throw Exceptions.ThrowEUnexpected();
}
}
public override EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel)
=> (EnvDTE.CodeElement)CodeNamespace.CreateUnknown(state, fileCodeModel, (int)SyntaxKind.NamespaceDeclaration, string.Empty);
public override EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type)
{
var project = state.Workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
var compilation = project.GetCompilationAsync().Result;
if (type is EnvDTE.vsCMTypeRef || type is int)
{
var specialType = GetSpecialType((EnvDTE.vsCMTypeRef)type);
return CodeTypeRef.Create(state, null, projectId, compilation.GetSpecialType(specialType));
}
string typeName;
object parent = null;
if (type is EnvDTE.CodeType codeType)
{
typeName = codeType.FullName;
parent = codeType;
}
else if (type is string str)
{
typeName = str;
}
else
{
throw Exceptions.ThrowEInvalidArg();
}
var typeSymbol = GetTypeSymbolFromFullName(typeName, compilation);
if (typeSymbol == null)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Unknown)
{
if (SyntaxFactsService.IsValidIdentifier(typeSymbol.Name))
{
throw Exceptions.ThrowEFail();
}
}
return CodeTypeRef.Create(state, parent, projectId, typeSymbol);
}
public override EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol)
{
if (typeSymbol.TypeKind == TypeKind.Array)
{
return EnvDTE.vsCMTypeRef.vsCMTypeRefArray;
}
else if (typeSymbol.TypeKind == TypeKind.Pointer)
{
return EnvDTE.vsCMTypeRef.vsCMTypeRefPointer;
}
else if (
typeSymbol.TypeKind == TypeKind.Dynamic ||
typeSymbol.TypeKind == TypeKind.Unknown)
{
return EnvDTE.vsCMTypeRef.vsCMTypeRefOther;
}
else
{
switch (typeSymbol.SpecialType)
{
case SpecialType.System_Void:
return EnvDTE.vsCMTypeRef.vsCMTypeRefVoid;
case SpecialType.System_String:
return EnvDTE.vsCMTypeRef.vsCMTypeRefString;
case SpecialType.System_Object:
return EnvDTE.vsCMTypeRef.vsCMTypeRefObject;
case SpecialType.System_Char:
return EnvDTE.vsCMTypeRef.vsCMTypeRefChar;
case SpecialType.System_Byte:
return EnvDTE.vsCMTypeRef.vsCMTypeRefByte;
case SpecialType.System_Boolean:
return EnvDTE.vsCMTypeRef.vsCMTypeRefBool;
case SpecialType.System_Int16:
return EnvDTE.vsCMTypeRef.vsCMTypeRefShort;
case SpecialType.System_Int32:
return EnvDTE.vsCMTypeRef.vsCMTypeRefInt;
case SpecialType.System_Int64:
return EnvDTE.vsCMTypeRef.vsCMTypeRefLong;
case SpecialType.System_Single:
return EnvDTE.vsCMTypeRef.vsCMTypeRefFloat;
case SpecialType.System_Double:
return EnvDTE.vsCMTypeRef.vsCMTypeRefDouble;
case SpecialType.System_Decimal:
return EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal;
case SpecialType.System_UInt16:
return (EnvDTE.vsCMTypeRef)EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedShort;
case SpecialType.System_UInt32:
return (EnvDTE.vsCMTypeRef)EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedInt;
case SpecialType.System_UInt64:
return (EnvDTE.vsCMTypeRef)EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedLong;
case SpecialType.System_SByte:
return (EnvDTE.vsCMTypeRef)EnvDTE80.vsCMTypeRef2.vsCMTypeRefSByte;
}
// Comment below is from native code
// The following are not supported
// vsCMTypeRefUnsignedChar - PT_UCHAR not in C# ??
// vsCMTypeRefReference - C++ specific
// vsCMTypeRefMCBoxedReference - C++ specific
}
if (typeSymbol.TypeKind == TypeKind.Class ||
typeSymbol.TypeKind == TypeKind.Interface ||
typeSymbol.TypeKind == TypeKind.Enum ||
typeSymbol.TypeKind == TypeKind.Struct ||
typeSymbol.TypeKind == TypeKind.Delegate)
{
return EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType;
}
return EnvDTE.vsCMTypeRef.vsCMTypeRefOther;
}
public override string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol)
=> typeSymbol.ToDisplayString(s_codeTypeRefAsFullNameFormat);
public override string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol)
=> typeSymbol.ToDisplayString(s_codeTypeRefAsStringFormat);
public override bool IsParameterNode(SyntaxNode node)
=> node is ParameterSyntax;
public override bool IsAttributeNode(SyntaxNode node)
=> node is AttributeSyntax;
public override bool IsAttributeArgumentNode(SyntaxNode node)
=> node is AttributeArgumentSyntax;
public override bool IsOptionNode(SyntaxNode node)
{
// Only VB implementation has Option statements
return false;
}
public override bool IsImportNode(SyntaxNode node)
=> node is UsingDirectiveSyntax;
public override string GetUnescapedName(string name)
{
return name != null && name.Length > 1 && name[0] == '@'
? name.Substring(1)
: name;
}
public override string GetName(SyntaxNode node)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
return ((BaseTypeDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.DelegateDeclaration:
return ((DelegateDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.MethodDeclaration:
return ((MethodDeclarationSyntax)node).ExplicitInterfaceSpecifier?.ToString() +
((MethodDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.ConstructorDeclaration:
return ((ConstructorDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.DestructorDeclaration:
return "~" + ((DestructorDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.PropertyDeclaration:
return ((PropertyDeclarationSyntax)node).ExplicitInterfaceSpecifier?.ToString() +
((PropertyDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.IndexerDeclaration:
return ((IndexerDeclarationSyntax)node).ExplicitInterfaceSpecifier?.ToString() +
((IndexerDeclarationSyntax)node).ThisKeyword.ToString();
case SyntaxKind.EventDeclaration:
return ((EventDeclarationSyntax)node).ExplicitInterfaceSpecifier?.ToString() +
((EventDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.Parameter:
return GetParameterName(node);
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return ((BaseNamespaceDeclarationSyntax)node).Name.ToString();
case SyntaxKind.OperatorDeclaration:
return "operator " + ((OperatorDeclarationSyntax)node).OperatorToken.ToString();
case SyntaxKind.ConversionOperatorDeclaration:
var conversionOperator = (ConversionOperatorDeclarationSyntax)node;
return (conversionOperator.ImplicitOrExplicitKeyword.Kind() == SyntaxKind.ImplicitKeyword ? "implicit " : "explicit ")
+ "operator "
+ conversionOperator.Type.ToString();
case SyntaxKind.EnumMemberDeclaration:
return ((EnumMemberDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.VariableDeclarator:
return ((VariableDeclaratorSyntax)node).Identifier.ToString();
case SyntaxKind.Attribute:
return ((AttributeSyntax)node).Name.ToString();
case SyntaxKind.AttributeArgument:
var attributeArgument = (AttributeArgumentSyntax)node;
return attributeArgument.NameEquals != null
? attributeArgument.NameEquals.Name.ToString()
: string.Empty;
case SyntaxKind.UsingDirective:
throw Exceptions.ThrowEFail();
default:
Debug.Fail("Invalid node kind: " + node.Kind());
throw new ArgumentException();
}
}
public override SyntaxNode GetNodeWithName(SyntaxNode node)
{
var kind = node.Kind();
if (kind == SyntaxKind.OperatorDeclaration ||
kind == SyntaxKind.ConversionOperatorDeclaration)
{
throw Exceptions.ThrowEFail();
}
return node;
}
public override SyntaxNode SetName(SyntaxNode node, string name)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
// In all cases, the resulting syntax for the new name has elastic trivia attached,
// whether via this call to SyntaxFactory.Identifier or via explicitly added elastic
// markers.
var newIdentifier = SyntaxFactory.Identifier(name);
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
return SetNameOfClassOrStruct(node, newIdentifier);
case SyntaxKind.InterfaceDeclaration:
return ((InterfaceDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.EnumDeclaration:
return ((EnumDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.DelegateDeclaration:
return ((DelegateDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.MethodDeclaration:
return ((MethodDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.ConstructorDeclaration:
return ((ConstructorDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.DestructorDeclaration:
return ((DestructorDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.PropertyDeclaration:
return ((PropertyDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.EventDeclaration:
return ((EventDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.Parameter:
return ((ParameterSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return ((BaseNamespaceDeclarationSyntax)node).WithName(
SyntaxFactory.ParseName(name)
.WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker))
.WithTrailingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker)));
case SyntaxKind.EnumMemberDeclaration:
return ((EnumMemberDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.VariableDeclarator:
return ((VariableDeclaratorSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.Attribute:
return ((AttributeSyntax)node).WithName(
SyntaxFactory.ParseName(name)
.WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker))
.WithTrailingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker)));
case SyntaxKind.AttributeArgument:
return ((AttributeArgumentSyntax)node).WithNameEquals(SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(name)));
default:
Debug.Fail("Invalid node kind: " + node.Kind());
throw new ArgumentException();
}
}
private static SyntaxNode SetNameOfClassOrStruct(SyntaxNode node, SyntaxToken newIdentifier)
{
var typeNode = (TypeDeclarationSyntax)node;
foreach (var member in typeNode.Members)
{
if (member.Kind() == SyntaxKind.ConstructorDeclaration)
{
var constructor = ((ConstructorDeclarationSyntax)member).WithIdentifier(newIdentifier);
typeNode = typeNode.ReplaceNode(member, constructor);
}
else if (member.Kind() == SyntaxKind.DestructorDeclaration)
{
var destructor = ((DestructorDeclarationSyntax)member).WithIdentifier(newIdentifier);
typeNode = typeNode.ReplaceNode(member, destructor);
}
}
if (typeNode.Kind() == SyntaxKind.StructDeclaration)
{
return ((StructDeclarationSyntax)typeNode).WithIdentifier(newIdentifier);
}
else
{
return ((ClassDeclarationSyntax)typeNode).WithIdentifier(newIdentifier);
}
}
public override string GetFullName(SyntaxNode node, SemanticModel semanticModel)
{
if (node.Kind() == SyntaxKind.UsingDirective)
{
throw Exceptions.ThrowEFail();
}
var symbol = node is AttributeSyntax
? semanticModel.GetTypeInfo(node).Type
: semanticModel.GetDeclaredSymbol(node);
return GetExternalSymbolFullName(symbol);
}
public override string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel)
{
var typeName = SyntaxFactory.ParseTypeName(name);
if (typeName is PredefinedTypeSyntax predefinedTypeNode)
{
if (SyntaxFactsService.TryGetPredefinedType(predefinedTypeNode.Keyword, out var predefinedType))
{
var specialType = predefinedType.ToSpecialType();
return semanticModel.Compilation.GetSpecialType(specialType).GetEscapedFullName();
}
}
else
{
var symbols = semanticModel.LookupNamespacesAndTypes(position, name: name);
if (symbols.Length > 0)
{
return symbols[0].GetEscapedFullName();
}
}
return name;
}
public override bool IsValidExternalSymbol(ISymbol symbol)
{
if (symbol is IMethodSymbol methodSymbol)
{
if (methodSymbol.MethodKind == MethodKind.PropertyGet ||
methodSymbol.MethodKind == MethodKind.PropertySet ||
methodSymbol.MethodKind == MethodKind.EventAdd ||
methodSymbol.MethodKind == MethodKind.EventRemove ||
methodSymbol.MethodKind == MethodKind.EventRaise)
{
return false;
}
}
return symbol.DeclaredAccessibility == Accessibility.Public
|| symbol.DeclaredAccessibility == Accessibility.Protected
|| symbol.DeclaredAccessibility == Accessibility.ProtectedOrInternal;
}
public override string GetExternalSymbolName(ISymbol symbol)
{
if (symbol == null)
{
throw Exceptions.ThrowEFail();
}
return symbol.ToDisplayString(s_externalNameFormat);
}
public override string GetExternalSymbolFullName(ISymbol symbol)
{
if (symbol == null)
{
throw Exceptions.ThrowEFail();
}
return symbol.ToDisplayString(s_externalFullNameFormat);
}
public override EnvDTE.vsCMAccess GetAccess(ISymbol symbol)
=> symbol.DeclaredAccessibility switch
{
Accessibility.Public => EnvDTE.vsCMAccess.vsCMAccessPublic,
Accessibility.Private => EnvDTE.vsCMAccess.vsCMAccessPrivate,
Accessibility.Internal => EnvDTE.vsCMAccess.vsCMAccessProject,
Accessibility.Protected => EnvDTE.vsCMAccess.vsCMAccessProtected,
Accessibility.ProtectedOrInternal => EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected,
Accessibility.ProtectedAndInternal =>
// there is no appropriate mapping for private protected in EnvDTE.vsCMAccess
// See https://github.com/dotnet/roslyn/issues/22406
EnvDTE.vsCMAccess.vsCMAccessProtected,
_ => throw Exceptions.ThrowEFail(),
};
public override EnvDTE.vsCMAccess GetAccess(SyntaxNode node)
{
var member = GetNodeWithModifiers(node);
if (member == null)
{
throw Exceptions.ThrowEFail();
}
var modifiers = member.GetModifiers();
if (modifiers.Any(t => t.Kind() == SyntaxKind.PublicKeyword))
{
return EnvDTE.vsCMAccess.vsCMAccessPublic;
}
else if (modifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword) && modifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword))
{
return EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected;
}
else if (modifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword))
{
return EnvDTE.vsCMAccess.vsCMAccessProject;
}
else if (modifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword))
{
return EnvDTE.vsCMAccess.vsCMAccessProtected;
}
else if (modifiers.Any(t => t.Kind() == SyntaxKind.PrivateKeyword))
{
return EnvDTE.vsCMAccess.vsCMAccessPrivate;
}
else
{
// The code does not specify the accessibility, so we need to
// determine the default accessibility.
return GetDefaultAccessibility(member);
}
}
public override SyntaxNode GetNodeWithModifiers(SyntaxNode node)
{
return node is VariableDeclaratorSyntax
? node.GetAncestor<MemberDeclarationSyntax>()
: node;
}
public override SyntaxNode GetNodeWithType(SyntaxNode node)
{
return node is VariableDeclaratorSyntax
? node.GetAncestor<MemberDeclarationSyntax>()
: node;
}
public override SyntaxNode GetNodeWithInitializer(SyntaxNode node)
=> node;
private EnvDTE.vsCMAccess GetDefaultAccessibility(SyntaxNode node)
{
if (node is EnumMemberDeclarationSyntax)
{
return EnvDTE.vsCMAccess.vsCMAccessPublic;
}
if (node is BaseFieldDeclarationSyntax ||
node is BaseMethodDeclarationSyntax ||
node is BasePropertyDeclarationSyntax)
{
// Members of interfaces and enums are public, while all other
// members are private.
if (node.HasAncestor<InterfaceDeclarationSyntax>() ||
node.HasAncestor<EnumDeclarationSyntax>())
{
return EnvDTE.vsCMAccess.vsCMAccessPublic;
}
else
{
return EnvDTE.vsCMAccess.vsCMAccessPrivate;
}
}
if (node is BaseTypeDeclarationSyntax ||
node is DelegateDeclarationSyntax)
{
// Types declared within types are private by default,
// otherwise internal.
if (node.HasAncestor<BaseTypeDeclarationSyntax>())
{
return EnvDTE.vsCMAccess.vsCMAccessPrivate;
}
else
{
return EnvDTE.vsCMAccess.vsCMAccessProject;
}
}
if (node is AccessorDeclarationSyntax ||
node is ArrowExpressionClauseSyntax)
{
return GetAccess(node.FirstAncestorOrSelf<BasePropertyDeclarationSyntax>());
}
throw Exceptions.ThrowEFail();
}
public override SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess newAccess)
{
if (!(node is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
if (member.Parent.Kind() == SyntaxKind.InterfaceDeclaration ||
member.Parent.Kind() == SyntaxKind.EnumDeclaration)
{
if (newAccess == EnvDTE.vsCMAccess.vsCMAccessDefault ||
newAccess == EnvDTE.vsCMAccess.vsCMAccessPublic)
{
return member;
}
else
{
throw Exceptions.ThrowEInvalidArg();
}
}
if (member is BaseTypeDeclarationSyntax ||
member is EnumDeclarationSyntax)
{
if (!(member.Parent is BaseTypeDeclarationSyntax) &&
(newAccess == EnvDTE.vsCMAccess.vsCMAccessPrivate ||
newAccess == EnvDTE.vsCMAccess.vsCMAccessProtected ||
newAccess == EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected))
{
throw Exceptions.ThrowEInvalidArg();
}
}
var modifierFlags = member.GetModifierFlags() & ~ModifierFlags.AccessModifierMask;
switch (newAccess)
{
case EnvDTE.vsCMAccess.vsCMAccessPrivate:
modifierFlags |= ModifierFlags.Private;
break;
case EnvDTE.vsCMAccess.vsCMAccessProtected:
modifierFlags |= ModifierFlags.Protected;
break;
case EnvDTE.vsCMAccess.vsCMAccessPublic:
modifierFlags |= ModifierFlags.Public;
break;
case EnvDTE.vsCMAccess.vsCMAccessProject:
modifierFlags |= ModifierFlags.Internal;
break;
case EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected:
modifierFlags |= ModifierFlags.Protected | ModifierFlags.Internal;
break;
case EnvDTE.vsCMAccess.vsCMAccessDefault:
break; // No change
default:
throw Exceptions.ThrowEUnexpected();
}
return member.UpdateModifiers(modifierFlags);
}
private IList<SyntaxTrivia> CollectComments(IList<SyntaxTrivia> triviaList)
{
var commentList = new List<SyntaxTrivia>();
for (var i = triviaList.Count - 1; i >= 0; i--)
{
var trivia = triviaList[i];
if (trivia.IsRegularComment())
{
commentList.Add(trivia);
}
else if (trivia.Kind() != SyntaxKind.WhitespaceTrivia &&
trivia.Kind() != SyntaxKind.EndOfLineTrivia)
{
break;
}
}
commentList.Reverse();
return commentList;
}
public override string GetComment(SyntaxNode node)
{
var firstToken = node.GetFirstToken();
var commentList = CollectComments(firstToken.LeadingTrivia.ToArray());
if (commentList.Count == 0)
{
return string.Empty;
}
var textBuilder = new StringBuilder();
foreach (var trivia in commentList)
{
if (trivia.IsRegularComment())
{
textBuilder.AppendLine(trivia.GetCommentText());
}
else
{
throw Exceptions.ThrowEFail();
}
}
return textBuilder.ToString();
}
public override SyntaxNode SetComment(SyntaxNode node, string value)
{
Debug.Assert(node is MemberDeclarationSyntax);
var memberDeclaration = (MemberDeclarationSyntax)node;
var text = memberDeclaration.SyntaxTree.GetText(CancellationToken.None);
var newLine = GetNewLineCharacter(text);
var commentText = string.Empty;
if (value != null)
{
var builder = new StringBuilder();
foreach (var line in value.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
builder.Append("// ");
builder.Append(line);
builder.Append(newLine);
}
commentText = builder.ToString();
}
var newTriviaList = SyntaxFactory.ParseLeadingTrivia(commentText);
var leadingTriviaList = memberDeclaration.GetLeadingTrivia().ToList();
var commentList = CollectComments(leadingTriviaList);
if (commentList.Count > 0)
{
// In this case, we're going to replace the existing comment.
var firstIndex = leadingTriviaList.FindIndex(t => t == commentList[0]);
var lastIndex = leadingTriviaList.FindIndex(t => t == commentList[commentList.Count - 1]);
var count = lastIndex - firstIndex + 1;
leadingTriviaList.RemoveRange(firstIndex, count);
// Note: single line comments have a trailing new-line but that won't be
// returned by CollectComments. So, we may need to remove an additional new line below.
if (firstIndex < leadingTriviaList.Count &&
leadingTriviaList[firstIndex].Kind() == SyntaxKind.EndOfLineTrivia)
{
leadingTriviaList.RemoveAt(firstIndex);
}
foreach (var trivia in newTriviaList.Reverse())
{
leadingTriviaList.Insert(firstIndex, trivia);
}
}
else
{
// Otherwise, just add the comment to the end of the leading trivia.
leadingTriviaList.AddRange(newTriviaList);
}
return memberDeclaration.WithLeadingTrivia(leadingTriviaList);
}
private static DocumentationCommentTriviaSyntax GetDocCommentNode(MemberDeclarationSyntax memberDeclaration)
{
var docCommentTrivia = memberDeclaration
.GetLeadingTrivia()
.Reverse()
.FirstOrDefault(t => t.IsDocComment());
if (!docCommentTrivia.IsDocComment())
{
return null;
}
return (DocumentationCommentTriviaSyntax)docCommentTrivia.GetStructure();
}
public override string GetDocComment(SyntaxNode node)
{
Debug.Assert(node is MemberDeclarationSyntax);
var memberDeclaration = (MemberDeclarationSyntax)node;
var documentationComment = GetDocCommentNode(memberDeclaration);
if (documentationComment == null)
{
return string.Empty;
}
var text = memberDeclaration.SyntaxTree.GetText(CancellationToken.None);
var newLine = GetNewLineCharacter(text);
var lines = documentationComment.ToString().Split(new[] { newLine }, StringSplitOptions.None);
// trim off leading whitespace and exterior trivia.
var lengthToStrip = lines[0].GetLeadingWhitespace().Length;
for (var i = 1; i < lines.Length; i++)
{
var line = lines[i].TrimStart();
if (line.StartsWith("///", StringComparison.Ordinal))
{
line = line.Substring(3);
}
if (line.Length > 0)
{
lengthToStrip = Math.Min(lengthToStrip, line.GetLeadingWhitespace().Length);
}
lines[i] = line;
}
for (var i = 0; i < lines.Length; i++)
{
var line = lines[i];
if (line.Length > lengthToStrip)
{
lines[i] = line.Substring(lengthToStrip);
}
}
return "<doc>\r\n" + lines.Join(newLine) + "</doc>";
}
public override SyntaxNode SetDocComment(SyntaxNode node, string value)
{
Debug.Assert(node is MemberDeclarationSyntax);
XDocument xmlDocument;
try
{
using var reader = new StringReader(value);
xmlDocument = XDocument.Load(reader);
}
catch
{
xmlDocument = null;
}
if (xmlDocument == null)
{
throw Exceptions.ThrowEInvalidArg();
}
if (!(xmlDocument.FirstNode is XElement docElement) ||
docElement.Name.ToString().ToLower() != "doc")
{
throw Exceptions.ThrowEInvalidArg();
}
var memberDeclaration = (MemberDeclarationSyntax)node;
var text = memberDeclaration.SyntaxTree.GetText(CancellationToken.None);
var newLine = GetNewLineCharacter(text);
var builder = new StringBuilder();
foreach (var child in docElement.Elements())
{
foreach (var line in child.ToString().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
builder.Append("/// ");
builder.Append(line);
builder.Append(newLine);
}
}
var newTriviaList = SyntaxFactory.ParseLeadingTrivia(builder.ToString());
var leadingTriviaList = memberDeclaration.GetLeadingTrivia().ToList();
var documentationComment = GetDocCommentNode(memberDeclaration);
if (documentationComment != null)
{
// In this case, we're going to replace the existing XML doc comment.
var index = leadingTriviaList.FindIndex(t => t == documentationComment.ParentTrivia);
leadingTriviaList.RemoveAt(index);
foreach (var triviaElement in newTriviaList.Reverse())
{
leadingTriviaList.Insert(index, triviaElement);
}
}
else
{
// Otherwise, just add the XML doc comment to the end of the leading trivia.
leadingTriviaList.AddRange(newTriviaList);
}
return memberDeclaration.WithLeadingTrivia(leadingTriviaList);
}
public override IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parentNode)
{
if (parentNode is BaseMethodDeclarationSyntax baseMethod)
{
return baseMethod.ParameterList.Parameters;
}
else if (parentNode is IndexerDeclarationSyntax indexer)
{
return indexer.ParameterList.Parameters;
}
else if (parentNode is DelegateDeclarationSyntax delegateDecl)
{
return delegateDecl.ParameterList.Parameters;
}
return SpecializedCollections.EmptyEnumerable<ParameterSyntax>();
}
public override bool IsExpressionBodiedProperty(SyntaxNode node)
=> (node as PropertyDeclarationSyntax)?.ExpressionBody != null;
public override bool TryGetAutoPropertyExpressionBody(SyntaxNode parentNode, out SyntaxNode accessorNode)
{
accessorNode = (parentNode as PropertyDeclarationSyntax)?.ExpressionBody;
return accessorNode != null;
}
public override bool IsAccessorNode(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return true;
}
return false;
}
public override MethodKind GetAccessorKind(SyntaxNode node)
=> node.Kind() switch
{
SyntaxKind.GetAccessorDeclaration => MethodKind.PropertyGet,
SyntaxKind.SetAccessorDeclaration => MethodKind.PropertySet,
SyntaxKind.AddAccessorDeclaration => MethodKind.EventAdd,
SyntaxKind.RemoveAccessorDeclaration => MethodKind.EventRemove,
_ => throw Exceptions.ThrowEUnexpected(),
};
private static SyntaxKind GetAccessorSyntaxKind(MethodKind methodKind)
=> methodKind switch
{
MethodKind.PropertyGet => SyntaxKind.GetAccessorDeclaration,
MethodKind.PropertySet => SyntaxKind.SetAccessorDeclaration,
MethodKind.EventAdd => SyntaxKind.AddAccessorDeclaration,
MethodKind.EventRemove => SyntaxKind.RemoveAccessorDeclaration,
_ => throw Exceptions.ThrowEUnexpected(),
};
public override bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode)
{
Debug.Assert(parentNode is BasePropertyDeclarationSyntax);
var basePropertyDeclaration = (BasePropertyDeclarationSyntax)parentNode;
var accessorKind = GetAccessorSyntaxKind(kind);
if (basePropertyDeclaration.AccessorList != null)
{
foreach (var accessor in basePropertyDeclaration.AccessorList.Accessors)
{
if (accessor.Kind() == accessorKind)
{
accessorNode = accessor;
return true;
}
}
}
accessorNode = null;
return false;
}
public override bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode)
{
foreach (ParameterSyntax parameter in GetParameterNodes(parentNode))
{
if (parameter.Identifier.ToString() == name)
{
parameterNode = parameter;
return true;
}
}
parameterNode = null;
return false;
}
public override bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode)
{
foreach (UsingDirectiveSyntax usingDirective in GetImportNodes(parentNode))
{
if (usingDirective.Name.ToString() == dottedName)
{
importNode = usingDirective;
return true;
}
}
importNode = null;
return false;
}
public override bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode)
{
// Only VB has Option statements
throw new NotSupportedException();
}
public override bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode)
{
// Only VB has Inherits statements
throw new NotSupportedException();
}
public override bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode)
{
// Only VB has Implements statements
throw new NotSupportedException();
}
public override bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode)
{
var count = -1;
foreach (AttributeSyntax attribute in GetAttributeNodes(parentNode))
{
if (attribute.Name.ToString() == name)
{
count++;
if (count == ordinal)
{
attributeNode = attribute;
return true;
}
}
}
attributeNode = null;
return false;
}
public override bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode)
{
Debug.Assert(attributeNode is AttributeSyntax);
var attribute = (AttributeSyntax)attributeNode;
if (attribute.ArgumentList != null &&
attribute.ArgumentList.Arguments.Count > index)
{
attributeArgumentNode = attribute.ArgumentList.Arguments[index];
return true;
}
attributeArgumentNode = null;
return false;
}
public override void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal)
{
// Only VB supports Option statements
throw new NotSupportedException();
}
public override void GetInheritsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode inheritsNode, out string namespaceName, out int ordinal)
{
// Only VB supports Inherits statements
throw new NotSupportedException();
}
public override void GetImplementsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode implementsNode, out string namespaceName, out int ordinal)
{
// Only VB supports Implements statements
throw new NotSupportedException();
}
public override void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal)
{
Debug.Assert(attributeNode is AttributeSyntax);
name = ((AttributeSyntax)attributeNode).Name.ToString();
ordinal = -1;
foreach (AttributeSyntax attribute in GetAttributeNodes(parentNode))
{
if (attribute.Name.ToString() == name)
{
ordinal++;
}
if (attribute == attributeNode)
{
break;
}
}
}
public override void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index)
{
Debug.Assert(attributeArgumentNode is AttributeArgumentSyntax);
var argument = (AttributeArgumentSyntax)attributeArgumentNode;
var attribute = (AttributeSyntax)argument.Ancestors().First(n => n.Kind() == SyntaxKind.Attribute);
attributeNode = attribute;
index = attribute.ArgumentList.Arguments.IndexOf((AttributeArgumentSyntax)attributeArgumentNode);
}
public override SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode)
{
Debug.Assert(attributeNode is AttributeSyntax);
Debug.Assert(attributeNode.Parent is AttributeListSyntax);
return (AttributeListSyntax)attributeNode.Parent;
}
public override string GetAttributeTarget(SyntaxNode attributeNode)
{
Debug.Assert(attributeNode is AttributeSyntax);
Debug.Assert(attributeNode.Parent is AttributeListSyntax);
var attributeList = (AttributeListSyntax)attributeNode.Parent;
if (attributeList.Target != null)
{
return attributeList.Target.Identifier.ToString();
}
return string.Empty;
}
public override SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string target)
{
Debug.Assert(attributeNode is AttributeListSyntax);
var attributeList = (AttributeListSyntax)attributeNode;
if (string.IsNullOrEmpty(target))
{
return attributeList.WithTarget(null);
}
else
{
return attributeList.WithTarget(
SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Identifier(target)));
}
}
public override string GetAttributeValue(SyntaxNode attributeNode)
{
Debug.Assert(attributeNode is AttributeSyntax);
var attribute = (AttributeSyntax)attributeNode;
var argumentList = attribute.ArgumentList;
if (argumentList != null)
{
return argumentList.Arguments.ToString();
}
return string.Empty;
}
public override SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value)
{
Debug.Assert(attributeNode is AttributeSyntax);
var attribute = (AttributeSyntax)attributeNode;
var argumentList = attribute.ArgumentList;
var parsedArgumentList = SyntaxFactory.ParseAttributeArgumentList("(" + value + ")");
var newArgumentList = argumentList != null
? argumentList.WithArguments(parsedArgumentList.Arguments)
: parsedArgumentList;
return attribute.WithArgumentList(newArgumentList);
}
public override SyntaxNode GetNodeWithAttributes(SyntaxNode node)
{
return node is VariableDeclaratorSyntax
? node.GetAncestor<MemberDeclarationSyntax>()
: node;
}
public override SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node)
{
if (node.HasAncestor<BaseFieldDeclarationSyntax>())
{
return node.GetAncestor<BaseFieldDeclarationSyntax>().Declaration.Variables.FirstOrDefault();
}
else if (node.HasAncestor<ParameterSyntax>())
{
return node.GetAncestor<ParameterSyntax>();
}
else
{
return node.Parent;
}
}
public override SyntaxNode CreateAttributeNode(string name, string value, string target = null)
{
var specifier = target != null
? SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Identifier(target),
SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), SyntaxKind.ColonToken, SyntaxFactory.TriviaList(SyntaxFactory.Space)))
: null;
return SyntaxFactory.AttributeList(
target: specifier,
attributes: SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Attribute(
name: SyntaxFactory.ParseName(name),
argumentList: SyntaxFactory.ParseAttributeArgumentList("(" + value + ")"))));
}
public override SyntaxNode CreateAttributeArgumentNode(string name, string value)
{
if (!string.IsNullOrEmpty(name))
{
return SyntaxFactory.AttributeArgument(
nameEquals: SyntaxFactory.NameEquals(name),
nameColon: null,
expression: SyntaxFactory.ParseExpression(value));
}
else
{
return SyntaxFactory.AttributeArgument(SyntaxFactory.ParseExpression(value));
}
}
public override SyntaxNode CreateImportNode(string name, string alias = null)
{
var nameSyntax = SyntaxFactory.ParseName(name);
if (!string.IsNullOrEmpty(alias))
{
var aliasSyntax = SyntaxFactory.NameEquals(alias);
return SyntaxFactory.UsingDirective(aliasSyntax, nameSyntax);
}
else
{
return SyntaxFactory.UsingDirective(nameSyntax);
}
}
public override SyntaxNode CreateParameterNode(string name, string type)
=> SyntaxFactory.Parameter(SyntaxFactory.Identifier(name)).WithType(SyntaxFactory.ParseTypeName(type));
public override string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode)
{
Debug.Assert(attributeArgumentNode is AttributeArgumentSyntax);
return ((AttributeArgumentSyntax)attributeArgumentNode).Expression.ToString();
}
public override string GetImportAlias(SyntaxNode importNode)
{
if (importNode is UsingDirectiveSyntax usingDirective)
{
return usingDirective.Alias != null
? usingDirective.Alias.Name.ToString()
: string.Empty;
}
throw new InvalidOperationException();
}
public override string GetImportNamespaceOrType(SyntaxNode importNode)
{
if (importNode is UsingDirectiveSyntax usingDirective)
{
return usingDirective.Name.ToString();
}
throw new InvalidOperationException();
}
public override void GetImportParentAndName(SyntaxNode importNode, out SyntaxNode namespaceNode, out string name)
{
if (importNode is UsingDirectiveSyntax usingDirective)
{
namespaceNode = usingDirective.Parent.Kind() == SyntaxKind.CompilationUnit
? null
: usingDirective.Parent;
name = usingDirective.Name.ToString();
return;
}
throw new InvalidOperationException();
}
public override string GetParameterName(SyntaxNode node)
{
if (node is ParameterSyntax parameter)
{
return parameter.Identifier.ToString();
}
throw new InvalidOperationException();
}
public override EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node)
{
if (node is ParameterSyntax parameter)
{
var kind = EnvDTE80.vsCMParameterKind.vsCMParameterKindNone;
var modifiers = parameter.Modifiers;
if (modifiers.Any(SyntaxKind.RefKeyword))
{
kind = EnvDTE80.vsCMParameterKind.vsCMParameterKindRef;
}
else if (modifiers.Any(SyntaxKind.OutKeyword))
{
kind = EnvDTE80.vsCMParameterKind.vsCMParameterKindOut;
}
else if (modifiers.Any(SyntaxKind.ParamsKeyword))
{
kind = EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray;
}
// Note: this is not an "else if" since it might be both
// optional and "ref".
if (parameter.Default != null)
{
kind |= EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional;
}
return kind;
}
throw new InvalidOperationException();
}
public override SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind)
{
if (!(node is ParameterSyntax parameter))
{
throw Exceptions.ThrowEFail();
}
// We can't do anything with "Optional", so just strip it out and ignore it.
if ((kind & EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional) != 0)
{
kind -= EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional;
}
SyntaxTokenList newModifiers;
switch (kind)
{
case EnvDTE80.vsCMParameterKind.vsCMParameterKindOut:
newModifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.OutKeyword));
break;
case EnvDTE80.vsCMParameterKind.vsCMParameterKindRef:
newModifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.RefKeyword));
break;
case EnvDTE80.vsCMParameterKind.vsCMParameterKindIn:
case EnvDTE80.vsCMParameterKind.vsCMParameterKindNone:
newModifiers = SyntaxFactory.TokenList();
break;
case EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray:
{
var parameterList = (ParameterListSyntax)parameter.Parent;
if (parameterList.Parameters.LastOrDefault() == parameter &&
parameter.Type is ArrayTypeSyntax)
{
newModifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ParamsKeyword));
break;
}
throw Exceptions.ThrowEInvalidArg();
}
default:
throw Exceptions.ThrowEInvalidArg();
}
return parameter.WithModifiers(newModifiers);
}
public override EnvDTE80.vsCMParameterKind UpdateParameterKind(EnvDTE80.vsCMParameterKind parameterKind, PARAMETER_PASSING_MODE passingMode)
{
var updatedParameterKind = parameterKind;
switch (passingMode)
{
case PARAMETER_PASSING_MODE.cmParameterTypeIn:
updatedParameterKind |= EnvDTE80.vsCMParameterKind.vsCMParameterKindNone;
updatedParameterKind &= ~EnvDTE80.vsCMParameterKind.vsCMParameterKindRef;
updatedParameterKind &= ~EnvDTE80.vsCMParameterKind.vsCMParameterKindOut;
break;
case PARAMETER_PASSING_MODE.cmParameterTypeInOut:
updatedParameterKind &= ~EnvDTE80.vsCMParameterKind.vsCMParameterKindNone;
updatedParameterKind |= EnvDTE80.vsCMParameterKind.vsCMParameterKindRef;
updatedParameterKind &= ~EnvDTE80.vsCMParameterKind.vsCMParameterKindOut;
break;
case PARAMETER_PASSING_MODE.cmParameterTypeOut:
updatedParameterKind &= ~EnvDTE80.vsCMParameterKind.vsCMParameterKindNone;
updatedParameterKind &= ~EnvDTE80.vsCMParameterKind.vsCMParameterKindRef;
updatedParameterKind |= EnvDTE80.vsCMParameterKind.vsCMParameterKindOut;
break;
}
return updatedParameterKind;
}
public override EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name)
{
if (kind == EnvDTE.vsCMFunction.vsCMFunctionSub)
{
return EnvDTE.vsCMFunction.vsCMFunctionFunction;
}
if (kind == EnvDTE.vsCMFunction.vsCMFunctionFunction)
{
return kind;
}
if (kind == EnvDTE.vsCMFunction.vsCMFunctionConstructor ||
kind == EnvDTE.vsCMFunction.vsCMFunctionDestructor)
{
if (containerNode is InterfaceDeclarationSyntax)
{
throw Exceptions.ThrowEFail();
}
return kind;
}
throw Exceptions.ThrowENotImpl();
}
public override bool SupportsEventThrower
{
get { return false; }
}
public override bool GetCanOverride(SyntaxNode memberNode)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
if (!(memberNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
if (member.Parent is InterfaceDeclarationSyntax)
{
return true;
}
var flags = member.GetModifierFlags();
return (flags & (ModifierFlags.Abstract | ModifierFlags.Virtual)) != 0;
}
public override SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
if (!(memberNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
if (member.Parent is InterfaceDeclarationSyntax)
{
if (!value)
{
throw Exceptions.ThrowEInvalidArg();
}
return memberNode;
}
var flags = member.GetModifierFlags();
if (value)
{
flags |= ModifierFlags.Virtual;
}
else
{
flags &= ~ModifierFlags.Virtual;
}
return member.UpdateModifiers(flags);
}
public override EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol)
{
Debug.Assert(typeNode is ClassDeclarationSyntax);
var type = (ClassDeclarationSyntax)typeNode;
var flags = type.GetModifierFlags();
return (flags & ModifierFlags.Partial) != 0
? EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass
: EnvDTE80.vsCMClassKind.vsCMClassKindMainClass;
}
public override SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind)
{
Debug.Assert(typeNode is ClassDeclarationSyntax);
var type = (ClassDeclarationSyntax)typeNode;
var flags = type.GetModifierFlags();
if (kind == EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass)
{
flags |= ModifierFlags.Partial;
}
else if (kind == EnvDTE80.vsCMClassKind.vsCMClassKindMainClass)
{
flags &= ~ModifierFlags.Partial;
}
return type.UpdateModifiers(flags);
}
public override EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode)
{
if (variableNode is EnumMemberDeclarationSyntax)
{
return EnvDTE80.vsCMConstKind.vsCMConstKindConst;
}
if (!(GetNodeWithModifiers(variableNode) is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
var flags = member.GetModifierFlags();
var result = EnvDTE80.vsCMConstKind.vsCMConstKindNone;
if ((flags & ModifierFlags.ReadOnly) != 0)
{
result |= EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly;
}
if ((flags & ModifierFlags.Const) != 0)
{
result |= EnvDTE80.vsCMConstKind.vsCMConstKindConst;
}
// Note: It's possible that we could return vsCMConstKindCont | vsCMConstKindReadOnly if the
// user had incorrectly specified both const and readonly in their code. That's OK since
// Code Model represents the source.
return result;
}
public override SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind)
{
Debug.Assert(variableNode is FieldDeclarationSyntax ||
variableNode is EnumMemberDeclarationSyntax);
if (variableNode is EnumMemberDeclarationSyntax)
{
if (kind != EnvDTE80.vsCMConstKind.vsCMConstKindConst &&
kind != EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly)
{
throw Exceptions.ThrowEInvalidArg();
}
return variableNode;
}
var member = (MemberDeclarationSyntax)variableNode;
var flags = member.GetModifierFlags();
flags &= ~(ModifierFlags.Const | ModifierFlags.ReadOnly);
switch (kind)
{
case EnvDTE80.vsCMConstKind.vsCMConstKindConst:
flags |= ModifierFlags.Const;
break;
case EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly:
flags |= ModifierFlags.ReadOnly;
break;
}
return member.UpdateModifiers(flags);
}
public override EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol)
{
Debug.Assert(typeNode is BaseTypeDeclarationSyntax);
var type = (BaseTypeDeclarationSyntax)typeNode;
var flags = type.GetModifierFlags();
return (flags & ModifierFlags.Partial) != 0
? EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial
: EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain;
}
public override SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind)
{
Debug.Assert(typeNode is BaseTypeDeclarationSyntax);
var type = (BaseTypeDeclarationSyntax)typeNode;
var flags = type.GetModifierFlags();
if (kind == EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial)
{
flags |= ModifierFlags.Partial;
}
else if (kind == EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain)
{
flags &= ~ModifierFlags.Partial;
}
return type.UpdateModifiers(flags);
}
public override EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol)
{
switch (symbol.MethodKind)
{
case MethodKind.Ordinary:
case MethodKind.ExplicitInterfaceImplementation:
return EnvDTE.vsCMFunction.vsCMFunctionFunction;
case MethodKind.Constructor:
case MethodKind.StaticConstructor:
return EnvDTE.vsCMFunction.vsCMFunctionConstructor;
case MethodKind.Destructor:
return EnvDTE.vsCMFunction.vsCMFunctionDestructor;
case MethodKind.UserDefinedOperator:
case MethodKind.Conversion:
return EnvDTE.vsCMFunction.vsCMFunctionOperator;
case MethodKind.PropertyGet:
case MethodKind.EventRemove:
return EnvDTE.vsCMFunction.vsCMFunctionPropertyGet;
case MethodKind.PropertySet:
case MethodKind.EventAdd:
return EnvDTE.vsCMFunction.vsCMFunctionPropertySet;
default:
throw Exceptions.ThrowEUnexpected();
}
}
public override EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol)
{
Debug.Assert(typeNode is ClassDeclarationSyntax);
var type = (ClassDeclarationSyntax)typeNode;
var flags = type.GetModifierFlags();
var result = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone;
if ((flags & ModifierFlags.Abstract) != 0)
{
result |= EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract;
}
if ((flags & ModifierFlags.New) != 0)
{
result |= EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew;
}
if ((flags & ModifierFlags.Sealed) != 0)
{
result |= EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed;
}
return result;
}
public override bool GetMustImplement(SyntaxNode memberNode)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
if (!(memberNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
if (member.Parent is InterfaceDeclarationSyntax)
{
return true;
}
var flags = member.GetModifierFlags();
return (flags & ModifierFlags.Abstract) != 0;
}
public override SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value)
{
Debug.Assert(memberNode is MethodDeclarationSyntax ||
memberNode is BasePropertyDeclarationSyntax ||
memberNode is EventFieldDeclarationSyntax);
if (!(memberNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
if (member.Parent is InterfaceDeclarationSyntax)
{
if (!value)
{
throw Exceptions.ThrowEInvalidArg();
}
return memberNode;
}
// If this is a class member and the class is not abstract, we throw.
if (member.Parent is ClassDeclarationSyntax)
{
var parentFlags = ((ClassDeclarationSyntax)member.Parent).GetModifierFlags();
if (value && (parentFlags & ModifierFlags.Abstract) == 0)
{
throw Exceptions.ThrowEInvalidArg();
}
}
var flags = member.GetModifierFlags();
if (value)
{
flags |= ModifierFlags.Abstract;
// If this is a method, remove the body if it is empty.
if (member is MethodDeclarationSyntax method)
{
if (method.Body != null && method.Body.Statements.Count == 0)
{
member = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), SyntaxKind.SemicolonToken, method.Body.CloseBraceToken.TrailingTrivia));
}
}
else
{
// If this is a property, remove the bodies of the accessors if they are empty.
// Note that "empty" means that the bodies contain no statements or just a single return statement.
if (member is BasePropertyDeclarationSyntax property && property.AccessorList != null)
{
var updatedAccessors = new List<AccessorDeclarationSyntax>();
foreach (var accessor in property.AccessorList.Accessors)
{
if (accessor.Body == null ||
accessor.Body.Statements.Count > 1 ||
(accessor.Body.Statements.Count == 1 && !accessor.Body.Statements[0].IsKind(SyntaxKind.ReturnStatement)))
{
// Leave this accessor as is
updatedAccessors.Add(accessor);
continue;
}
var updatedAccessor = accessor.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), SyntaxKind.SemicolonToken, accessor.Body.CloseBraceToken.TrailingTrivia));
updatedAccessors.Add(updatedAccessor);
}
var updatedAccessorList = property.AccessorList.WithAccessors(SyntaxFactory.List<AccessorDeclarationSyntax>(updatedAccessors));
member = property.ReplaceNode(property.AccessorList, updatedAccessorList);
}
}
}
else
{
flags &= ~ModifierFlags.Abstract;
// If this is a method, add a body.
if (member is MethodDeclarationSyntax method)
{
if (method.Body == null)
{
var newBody = SyntaxFactory.Block();
newBody = newBody.WithCloseBraceToken(newBody.CloseBraceToken.WithTrailingTrivia(method.SemicolonToken.TrailingTrivia));
member = method.WithSemicolonToken(default).WithBody(newBody);
}
}
else
{
// If this is a property, add bodies to the accessors if they don't have them.
if (member is BasePropertyDeclarationSyntax property && property.AccessorList != null)
{
var updatedAccessors = new List<AccessorDeclarationSyntax>();
foreach (var accessor in property.AccessorList.Accessors)
{
if (accessor.Body != null)
{
// Leave this accessor as is
updatedAccessors.Add(accessor);
continue;
}
var newBody = SyntaxFactory.Block();
newBody = newBody.WithCloseBraceToken(newBody.CloseBraceToken.WithTrailingTrivia(accessor.SemicolonToken.TrailingTrivia));
var updatedAccessor = accessor.WithSemicolonToken(default).WithBody(newBody);
updatedAccessors.Add(updatedAccessor);
}
var updatedAccessorList = property.AccessorList.WithAccessors(SyntaxFactory.List<AccessorDeclarationSyntax>(updatedAccessors));
member = property.ReplaceNode(property.AccessorList, updatedAccessorList);
}
}
}
return member.UpdateModifiers(flags);
}
public override SyntaxNode SetInheritanceKind(SyntaxNode typeNode, EnvDTE80.vsCMInheritanceKind kind)
{
Debug.Assert(typeNode is ClassDeclarationSyntax);
if (!(typeNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
var flags = member.GetModifierFlags();
flags &= ~(ModifierFlags.Abstract | ModifierFlags.New | ModifierFlags.Sealed);
if (kind != EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone)
{
if ((kind & EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) != 0)
{
flags |= ModifierFlags.Abstract;
}
else if ((kind & EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed) != 0)
{
flags |= ModifierFlags.Sealed;
}
// Can have new in combination with the above flags
if ((kind & EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) != 0)
{
flags |= ModifierFlags.New;
}
}
return member.UpdateModifiers(flags);
}
public override EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode)
{
Debug.Assert(memberNode is BaseMethodDeclarationSyntax ||
memberNode is BasePropertyDeclarationSyntax ||
memberNode is EventFieldDeclarationSyntax);
var member = (MemberDeclarationSyntax)memberNode;
var flags = member.GetModifierFlags();
var containingType = member.FirstAncestorOrSelf<TypeDeclarationSyntax>();
var result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone;
if ((flags & ModifierFlags.Abstract) != 0 || containingType?.Kind() == SyntaxKind.InterfaceDeclaration)
{
result |= EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract;
}
if ((flags & ModifierFlags.Virtual) != 0 || containingType?.Kind() == SyntaxKind.InterfaceDeclaration)
{
result |= EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual;
}
if ((flags & ModifierFlags.Override) != 0)
{
result |= EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride;
}
if ((flags & ModifierFlags.New) != 0)
{
result |= EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew;
}
if ((flags & ModifierFlags.Sealed) != 0)
{
result |= EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed;
}
return result;
}
public override SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind)
{
Debug.Assert(memberNode is BaseMethodDeclarationSyntax ||
memberNode is BasePropertyDeclarationSyntax ||
memberNode is EventFieldDeclarationSyntax);
// The legacy C# code model sets the MustImplement property here depending on whether the Abstract kind is set
// TODO(DustinCa): VB implements MustImplement in terms of OverrideKind, should we do the same?
memberNode = SetMustImplement(memberNode, (kind & EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) != 0);
var member = (MemberDeclarationSyntax)memberNode;
var flags = member.GetModifierFlags();
flags &= ~(ModifierFlags.Abstract | ModifierFlags.Virtual | ModifierFlags.Override | ModifierFlags.New | ModifierFlags.Sealed);
if (member.IsParentKind(SyntaxKind.InterfaceDeclaration))
{
if ((kind & (EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride | EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed)) != 0)
{
throw Exceptions.ThrowEInvalidArg();
}
else if ((kind & (EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract | EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual)) != 0)
{
// Switch these flags off
kind &= ~(EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract | EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual);
}
}
if (kind != EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone)
{
if ((kind & EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) != 0)
{
flags |= ModifierFlags.Abstract;
}
if ((kind & EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) != 0)
{
flags |= ModifierFlags.Virtual;
}
if ((kind & EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride) != 0)
{
flags |= ModifierFlags.Override;
}
if ((kind & EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) != 0)
{
flags |= ModifierFlags.Sealed;
}
if ((kind & EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew) != 0)
{
flags |= ModifierFlags.New;
}
}
return member.UpdateModifiers(flags);
}
public override bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
var member = (MemberDeclarationSyntax)memberNode;
return (member.GetModifierFlags() & ModifierFlags.Abstract) != 0;
}
public override SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
if (!(memberNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
var flags = member.GetModifierFlags();
if (value)
{
flags |= ModifierFlags.Abstract;
}
else
{
flags &= ~ModifierFlags.Abstract;
}
return member.UpdateModifiers(flags);
}
public override bool GetIsConstant(SyntaxNode variableNode)
{
Debug.Assert(variableNode is MemberDeclarationSyntax ||
variableNode is VariableDeclaratorSyntax);
if (variableNode is EnumMemberDeclarationSyntax)
{
return true;
}
if (!(GetNodeWithModifiers(variableNode) is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
// C# legacy Code Model returns true for readonly fields as well.
return (member.GetModifierFlags() & (ModifierFlags.Const | ModifierFlags.ReadOnly)) != 0;
}
public override SyntaxNode SetIsConstant(SyntaxNode variableNode, bool value)
{
Debug.Assert(variableNode is MemberDeclarationSyntax);
if (variableNode is EnumMemberDeclarationSyntax)
{
if (!value)
{
throw Exceptions.ThrowEFail();
}
return variableNode;
}
if (!(variableNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
if (GetIsConstant(member) == value)
{
return member;
}
var flags = member.GetModifierFlags();
if (value)
{
flags |= ModifierFlags.Const;
}
else
{
flags &= ~(ModifierFlags.Const | ModifierFlags.ReadOnly);
}
return member.UpdateModifiers(flags);
}
public override bool GetIsDefault(SyntaxNode propertyNode)
{
Debug.Assert(propertyNode is BasePropertyDeclarationSyntax);
if (!(propertyNode is BasePropertyDeclarationSyntax property))
{
throw Exceptions.ThrowEFail();
}
return property.IsKind(SyntaxKind.IndexerDeclaration);
}
public override SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value)
{
// The C# legacy Code Model throws this specific exception rather than a COM exception.
throw new InvalidOperationException();
}
public override bool GetIsGeneric(SyntaxNode memberNode)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
if (!(GetNodeWithModifiers(memberNode) is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
return member.GetArity() > 0;
}
public override bool GetIsPropertyStyleEvent(SyntaxNode eventNode)
{
Debug.Assert(eventNode is EventFieldDeclarationSyntax ||
eventNode is EventDeclarationSyntax);
return eventNode is EventDeclarationSyntax;
}
public override bool GetIsShared(SyntaxNode memberNode, ISymbol symbol)
{
Debug.Assert(memberNode is MemberDeclarationSyntax ||
memberNode is VariableDeclaratorSyntax);
if (!(GetNodeWithModifiers(memberNode) is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
return (member.GetModifierFlags() & ModifierFlags.Static) != 0;
}
public override SyntaxNode SetIsShared(SyntaxNode memberNode, bool value)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
if (!(memberNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
var flags = member.GetModifierFlags();
if (value)
{
flags |= ModifierFlags.Static;
}
else
{
flags &= ~ModifierFlags.Static;
}
return member.UpdateModifiers(flags);
}
public override EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode)
{
Debug.Assert(memberNode is BasePropertyDeclarationSyntax);
if (!(memberNode is BasePropertyDeclarationSyntax property))
{
throw Exceptions.ThrowEFail();
}
var hasGetter = property.AccessorList != null && property.AccessorList.Accessors.Any(SyntaxKind.GetAccessorDeclaration);
var hasSetter = property.AccessorList != null && property.AccessorList.Accessors.Any(SyntaxKind.SetAccessorDeclaration);
if (!hasGetter && !hasSetter)
{
var expressionBody = property.GetExpressionBody();
if (expressionBody != null)
{
hasGetter = true;
}
}
if (hasGetter && hasSetter)
{
return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite;
}
else if (hasSetter)
{
return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindWriteOnly;
}
else if (hasGetter)
{
return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadOnly;
}
else
{
return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite;
}
}
public override SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol)
{
Debug.Assert(node is MemberDeclarationSyntax ||
node is ParameterSyntax);
TypeSyntax oldType;
if (node is MemberDeclarationSyntax memberDeclaration)
{
oldType = memberDeclaration.GetMemberType();
}
else if (node is ParameterSyntax parameter)
{
oldType = parameter.Type;
}
else
{
throw Exceptions.ThrowEFail();
}
if (oldType == null)
{
throw Exceptions.ThrowEFail();
}
var typeName = typeSymbol.ToDisplayString(s_setTypeFormat);
var newType = SyntaxFactory.ParseTypeName(typeName);
return node.ReplaceNode(oldType, newType);
}
private Document Delete(Document document, VariableDeclaratorSyntax node)
{
var fieldDeclaration = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>();
// If we won't have anything left, then just delete the whole declaration
if (fieldDeclaration.Declaration.Variables.Count == 1)
{
return Delete(document, fieldDeclaration);
}
else
{
var newFieldDeclaration = fieldDeclaration.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
return document.ReplaceNodeSynchronously(fieldDeclaration, newFieldDeclaration, CancellationToken.None);
}
}
private Document Delete(Document document, EnumMemberDeclarationSyntax node)
{
var enumDeclaration = (EnumDeclarationSyntax)node.Parent;
var members = enumDeclaration.Members;
var newMembers = members.Remove(node);
var newEnumDeclaration = enumDeclaration.WithMembers(newMembers);
// If we're removing the last enum member, we may need to move any trailing trivia
// to the enum member that comes before it.
var memberIndex = members.IndexOf(node);
if (memberIndex == members.Count - 1 && newMembers.Count > 0)
{
var trailingTrivia = node.GetTrailingTrivia();
var lastMember = newEnumDeclaration.Members.Last();
newEnumDeclaration = newEnumDeclaration.ReplaceNode(lastMember, lastMember.WithTrailingTrivia(trailingTrivia));
}
return document.ReplaceNodeSynchronously(enumDeclaration, newEnumDeclaration, CancellationToken.None);
}
private Document Delete(Document document, AttributeSyntax node)
{
var attributeList = node.FirstAncestorOrSelf<AttributeListSyntax>();
// If we don't have anything left, then just delete the whole attribute list.
if (attributeList.Attributes.Count == 1)
{
var text = document.GetTextSynchronously(CancellationToken.None);
// Note that we want to keep all leading trivia and delete all trailing trivia.
var deletionStart = attributeList.SpanStart;
var deletionEnd = attributeList.FullSpan.End;
text = text.Replace(TextSpan.FromBounds(deletionStart, deletionEnd), string.Empty);
return document.WithText(text);
}
else
{
var newAttributeList = attributeList.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
return document.ReplaceNodeSynchronously(attributeList, newAttributeList, CancellationToken.None);
}
}
private Document Delete(Document document, AttributeArgumentSyntax node)
{
var argumentList = node.FirstAncestorOrSelf<AttributeArgumentListSyntax>();
var newArgumentList = argumentList.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
return document.ReplaceNodeSynchronously(argumentList, newArgumentList, CancellationToken.None);
}
private Document Delete(Document document, ParameterSyntax node)
{
var parameterList = node.FirstAncestorOrSelf<ParameterListSyntax>();
var newParameterList = parameterList.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
return document.ReplaceNodeSynchronously(parameterList, newParameterList, CancellationToken.None);
}
private Document DeleteMember(Document document, SyntaxNode node)
{
var text = document.GetTextSynchronously(CancellationToken.None);
// We want to delete all the leading trivia from the node back to,
// but not including:
// * the first preprocessor directive
// - or -
// * the first comment after a white-space only line
// We also want to delete all the trailing trivia
var deletionEnd = node.FullSpan.End;
var deletionStart = node.SpanStart;
var contiguousEndOfLines = 0;
foreach (var trivia in node.GetLeadingTrivia().Reverse())
{
if (trivia.IsDirective)
{
break;
}
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
if (contiguousEndOfLines > 0)
{
break;
}
else
{
contiguousEndOfLines++;
}
}
else if (trivia.Kind() != SyntaxKind.WhitespaceTrivia)
{
contiguousEndOfLines = 0;
}
deletionStart = trivia.FullSpan.Start;
}
text = text.Replace(TextSpan.FromBounds(deletionStart, deletionEnd), string.Empty);
return document.WithText(text);
}
public override Document Delete(Document document, SyntaxNode node)
=> node.Kind() switch
{
SyntaxKind.VariableDeclarator => Delete(document, (VariableDeclaratorSyntax)node),
SyntaxKind.EnumMemberDeclaration => Delete(document, (EnumMemberDeclarationSyntax)node),
SyntaxKind.Attribute => Delete(document, (AttributeSyntax)node),
SyntaxKind.AttributeArgument => Delete(document, (AttributeArgumentSyntax)node),
SyntaxKind.Parameter => Delete(document, (ParameterSyntax)node),
_ => DeleteMember(document, node),
};
public override string GetMethodXml(SyntaxNode node, SemanticModel semanticModel)
{
if (!(node is MethodDeclarationSyntax methodDeclaration))
{
throw Exceptions.ThrowEUnexpected();
}
return MethodXmlBuilder.Generate(methodDeclaration, semanticModel);
}
public override string GetInitExpression(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.EnumMemberDeclaration:
var enumMemberDeclaration = (EnumMemberDeclarationSyntax)node;
return enumMemberDeclaration.EqualsValue?.Value.ToString();
case SyntaxKind.VariableDeclarator:
var variableDeclarator = (VariableDeclaratorSyntax)node;
return variableDeclarator.Initializer?.Value.ToString();
case SyntaxKind.Parameter:
var parameter = (ParameterSyntax)node;
return parameter.Default?.Value.ToString();
default:
throw Exceptions.ThrowEFail();
}
}
public override SyntaxNode AddInitExpression(SyntaxNode node, string value)
{
switch (node.Kind())
{
case SyntaxKind.EnumMemberDeclaration:
{
var enumMemberDeclaration = (EnumMemberDeclarationSyntax)node;
if (string.IsNullOrWhiteSpace(value))
{
return enumMemberDeclaration.WithEqualsValue(null);
}
var expression = SyntaxFactory.ParseExpression(value);
var equalsValueClause = enumMemberDeclaration.EqualsValue != null
? enumMemberDeclaration.EqualsValue.WithValue(expression)
: SyntaxFactory.EqualsValueClause(expression);
return enumMemberDeclaration.WithEqualsValue(equalsValueClause);
}
case SyntaxKind.VariableDeclarator:
{
var variableDeclarator = (VariableDeclaratorSyntax)node;
if (string.IsNullOrWhiteSpace(value))
{
return variableDeclarator.WithInitializer(null);
}
var expression = SyntaxFactory.ParseExpression(value);
var equalsValueClause = variableDeclarator.Initializer != null
? variableDeclarator.Initializer.WithValue(expression)
: SyntaxFactory.EqualsValueClause(expression);
return variableDeclarator.WithInitializer(equalsValueClause);
}
case SyntaxKind.Parameter:
{
var parameter = (ParameterSyntax)node;
if (string.IsNullOrWhiteSpace(value))
{
return parameter.WithDefault(null);
}
var expression = SyntaxFactory.ParseExpression(value);
var equalsValueClause = parameter.Default != null
? parameter.Default.WithValue(expression)
: SyntaxFactory.EqualsValueClause(expression);
return parameter.WithDefault(equalsValueClause);
}
default:
throw Exceptions.ThrowEFail();
}
}
public override CodeGenerationDestination GetDestination(SyntaxNode node)
=> CSharpCodeGenerationHelpers.GetDestination(node);
protected override Accessibility GetDefaultAccessibility(SymbolKind targetSymbolKind, CodeGenerationDestination destination)
{
switch (targetSymbolKind)
{
case SymbolKind.Field:
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Event:
return Accessibility.Private;
case SymbolKind.NamedType:
switch (destination)
{
case CodeGenerationDestination.ClassType:
case CodeGenerationDestination.EnumType:
case CodeGenerationDestination.InterfaceType:
case CodeGenerationDestination.StructType:
return Accessibility.Private;
default:
return Accessibility.Internal;
}
default:
Debug.Fail("Invalid symbol kind: " + targetSymbolKind);
throw Exceptions.ThrowEFail();
}
}
protected override ITypeSymbol GetTypeSymbolFromPartialName(string partialName, SemanticModel semanticModel, int position)
{
var parsedTypeName = SyntaxFactory.ParseTypeName(partialName);
return semanticModel.GetSpeculativeTypeInfo(position, parsedTypeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
}
public override ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation)
{
ITypeSymbol typeSymbol = compilation.GetTypeByMetadataName(fullName);
if (typeSymbol == null)
{
var parsedTypeName = SyntaxFactory.ParseTypeName(fullName);
// Check to see if the name we parsed has any skipped text. If it does, don't bother trying to
// speculatively bind it because we'll likely just get the wrong thing since we found a bunch
// of non-sensical tokens.
if (parsedTypeName.ContainsSkippedText)
{
return null;
}
// If we couldn't get the name, we just grab the first tree in the compilation to
// speculatively bind at position zero. However, if there *aren't* any trees, we fork the
// compilation with an empty tree for the purposes of speculative binding.
//
// I'm a bad person.
var tree = compilation.SyntaxTrees.FirstOrDefault();
if (tree == null)
{
tree = SyntaxFactory.ParseSyntaxTree("");
compilation = compilation.AddSyntaxTrees(tree);
}
var semanticModel = compilation.GetSemanticModel(tree);
typeSymbol = semanticModel.GetSpeculativeTypeInfo(0, parsedTypeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
}
if (typeSymbol == null)
{
Debug.Fail("Could not find type: " + fullName);
throw new ArgumentException();
}
return typeSymbol;
}
public override SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type)
{
return SyntaxFactory.ReturnStatement(
SyntaxFactory.DefaultExpression(
SyntaxFactory.ParseTypeName(type.ToDisplayString())));
}
protected override int GetAttributeIndexInContainer(SyntaxNode containerNode, Func<SyntaxNode, bool> predicate)
{
var attributes = GetAttributeNodes(containerNode).ToArray();
var index = 0;
while (index < attributes.Length)
{
var attribute = (AttributeSyntax)attributes[index];
if (predicate(attribute))
{
var attributeDeclaration = (AttributeListSyntax)attribute.Parent;
// If this attribute is part of a declaration with multiple attributes,
// make sure to return the index of the last attribute in the declaration.
if (attributeDeclaration.Attributes.Count > 1)
{
var indexOfAttributeInDeclaration = attributeDeclaration.Attributes.IndexOf(attribute);
return index + (attributeDeclaration.Attributes.Count - indexOfAttributeInDeclaration);
}
return index + 1;
}
index++;
}
return -1;
}
protected override int GetAttributeArgumentIndexInContainer(SyntaxNode containerNode, Func<SyntaxNode, bool> predicate)
{
var attributeArguments = GetAttributeArgumentNodes(containerNode).ToArray();
for (var index = 0; index < attributeArguments.Length; index++)
{
if (predicate(attributeArguments[index]))
{
return index + 1;
}
}
return -1;
}
protected override int GetImportIndexInContainer(SyntaxNode containerNode, Func<SyntaxNode, bool> predicate)
{
var imports = GetImportNodes(containerNode).ToArray();
for (var index = 0; index < imports.Length; index++)
{
if (predicate(imports[index]))
{
return index + 1;
}
}
return -1;
}
protected override int GetParameterIndexInContainer(SyntaxNode containerNode, Func<SyntaxNode, bool> predicate)
{
var parameters = GetParameterNodes(containerNode).ToArray();
for (var index = 0; index < parameters.Length; index++)
{
if (predicate(parameters[index]))
{
return index + 1;
}
}
return -1;
}
protected override int GetMemberIndexInContainer(SyntaxNode containerNode, Func<SyntaxNode, bool> predicate)
{
var members = GetLogicalMemberNodes(containerNode).ToArray();
var index = 0;
while (index < members.Length)
{
var member = members[index];
if (predicate(member))
{
// If a variable declarator was specified, make sure we return
// the index of the last variable declarator in the parenting field declaration.
if (member.IsKind(SyntaxKind.VariableDeclarator, out VariableDeclaratorSyntax variableDeclarator))
{
var variableDeclaration = (VariableDeclarationSyntax)member.Parent;
var indexOfDeclaratorInField = variableDeclaration.Variables.IndexOf(variableDeclarator);
return index + (variableDeclaration.Variables.Count - indexOfDeclaratorInField);
}
// Note: we always return the item *after* this index.
return index + 1;
}
index++;
}
return -1;
}
protected override SyntaxNode GetFieldFromVariableNode(SyntaxNode node)
{
return node.Kind() == SyntaxKind.VariableDeclarator
? node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>()
: node;
}
protected override SyntaxNode GetVariableFromFieldNode(SyntaxNode finalNode)
{
// Work around the fact that code model really deals in terms of variable declarators
return finalNode is BaseFieldDeclarationSyntax
? ((BaseFieldDeclarationSyntax)finalNode).Declaration.Variables.Single()
: finalNode;
}
protected override SyntaxNode GetAttributeFromAttributeDeclarationNode(SyntaxNode node)
{
return node is AttributeListSyntax
? ((AttributeListSyntax)node).Attributes.First()
: node;
}
protected override TextSpan GetSpanToFormat(SyntaxNode root, TextSpan span)
{
var startToken = root.FindToken(span.Start).GetPreviousToken();
if (startToken.Kind() == SyntaxKind.OpenBraceToken)
{
startToken = startToken.GetPreviousToken();
}
var endToken = root.FindToken(span.End).GetNextToken();
if (endToken.Kind() == SyntaxKind.CloseBraceToken)
{
endToken = endToken.GetPreviousToken();
}
startToken = GetTokenWithoutAnnotation(startToken, t => t.GetPreviousToken());
endToken = GetTokenWithoutAnnotation(endToken, t => t.GetNextToken());
return GetEncompassingSpan(root, startToken, endToken);
}
protected SyntaxNode InsertMemberNodeIntoContainerCore(int index, SyntaxNode member, SyntaxNode container)
{
if (container is CompilationUnitSyntax compilationUnit)
{
var newMembers = compilationUnit.Members.Insert(index, (MemberDeclarationSyntax)member);
return compilationUnit.WithMembers(newMembers);
}
else if (container is BaseNamespaceDeclarationSyntax namespaceDeclaration)
{
var newMembers = namespaceDeclaration.Members.Insert(index, (MemberDeclarationSyntax)member);
return namespaceDeclaration.WithMembers(newMembers);
}
else if (container is TypeDeclarationSyntax typeDeclaration)
{
var newMembers = typeDeclaration.Members.Insert(index, (MemberDeclarationSyntax)member);
return typeDeclaration.WithMembers(newMembers);
}
else if (container is EnumDeclarationSyntax enumDeclaration)
{
// If we're inserting at the end of the list of enum members, we may need to strip the trailing
// line from the last enum member and add it to the separator that comes after it.
if (index > 0 && index == enumDeclaration.Members.Count)
{
var lastMember = enumDeclaration.Members[index - 1];
var trailingTrivia = lastMember.GetTrailingTrivia();
enumDeclaration = enumDeclaration.ReplaceNode(lastMember, lastMember.WithTrailingTrivia(SyntaxTriviaList.Empty));
var newMembers = enumDeclaration.Members.Insert(index, (EnumMemberDeclarationSyntax)member);
enumDeclaration = enumDeclaration.WithMembers(newMembers);
var separator = enumDeclaration.Members.GetSeparator(index - 1);
return enumDeclaration.ReplaceToken(separator, separator.WithTrailingTrivia(trailingTrivia));
}
else
{
var newMembers = enumDeclaration.Members.Insert(index, (EnumMemberDeclarationSyntax)member);
return enumDeclaration.WithMembers(newMembers);
}
}
throw Exceptions.ThrowEFail();
}
private static MemberDeclarationSyntax GetMember(SyntaxNode container, int index)
{
if (container is CompilationUnitSyntax compilationUnit)
{
return compilationUnit.Members[index];
}
else if (container is BaseNamespaceDeclarationSyntax namespaceDeclaration)
{
return namespaceDeclaration.Members[index];
}
else if (container is TypeDeclarationSyntax typeDeclaration)
{
return typeDeclaration.Members[index];
}
else if (container is EnumDeclarationSyntax enumDeclaration)
{
return enumDeclaration.Members[index];
}
throw Exceptions.ThrowEFail();
}
private SyntaxNode EnsureAfterEndRegion(int index, SyntaxNode container)
{
// If the next token after our member has only whitespace and #endregion as leading
// trivia, we'll move that to be leading trivia of our member.
var newContainer = container;
var newMember = GetMember(newContainer, index);
var lastToken = newMember.GetLastToken();
var nextToken = lastToken.GetNextToken();
var triviaList = nextToken.LeadingTrivia;
var lastNonWhitespaceTrivia = triviaList.LastOrDefault(trivia => !trivia.IsWhitespaceOrEndOfLine());
if (lastNonWhitespaceTrivia.Kind() == SyntaxKind.EndRegionDirectiveTrivia)
{
newContainer = newContainer
.ReplaceToken(nextToken, nextToken.WithLeadingTrivia(SyntaxTriviaList.Empty));
newMember = GetMember(newContainer, index);
var firstToken = newMember.GetFirstToken();
newContainer = newContainer
.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(triviaList));
}
return newContainer;
}
protected override SyntaxNode InsertMemberNodeIntoContainer(int index, SyntaxNode member, SyntaxNode container)
{
var newContainer = InsertMemberNodeIntoContainerCore(index, member, container);
newContainer = EnsureAfterEndRegion(index, newContainer);
return newContainer;
}
protected override SyntaxNode InsertAttributeArgumentIntoContainer(int index, SyntaxNode attributeArgument, SyntaxNode container)
{
if (container is AttributeSyntax attribute)
{
var argumentList = attribute.ArgumentList;
AttributeArgumentListSyntax newArgumentList;
if (argumentList == null)
{
newArgumentList = SyntaxFactory.AttributeArgumentList(
SyntaxFactory.SingletonSeparatedList(
(AttributeArgumentSyntax)attributeArgument));
}
else
{
var newArguments = argumentList.Arguments.Insert(index, (AttributeArgumentSyntax)attributeArgument);
newArgumentList = argumentList.WithArguments(newArguments);
}
return attribute.WithArgumentList(newArgumentList);
}
throw Exceptions.ThrowEFail();
}
protected override SyntaxNode InsertAttributeListIntoContainer(int index, SyntaxNode list, SyntaxNode container)
{
// If the attribute list is being inserted at the first index and the container is not the compilation unit, copy leading trivia
// to the list that is being inserted.
if (index == 0 && !(container is CompilationUnitSyntax))
{
var firstToken = container.GetFirstToken();
if (firstToken.HasLeadingTrivia)
{
var trivia = firstToken.LeadingTrivia;
container = container.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(SyntaxTriviaList.Empty));
list = list.WithLeadingTrivia(trivia);
}
}
if (container is CompilationUnitSyntax compilationUnit)
{
var newAttributeLists = compilationUnit.AttributeLists.Insert(index, (AttributeListSyntax)list);
return compilationUnit.WithAttributeLists(newAttributeLists);
}
else if (container is EnumDeclarationSyntax enumDeclaration)
{
var newAttributeLists = enumDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return enumDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is ClassDeclarationSyntax classDeclaration)
{
var newAttributeLists = classDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return classDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is StructDeclarationSyntax structDeclaration)
{
var newAttributeLists = structDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return structDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is InterfaceDeclarationSyntax interfaceDeclaration)
{
var newAttributeLists = interfaceDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return interfaceDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is MethodDeclarationSyntax method)
{
var newAttributeLists = method.AttributeLists.Insert(index, (AttributeListSyntax)list);
return method.WithAttributeLists(newAttributeLists);
}
else if (container is OperatorDeclarationSyntax operationDeclaration)
{
var newAttributeLists = operationDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return operationDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is ConversionOperatorDeclarationSyntax conversion)
{
var newAttributeLists = conversion.AttributeLists.Insert(index, (AttributeListSyntax)list);
return conversion.WithAttributeLists(newAttributeLists);
}
else if (container is ConstructorDeclarationSyntax constructor)
{
var newAttributeLists = constructor.AttributeLists.Insert(index, (AttributeListSyntax)list);
return constructor.WithAttributeLists(newAttributeLists);
}
else if (container is DestructorDeclarationSyntax destructor)
{
var newAttributeLists = destructor.AttributeLists.Insert(index, (AttributeListSyntax)list);
return destructor.WithAttributeLists(newAttributeLists);
}
else if (container is PropertyDeclarationSyntax property)
{
var newAttributeLists = property.AttributeLists.Insert(index, (AttributeListSyntax)list);
return property.WithAttributeLists(newAttributeLists);
}
else if (container is EventDeclarationSyntax eventDeclaration)
{
var newAttributeLists = eventDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return eventDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is IndexerDeclarationSyntax indexer)
{
var newAttributeLists = indexer.AttributeLists.Insert(index, (AttributeListSyntax)list);
return indexer.WithAttributeLists(newAttributeLists);
}
else if (container is FieldDeclarationSyntax field)
{
var newAttributeLists = field.AttributeLists.Insert(index, (AttributeListSyntax)list);
return field.WithAttributeLists(newAttributeLists);
}
else if (container is EventFieldDeclarationSyntax eventFieldDeclaration)
{
var newAttributeLists = eventFieldDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return eventFieldDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is DelegateDeclarationSyntax delegateDeclaration)
{
var newAttributeLists = delegateDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return delegateDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is EnumMemberDeclarationSyntax member)
{
var newAttributeLists = member.AttributeLists.Insert(index, (AttributeListSyntax)list);
return member.WithAttributeLists(newAttributeLists);
}
else if (container is ParameterSyntax parameter)
{
var newAttributeLists = parameter.AttributeLists.Insert(index, (AttributeListSyntax)list);
return parameter.WithAttributeLists(newAttributeLists);
}
else if (container is VariableDeclaratorSyntax ||
container is VariableDeclarationSyntax)
{
return InsertAttributeListIntoContainer(index, list, container.Parent);
}
throw Exceptions.ThrowEUnexpected();
}
protected override SyntaxNode InsertImportIntoContainer(int index, SyntaxNode importNode, SyntaxNode container)
{
var import = (UsingDirectiveSyntax)importNode;
if (container is CompilationUnitSyntax compilationUnit)
{
var usingsList = compilationUnit.Usings.Insert(index, import);
return compilationUnit.WithUsings(usingsList);
}
throw Exceptions.ThrowEUnexpected();
}
protected override SyntaxNode InsertParameterIntoContainer(int index, SyntaxNode parameter, SyntaxNode container)
{
if (container is BaseMethodDeclarationSyntax method)
{
var parameterList = method.ParameterList.Parameters.Insert(index, (ParameterSyntax)parameter);
return method.WithParameterList(method.ParameterList.WithParameters(parameterList));
}
else if (container is IndexerDeclarationSyntax indexer)
{
var parameterList = indexer.ParameterList.Parameters.Insert(index, (ParameterSyntax)parameter);
return indexer.WithParameterList(indexer.ParameterList.WithParameters(parameterList));
}
else if (container is DelegateDeclarationSyntax delegateDeclaration)
{
var parameterList = delegateDeclaration.ParameterList.Parameters.Insert(index, (ParameterSyntax)parameter);
return delegateDeclaration.WithParameterList(delegateDeclaration.ParameterList.WithParameters(parameterList));
}
throw Exceptions.ThrowEUnexpected();
}
protected override bool IsCodeModelNode(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.CompilationUnit:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMemberDeclaration:
case SyntaxKind.FieldDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.UsingDirective:
return true;
default:
return false;
}
}
public override bool IsNamespace(SyntaxNode node)
=> node is BaseNamespaceDeclarationSyntax;
public override bool IsType(SyntaxNode node)
{
return node.IsKind(SyntaxKind.ClassDeclaration)
|| node.IsKind(SyntaxKind.InterfaceDeclaration)
|| node.IsKind(SyntaxKind.StructDeclaration)
|| node.IsKind(SyntaxKind.EnumDeclaration)
|| node.IsKind(SyntaxKind.DelegateDeclaration);
}
private static bool IsAutoImplementedProperty(PropertyDeclarationSyntax propertyDeclaration)
{
if (propertyDeclaration.IsParentKind(SyntaxKind.InterfaceDeclaration))
{
return false;
}
var modifierFlags = propertyDeclaration.GetModifierFlags();
if ((modifierFlags & ModifierFlags.Abstract) != 0 ||
(modifierFlags & ModifierFlags.Extern) != 0)
{
return false;
}
if (propertyDeclaration.AccessorList == null)
{
return false;
}
AccessorDeclarationSyntax getAccessor = null;
AccessorDeclarationSyntax setAccessor = null;
foreach (var accessor in propertyDeclaration.AccessorList.Accessors)
{
switch (accessor.Kind())
{
case SyntaxKind.GetAccessorDeclaration:
if (getAccessor == null)
{
getAccessor = accessor;
}
break;
case SyntaxKind.SetAccessorDeclaration:
if (setAccessor == null)
{
setAccessor = accessor;
}
break;
}
}
if (getAccessor == null || setAccessor == null)
{
return false;
}
return getAccessor.Body == null && setAccessor.Body == null;
}
private static bool IsExtensionMethod(MethodDeclarationSyntax methodDeclaration)
{
if (!methodDeclaration.IsParentKind(SyntaxKind.ClassDeclaration, out ClassDeclarationSyntax classDecl) ||
!classDecl.Modifiers.Any(SyntaxKind.StaticKeyword))
{
return false;
}
if (methodDeclaration.ParameterList == null ||
methodDeclaration.ParameterList.Parameters.Count == 0)
{
return false;
}
return methodDeclaration.ParameterList.Parameters[0].Modifiers.Any(SyntaxKind.ThisKeyword);
}
private static bool IsPartialMethod(MethodDeclarationSyntax methodDeclaration)
=> methodDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword);
public override string[] GetFunctionExtenderNames()
=> new[] { ExtenderNames.ExtensionMethod, ExtenderNames.PartialMethod };
public override object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol)
{
if (node == null || node.Kind() != SyntaxKind.MethodDeclaration ||
symbol == null || symbol.Kind != SymbolKind.Method)
{
throw Exceptions.ThrowEUnexpected();
}
if (StringComparer.Ordinal.Equals(name, ExtenderNames.PartialMethod))
{
var methodDeclaration = (MethodDeclarationSyntax)node;
var isPartial = IsPartialMethod(methodDeclaration);
var isDeclaration = false;
var hasOtherPart = false;
if (isPartial)
{
var methodSymbol = (IMethodSymbol)symbol;
isDeclaration = methodSymbol.PartialDefinitionPart == null;
hasOtherPart = isDeclaration
? methodSymbol.PartialImplementationPart != null
: methodSymbol.PartialDefinitionPart != null;
}
return PartialMethodExtender.Create(isPartial, isDeclaration, hasOtherPart);
}
else if (StringComparer.Ordinal.Equals(name, ExtenderNames.ExtensionMethod))
{
var methodDeclaration = (MethodDeclarationSyntax)node;
var isExtension = IsExtensionMethod(methodDeclaration);
return ExtensionMethodExtender.Create(isExtension);
}
throw Exceptions.ThrowEFail();
}
public override string[] GetPropertyExtenderNames()
=> new[] { ExtenderNames.AutoImplementedProperty };
public override object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol)
{
if (node == null || node.Kind() != SyntaxKind.PropertyDeclaration ||
symbol == null || symbol.Kind != SymbolKind.Property)
{
throw Exceptions.ThrowEUnexpected();
}
if (StringComparer.Ordinal.Equals(name, ExtenderNames.AutoImplementedProperty))
{
var propertyDeclaration = (PropertyDeclarationSyntax)node;
var isAutoImplemented = IsAutoImplementedProperty(propertyDeclaration);
return AutoImplementedPropertyExtender.Create(isAutoImplemented);
}
throw Exceptions.ThrowEFail();
}
public override string[] GetExternalTypeExtenderNames()
=> new[] { ExtenderNames.ExternalLocation };
public override object GetExternalTypeExtender(string name, string externalLocation)
{
Debug.Assert(externalLocation != null);
if (StringComparer.Ordinal.Equals(name, ExtenderNames.ExternalLocation))
{
return CodeTypeLocationExtender.Create(externalLocation);
}
throw Exceptions.ThrowEFail();
}
public override string[] GetTypeExtenderNames()
=> Array.Empty<string>();
public override object GetTypeExtender(string name, AbstractCodeType symbol)
=> throw Exceptions.ThrowEFail();
protected override bool AddBlankLineToMethodBody(SyntaxNode node, SyntaxNode newNode)
{
return node is MethodDeclarationSyntax methodDeclaration
&& methodDeclaration.Body == null
&& newNode is MethodDeclarationSyntax newMethodDeclaration
&& newMethodDeclaration.Body != null;
}
private static TypeDeclarationSyntax InsertIntoBaseList(TypeDeclarationSyntax typeDeclaration, ITypeSymbol typeSymbol, SemanticModel semanticModel, int insertionIndex)
{
var position = typeDeclaration.SpanStart;
var identifier = typeDeclaration.Identifier;
if (identifier.HasTrailingTrivia)
{
typeDeclaration = typeDeclaration.WithIdentifier(
identifier.WithTrailingTrivia(identifier.TrailingTrivia.SkipWhile(t => t.IsWhitespaceOrEndOfLine())));
}
var typeName = SyntaxFactory.ParseTypeName(typeSymbol.ToMinimalDisplayString(semanticModel, position));
var baseList = typeDeclaration.BaseList != null
? typeDeclaration.BaseList.WithTypes(typeDeclaration.BaseList.Types.Insert(insertionIndex, SyntaxFactory.SimpleBaseType(typeName)))
: SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList((BaseTypeSyntax)SyntaxFactory.SimpleBaseType(typeName)));
return typeDeclaration.WithBaseList(baseList);
}
public override bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol)
{
if (node.IsKind(SyntaxKind.ClassDeclaration))
{
return typeSymbol.TypeKind == TypeKind.Class;
}
else if (node.IsKind(SyntaxKind.InterfaceDeclaration))
{
return typeSymbol.TypeKind == TypeKind.Interface;
}
return false;
}
public override SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position)
{
if (!node.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.InterfaceDeclaration))
{
throw Exceptions.ThrowEFail();
}
var typeDeclaration = (TypeDeclarationSyntax)node;
var baseCount = typeDeclaration.BaseList != null
? typeDeclaration.BaseList.Types.Count
: 0;
int insertionIndex;
if (typeDeclaration.IsKind(SyntaxKind.ClassDeclaration))
{
insertionIndex = 0;
}
else if (position != null)
{
insertionIndex = position.Value;
if (insertionIndex > baseCount)
{
throw Exceptions.ThrowEInvalidArg();
}
}
else
{
insertionIndex = baseCount;
}
return InsertIntoBaseList(typeDeclaration, typeSymbol, semanticModel, insertionIndex);
}
public override SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel)
{
if (!node.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.InterfaceDeclaration))
{
throw Exceptions.ThrowEFail();
}
var typeDeclaration = (TypeDeclarationSyntax)node;
if (typeDeclaration.BaseList == null ||
typeDeclaration.BaseList.Types.Count == 0)
{
throw Exceptions.ThrowEInvalidArg();
}
var isFirst = true;
BaseTypeSyntax baseType = null;
foreach (var type in typeDeclaration.BaseList.Types)
{
if (!isFirst && node.IsKind(SyntaxKind.ClassDeclaration))
{
break;
}
var typeInfo = semanticModel.GetTypeInfo(type.Type, CancellationToken.None);
if (typeInfo.Type != null &&
typeInfo.Type.Equals(typeSymbol))
{
baseType = type;
break;
}
isFirst = false;
}
if (baseType == null)
{
throw Exceptions.ThrowEInvalidArg();
}
var newTypes = typeDeclaration.BaseList.Types.Remove(baseType);
var newBaseList = typeDeclaration.BaseList.WithTypes(newTypes);
if (newBaseList.Types.Count == 0)
{
newBaseList = null;
}
return typeDeclaration.WithBaseList(newBaseList);
}
public override bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol)
{
if (node.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration))
{
return typeSymbol.TypeKind == TypeKind.Interface;
}
return false;
}
public override SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position)
{
if (!node.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration))
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.Kind != SymbolKind.NamedType ||
typeSymbol.TypeKind != TypeKind.Interface)
{
throw Exceptions.ThrowEInvalidArg();
}
var typeDeclaration = (TypeDeclarationSyntax)node;
var baseCount = typeDeclaration.BaseList != null
? typeDeclaration.BaseList.Types.Count
: 0;
int insertionIndex;
if (position != null)
{
insertionIndex = position.Value;
if (insertionIndex > baseCount)
{
throw Exceptions.ThrowEInvalidArg();
}
}
else
{
insertionIndex = baseCount;
}
return InsertIntoBaseList(typeDeclaration, typeSymbol, semanticModel, insertionIndex);
}
public override SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel)
{
if (!node.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration))
{
throw Exceptions.ThrowEFail();
}
var typeDeclaration = (TypeDeclarationSyntax)node;
if (typeDeclaration.BaseList == null ||
typeDeclaration.BaseList.Types.Count == 0)
{
throw Exceptions.ThrowEInvalidArg();
}
BaseTypeSyntax baseType = null;
foreach (var type in typeDeclaration.BaseList.Types)
{
var typeInfo = semanticModel.GetTypeInfo(type.Type, CancellationToken.None);
if (typeInfo.Type != null &&
typeInfo.Type.Equals(typeSymbol))
{
baseType = type;
break;
}
}
if (baseType == null)
{
throw Exceptions.ThrowEInvalidArg();
}
var newTypes = typeDeclaration.BaseList.Types.Remove(baseType);
var newBaseList = typeDeclaration.BaseList.WithTypes(newTypes);
if (newBaseList.Types.Count == 0)
{
newBaseList = null;
}
return typeDeclaration.WithBaseList(newBaseList);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders;
using Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.MethodXml;
using Microsoft.VisualStudio.LanguageServices.CSharp.Utilities;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel
{
internal partial class CSharpCodeModelService : AbstractCodeModelService
{
internal CSharpCodeModelService(
HostLanguageServices languageServiceProvider,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
IThreadingContext threadingContext)
: base(languageServiceProvider,
editorOptionsFactoryService,
refactorNotifyServices,
BlankLineInGeneratedMethodFormattingRule.Instance,
EndRegionFormattingRule.Instance,
threadingContext)
{
}
private static readonly SymbolDisplayFormat s_codeTypeRefAsFullNameFormat =
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.ExpandNullable);
private static readonly SymbolDisplayFormat s_codeTypeRefAsStringFormat =
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
private static readonly SymbolDisplayFormat s_externalNameFormat =
new(
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
parameterOptions: SymbolDisplayParameterOptions.IncludeName);
private static readonly SymbolDisplayFormat s_externalFullNameFormat =
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
parameterOptions: SymbolDisplayParameterOptions.IncludeName);
private static readonly SymbolDisplayFormat s_setTypeFormat =
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
private static bool IsNameableNode(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMemberDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.RecordStructDeclaration:
return true;
case SyntaxKind.VariableDeclarator:
// Could be a regular field or an event field.
return node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>() != null;
default:
return false;
}
}
public override EnvDTE.vsCMElement GetElementKind(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return EnvDTE.vsCMElement.vsCMElementClass;
default:
Debug.Fail("Unsupported element kind: " + node.Kind());
throw Exceptions.ThrowEInvalidArg();
}
}
public override bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope)
{
switch (node.Kind())
{
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementNamespace &&
node.Parent != null)
{
return true;
}
break;
case SyntaxKind.ClassDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementClass)
{
return true;
}
break;
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementFunction)
{
return true;
}
break;
case SyntaxKind.EnumMemberDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementVariable)
{
return true;
}
break;
case SyntaxKind.FieldDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementVariable)
{
return true;
}
break;
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementEvent)
{
return true;
}
break;
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementProperty)
{
return true;
}
break;
case SyntaxKind.Attribute:
if (scope == EnvDTE.vsCMElement.vsCMElementAttribute)
{
return true;
}
break;
case SyntaxKind.InterfaceDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementInterface)
{
return true;
}
break;
case SyntaxKind.DelegateDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementDelegate)
{
return true;
}
break;
case SyntaxKind.EnumDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementEnum)
{
return true;
}
break;
case SyntaxKind.StructDeclaration:
if (scope == EnvDTE.vsCMElement.vsCMElementStruct)
{
return true;
}
break;
case SyntaxKind.UsingDirective:
if (scope == EnvDTE.vsCMElement.vsCMElementImportStmt &&
((UsingDirectiveSyntax)node).Name != null)
{
return true;
}
break;
case SyntaxKind.VariableDeclaration:
case SyntaxKind.VariableDeclarator:
// The parent of a VariableDeclarator might be an event or
// a field declaration. If the parent matches the desired
// scope, then this node matches the scope as well.
return MatchesScope(node.Parent, scope);
case SyntaxKind.Parameter:
if (scope == EnvDTE.vsCMElement.vsCMElementParameter)
{
return true;
}
break;
default:
return false;
}
return false;
}
public override IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent)
{
// Only VB has Option statements
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
public override IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent)
=> parent switch
{
CompilationUnitSyntax compilationUnit => compilationUnit.Usings,
BaseNamespaceDeclarationSyntax baseNamespace => baseNamespace.Usings,
_ => SpecializedCollections.EmptyEnumerable<SyntaxNode>(),
};
private static IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxList<AttributeListSyntax> attributeDeclarationList)
{
foreach (var attributeDeclaration in attributeDeclarationList)
{
foreach (var attribute in attributeDeclaration.Attributes)
{
yield return attribute;
}
}
}
public override IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent)
{
if (parent is CompilationUnitSyntax compilationUnit)
{
return GetAttributeNodes(compilationUnit.AttributeLists);
}
else if (parent is BaseTypeDeclarationSyntax baseType)
{
return GetAttributeNodes(baseType.AttributeLists);
}
else if (parent is BaseMethodDeclarationSyntax baseMethod)
{
return GetAttributeNodes(baseMethod.AttributeLists);
}
else if (parent is BasePropertyDeclarationSyntax baseProperty)
{
return GetAttributeNodes(baseProperty.AttributeLists);
}
else if (parent is BaseFieldDeclarationSyntax baseField)
{
return GetAttributeNodes(baseField.AttributeLists);
}
else if (parent is DelegateDeclarationSyntax delegateDecl)
{
return GetAttributeNodes(delegateDecl.AttributeLists);
}
else if (parent is EnumMemberDeclarationSyntax enumMember)
{
return GetAttributeNodes(enumMember.AttributeLists);
}
else if (parent is ParameterSyntax parameter)
{
return GetAttributeNodes(parameter.AttributeLists);
}
else if (parent is VariableDeclaratorSyntax ||
parent is VariableDeclarationSyntax)
{
return GetAttributeNodes(parent.Parent);
}
else if (parent is AccessorDeclarationSyntax accessor)
{
return GetAttributeNodes(accessor.AttributeLists);
}
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
public override IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent)
{
if (parent is AttributeSyntax attribute)
{
if (attribute.ArgumentList == null)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
return attribute.ArgumentList.Arguments;
}
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
public override IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent)
{
// Only VB has Inherits statements
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
public override IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent)
{
// Only VB has Implements statements
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
private static bool IsContainerNode(SyntaxNode container) =>
container is CompilationUnitSyntax ||
container is BaseNamespaceDeclarationSyntax ||
container is BaseTypeDeclarationSyntax;
private static bool IsNamespaceOrTypeDeclaration(SyntaxNode node) =>
node is BaseNamespaceDeclarationSyntax ||
node is BaseTypeDeclarationSyntax ||
node is DelegateDeclarationSyntax;
private static IEnumerable<MemberDeclarationSyntax> GetChildMemberNodes(SyntaxNode container)
{
if (container is CompilationUnitSyntax compilationUnit)
{
foreach (var member in compilationUnit.Members)
{
if (IsNamespaceOrTypeDeclaration(member))
{
yield return member;
}
}
}
else if (container is BaseNamespaceDeclarationSyntax namespaceDecl)
{
foreach (var member in namespaceDecl.Members)
{
if (IsNamespaceOrTypeDeclaration(member))
{
yield return member;
}
}
}
else if (container is TypeDeclarationSyntax typeDecl)
{
foreach (var member in typeDecl.Members)
{
if (member.Kind() != SyntaxKind.NamespaceDeclaration)
{
yield return member;
}
}
}
else if (container is EnumDeclarationSyntax enumDecl)
{
foreach (var member in enumDecl.Members)
{
yield return member;
}
}
}
private static bool NodeIsSupported(bool test, SyntaxNode node)
=> !test || IsNameableNode(node);
/// <summary>
/// Retrieves the members of a specified <paramref name="container"/> node. The members that are
/// returned can be controlled by passing various parameters.
/// </summary>
/// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param>
/// <param name="includeSelf">If true, the container is returned as well.</param>
/// <param name="recursive">If true, members are recursed to return descendant members as well
/// as immediate children. For example, a namespace would return the namespaces and types within.
/// However, if <paramref name="recursive"/> is true, members with the namespaces and types would
/// also be returned.</param>
/// <param name="logicalFields">If true, field declarations are broken into their respective declarators.
/// For example, the field "int x, y" would return two declarators, one for x and one for y in place
/// of the field.</param>
/// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param>
public override IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes)
{
// Filter out all records from code model, they are not supported at all.
return GetMemberNodesWorker(container, includeSelf, recursive, logicalFields, onlySupportedNodes).Where(t => t is not RecordDeclarationSyntax);
}
private IEnumerable<SyntaxNode> GetMemberNodesWorker(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes)
{
if (!IsContainerNode(container))
{
yield break;
}
if (includeSelf && NodeIsSupported(onlySupportedNodes, container))
{
yield return container;
}
foreach (var member in GetChildMemberNodes(container))
{
if (member is BaseFieldDeclarationSyntax baseField)
{
// For fields, the 'logical' and 'supported' flags are intrinsically tied.
// * If 'logical' is true, only declarators should be returned, regardless of the value of 'supported'.
// * If 'logical' is false, the field should only be returned if 'supported' is also false.
if (logicalFields)
{
foreach (var declarator in baseField.Declaration.Variables)
{
// We know that variable declarators are supported, so there's no need to check them here.
yield return declarator;
}
}
else if (!onlySupportedNodes)
{
// Only return field declarations if the supported flag is false.
yield return member;
}
}
else if (NodeIsSupported(onlySupportedNodes, member))
{
yield return member;
}
if (recursive && IsContainerNode(member))
{
foreach (var innerMember in GetMemberNodes(member, includeSelf: false, recursive: true, logicalFields: logicalFields, onlySupportedNodes: onlySupportedNodes))
{
yield return innerMember;
}
}
}
}
public override string Language
{
get { return EnvDTE.CodeModelLanguageConstants.vsCMLanguageCSharp; }
}
public override string AssemblyAttributeString
{
get
{
return "assembly";
}
}
/// <summary>
/// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/>
/// </summary>
public override EnvDTE.CodeElement CreateInternalCodeElement(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNode node)
{
// Attributes, attribute arguments, parameters, imports directives, and
// accessor functions do not have their own node keys. Rather, they are
// based off their parents node keys and other data.
switch (node.Kind())
{
case SyntaxKind.Attribute:
return (EnvDTE.CodeElement)CreateInternalCodeAttribute(state, fileCodeModel, node);
case SyntaxKind.AttributeArgument:
return (EnvDTE.CodeElement)CreateInternalCodeAttributeArgument(state, fileCodeModel, (AttributeArgumentSyntax)node);
case SyntaxKind.Parameter:
return (EnvDTE.CodeElement)CreateInternalCodeParameter(state, fileCodeModel, (ParameterSyntax)node);
case SyntaxKind.UsingDirective:
return CreateInternalCodeImport(state, fileCodeModel, (UsingDirectiveSyntax)node);
}
if (IsAccessorNode(node))
{
return (EnvDTE.CodeElement)CreateInternalCodeAccessorFunction(state, fileCodeModel, node);
}
var nodeKey = GetNodeKey(node);
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
return (EnvDTE.CodeElement)CodeClass.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.InterfaceDeclaration:
return (EnvDTE.CodeElement)CodeInterface.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.StructDeclaration:
return (EnvDTE.CodeElement)CodeStruct.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.EnumDeclaration:
return (EnvDTE.CodeElement)CodeEnum.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.EnumMemberDeclaration:
return (EnvDTE.CodeElement)CodeVariable.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.DelegateDeclaration:
return (EnvDTE.CodeElement)CodeDelegate.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
return (EnvDTE.CodeElement)CodeFunction.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return (EnvDTE.CodeElement)CodeNamespace.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
return (EnvDTE.CodeElement)CodeProperty.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.EventDeclaration:
return (EnvDTE.CodeElement)CodeEvent.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
case SyntaxKind.VariableDeclarator:
var baseFieldDeclaration = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>();
if (baseFieldDeclaration != null)
{
if (baseFieldDeclaration.Kind() == SyntaxKind.FieldDeclaration)
{
return (EnvDTE.CodeElement)CodeVariable.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
}
else if (baseFieldDeclaration.Kind() == SyntaxKind.EventFieldDeclaration)
{
return (EnvDTE.CodeElement)CodeEvent.Create(state, fileCodeModel, nodeKey, (int)node.Kind());
}
}
throw Exceptions.ThrowEUnexpected();
default:
throw new InvalidOperationException();
}
}
public override EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return (EnvDTE.CodeElement)CodeNamespace.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.ClassDeclaration:
return (EnvDTE.CodeElement)CodeClass.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.InterfaceDeclaration:
return (EnvDTE.CodeElement)CodeInterface.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.StructDeclaration:
return (EnvDTE.CodeElement)CodeStruct.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.EnumDeclaration:
return (EnvDTE.CodeElement)CodeEnum.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.DelegateDeclaration:
return (EnvDTE.CodeElement)CodeDelegate.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
return (EnvDTE.CodeElement)CodeFunction.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
return (EnvDTE.CodeElement)CodeProperty.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.EventDeclaration:
return (EnvDTE.CodeElement)CodeEvent.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
case SyntaxKind.VariableDeclarator:
var eventFieldDeclaration = node.FirstAncestorOrSelf<EventFieldDeclarationSyntax>();
if (eventFieldDeclaration != null)
{
return (EnvDTE.CodeElement)CodeEvent.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
}
goto case SyntaxKind.EnumMemberDeclaration;
case SyntaxKind.EnumMemberDeclaration:
return (EnvDTE.CodeElement)CodeVariable.CreateUnknown(state, fileCodeModel, node.RawKind, GetName(node));
default:
throw Exceptions.ThrowEUnexpected();
}
}
public override EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel)
=> (EnvDTE.CodeElement)CodeNamespace.CreateUnknown(state, fileCodeModel, (int)SyntaxKind.NamespaceDeclaration, string.Empty);
public override EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type)
{
var project = state.Workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
var compilation = project.GetCompilationAsync().Result;
if (type is EnvDTE.vsCMTypeRef || type is int)
{
var specialType = GetSpecialType((EnvDTE.vsCMTypeRef)type);
return CodeTypeRef.Create(state, null, projectId, compilation.GetSpecialType(specialType));
}
string typeName;
object parent = null;
if (type is EnvDTE.CodeType codeType)
{
typeName = codeType.FullName;
parent = codeType;
}
else if (type is string str)
{
typeName = str;
}
else
{
throw Exceptions.ThrowEInvalidArg();
}
var typeSymbol = GetTypeSymbolFromFullName(typeName, compilation);
if (typeSymbol == null)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Unknown)
{
if (SyntaxFactsService.IsValidIdentifier(typeSymbol.Name))
{
throw Exceptions.ThrowEFail();
}
}
return CodeTypeRef.Create(state, parent, projectId, typeSymbol);
}
public override EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol)
{
if (typeSymbol.TypeKind == TypeKind.Array)
{
return EnvDTE.vsCMTypeRef.vsCMTypeRefArray;
}
else if (typeSymbol.TypeKind == TypeKind.Pointer)
{
return EnvDTE.vsCMTypeRef.vsCMTypeRefPointer;
}
else if (
typeSymbol.TypeKind == TypeKind.Dynamic ||
typeSymbol.TypeKind == TypeKind.Unknown)
{
return EnvDTE.vsCMTypeRef.vsCMTypeRefOther;
}
else
{
switch (typeSymbol.SpecialType)
{
case SpecialType.System_Void:
return EnvDTE.vsCMTypeRef.vsCMTypeRefVoid;
case SpecialType.System_String:
return EnvDTE.vsCMTypeRef.vsCMTypeRefString;
case SpecialType.System_Object:
return EnvDTE.vsCMTypeRef.vsCMTypeRefObject;
case SpecialType.System_Char:
return EnvDTE.vsCMTypeRef.vsCMTypeRefChar;
case SpecialType.System_Byte:
return EnvDTE.vsCMTypeRef.vsCMTypeRefByte;
case SpecialType.System_Boolean:
return EnvDTE.vsCMTypeRef.vsCMTypeRefBool;
case SpecialType.System_Int16:
return EnvDTE.vsCMTypeRef.vsCMTypeRefShort;
case SpecialType.System_Int32:
return EnvDTE.vsCMTypeRef.vsCMTypeRefInt;
case SpecialType.System_Int64:
return EnvDTE.vsCMTypeRef.vsCMTypeRefLong;
case SpecialType.System_Single:
return EnvDTE.vsCMTypeRef.vsCMTypeRefFloat;
case SpecialType.System_Double:
return EnvDTE.vsCMTypeRef.vsCMTypeRefDouble;
case SpecialType.System_Decimal:
return EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal;
case SpecialType.System_UInt16:
return (EnvDTE.vsCMTypeRef)EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedShort;
case SpecialType.System_UInt32:
return (EnvDTE.vsCMTypeRef)EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedInt;
case SpecialType.System_UInt64:
return (EnvDTE.vsCMTypeRef)EnvDTE80.vsCMTypeRef2.vsCMTypeRefUnsignedLong;
case SpecialType.System_SByte:
return (EnvDTE.vsCMTypeRef)EnvDTE80.vsCMTypeRef2.vsCMTypeRefSByte;
}
// Comment below is from native code
// The following are not supported
// vsCMTypeRefUnsignedChar - PT_UCHAR not in C# ??
// vsCMTypeRefReference - C++ specific
// vsCMTypeRefMCBoxedReference - C++ specific
}
if (typeSymbol.TypeKind == TypeKind.Class ||
typeSymbol.TypeKind == TypeKind.Interface ||
typeSymbol.TypeKind == TypeKind.Enum ||
typeSymbol.TypeKind == TypeKind.Struct ||
typeSymbol.TypeKind == TypeKind.Delegate)
{
return EnvDTE.vsCMTypeRef.vsCMTypeRefCodeType;
}
return EnvDTE.vsCMTypeRef.vsCMTypeRefOther;
}
public override string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol)
=> typeSymbol.ToDisplayString(s_codeTypeRefAsFullNameFormat);
public override string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol)
=> typeSymbol.ToDisplayString(s_codeTypeRefAsStringFormat);
public override bool IsParameterNode(SyntaxNode node)
=> node is ParameterSyntax;
public override bool IsAttributeNode(SyntaxNode node)
=> node is AttributeSyntax;
public override bool IsAttributeArgumentNode(SyntaxNode node)
=> node is AttributeArgumentSyntax;
public override bool IsOptionNode(SyntaxNode node)
{
// Only VB implementation has Option statements
return false;
}
public override bool IsImportNode(SyntaxNode node)
=> node is UsingDirectiveSyntax;
public override string GetUnescapedName(string name)
{
return name != null && name.Length > 1 && name[0] == '@'
? name.Substring(1)
: name;
}
public override string GetName(SyntaxNode node)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.EnumDeclaration:
return ((BaseTypeDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.DelegateDeclaration:
return ((DelegateDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.MethodDeclaration:
return ((MethodDeclarationSyntax)node).ExplicitInterfaceSpecifier?.ToString() +
((MethodDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.ConstructorDeclaration:
return ((ConstructorDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.DestructorDeclaration:
return "~" + ((DestructorDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.PropertyDeclaration:
return ((PropertyDeclarationSyntax)node).ExplicitInterfaceSpecifier?.ToString() +
((PropertyDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.IndexerDeclaration:
return ((IndexerDeclarationSyntax)node).ExplicitInterfaceSpecifier?.ToString() +
((IndexerDeclarationSyntax)node).ThisKeyword.ToString();
case SyntaxKind.EventDeclaration:
return ((EventDeclarationSyntax)node).ExplicitInterfaceSpecifier?.ToString() +
((EventDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.Parameter:
return GetParameterName(node);
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return ((BaseNamespaceDeclarationSyntax)node).Name.ToString();
case SyntaxKind.OperatorDeclaration:
return "operator " + ((OperatorDeclarationSyntax)node).OperatorToken.ToString();
case SyntaxKind.ConversionOperatorDeclaration:
var conversionOperator = (ConversionOperatorDeclarationSyntax)node;
return (conversionOperator.ImplicitOrExplicitKeyword.Kind() == SyntaxKind.ImplicitKeyword ? "implicit " : "explicit ")
+ "operator "
+ conversionOperator.Type.ToString();
case SyntaxKind.EnumMemberDeclaration:
return ((EnumMemberDeclarationSyntax)node).Identifier.ToString();
case SyntaxKind.VariableDeclarator:
return ((VariableDeclaratorSyntax)node).Identifier.ToString();
case SyntaxKind.Attribute:
return ((AttributeSyntax)node).Name.ToString();
case SyntaxKind.AttributeArgument:
var attributeArgument = (AttributeArgumentSyntax)node;
return attributeArgument.NameEquals != null
? attributeArgument.NameEquals.Name.ToString()
: string.Empty;
case SyntaxKind.UsingDirective:
throw Exceptions.ThrowEFail();
default:
Debug.Fail("Invalid node kind: " + node.Kind());
throw new ArgumentException();
}
}
public override SyntaxNode GetNodeWithName(SyntaxNode node)
{
var kind = node.Kind();
if (kind == SyntaxKind.OperatorDeclaration ||
kind == SyntaxKind.ConversionOperatorDeclaration)
{
throw Exceptions.ThrowEFail();
}
return node;
}
public override SyntaxNode SetName(SyntaxNode node, string name)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
// In all cases, the resulting syntax for the new name has elastic trivia attached,
// whether via this call to SyntaxFactory.Identifier or via explicitly added elastic
// markers.
var newIdentifier = SyntaxFactory.Identifier(name);
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.StructDeclaration:
return SetNameOfClassOrStruct(node, newIdentifier);
case SyntaxKind.InterfaceDeclaration:
return ((InterfaceDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.EnumDeclaration:
return ((EnumDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.DelegateDeclaration:
return ((DelegateDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.MethodDeclaration:
return ((MethodDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.ConstructorDeclaration:
return ((ConstructorDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.DestructorDeclaration:
return ((DestructorDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.PropertyDeclaration:
return ((PropertyDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.EventDeclaration:
return ((EventDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.Parameter:
return ((ParameterSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
return ((BaseNamespaceDeclarationSyntax)node).WithName(
SyntaxFactory.ParseName(name)
.WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker))
.WithTrailingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker)));
case SyntaxKind.EnumMemberDeclaration:
return ((EnumMemberDeclarationSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.VariableDeclarator:
return ((VariableDeclaratorSyntax)node).WithIdentifier(newIdentifier);
case SyntaxKind.Attribute:
return ((AttributeSyntax)node).WithName(
SyntaxFactory.ParseName(name)
.WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker))
.WithTrailingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker)));
case SyntaxKind.AttributeArgument:
return ((AttributeArgumentSyntax)node).WithNameEquals(SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(name)));
default:
Debug.Fail("Invalid node kind: " + node.Kind());
throw new ArgumentException();
}
}
private static SyntaxNode SetNameOfClassOrStruct(SyntaxNode node, SyntaxToken newIdentifier)
{
var typeNode = (TypeDeclarationSyntax)node;
foreach (var member in typeNode.Members)
{
if (member.Kind() == SyntaxKind.ConstructorDeclaration)
{
var constructor = ((ConstructorDeclarationSyntax)member).WithIdentifier(newIdentifier);
typeNode = typeNode.ReplaceNode(member, constructor);
}
else if (member.Kind() == SyntaxKind.DestructorDeclaration)
{
var destructor = ((DestructorDeclarationSyntax)member).WithIdentifier(newIdentifier);
typeNode = typeNode.ReplaceNode(member, destructor);
}
}
if (typeNode.Kind() == SyntaxKind.StructDeclaration)
{
return ((StructDeclarationSyntax)typeNode).WithIdentifier(newIdentifier);
}
else
{
return ((ClassDeclarationSyntax)typeNode).WithIdentifier(newIdentifier);
}
}
public override string GetFullName(SyntaxNode node, SemanticModel semanticModel)
{
if (node.Kind() == SyntaxKind.UsingDirective)
{
throw Exceptions.ThrowEFail();
}
var symbol = node is AttributeSyntax
? semanticModel.GetTypeInfo(node).Type
: semanticModel.GetDeclaredSymbol(node);
return GetExternalSymbolFullName(symbol);
}
public override string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel)
{
var typeName = SyntaxFactory.ParseTypeName(name);
if (typeName is PredefinedTypeSyntax predefinedTypeNode)
{
if (SyntaxFactsService.TryGetPredefinedType(predefinedTypeNode.Keyword, out var predefinedType))
{
var specialType = predefinedType.ToSpecialType();
return semanticModel.Compilation.GetSpecialType(specialType).GetEscapedFullName();
}
}
else
{
var symbols = semanticModel.LookupNamespacesAndTypes(position, name: name);
if (symbols.Length > 0)
{
return symbols[0].GetEscapedFullName();
}
}
return name;
}
public override bool IsValidExternalSymbol(ISymbol symbol)
{
if (symbol is IMethodSymbol methodSymbol)
{
if (methodSymbol.MethodKind == MethodKind.PropertyGet ||
methodSymbol.MethodKind == MethodKind.PropertySet ||
methodSymbol.MethodKind == MethodKind.EventAdd ||
methodSymbol.MethodKind == MethodKind.EventRemove ||
methodSymbol.MethodKind == MethodKind.EventRaise)
{
return false;
}
}
return symbol.DeclaredAccessibility == Accessibility.Public
|| symbol.DeclaredAccessibility == Accessibility.Protected
|| symbol.DeclaredAccessibility == Accessibility.ProtectedOrInternal;
}
public override string GetExternalSymbolName(ISymbol symbol)
{
if (symbol == null)
{
throw Exceptions.ThrowEFail();
}
return symbol.ToDisplayString(s_externalNameFormat);
}
public override string GetExternalSymbolFullName(ISymbol symbol)
{
if (symbol == null)
{
throw Exceptions.ThrowEFail();
}
return symbol.ToDisplayString(s_externalFullNameFormat);
}
public override EnvDTE.vsCMAccess GetAccess(ISymbol symbol)
=> symbol.DeclaredAccessibility switch
{
Accessibility.Public => EnvDTE.vsCMAccess.vsCMAccessPublic,
Accessibility.Private => EnvDTE.vsCMAccess.vsCMAccessPrivate,
Accessibility.Internal => EnvDTE.vsCMAccess.vsCMAccessProject,
Accessibility.Protected => EnvDTE.vsCMAccess.vsCMAccessProtected,
Accessibility.ProtectedOrInternal => EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected,
Accessibility.ProtectedAndInternal =>
// there is no appropriate mapping for private protected in EnvDTE.vsCMAccess
// See https://github.com/dotnet/roslyn/issues/22406
EnvDTE.vsCMAccess.vsCMAccessProtected,
_ => throw Exceptions.ThrowEFail(),
};
public override EnvDTE.vsCMAccess GetAccess(SyntaxNode node)
{
var member = GetNodeWithModifiers(node);
if (member == null)
{
throw Exceptions.ThrowEFail();
}
var modifiers = member.GetModifiers();
if (modifiers.Any(t => t.Kind() == SyntaxKind.PublicKeyword))
{
return EnvDTE.vsCMAccess.vsCMAccessPublic;
}
else if (modifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword) && modifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword))
{
return EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected;
}
else if (modifiers.Any(t => t.Kind() == SyntaxKind.InternalKeyword))
{
return EnvDTE.vsCMAccess.vsCMAccessProject;
}
else if (modifiers.Any(t => t.Kind() == SyntaxKind.ProtectedKeyword))
{
return EnvDTE.vsCMAccess.vsCMAccessProtected;
}
else if (modifiers.Any(t => t.Kind() == SyntaxKind.PrivateKeyword))
{
return EnvDTE.vsCMAccess.vsCMAccessPrivate;
}
else
{
// The code does not specify the accessibility, so we need to
// determine the default accessibility.
return GetDefaultAccessibility(member);
}
}
public override SyntaxNode GetNodeWithModifiers(SyntaxNode node)
{
return node is VariableDeclaratorSyntax
? node.GetAncestor<MemberDeclarationSyntax>()
: node;
}
public override SyntaxNode GetNodeWithType(SyntaxNode node)
{
return node is VariableDeclaratorSyntax
? node.GetAncestor<MemberDeclarationSyntax>()
: node;
}
public override SyntaxNode GetNodeWithInitializer(SyntaxNode node)
=> node;
private EnvDTE.vsCMAccess GetDefaultAccessibility(SyntaxNode node)
{
if (node is EnumMemberDeclarationSyntax)
{
return EnvDTE.vsCMAccess.vsCMAccessPublic;
}
if (node is BaseFieldDeclarationSyntax ||
node is BaseMethodDeclarationSyntax ||
node is BasePropertyDeclarationSyntax)
{
// Members of interfaces and enums are public, while all other
// members are private.
if (node.HasAncestor<InterfaceDeclarationSyntax>() ||
node.HasAncestor<EnumDeclarationSyntax>())
{
return EnvDTE.vsCMAccess.vsCMAccessPublic;
}
else
{
return EnvDTE.vsCMAccess.vsCMAccessPrivate;
}
}
if (node is BaseTypeDeclarationSyntax ||
node is DelegateDeclarationSyntax)
{
// Types declared within types are private by default,
// otherwise internal.
if (node.HasAncestor<BaseTypeDeclarationSyntax>())
{
return EnvDTE.vsCMAccess.vsCMAccessPrivate;
}
else
{
return EnvDTE.vsCMAccess.vsCMAccessProject;
}
}
if (node is AccessorDeclarationSyntax ||
node is ArrowExpressionClauseSyntax)
{
return GetAccess(node.FirstAncestorOrSelf<BasePropertyDeclarationSyntax>());
}
throw Exceptions.ThrowEFail();
}
public override SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess newAccess)
{
if (!(node is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
if (member.Parent.Kind() == SyntaxKind.InterfaceDeclaration ||
member.Parent.Kind() == SyntaxKind.EnumDeclaration)
{
if (newAccess == EnvDTE.vsCMAccess.vsCMAccessDefault ||
newAccess == EnvDTE.vsCMAccess.vsCMAccessPublic)
{
return member;
}
else
{
throw Exceptions.ThrowEInvalidArg();
}
}
if (member is BaseTypeDeclarationSyntax ||
member is EnumDeclarationSyntax)
{
if (!(member.Parent is BaseTypeDeclarationSyntax) &&
(newAccess == EnvDTE.vsCMAccess.vsCMAccessPrivate ||
newAccess == EnvDTE.vsCMAccess.vsCMAccessProtected ||
newAccess == EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected))
{
throw Exceptions.ThrowEInvalidArg();
}
}
var modifierFlags = member.GetModifierFlags() & ~ModifierFlags.AccessModifierMask;
switch (newAccess)
{
case EnvDTE.vsCMAccess.vsCMAccessPrivate:
modifierFlags |= ModifierFlags.Private;
break;
case EnvDTE.vsCMAccess.vsCMAccessProtected:
modifierFlags |= ModifierFlags.Protected;
break;
case EnvDTE.vsCMAccess.vsCMAccessPublic:
modifierFlags |= ModifierFlags.Public;
break;
case EnvDTE.vsCMAccess.vsCMAccessProject:
modifierFlags |= ModifierFlags.Internal;
break;
case EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected:
modifierFlags |= ModifierFlags.Protected | ModifierFlags.Internal;
break;
case EnvDTE.vsCMAccess.vsCMAccessDefault:
break; // No change
default:
throw Exceptions.ThrowEUnexpected();
}
return member.UpdateModifiers(modifierFlags);
}
private IList<SyntaxTrivia> CollectComments(IList<SyntaxTrivia> triviaList)
{
var commentList = new List<SyntaxTrivia>();
for (var i = triviaList.Count - 1; i >= 0; i--)
{
var trivia = triviaList[i];
if (trivia.IsRegularComment())
{
commentList.Add(trivia);
}
else if (trivia.Kind() != SyntaxKind.WhitespaceTrivia &&
trivia.Kind() != SyntaxKind.EndOfLineTrivia)
{
break;
}
}
commentList.Reverse();
return commentList;
}
public override string GetComment(SyntaxNode node)
{
var firstToken = node.GetFirstToken();
var commentList = CollectComments(firstToken.LeadingTrivia.ToArray());
if (commentList.Count == 0)
{
return string.Empty;
}
var textBuilder = new StringBuilder();
foreach (var trivia in commentList)
{
if (trivia.IsRegularComment())
{
textBuilder.AppendLine(trivia.GetCommentText());
}
else
{
throw Exceptions.ThrowEFail();
}
}
return textBuilder.ToString();
}
public override SyntaxNode SetComment(SyntaxNode node, string value)
{
Debug.Assert(node is MemberDeclarationSyntax);
var memberDeclaration = (MemberDeclarationSyntax)node;
var text = memberDeclaration.SyntaxTree.GetText(CancellationToken.None);
var newLine = GetNewLineCharacter(text);
var commentText = string.Empty;
if (value != null)
{
var builder = new StringBuilder();
foreach (var line in value.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
builder.Append("// ");
builder.Append(line);
builder.Append(newLine);
}
commentText = builder.ToString();
}
var newTriviaList = SyntaxFactory.ParseLeadingTrivia(commentText);
var leadingTriviaList = memberDeclaration.GetLeadingTrivia().ToList();
var commentList = CollectComments(leadingTriviaList);
if (commentList.Count > 0)
{
// In this case, we're going to replace the existing comment.
var firstIndex = leadingTriviaList.FindIndex(t => t == commentList[0]);
var lastIndex = leadingTriviaList.FindIndex(t => t == commentList[commentList.Count - 1]);
var count = lastIndex - firstIndex + 1;
leadingTriviaList.RemoveRange(firstIndex, count);
// Note: single line comments have a trailing new-line but that won't be
// returned by CollectComments. So, we may need to remove an additional new line below.
if (firstIndex < leadingTriviaList.Count &&
leadingTriviaList[firstIndex].Kind() == SyntaxKind.EndOfLineTrivia)
{
leadingTriviaList.RemoveAt(firstIndex);
}
foreach (var trivia in newTriviaList.Reverse())
{
leadingTriviaList.Insert(firstIndex, trivia);
}
}
else
{
// Otherwise, just add the comment to the end of the leading trivia.
leadingTriviaList.AddRange(newTriviaList);
}
return memberDeclaration.WithLeadingTrivia(leadingTriviaList);
}
private static DocumentationCommentTriviaSyntax GetDocCommentNode(MemberDeclarationSyntax memberDeclaration)
{
var docCommentTrivia = memberDeclaration
.GetLeadingTrivia()
.Reverse()
.FirstOrDefault(t => t.IsDocComment());
if (!docCommentTrivia.IsDocComment())
{
return null;
}
return (DocumentationCommentTriviaSyntax)docCommentTrivia.GetStructure();
}
public override string GetDocComment(SyntaxNode node)
{
Debug.Assert(node is MemberDeclarationSyntax);
var memberDeclaration = (MemberDeclarationSyntax)node;
var documentationComment = GetDocCommentNode(memberDeclaration);
if (documentationComment == null)
{
return string.Empty;
}
var text = memberDeclaration.SyntaxTree.GetText(CancellationToken.None);
var newLine = GetNewLineCharacter(text);
var lines = documentationComment.ToString().Split(new[] { newLine }, StringSplitOptions.None);
// trim off leading whitespace and exterior trivia.
var lengthToStrip = lines[0].GetLeadingWhitespace().Length;
for (var i = 1; i < lines.Length; i++)
{
var line = lines[i].TrimStart();
if (line.StartsWith("///", StringComparison.Ordinal))
{
line = line.Substring(3);
}
if (line.Length > 0)
{
lengthToStrip = Math.Min(lengthToStrip, line.GetLeadingWhitespace().Length);
}
lines[i] = line;
}
for (var i = 0; i < lines.Length; i++)
{
var line = lines[i];
if (line.Length > lengthToStrip)
{
lines[i] = line.Substring(lengthToStrip);
}
}
return "<doc>\r\n" + lines.Join(newLine) + "</doc>";
}
public override SyntaxNode SetDocComment(SyntaxNode node, string value)
{
Debug.Assert(node is MemberDeclarationSyntax);
XDocument xmlDocument;
try
{
using var reader = new StringReader(value);
xmlDocument = XDocument.Load(reader);
}
catch
{
xmlDocument = null;
}
if (xmlDocument == null)
{
throw Exceptions.ThrowEInvalidArg();
}
if (!(xmlDocument.FirstNode is XElement docElement) ||
docElement.Name.ToString().ToLower() != "doc")
{
throw Exceptions.ThrowEInvalidArg();
}
var memberDeclaration = (MemberDeclarationSyntax)node;
var text = memberDeclaration.SyntaxTree.GetText(CancellationToken.None);
var newLine = GetNewLineCharacter(text);
var builder = new StringBuilder();
foreach (var child in docElement.Elements())
{
foreach (var line in child.ToString().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
builder.Append("/// ");
builder.Append(line);
builder.Append(newLine);
}
}
var newTriviaList = SyntaxFactory.ParseLeadingTrivia(builder.ToString());
var leadingTriviaList = memberDeclaration.GetLeadingTrivia().ToList();
var documentationComment = GetDocCommentNode(memberDeclaration);
if (documentationComment != null)
{
// In this case, we're going to replace the existing XML doc comment.
var index = leadingTriviaList.FindIndex(t => t == documentationComment.ParentTrivia);
leadingTriviaList.RemoveAt(index);
foreach (var triviaElement in newTriviaList.Reverse())
{
leadingTriviaList.Insert(index, triviaElement);
}
}
else
{
// Otherwise, just add the XML doc comment to the end of the leading trivia.
leadingTriviaList.AddRange(newTriviaList);
}
return memberDeclaration.WithLeadingTrivia(leadingTriviaList);
}
public override IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parentNode)
{
if (parentNode is BaseMethodDeclarationSyntax baseMethod)
{
return baseMethod.ParameterList.Parameters;
}
else if (parentNode is IndexerDeclarationSyntax indexer)
{
return indexer.ParameterList.Parameters;
}
else if (parentNode is DelegateDeclarationSyntax delegateDecl)
{
return delegateDecl.ParameterList.Parameters;
}
return SpecializedCollections.EmptyEnumerable<ParameterSyntax>();
}
public override bool IsExpressionBodiedProperty(SyntaxNode node)
=> (node as PropertyDeclarationSyntax)?.ExpressionBody != null;
public override bool TryGetAutoPropertyExpressionBody(SyntaxNode parentNode, out SyntaxNode accessorNode)
{
accessorNode = (parentNode as PropertyDeclarationSyntax)?.ExpressionBody;
return accessorNode != null;
}
public override bool IsAccessorNode(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return true;
}
return false;
}
public override MethodKind GetAccessorKind(SyntaxNode node)
=> node.Kind() switch
{
SyntaxKind.GetAccessorDeclaration => MethodKind.PropertyGet,
SyntaxKind.SetAccessorDeclaration => MethodKind.PropertySet,
SyntaxKind.AddAccessorDeclaration => MethodKind.EventAdd,
SyntaxKind.RemoveAccessorDeclaration => MethodKind.EventRemove,
_ => throw Exceptions.ThrowEUnexpected(),
};
private static SyntaxKind GetAccessorSyntaxKind(MethodKind methodKind)
=> methodKind switch
{
MethodKind.PropertyGet => SyntaxKind.GetAccessorDeclaration,
MethodKind.PropertySet => SyntaxKind.SetAccessorDeclaration,
MethodKind.EventAdd => SyntaxKind.AddAccessorDeclaration,
MethodKind.EventRemove => SyntaxKind.RemoveAccessorDeclaration,
_ => throw Exceptions.ThrowEUnexpected(),
};
public override bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode)
{
Debug.Assert(parentNode is BasePropertyDeclarationSyntax);
var basePropertyDeclaration = (BasePropertyDeclarationSyntax)parentNode;
var accessorKind = GetAccessorSyntaxKind(kind);
if (basePropertyDeclaration.AccessorList != null)
{
foreach (var accessor in basePropertyDeclaration.AccessorList.Accessors)
{
if (accessor.Kind() == accessorKind)
{
accessorNode = accessor;
return true;
}
}
}
accessorNode = null;
return false;
}
public override bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode)
{
foreach (ParameterSyntax parameter in GetParameterNodes(parentNode))
{
if (parameter.Identifier.ToString() == name)
{
parameterNode = parameter;
return true;
}
}
parameterNode = null;
return false;
}
public override bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode)
{
foreach (UsingDirectiveSyntax usingDirective in GetImportNodes(parentNode))
{
if (usingDirective.Name.ToString() == dottedName)
{
importNode = usingDirective;
return true;
}
}
importNode = null;
return false;
}
public override bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode)
{
// Only VB has Option statements
throw new NotSupportedException();
}
public override bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode)
{
// Only VB has Inherits statements
throw new NotSupportedException();
}
public override bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode)
{
// Only VB has Implements statements
throw new NotSupportedException();
}
public override bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode)
{
var count = -1;
foreach (AttributeSyntax attribute in GetAttributeNodes(parentNode))
{
if (attribute.Name.ToString() == name)
{
count++;
if (count == ordinal)
{
attributeNode = attribute;
return true;
}
}
}
attributeNode = null;
return false;
}
public override bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode)
{
Debug.Assert(attributeNode is AttributeSyntax);
var attribute = (AttributeSyntax)attributeNode;
if (attribute.ArgumentList != null &&
attribute.ArgumentList.Arguments.Count > index)
{
attributeArgumentNode = attribute.ArgumentList.Arguments[index];
return true;
}
attributeArgumentNode = null;
return false;
}
public override void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal)
{
// Only VB supports Option statements
throw new NotSupportedException();
}
public override void GetInheritsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode inheritsNode, out string namespaceName, out int ordinal)
{
// Only VB supports Inherits statements
throw new NotSupportedException();
}
public override void GetImplementsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode implementsNode, out string namespaceName, out int ordinal)
{
// Only VB supports Implements statements
throw new NotSupportedException();
}
public override void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal)
{
Debug.Assert(attributeNode is AttributeSyntax);
name = ((AttributeSyntax)attributeNode).Name.ToString();
ordinal = -1;
foreach (AttributeSyntax attribute in GetAttributeNodes(parentNode))
{
if (attribute.Name.ToString() == name)
{
ordinal++;
}
if (attribute == attributeNode)
{
break;
}
}
}
public override void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index)
{
Debug.Assert(attributeArgumentNode is AttributeArgumentSyntax);
var argument = (AttributeArgumentSyntax)attributeArgumentNode;
var attribute = (AttributeSyntax)argument.Ancestors().First(n => n.Kind() == SyntaxKind.Attribute);
attributeNode = attribute;
index = attribute.ArgumentList.Arguments.IndexOf((AttributeArgumentSyntax)attributeArgumentNode);
}
public override SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode)
{
Debug.Assert(attributeNode is AttributeSyntax);
Debug.Assert(attributeNode.Parent is AttributeListSyntax);
return (AttributeListSyntax)attributeNode.Parent;
}
public override string GetAttributeTarget(SyntaxNode attributeNode)
{
Debug.Assert(attributeNode is AttributeSyntax);
Debug.Assert(attributeNode.Parent is AttributeListSyntax);
var attributeList = (AttributeListSyntax)attributeNode.Parent;
if (attributeList.Target != null)
{
return attributeList.Target.Identifier.ToString();
}
return string.Empty;
}
public override SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string target)
{
Debug.Assert(attributeNode is AttributeListSyntax);
var attributeList = (AttributeListSyntax)attributeNode;
if (string.IsNullOrEmpty(target))
{
return attributeList.WithTarget(null);
}
else
{
return attributeList.WithTarget(
SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Identifier(target)));
}
}
public override string GetAttributeValue(SyntaxNode attributeNode)
{
Debug.Assert(attributeNode is AttributeSyntax);
var attribute = (AttributeSyntax)attributeNode;
var argumentList = attribute.ArgumentList;
if (argumentList != null)
{
return argumentList.Arguments.ToString();
}
return string.Empty;
}
public override SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value)
{
Debug.Assert(attributeNode is AttributeSyntax);
var attribute = (AttributeSyntax)attributeNode;
var argumentList = attribute.ArgumentList;
var parsedArgumentList = SyntaxFactory.ParseAttributeArgumentList("(" + value + ")");
var newArgumentList = argumentList != null
? argumentList.WithArguments(parsedArgumentList.Arguments)
: parsedArgumentList;
return attribute.WithArgumentList(newArgumentList);
}
public override SyntaxNode GetNodeWithAttributes(SyntaxNode node)
{
return node is VariableDeclaratorSyntax
? node.GetAncestor<MemberDeclarationSyntax>()
: node;
}
public override SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node)
{
if (node.HasAncestor<BaseFieldDeclarationSyntax>())
{
return node.GetAncestor<BaseFieldDeclarationSyntax>().Declaration.Variables.FirstOrDefault();
}
else if (node.HasAncestor<ParameterSyntax>())
{
return node.GetAncestor<ParameterSyntax>();
}
else
{
return node.Parent;
}
}
public override SyntaxNode CreateAttributeNode(string name, string value, string target = null)
{
var specifier = target != null
? SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Identifier(target),
SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), SyntaxKind.ColonToken, SyntaxFactory.TriviaList(SyntaxFactory.Space)))
: null;
return SyntaxFactory.AttributeList(
target: specifier,
attributes: SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Attribute(
name: SyntaxFactory.ParseName(name),
argumentList: SyntaxFactory.ParseAttributeArgumentList("(" + value + ")"))));
}
public override SyntaxNode CreateAttributeArgumentNode(string name, string value)
{
if (!string.IsNullOrEmpty(name))
{
return SyntaxFactory.AttributeArgument(
nameEquals: SyntaxFactory.NameEquals(name),
nameColon: null,
expression: SyntaxFactory.ParseExpression(value));
}
else
{
return SyntaxFactory.AttributeArgument(SyntaxFactory.ParseExpression(value));
}
}
public override SyntaxNode CreateImportNode(string name, string alias = null)
{
var nameSyntax = SyntaxFactory.ParseName(name);
if (!string.IsNullOrEmpty(alias))
{
var aliasSyntax = SyntaxFactory.NameEquals(alias);
return SyntaxFactory.UsingDirective(aliasSyntax, nameSyntax);
}
else
{
return SyntaxFactory.UsingDirective(nameSyntax);
}
}
public override SyntaxNode CreateParameterNode(string name, string type)
=> SyntaxFactory.Parameter(SyntaxFactory.Identifier(name)).WithType(SyntaxFactory.ParseTypeName(type));
public override string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode)
{
Debug.Assert(attributeArgumentNode is AttributeArgumentSyntax);
return ((AttributeArgumentSyntax)attributeArgumentNode).Expression.ToString();
}
public override string GetImportAlias(SyntaxNode importNode)
{
if (importNode is UsingDirectiveSyntax usingDirective)
{
return usingDirective.Alias != null
? usingDirective.Alias.Name.ToString()
: string.Empty;
}
throw new InvalidOperationException();
}
public override string GetImportNamespaceOrType(SyntaxNode importNode)
{
if (importNode is UsingDirectiveSyntax usingDirective)
{
return usingDirective.Name.ToString();
}
throw new InvalidOperationException();
}
public override void GetImportParentAndName(SyntaxNode importNode, out SyntaxNode namespaceNode, out string name)
{
if (importNode is UsingDirectiveSyntax usingDirective)
{
namespaceNode = usingDirective.Parent.Kind() == SyntaxKind.CompilationUnit
? null
: usingDirective.Parent;
name = usingDirective.Name.ToString();
return;
}
throw new InvalidOperationException();
}
public override string GetParameterName(SyntaxNode node)
{
if (node is ParameterSyntax parameter)
{
return parameter.Identifier.ToString();
}
throw new InvalidOperationException();
}
public override EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node)
{
if (node is ParameterSyntax parameter)
{
var kind = EnvDTE80.vsCMParameterKind.vsCMParameterKindNone;
var modifiers = parameter.Modifiers;
if (modifiers.Any(SyntaxKind.RefKeyword))
{
kind = EnvDTE80.vsCMParameterKind.vsCMParameterKindRef;
}
else if (modifiers.Any(SyntaxKind.OutKeyword))
{
kind = EnvDTE80.vsCMParameterKind.vsCMParameterKindOut;
}
else if (modifiers.Any(SyntaxKind.ParamsKeyword))
{
kind = EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray;
}
// Note: this is not an "else if" since it might be both
// optional and "ref".
if (parameter.Default != null)
{
kind |= EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional;
}
return kind;
}
throw new InvalidOperationException();
}
public override SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind)
{
if (!(node is ParameterSyntax parameter))
{
throw Exceptions.ThrowEFail();
}
// We can't do anything with "Optional", so just strip it out and ignore it.
if ((kind & EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional) != 0)
{
kind -= EnvDTE80.vsCMParameterKind.vsCMParameterKindOptional;
}
SyntaxTokenList newModifiers;
switch (kind)
{
case EnvDTE80.vsCMParameterKind.vsCMParameterKindOut:
newModifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.OutKeyword));
break;
case EnvDTE80.vsCMParameterKind.vsCMParameterKindRef:
newModifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.RefKeyword));
break;
case EnvDTE80.vsCMParameterKind.vsCMParameterKindIn:
case EnvDTE80.vsCMParameterKind.vsCMParameterKindNone:
newModifiers = SyntaxFactory.TokenList();
break;
case EnvDTE80.vsCMParameterKind.vsCMParameterKindParamArray:
{
var parameterList = (ParameterListSyntax)parameter.Parent;
if (parameterList.Parameters.LastOrDefault() == parameter &&
parameter.Type is ArrayTypeSyntax)
{
newModifiers = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ParamsKeyword));
break;
}
throw Exceptions.ThrowEInvalidArg();
}
default:
throw Exceptions.ThrowEInvalidArg();
}
return parameter.WithModifiers(newModifiers);
}
public override EnvDTE80.vsCMParameterKind UpdateParameterKind(EnvDTE80.vsCMParameterKind parameterKind, PARAMETER_PASSING_MODE passingMode)
{
var updatedParameterKind = parameterKind;
switch (passingMode)
{
case PARAMETER_PASSING_MODE.cmParameterTypeIn:
updatedParameterKind |= EnvDTE80.vsCMParameterKind.vsCMParameterKindNone;
updatedParameterKind &= ~EnvDTE80.vsCMParameterKind.vsCMParameterKindRef;
updatedParameterKind &= ~EnvDTE80.vsCMParameterKind.vsCMParameterKindOut;
break;
case PARAMETER_PASSING_MODE.cmParameterTypeInOut:
updatedParameterKind &= ~EnvDTE80.vsCMParameterKind.vsCMParameterKindNone;
updatedParameterKind |= EnvDTE80.vsCMParameterKind.vsCMParameterKindRef;
updatedParameterKind &= ~EnvDTE80.vsCMParameterKind.vsCMParameterKindOut;
break;
case PARAMETER_PASSING_MODE.cmParameterTypeOut:
updatedParameterKind &= ~EnvDTE80.vsCMParameterKind.vsCMParameterKindNone;
updatedParameterKind &= ~EnvDTE80.vsCMParameterKind.vsCMParameterKindRef;
updatedParameterKind |= EnvDTE80.vsCMParameterKind.vsCMParameterKindOut;
break;
}
return updatedParameterKind;
}
public override EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name)
{
if (kind == EnvDTE.vsCMFunction.vsCMFunctionSub)
{
return EnvDTE.vsCMFunction.vsCMFunctionFunction;
}
if (kind == EnvDTE.vsCMFunction.vsCMFunctionFunction)
{
return kind;
}
if (kind == EnvDTE.vsCMFunction.vsCMFunctionConstructor ||
kind == EnvDTE.vsCMFunction.vsCMFunctionDestructor)
{
if (containerNode is InterfaceDeclarationSyntax)
{
throw Exceptions.ThrowEFail();
}
return kind;
}
throw Exceptions.ThrowENotImpl();
}
public override bool SupportsEventThrower
{
get { return false; }
}
public override bool GetCanOverride(SyntaxNode memberNode)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
if (!(memberNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
if (member.Parent is InterfaceDeclarationSyntax)
{
return true;
}
var flags = member.GetModifierFlags();
return (flags & (ModifierFlags.Abstract | ModifierFlags.Virtual)) != 0;
}
public override SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
if (!(memberNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
if (member.Parent is InterfaceDeclarationSyntax)
{
if (!value)
{
throw Exceptions.ThrowEInvalidArg();
}
return memberNode;
}
var flags = member.GetModifierFlags();
if (value)
{
flags |= ModifierFlags.Virtual;
}
else
{
flags &= ~ModifierFlags.Virtual;
}
return member.UpdateModifiers(flags);
}
public override EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol)
{
Debug.Assert(typeNode is ClassDeclarationSyntax);
var type = (ClassDeclarationSyntax)typeNode;
var flags = type.GetModifierFlags();
return (flags & ModifierFlags.Partial) != 0
? EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass
: EnvDTE80.vsCMClassKind.vsCMClassKindMainClass;
}
public override SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind)
{
Debug.Assert(typeNode is ClassDeclarationSyntax);
var type = (ClassDeclarationSyntax)typeNode;
var flags = type.GetModifierFlags();
if (kind == EnvDTE80.vsCMClassKind.vsCMClassKindPartialClass)
{
flags |= ModifierFlags.Partial;
}
else if (kind == EnvDTE80.vsCMClassKind.vsCMClassKindMainClass)
{
flags &= ~ModifierFlags.Partial;
}
return type.UpdateModifiers(flags);
}
public override EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode)
{
if (variableNode is EnumMemberDeclarationSyntax)
{
return EnvDTE80.vsCMConstKind.vsCMConstKindConst;
}
if (!(GetNodeWithModifiers(variableNode) is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
var flags = member.GetModifierFlags();
var result = EnvDTE80.vsCMConstKind.vsCMConstKindNone;
if ((flags & ModifierFlags.ReadOnly) != 0)
{
result |= EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly;
}
if ((flags & ModifierFlags.Const) != 0)
{
result |= EnvDTE80.vsCMConstKind.vsCMConstKindConst;
}
// Note: It's possible that we could return vsCMConstKindCont | vsCMConstKindReadOnly if the
// user had incorrectly specified both const and readonly in their code. That's OK since
// Code Model represents the source.
return result;
}
public override SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind)
{
Debug.Assert(variableNode is FieldDeclarationSyntax ||
variableNode is EnumMemberDeclarationSyntax);
if (variableNode is EnumMemberDeclarationSyntax)
{
if (kind != EnvDTE80.vsCMConstKind.vsCMConstKindConst &&
kind != EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly)
{
throw Exceptions.ThrowEInvalidArg();
}
return variableNode;
}
var member = (MemberDeclarationSyntax)variableNode;
var flags = member.GetModifierFlags();
flags &= ~(ModifierFlags.Const | ModifierFlags.ReadOnly);
switch (kind)
{
case EnvDTE80.vsCMConstKind.vsCMConstKindConst:
flags |= ModifierFlags.Const;
break;
case EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly:
flags |= ModifierFlags.ReadOnly;
break;
}
return member.UpdateModifiers(flags);
}
public override EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol)
{
Debug.Assert(typeNode is BaseTypeDeclarationSyntax);
var type = (BaseTypeDeclarationSyntax)typeNode;
var flags = type.GetModifierFlags();
return (flags & ModifierFlags.Partial) != 0
? EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial
: EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain;
}
public override SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind)
{
Debug.Assert(typeNode is BaseTypeDeclarationSyntax);
var type = (BaseTypeDeclarationSyntax)typeNode;
var flags = type.GetModifierFlags();
if (kind == EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindPartial)
{
flags |= ModifierFlags.Partial;
}
else if (kind == EnvDTE80.vsCMDataTypeKind.vsCMDataTypeKindMain)
{
flags &= ~ModifierFlags.Partial;
}
return type.UpdateModifiers(flags);
}
public override EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol)
{
switch (symbol.MethodKind)
{
case MethodKind.Ordinary:
case MethodKind.ExplicitInterfaceImplementation:
return EnvDTE.vsCMFunction.vsCMFunctionFunction;
case MethodKind.Constructor:
case MethodKind.StaticConstructor:
return EnvDTE.vsCMFunction.vsCMFunctionConstructor;
case MethodKind.Destructor:
return EnvDTE.vsCMFunction.vsCMFunctionDestructor;
case MethodKind.UserDefinedOperator:
case MethodKind.Conversion:
return EnvDTE.vsCMFunction.vsCMFunctionOperator;
case MethodKind.PropertyGet:
case MethodKind.EventRemove:
return EnvDTE.vsCMFunction.vsCMFunctionPropertyGet;
case MethodKind.PropertySet:
case MethodKind.EventAdd:
return EnvDTE.vsCMFunction.vsCMFunctionPropertySet;
default:
throw Exceptions.ThrowEUnexpected();
}
}
public override EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol)
{
Debug.Assert(typeNode is ClassDeclarationSyntax);
var type = (ClassDeclarationSyntax)typeNode;
var flags = type.GetModifierFlags();
var result = EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone;
if ((flags & ModifierFlags.Abstract) != 0)
{
result |= EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract;
}
if ((flags & ModifierFlags.New) != 0)
{
result |= EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew;
}
if ((flags & ModifierFlags.Sealed) != 0)
{
result |= EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed;
}
return result;
}
public override bool GetMustImplement(SyntaxNode memberNode)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
if (!(memberNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
if (member.Parent is InterfaceDeclarationSyntax)
{
return true;
}
var flags = member.GetModifierFlags();
return (flags & ModifierFlags.Abstract) != 0;
}
public override SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value)
{
Debug.Assert(memberNode is MethodDeclarationSyntax ||
memberNode is BasePropertyDeclarationSyntax ||
memberNode is EventFieldDeclarationSyntax);
if (!(memberNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
if (member.Parent is InterfaceDeclarationSyntax)
{
if (!value)
{
throw Exceptions.ThrowEInvalidArg();
}
return memberNode;
}
// If this is a class member and the class is not abstract, we throw.
if (member.Parent is ClassDeclarationSyntax)
{
var parentFlags = ((ClassDeclarationSyntax)member.Parent).GetModifierFlags();
if (value && (parentFlags & ModifierFlags.Abstract) == 0)
{
throw Exceptions.ThrowEInvalidArg();
}
}
var flags = member.GetModifierFlags();
if (value)
{
flags |= ModifierFlags.Abstract;
// If this is a method, remove the body if it is empty.
if (member is MethodDeclarationSyntax method)
{
if (method.Body != null && method.Body.Statements.Count == 0)
{
member = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), SyntaxKind.SemicolonToken, method.Body.CloseBraceToken.TrailingTrivia));
}
}
else
{
// If this is a property, remove the bodies of the accessors if they are empty.
// Note that "empty" means that the bodies contain no statements or just a single return statement.
if (member is BasePropertyDeclarationSyntax property && property.AccessorList != null)
{
var updatedAccessors = new List<AccessorDeclarationSyntax>();
foreach (var accessor in property.AccessorList.Accessors)
{
if (accessor.Body == null ||
accessor.Body.Statements.Count > 1 ||
(accessor.Body.Statements.Count == 1 && !accessor.Body.Statements[0].IsKind(SyntaxKind.ReturnStatement)))
{
// Leave this accessor as is
updatedAccessors.Add(accessor);
continue;
}
var updatedAccessor = accessor.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), SyntaxKind.SemicolonToken, accessor.Body.CloseBraceToken.TrailingTrivia));
updatedAccessors.Add(updatedAccessor);
}
var updatedAccessorList = property.AccessorList.WithAccessors(SyntaxFactory.List<AccessorDeclarationSyntax>(updatedAccessors));
member = property.ReplaceNode(property.AccessorList, updatedAccessorList);
}
}
}
else
{
flags &= ~ModifierFlags.Abstract;
// If this is a method, add a body.
if (member is MethodDeclarationSyntax method)
{
if (method.Body == null)
{
var newBody = SyntaxFactory.Block();
newBody = newBody.WithCloseBraceToken(newBody.CloseBraceToken.WithTrailingTrivia(method.SemicolonToken.TrailingTrivia));
member = method.WithSemicolonToken(default).WithBody(newBody);
}
}
else
{
// If this is a property, add bodies to the accessors if they don't have them.
if (member is BasePropertyDeclarationSyntax property && property.AccessorList != null)
{
var updatedAccessors = new List<AccessorDeclarationSyntax>();
foreach (var accessor in property.AccessorList.Accessors)
{
if (accessor.Body != null)
{
// Leave this accessor as is
updatedAccessors.Add(accessor);
continue;
}
var newBody = SyntaxFactory.Block();
newBody = newBody.WithCloseBraceToken(newBody.CloseBraceToken.WithTrailingTrivia(accessor.SemicolonToken.TrailingTrivia));
var updatedAccessor = accessor.WithSemicolonToken(default).WithBody(newBody);
updatedAccessors.Add(updatedAccessor);
}
var updatedAccessorList = property.AccessorList.WithAccessors(SyntaxFactory.List<AccessorDeclarationSyntax>(updatedAccessors));
member = property.ReplaceNode(property.AccessorList, updatedAccessorList);
}
}
}
return member.UpdateModifiers(flags);
}
public override SyntaxNode SetInheritanceKind(SyntaxNode typeNode, EnvDTE80.vsCMInheritanceKind kind)
{
Debug.Assert(typeNode is ClassDeclarationSyntax);
if (!(typeNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
var flags = member.GetModifierFlags();
flags &= ~(ModifierFlags.Abstract | ModifierFlags.New | ModifierFlags.Sealed);
if (kind != EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNone)
{
if ((kind & EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) != 0)
{
flags |= ModifierFlags.Abstract;
}
else if ((kind & EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed) != 0)
{
flags |= ModifierFlags.Sealed;
}
// Can have new in combination with the above flags
if ((kind & EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindNew) != 0)
{
flags |= ModifierFlags.New;
}
}
return member.UpdateModifiers(flags);
}
public override EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode)
{
Debug.Assert(memberNode is BaseMethodDeclarationSyntax ||
memberNode is BasePropertyDeclarationSyntax ||
memberNode is EventFieldDeclarationSyntax);
var member = (MemberDeclarationSyntax)memberNode;
var flags = member.GetModifierFlags();
var containingType = member.FirstAncestorOrSelf<TypeDeclarationSyntax>();
var result = EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone;
if ((flags & ModifierFlags.Abstract) != 0 || containingType?.Kind() == SyntaxKind.InterfaceDeclaration)
{
result |= EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract;
}
if ((flags & ModifierFlags.Virtual) != 0 || containingType?.Kind() == SyntaxKind.InterfaceDeclaration)
{
result |= EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual;
}
if ((flags & ModifierFlags.Override) != 0)
{
result |= EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride;
}
if ((flags & ModifierFlags.New) != 0)
{
result |= EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew;
}
if ((flags & ModifierFlags.Sealed) != 0)
{
result |= EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed;
}
return result;
}
public override SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind)
{
Debug.Assert(memberNode is BaseMethodDeclarationSyntax ||
memberNode is BasePropertyDeclarationSyntax ||
memberNode is EventFieldDeclarationSyntax);
// The legacy C# code model sets the MustImplement property here depending on whether the Abstract kind is set
// TODO(DustinCa): VB implements MustImplement in terms of OverrideKind, should we do the same?
memberNode = SetMustImplement(memberNode, (kind & EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) != 0);
var member = (MemberDeclarationSyntax)memberNode;
var flags = member.GetModifierFlags();
flags &= ~(ModifierFlags.Abstract | ModifierFlags.Virtual | ModifierFlags.Override | ModifierFlags.New | ModifierFlags.Sealed);
if (member.IsParentKind(SyntaxKind.InterfaceDeclaration))
{
if ((kind & (EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride | EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed)) != 0)
{
throw Exceptions.ThrowEInvalidArg();
}
else if ((kind & (EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract | EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual)) != 0)
{
// Switch these flags off
kind &= ~(EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract | EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual);
}
}
if (kind != EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone)
{
if ((kind & EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) != 0)
{
flags |= ModifierFlags.Abstract;
}
if ((kind & EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) != 0)
{
flags |= ModifierFlags.Virtual;
}
if ((kind & EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride) != 0)
{
flags |= ModifierFlags.Override;
}
if ((kind & EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) != 0)
{
flags |= ModifierFlags.Sealed;
}
if ((kind & EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew) != 0)
{
flags |= ModifierFlags.New;
}
}
return member.UpdateModifiers(flags);
}
public override bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
var member = (MemberDeclarationSyntax)memberNode;
return (member.GetModifierFlags() & ModifierFlags.Abstract) != 0;
}
public override SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
if (!(memberNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
var flags = member.GetModifierFlags();
if (value)
{
flags |= ModifierFlags.Abstract;
}
else
{
flags &= ~ModifierFlags.Abstract;
}
return member.UpdateModifiers(flags);
}
public override bool GetIsConstant(SyntaxNode variableNode)
{
Debug.Assert(variableNode is MemberDeclarationSyntax ||
variableNode is VariableDeclaratorSyntax);
if (variableNode is EnumMemberDeclarationSyntax)
{
return true;
}
if (!(GetNodeWithModifiers(variableNode) is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
// C# legacy Code Model returns true for readonly fields as well.
return (member.GetModifierFlags() & (ModifierFlags.Const | ModifierFlags.ReadOnly)) != 0;
}
public override SyntaxNode SetIsConstant(SyntaxNode variableNode, bool value)
{
Debug.Assert(variableNode is MemberDeclarationSyntax);
if (variableNode is EnumMemberDeclarationSyntax)
{
if (!value)
{
throw Exceptions.ThrowEFail();
}
return variableNode;
}
if (!(variableNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
if (GetIsConstant(member) == value)
{
return member;
}
var flags = member.GetModifierFlags();
if (value)
{
flags |= ModifierFlags.Const;
}
else
{
flags &= ~(ModifierFlags.Const | ModifierFlags.ReadOnly);
}
return member.UpdateModifiers(flags);
}
public override bool GetIsDefault(SyntaxNode propertyNode)
{
Debug.Assert(propertyNode is BasePropertyDeclarationSyntax);
if (!(propertyNode is BasePropertyDeclarationSyntax property))
{
throw Exceptions.ThrowEFail();
}
return property.IsKind(SyntaxKind.IndexerDeclaration);
}
public override SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value)
{
// The C# legacy Code Model throws this specific exception rather than a COM exception.
throw new InvalidOperationException();
}
public override bool GetIsGeneric(SyntaxNode memberNode)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
if (!(GetNodeWithModifiers(memberNode) is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
return member.GetArity() > 0;
}
public override bool GetIsPropertyStyleEvent(SyntaxNode eventNode)
{
Debug.Assert(eventNode is EventFieldDeclarationSyntax ||
eventNode is EventDeclarationSyntax);
return eventNode is EventDeclarationSyntax;
}
public override bool GetIsShared(SyntaxNode memberNode, ISymbol symbol)
{
Debug.Assert(memberNode is MemberDeclarationSyntax ||
memberNode is VariableDeclaratorSyntax);
if (!(GetNodeWithModifiers(memberNode) is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
return (member.GetModifierFlags() & ModifierFlags.Static) != 0;
}
public override SyntaxNode SetIsShared(SyntaxNode memberNode, bool value)
{
Debug.Assert(memberNode is MemberDeclarationSyntax);
if (!(memberNode is MemberDeclarationSyntax member))
{
throw Exceptions.ThrowEFail();
}
var flags = member.GetModifierFlags();
if (value)
{
flags |= ModifierFlags.Static;
}
else
{
flags &= ~ModifierFlags.Static;
}
return member.UpdateModifiers(flags);
}
public override EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode)
{
Debug.Assert(memberNode is BasePropertyDeclarationSyntax);
if (!(memberNode is BasePropertyDeclarationSyntax property))
{
throw Exceptions.ThrowEFail();
}
var hasGetter = property.AccessorList != null && property.AccessorList.Accessors.Any(SyntaxKind.GetAccessorDeclaration);
var hasSetter = property.AccessorList != null && property.AccessorList.Accessors.Any(SyntaxKind.SetAccessorDeclaration);
if (!hasGetter && !hasSetter)
{
var expressionBody = property.GetExpressionBody();
if (expressionBody != null)
{
hasGetter = true;
}
}
if (hasGetter && hasSetter)
{
return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite;
}
else if (hasSetter)
{
return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindWriteOnly;
}
else if (hasGetter)
{
return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadOnly;
}
else
{
return EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite;
}
}
public override SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol)
{
Debug.Assert(node is MemberDeclarationSyntax ||
node is ParameterSyntax);
TypeSyntax oldType;
if (node is MemberDeclarationSyntax memberDeclaration)
{
oldType = memberDeclaration.GetMemberType();
}
else if (node is ParameterSyntax parameter)
{
oldType = parameter.Type;
}
else
{
throw Exceptions.ThrowEFail();
}
if (oldType == null)
{
throw Exceptions.ThrowEFail();
}
var typeName = typeSymbol.ToDisplayString(s_setTypeFormat);
var newType = SyntaxFactory.ParseTypeName(typeName);
return node.ReplaceNode(oldType, newType);
}
private Document Delete(Document document, VariableDeclaratorSyntax node)
{
var fieldDeclaration = node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>();
// If we won't have anything left, then just delete the whole declaration
if (fieldDeclaration.Declaration.Variables.Count == 1)
{
return Delete(document, fieldDeclaration);
}
else
{
var newFieldDeclaration = fieldDeclaration.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
return document.ReplaceNodeSynchronously(fieldDeclaration, newFieldDeclaration, CancellationToken.None);
}
}
private Document Delete(Document document, EnumMemberDeclarationSyntax node)
{
var enumDeclaration = (EnumDeclarationSyntax)node.Parent;
var members = enumDeclaration.Members;
var newMembers = members.Remove(node);
var newEnumDeclaration = enumDeclaration.WithMembers(newMembers);
// If we're removing the last enum member, we may need to move any trailing trivia
// to the enum member that comes before it.
var memberIndex = members.IndexOf(node);
if (memberIndex == members.Count - 1 && newMembers.Count > 0)
{
var trailingTrivia = node.GetTrailingTrivia();
var lastMember = newEnumDeclaration.Members.Last();
newEnumDeclaration = newEnumDeclaration.ReplaceNode(lastMember, lastMember.WithTrailingTrivia(trailingTrivia));
}
return document.ReplaceNodeSynchronously(enumDeclaration, newEnumDeclaration, CancellationToken.None);
}
private Document Delete(Document document, AttributeSyntax node)
{
var attributeList = node.FirstAncestorOrSelf<AttributeListSyntax>();
// If we don't have anything left, then just delete the whole attribute list.
if (attributeList.Attributes.Count == 1)
{
var text = document.GetTextSynchronously(CancellationToken.None);
// Note that we want to keep all leading trivia and delete all trailing trivia.
var deletionStart = attributeList.SpanStart;
var deletionEnd = attributeList.FullSpan.End;
text = text.Replace(TextSpan.FromBounds(deletionStart, deletionEnd), string.Empty);
return document.WithText(text);
}
else
{
var newAttributeList = attributeList.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
return document.ReplaceNodeSynchronously(attributeList, newAttributeList, CancellationToken.None);
}
}
private Document Delete(Document document, AttributeArgumentSyntax node)
{
var argumentList = node.FirstAncestorOrSelf<AttributeArgumentListSyntax>();
var newArgumentList = argumentList.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
return document.ReplaceNodeSynchronously(argumentList, newArgumentList, CancellationToken.None);
}
private Document Delete(Document document, ParameterSyntax node)
{
var parameterList = node.FirstAncestorOrSelf<ParameterListSyntax>();
var newParameterList = parameterList.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
return document.ReplaceNodeSynchronously(parameterList, newParameterList, CancellationToken.None);
}
private Document DeleteMember(Document document, SyntaxNode node)
{
var text = document.GetTextSynchronously(CancellationToken.None);
// We want to delete all the leading trivia from the node back to,
// but not including:
// * the first preprocessor directive
// - or -
// * the first comment after a white-space only line
// We also want to delete all the trailing trivia
var deletionEnd = node.FullSpan.End;
var deletionStart = node.SpanStart;
var contiguousEndOfLines = 0;
foreach (var trivia in node.GetLeadingTrivia().Reverse())
{
if (trivia.IsDirective)
{
break;
}
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
if (contiguousEndOfLines > 0)
{
break;
}
else
{
contiguousEndOfLines++;
}
}
else if (trivia.Kind() != SyntaxKind.WhitespaceTrivia)
{
contiguousEndOfLines = 0;
}
deletionStart = trivia.FullSpan.Start;
}
text = text.Replace(TextSpan.FromBounds(deletionStart, deletionEnd), string.Empty);
return document.WithText(text);
}
public override Document Delete(Document document, SyntaxNode node)
=> node.Kind() switch
{
SyntaxKind.VariableDeclarator => Delete(document, (VariableDeclaratorSyntax)node),
SyntaxKind.EnumMemberDeclaration => Delete(document, (EnumMemberDeclarationSyntax)node),
SyntaxKind.Attribute => Delete(document, (AttributeSyntax)node),
SyntaxKind.AttributeArgument => Delete(document, (AttributeArgumentSyntax)node),
SyntaxKind.Parameter => Delete(document, (ParameterSyntax)node),
_ => DeleteMember(document, node),
};
public override string GetMethodXml(SyntaxNode node, SemanticModel semanticModel)
{
if (!(node is MethodDeclarationSyntax methodDeclaration))
{
throw Exceptions.ThrowEUnexpected();
}
return MethodXmlBuilder.Generate(methodDeclaration, semanticModel);
}
public override string GetInitExpression(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.EnumMemberDeclaration:
var enumMemberDeclaration = (EnumMemberDeclarationSyntax)node;
return enumMemberDeclaration.EqualsValue?.Value.ToString();
case SyntaxKind.VariableDeclarator:
var variableDeclarator = (VariableDeclaratorSyntax)node;
return variableDeclarator.Initializer?.Value.ToString();
case SyntaxKind.Parameter:
var parameter = (ParameterSyntax)node;
return parameter.Default?.Value.ToString();
default:
throw Exceptions.ThrowEFail();
}
}
public override SyntaxNode AddInitExpression(SyntaxNode node, string value)
{
switch (node.Kind())
{
case SyntaxKind.EnumMemberDeclaration:
{
var enumMemberDeclaration = (EnumMemberDeclarationSyntax)node;
if (string.IsNullOrWhiteSpace(value))
{
return enumMemberDeclaration.WithEqualsValue(null);
}
var expression = SyntaxFactory.ParseExpression(value);
var equalsValueClause = enumMemberDeclaration.EqualsValue != null
? enumMemberDeclaration.EqualsValue.WithValue(expression)
: SyntaxFactory.EqualsValueClause(expression);
return enumMemberDeclaration.WithEqualsValue(equalsValueClause);
}
case SyntaxKind.VariableDeclarator:
{
var variableDeclarator = (VariableDeclaratorSyntax)node;
if (string.IsNullOrWhiteSpace(value))
{
return variableDeclarator.WithInitializer(null);
}
var expression = SyntaxFactory.ParseExpression(value);
var equalsValueClause = variableDeclarator.Initializer != null
? variableDeclarator.Initializer.WithValue(expression)
: SyntaxFactory.EqualsValueClause(expression);
return variableDeclarator.WithInitializer(equalsValueClause);
}
case SyntaxKind.Parameter:
{
var parameter = (ParameterSyntax)node;
if (string.IsNullOrWhiteSpace(value))
{
return parameter.WithDefault(null);
}
var expression = SyntaxFactory.ParseExpression(value);
var equalsValueClause = parameter.Default != null
? parameter.Default.WithValue(expression)
: SyntaxFactory.EqualsValueClause(expression);
return parameter.WithDefault(equalsValueClause);
}
default:
throw Exceptions.ThrowEFail();
}
}
public override CodeGenerationDestination GetDestination(SyntaxNode node)
=> CSharpCodeGenerationHelpers.GetDestination(node);
protected override Accessibility GetDefaultAccessibility(SymbolKind targetSymbolKind, CodeGenerationDestination destination)
{
switch (targetSymbolKind)
{
case SymbolKind.Field:
case SymbolKind.Method:
case SymbolKind.Property:
case SymbolKind.Event:
return Accessibility.Private;
case SymbolKind.NamedType:
switch (destination)
{
case CodeGenerationDestination.ClassType:
case CodeGenerationDestination.EnumType:
case CodeGenerationDestination.InterfaceType:
case CodeGenerationDestination.StructType:
return Accessibility.Private;
default:
return Accessibility.Internal;
}
default:
Debug.Fail("Invalid symbol kind: " + targetSymbolKind);
throw Exceptions.ThrowEFail();
}
}
protected override ITypeSymbol GetTypeSymbolFromPartialName(string partialName, SemanticModel semanticModel, int position)
{
var parsedTypeName = SyntaxFactory.ParseTypeName(partialName);
return semanticModel.GetSpeculativeTypeInfo(position, parsedTypeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
}
public override ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation)
{
ITypeSymbol typeSymbol = compilation.GetTypeByMetadataName(fullName);
if (typeSymbol == null)
{
var parsedTypeName = SyntaxFactory.ParseTypeName(fullName);
// Check to see if the name we parsed has any skipped text. If it does, don't bother trying to
// speculatively bind it because we'll likely just get the wrong thing since we found a bunch
// of non-sensical tokens.
if (parsedTypeName.ContainsSkippedText)
{
return null;
}
// If we couldn't get the name, we just grab the first tree in the compilation to
// speculatively bind at position zero. However, if there *aren't* any trees, we fork the
// compilation with an empty tree for the purposes of speculative binding.
//
// I'm a bad person.
var tree = compilation.SyntaxTrees.FirstOrDefault();
if (tree == null)
{
tree = SyntaxFactory.ParseSyntaxTree("");
compilation = compilation.AddSyntaxTrees(tree);
}
var semanticModel = compilation.GetSemanticModel(tree);
typeSymbol = semanticModel.GetSpeculativeTypeInfo(0, parsedTypeName, SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
}
if (typeSymbol == null)
{
Debug.Fail("Could not find type: " + fullName);
throw new ArgumentException();
}
return typeSymbol;
}
public override SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type)
{
return SyntaxFactory.ReturnStatement(
SyntaxFactory.DefaultExpression(
SyntaxFactory.ParseTypeName(type.ToDisplayString())));
}
protected override int GetAttributeIndexInContainer(SyntaxNode containerNode, Func<SyntaxNode, bool> predicate)
{
var attributes = GetAttributeNodes(containerNode).ToArray();
var index = 0;
while (index < attributes.Length)
{
var attribute = (AttributeSyntax)attributes[index];
if (predicate(attribute))
{
var attributeDeclaration = (AttributeListSyntax)attribute.Parent;
// If this attribute is part of a declaration with multiple attributes,
// make sure to return the index of the last attribute in the declaration.
if (attributeDeclaration.Attributes.Count > 1)
{
var indexOfAttributeInDeclaration = attributeDeclaration.Attributes.IndexOf(attribute);
return index + (attributeDeclaration.Attributes.Count - indexOfAttributeInDeclaration);
}
return index + 1;
}
index++;
}
return -1;
}
protected override int GetAttributeArgumentIndexInContainer(SyntaxNode containerNode, Func<SyntaxNode, bool> predicate)
{
var attributeArguments = GetAttributeArgumentNodes(containerNode).ToArray();
for (var index = 0; index < attributeArguments.Length; index++)
{
if (predicate(attributeArguments[index]))
{
return index + 1;
}
}
return -1;
}
protected override int GetImportIndexInContainer(SyntaxNode containerNode, Func<SyntaxNode, bool> predicate)
{
var imports = GetImportNodes(containerNode).ToArray();
for (var index = 0; index < imports.Length; index++)
{
if (predicate(imports[index]))
{
return index + 1;
}
}
return -1;
}
protected override int GetParameterIndexInContainer(SyntaxNode containerNode, Func<SyntaxNode, bool> predicate)
{
var parameters = GetParameterNodes(containerNode).ToArray();
for (var index = 0; index < parameters.Length; index++)
{
if (predicate(parameters[index]))
{
return index + 1;
}
}
return -1;
}
protected override int GetMemberIndexInContainer(SyntaxNode containerNode, Func<SyntaxNode, bool> predicate)
{
var members = GetLogicalMemberNodes(containerNode).ToArray();
var index = 0;
while (index < members.Length)
{
var member = members[index];
if (predicate(member))
{
// If a variable declarator was specified, make sure we return
// the index of the last variable declarator in the parenting field declaration.
if (member.IsKind(SyntaxKind.VariableDeclarator, out VariableDeclaratorSyntax variableDeclarator))
{
var variableDeclaration = (VariableDeclarationSyntax)member.Parent;
var indexOfDeclaratorInField = variableDeclaration.Variables.IndexOf(variableDeclarator);
return index + (variableDeclaration.Variables.Count - indexOfDeclaratorInField);
}
// Note: we always return the item *after* this index.
return index + 1;
}
index++;
}
return -1;
}
protected override SyntaxNode GetFieldFromVariableNode(SyntaxNode node)
{
return node.Kind() == SyntaxKind.VariableDeclarator
? node.FirstAncestorOrSelf<BaseFieldDeclarationSyntax>()
: node;
}
protected override SyntaxNode GetVariableFromFieldNode(SyntaxNode finalNode)
{
// Work around the fact that code model really deals in terms of variable declarators
return finalNode is BaseFieldDeclarationSyntax
? ((BaseFieldDeclarationSyntax)finalNode).Declaration.Variables.Single()
: finalNode;
}
protected override SyntaxNode GetAttributeFromAttributeDeclarationNode(SyntaxNode node)
{
return node is AttributeListSyntax
? ((AttributeListSyntax)node).Attributes.First()
: node;
}
protected override TextSpan GetSpanToFormat(SyntaxNode root, TextSpan span)
{
var startToken = root.FindToken(span.Start).GetPreviousToken();
if (startToken.Kind() == SyntaxKind.OpenBraceToken)
{
startToken = startToken.GetPreviousToken();
}
var endToken = root.FindToken(span.End).GetNextToken();
if (endToken.Kind() == SyntaxKind.CloseBraceToken)
{
endToken = endToken.GetPreviousToken();
}
startToken = GetTokenWithoutAnnotation(startToken, t => t.GetPreviousToken());
endToken = GetTokenWithoutAnnotation(endToken, t => t.GetNextToken());
return GetEncompassingSpan(root, startToken, endToken);
}
protected SyntaxNode InsertMemberNodeIntoContainerCore(int index, SyntaxNode member, SyntaxNode container)
{
if (container is CompilationUnitSyntax compilationUnit)
{
var newMembers = compilationUnit.Members.Insert(index, (MemberDeclarationSyntax)member);
return compilationUnit.WithMembers(newMembers);
}
else if (container is BaseNamespaceDeclarationSyntax namespaceDeclaration)
{
var newMembers = namespaceDeclaration.Members.Insert(index, (MemberDeclarationSyntax)member);
return namespaceDeclaration.WithMembers(newMembers);
}
else if (container is TypeDeclarationSyntax typeDeclaration)
{
var newMembers = typeDeclaration.Members.Insert(index, (MemberDeclarationSyntax)member);
return typeDeclaration.WithMembers(newMembers);
}
else if (container is EnumDeclarationSyntax enumDeclaration)
{
// If we're inserting at the end of the list of enum members, we may need to strip the trailing
// line from the last enum member and add it to the separator that comes after it.
if (index > 0 && index == enumDeclaration.Members.Count)
{
var lastMember = enumDeclaration.Members[index - 1];
var trailingTrivia = lastMember.GetTrailingTrivia();
enumDeclaration = enumDeclaration.ReplaceNode(lastMember, lastMember.WithTrailingTrivia(SyntaxTriviaList.Empty));
var newMembers = enumDeclaration.Members.Insert(index, (EnumMemberDeclarationSyntax)member);
enumDeclaration = enumDeclaration.WithMembers(newMembers);
var separator = enumDeclaration.Members.GetSeparator(index - 1);
return enumDeclaration.ReplaceToken(separator, separator.WithTrailingTrivia(trailingTrivia));
}
else
{
var newMembers = enumDeclaration.Members.Insert(index, (EnumMemberDeclarationSyntax)member);
return enumDeclaration.WithMembers(newMembers);
}
}
throw Exceptions.ThrowEFail();
}
private static MemberDeclarationSyntax GetMember(SyntaxNode container, int index)
{
if (container is CompilationUnitSyntax compilationUnit)
{
return compilationUnit.Members[index];
}
else if (container is BaseNamespaceDeclarationSyntax namespaceDeclaration)
{
return namespaceDeclaration.Members[index];
}
else if (container is TypeDeclarationSyntax typeDeclaration)
{
return typeDeclaration.Members[index];
}
else if (container is EnumDeclarationSyntax enumDeclaration)
{
return enumDeclaration.Members[index];
}
throw Exceptions.ThrowEFail();
}
private SyntaxNode EnsureAfterEndRegion(int index, SyntaxNode container)
{
// If the next token after our member has only whitespace and #endregion as leading
// trivia, we'll move that to be leading trivia of our member.
var newContainer = container;
var newMember = GetMember(newContainer, index);
var lastToken = newMember.GetLastToken();
var nextToken = lastToken.GetNextToken();
var triviaList = nextToken.LeadingTrivia;
var lastNonWhitespaceTrivia = triviaList.LastOrDefault(trivia => !trivia.IsWhitespaceOrEndOfLine());
if (lastNonWhitespaceTrivia.Kind() == SyntaxKind.EndRegionDirectiveTrivia)
{
newContainer = newContainer
.ReplaceToken(nextToken, nextToken.WithLeadingTrivia(SyntaxTriviaList.Empty));
newMember = GetMember(newContainer, index);
var firstToken = newMember.GetFirstToken();
newContainer = newContainer
.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(triviaList));
}
return newContainer;
}
protected override SyntaxNode InsertMemberNodeIntoContainer(int index, SyntaxNode member, SyntaxNode container)
{
var newContainer = InsertMemberNodeIntoContainerCore(index, member, container);
newContainer = EnsureAfterEndRegion(index, newContainer);
return newContainer;
}
protected override SyntaxNode InsertAttributeArgumentIntoContainer(int index, SyntaxNode attributeArgument, SyntaxNode container)
{
if (container is AttributeSyntax attribute)
{
var argumentList = attribute.ArgumentList;
AttributeArgumentListSyntax newArgumentList;
if (argumentList == null)
{
newArgumentList = SyntaxFactory.AttributeArgumentList(
SyntaxFactory.SingletonSeparatedList(
(AttributeArgumentSyntax)attributeArgument));
}
else
{
var newArguments = argumentList.Arguments.Insert(index, (AttributeArgumentSyntax)attributeArgument);
newArgumentList = argumentList.WithArguments(newArguments);
}
return attribute.WithArgumentList(newArgumentList);
}
throw Exceptions.ThrowEFail();
}
protected override SyntaxNode InsertAttributeListIntoContainer(int index, SyntaxNode list, SyntaxNode container)
{
// If the attribute list is being inserted at the first index and the container is not the compilation unit, copy leading trivia
// to the list that is being inserted.
if (index == 0 && !(container is CompilationUnitSyntax))
{
var firstToken = container.GetFirstToken();
if (firstToken.HasLeadingTrivia)
{
var trivia = firstToken.LeadingTrivia;
container = container.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(SyntaxTriviaList.Empty));
list = list.WithLeadingTrivia(trivia);
}
}
if (container is CompilationUnitSyntax compilationUnit)
{
var newAttributeLists = compilationUnit.AttributeLists.Insert(index, (AttributeListSyntax)list);
return compilationUnit.WithAttributeLists(newAttributeLists);
}
else if (container is EnumDeclarationSyntax enumDeclaration)
{
var newAttributeLists = enumDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return enumDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is ClassDeclarationSyntax classDeclaration)
{
var newAttributeLists = classDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return classDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is StructDeclarationSyntax structDeclaration)
{
var newAttributeLists = structDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return structDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is InterfaceDeclarationSyntax interfaceDeclaration)
{
var newAttributeLists = interfaceDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return interfaceDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is MethodDeclarationSyntax method)
{
var newAttributeLists = method.AttributeLists.Insert(index, (AttributeListSyntax)list);
return method.WithAttributeLists(newAttributeLists);
}
else if (container is OperatorDeclarationSyntax operationDeclaration)
{
var newAttributeLists = operationDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return operationDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is ConversionOperatorDeclarationSyntax conversion)
{
var newAttributeLists = conversion.AttributeLists.Insert(index, (AttributeListSyntax)list);
return conversion.WithAttributeLists(newAttributeLists);
}
else if (container is ConstructorDeclarationSyntax constructor)
{
var newAttributeLists = constructor.AttributeLists.Insert(index, (AttributeListSyntax)list);
return constructor.WithAttributeLists(newAttributeLists);
}
else if (container is DestructorDeclarationSyntax destructor)
{
var newAttributeLists = destructor.AttributeLists.Insert(index, (AttributeListSyntax)list);
return destructor.WithAttributeLists(newAttributeLists);
}
else if (container is PropertyDeclarationSyntax property)
{
var newAttributeLists = property.AttributeLists.Insert(index, (AttributeListSyntax)list);
return property.WithAttributeLists(newAttributeLists);
}
else if (container is EventDeclarationSyntax eventDeclaration)
{
var newAttributeLists = eventDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return eventDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is IndexerDeclarationSyntax indexer)
{
var newAttributeLists = indexer.AttributeLists.Insert(index, (AttributeListSyntax)list);
return indexer.WithAttributeLists(newAttributeLists);
}
else if (container is FieldDeclarationSyntax field)
{
var newAttributeLists = field.AttributeLists.Insert(index, (AttributeListSyntax)list);
return field.WithAttributeLists(newAttributeLists);
}
else if (container is EventFieldDeclarationSyntax eventFieldDeclaration)
{
var newAttributeLists = eventFieldDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return eventFieldDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is DelegateDeclarationSyntax delegateDeclaration)
{
var newAttributeLists = delegateDeclaration.AttributeLists.Insert(index, (AttributeListSyntax)list);
return delegateDeclaration.WithAttributeLists(newAttributeLists);
}
else if (container is EnumMemberDeclarationSyntax member)
{
var newAttributeLists = member.AttributeLists.Insert(index, (AttributeListSyntax)list);
return member.WithAttributeLists(newAttributeLists);
}
else if (container is ParameterSyntax parameter)
{
var newAttributeLists = parameter.AttributeLists.Insert(index, (AttributeListSyntax)list);
return parameter.WithAttributeLists(newAttributeLists);
}
else if (container is VariableDeclaratorSyntax ||
container is VariableDeclarationSyntax)
{
return InsertAttributeListIntoContainer(index, list, container.Parent);
}
throw Exceptions.ThrowEUnexpected();
}
protected override SyntaxNode InsertImportIntoContainer(int index, SyntaxNode importNode, SyntaxNode container)
{
var import = (UsingDirectiveSyntax)importNode;
if (container is CompilationUnitSyntax compilationUnit)
{
var usingsList = compilationUnit.Usings.Insert(index, import);
return compilationUnit.WithUsings(usingsList);
}
throw Exceptions.ThrowEUnexpected();
}
protected override SyntaxNode InsertParameterIntoContainer(int index, SyntaxNode parameter, SyntaxNode container)
{
if (container is BaseMethodDeclarationSyntax method)
{
var parameterList = method.ParameterList.Parameters.Insert(index, (ParameterSyntax)parameter);
return method.WithParameterList(method.ParameterList.WithParameters(parameterList));
}
else if (container is IndexerDeclarationSyntax indexer)
{
var parameterList = indexer.ParameterList.Parameters.Insert(index, (ParameterSyntax)parameter);
return indexer.WithParameterList(indexer.ParameterList.WithParameters(parameterList));
}
else if (container is DelegateDeclarationSyntax delegateDeclaration)
{
var parameterList = delegateDeclaration.ParameterList.Parameters.Insert(index, (ParameterSyntax)parameter);
return delegateDeclaration.WithParameterList(delegateDeclaration.ParameterList.WithParameters(parameterList));
}
throw Exceptions.ThrowEUnexpected();
}
protected override bool IsCodeModelNode(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.CompilationUnit:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMemberDeclaration:
case SyntaxKind.FieldDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.UsingDirective:
return true;
default:
return false;
}
}
public override bool IsNamespace(SyntaxNode node)
=> node is BaseNamespaceDeclarationSyntax;
public override bool IsType(SyntaxNode node)
{
return node.IsKind(SyntaxKind.ClassDeclaration)
|| node.IsKind(SyntaxKind.InterfaceDeclaration)
|| node.IsKind(SyntaxKind.StructDeclaration)
|| node.IsKind(SyntaxKind.EnumDeclaration)
|| node.IsKind(SyntaxKind.DelegateDeclaration);
}
private static bool IsAutoImplementedProperty(PropertyDeclarationSyntax propertyDeclaration)
{
if (propertyDeclaration.IsParentKind(SyntaxKind.InterfaceDeclaration))
{
return false;
}
var modifierFlags = propertyDeclaration.GetModifierFlags();
if ((modifierFlags & ModifierFlags.Abstract) != 0 ||
(modifierFlags & ModifierFlags.Extern) != 0)
{
return false;
}
if (propertyDeclaration.AccessorList == null)
{
return false;
}
AccessorDeclarationSyntax getAccessor = null;
AccessorDeclarationSyntax setAccessor = null;
foreach (var accessor in propertyDeclaration.AccessorList.Accessors)
{
switch (accessor.Kind())
{
case SyntaxKind.GetAccessorDeclaration:
if (getAccessor == null)
{
getAccessor = accessor;
}
break;
case SyntaxKind.SetAccessorDeclaration:
if (setAccessor == null)
{
setAccessor = accessor;
}
break;
}
}
if (getAccessor == null || setAccessor == null)
{
return false;
}
return getAccessor.Body == null && setAccessor.Body == null;
}
private static bool IsExtensionMethod(MethodDeclarationSyntax methodDeclaration)
{
if (!methodDeclaration.IsParentKind(SyntaxKind.ClassDeclaration, out ClassDeclarationSyntax classDecl) ||
!classDecl.Modifiers.Any(SyntaxKind.StaticKeyword))
{
return false;
}
if (methodDeclaration.ParameterList == null ||
methodDeclaration.ParameterList.Parameters.Count == 0)
{
return false;
}
return methodDeclaration.ParameterList.Parameters[0].Modifiers.Any(SyntaxKind.ThisKeyword);
}
private static bool IsPartialMethod(MethodDeclarationSyntax methodDeclaration)
=> methodDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword);
public override string[] GetFunctionExtenderNames()
=> new[] { ExtenderNames.ExtensionMethod, ExtenderNames.PartialMethod };
public override object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol)
{
if (node == null || node.Kind() != SyntaxKind.MethodDeclaration ||
symbol == null || symbol.Kind != SymbolKind.Method)
{
throw Exceptions.ThrowEUnexpected();
}
if (StringComparer.Ordinal.Equals(name, ExtenderNames.PartialMethod))
{
var methodDeclaration = (MethodDeclarationSyntax)node;
var isPartial = IsPartialMethod(methodDeclaration);
var isDeclaration = false;
var hasOtherPart = false;
if (isPartial)
{
var methodSymbol = (IMethodSymbol)symbol;
isDeclaration = methodSymbol.PartialDefinitionPart == null;
hasOtherPart = isDeclaration
? methodSymbol.PartialImplementationPart != null
: methodSymbol.PartialDefinitionPart != null;
}
return PartialMethodExtender.Create(isPartial, isDeclaration, hasOtherPart);
}
else if (StringComparer.Ordinal.Equals(name, ExtenderNames.ExtensionMethod))
{
var methodDeclaration = (MethodDeclarationSyntax)node;
var isExtension = IsExtensionMethod(methodDeclaration);
return ExtensionMethodExtender.Create(isExtension);
}
throw Exceptions.ThrowEFail();
}
public override string[] GetPropertyExtenderNames()
=> new[] { ExtenderNames.AutoImplementedProperty };
public override object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol)
{
if (node == null || node.Kind() != SyntaxKind.PropertyDeclaration ||
symbol == null || symbol.Kind != SymbolKind.Property)
{
throw Exceptions.ThrowEUnexpected();
}
if (StringComparer.Ordinal.Equals(name, ExtenderNames.AutoImplementedProperty))
{
var propertyDeclaration = (PropertyDeclarationSyntax)node;
var isAutoImplemented = IsAutoImplementedProperty(propertyDeclaration);
return AutoImplementedPropertyExtender.Create(isAutoImplemented);
}
throw Exceptions.ThrowEFail();
}
public override string[] GetExternalTypeExtenderNames()
=> new[] { ExtenderNames.ExternalLocation };
public override object GetExternalTypeExtender(string name, string externalLocation)
{
Debug.Assert(externalLocation != null);
if (StringComparer.Ordinal.Equals(name, ExtenderNames.ExternalLocation))
{
return CodeTypeLocationExtender.Create(externalLocation);
}
throw Exceptions.ThrowEFail();
}
public override string[] GetTypeExtenderNames()
=> Array.Empty<string>();
public override object GetTypeExtender(string name, AbstractCodeType symbol)
=> throw Exceptions.ThrowEFail();
protected override bool AddBlankLineToMethodBody(SyntaxNode node, SyntaxNode newNode)
{
return node is MethodDeclarationSyntax methodDeclaration
&& methodDeclaration.Body == null
&& newNode is MethodDeclarationSyntax newMethodDeclaration
&& newMethodDeclaration.Body != null;
}
private static TypeDeclarationSyntax InsertIntoBaseList(TypeDeclarationSyntax typeDeclaration, ITypeSymbol typeSymbol, SemanticModel semanticModel, int insertionIndex)
{
var position = typeDeclaration.SpanStart;
var identifier = typeDeclaration.Identifier;
if (identifier.HasTrailingTrivia)
{
typeDeclaration = typeDeclaration.WithIdentifier(
identifier.WithTrailingTrivia(identifier.TrailingTrivia.SkipWhile(t => t.IsWhitespaceOrEndOfLine())));
}
var typeName = SyntaxFactory.ParseTypeName(typeSymbol.ToMinimalDisplayString(semanticModel, position));
var baseList = typeDeclaration.BaseList != null
? typeDeclaration.BaseList.WithTypes(typeDeclaration.BaseList.Types.Insert(insertionIndex, SyntaxFactory.SimpleBaseType(typeName)))
: SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList((BaseTypeSyntax)SyntaxFactory.SimpleBaseType(typeName)));
return typeDeclaration.WithBaseList(baseList);
}
public override bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol)
{
if (node.IsKind(SyntaxKind.ClassDeclaration))
{
return typeSymbol.TypeKind == TypeKind.Class;
}
else if (node.IsKind(SyntaxKind.InterfaceDeclaration))
{
return typeSymbol.TypeKind == TypeKind.Interface;
}
return false;
}
public override SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position)
{
if (!node.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.InterfaceDeclaration))
{
throw Exceptions.ThrowEFail();
}
var typeDeclaration = (TypeDeclarationSyntax)node;
var baseCount = typeDeclaration.BaseList != null
? typeDeclaration.BaseList.Types.Count
: 0;
int insertionIndex;
if (typeDeclaration.IsKind(SyntaxKind.ClassDeclaration))
{
insertionIndex = 0;
}
else if (position != null)
{
insertionIndex = position.Value;
if (insertionIndex > baseCount)
{
throw Exceptions.ThrowEInvalidArg();
}
}
else
{
insertionIndex = baseCount;
}
return InsertIntoBaseList(typeDeclaration, typeSymbol, semanticModel, insertionIndex);
}
public override SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel)
{
if (!node.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.InterfaceDeclaration))
{
throw Exceptions.ThrowEFail();
}
var typeDeclaration = (TypeDeclarationSyntax)node;
if (typeDeclaration.BaseList == null ||
typeDeclaration.BaseList.Types.Count == 0)
{
throw Exceptions.ThrowEInvalidArg();
}
var isFirst = true;
BaseTypeSyntax baseType = null;
foreach (var type in typeDeclaration.BaseList.Types)
{
if (!isFirst && node.IsKind(SyntaxKind.ClassDeclaration))
{
break;
}
var typeInfo = semanticModel.GetTypeInfo(type.Type, CancellationToken.None);
if (typeInfo.Type != null &&
typeInfo.Type.Equals(typeSymbol))
{
baseType = type;
break;
}
isFirst = false;
}
if (baseType == null)
{
throw Exceptions.ThrowEInvalidArg();
}
var newTypes = typeDeclaration.BaseList.Types.Remove(baseType);
var newBaseList = typeDeclaration.BaseList.WithTypes(newTypes);
if (newBaseList.Types.Count == 0)
{
newBaseList = null;
}
return typeDeclaration.WithBaseList(newBaseList);
}
public override bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol)
{
if (node.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration))
{
return typeSymbol.TypeKind == TypeKind.Interface;
}
return false;
}
public override SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position)
{
if (!node.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration))
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.Kind != SymbolKind.NamedType ||
typeSymbol.TypeKind != TypeKind.Interface)
{
throw Exceptions.ThrowEInvalidArg();
}
var typeDeclaration = (TypeDeclarationSyntax)node;
var baseCount = typeDeclaration.BaseList != null
? typeDeclaration.BaseList.Types.Count
: 0;
int insertionIndex;
if (position != null)
{
insertionIndex = position.Value;
if (insertionIndex > baseCount)
{
throw Exceptions.ThrowEInvalidArg();
}
}
else
{
insertionIndex = baseCount;
}
return InsertIntoBaseList(typeDeclaration, typeSymbol, semanticModel, insertionIndex);
}
public override SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel)
{
if (!node.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration))
{
throw Exceptions.ThrowEFail();
}
var typeDeclaration = (TypeDeclarationSyntax)node;
if (typeDeclaration.BaseList == null ||
typeDeclaration.BaseList.Types.Count == 0)
{
throw Exceptions.ThrowEInvalidArg();
}
BaseTypeSyntax baseType = null;
foreach (var type in typeDeclaration.BaseList.Types)
{
var typeInfo = semanticModel.GetTypeInfo(type.Type, CancellationToken.None);
if (typeInfo.Type != null &&
typeInfo.Type.Equals(typeSymbol))
{
baseType = type;
break;
}
}
if (baseType == null)
{
throw Exceptions.ThrowEInvalidArg();
}
var newTypes = typeDeclaration.BaseList.Types.Remove(baseType);
var newBaseList = typeDeclaration.BaseList.WithTypes(newTypes);
if (newBaseList.Types.Count == 0)
{
newBaseList = null;
}
return typeDeclaration.WithBaseList(newBaseList);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Portable/Emitter/Model/GenericMethodInstanceReference.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
/// <summary>
/// Represents a reference to a generic method instantiation, closed over type parameters,
/// e.g. MyNamespace.Class.Method{T}()
/// </summary>
internal sealed class GenericMethodInstanceReference : MethodReference, Cci.IGenericMethodInstanceReference
{
public GenericMethodInstanceReference(MethodSymbol underlyingMethod)
: base(underlyingMethod)
{
}
public override void Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit((Cci.IGenericMethodInstanceReference)this);
}
IEnumerable<Cci.ITypeReference> Cci.IGenericMethodInstanceReference.GetGenericArguments(EmitContext context)
{
PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;
foreach (var arg in UnderlyingMethod.TypeArgumentsWithAnnotations)
{
Debug.Assert(arg.CustomModifiers.IsEmpty);
yield return moduleBeingBuilt.Translate(arg.Type, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics);
}
}
Cci.IMethodReference Cci.IGenericMethodInstanceReference.GetGenericMethod(EmitContext context)
{
// NoPia method might come through here.
return ((PEModuleBuilder)context.Module).Translate(
UnderlyingMethod.OriginalDefinition,
syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode,
diagnostics: context.Diagnostics,
needDeclaration: true);
}
public override Cci.IGenericMethodInstanceReference AsGenericMethodInstanceReference
{
get
{
return this;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
/// <summary>
/// Represents a reference to a generic method instantiation, closed over type parameters,
/// e.g. MyNamespace.Class.Method{T}()
/// </summary>
internal sealed class GenericMethodInstanceReference : MethodReference, Cci.IGenericMethodInstanceReference
{
public GenericMethodInstanceReference(MethodSymbol underlyingMethod)
: base(underlyingMethod)
{
}
public override void Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit((Cci.IGenericMethodInstanceReference)this);
}
IEnumerable<Cci.ITypeReference> Cci.IGenericMethodInstanceReference.GetGenericArguments(EmitContext context)
{
PEModuleBuilder moduleBeingBuilt = (PEModuleBuilder)context.Module;
foreach (var arg in UnderlyingMethod.TypeArgumentsWithAnnotations)
{
Debug.Assert(arg.CustomModifiers.IsEmpty);
yield return moduleBeingBuilt.Translate(arg.Type, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics);
}
}
Cci.IMethodReference Cci.IGenericMethodInstanceReference.GetGenericMethod(EmitContext context)
{
// NoPia method might come through here.
return ((PEModuleBuilder)context.Module).Translate(
UnderlyingMethod.OriginalDefinition,
syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode,
diagnostics: context.Diagnostics,
needDeclaration: true);
}
public override Cci.IGenericMethodInstanceReference AsGenericMethodInstanceReference
{
get
{
return this;
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/Core/Def/ValueTracking/ValueTrackingToolWindow.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Windows.Controls;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
namespace Microsoft.VisualStudio.LanguageServices.ValueTracking
{
[Guid(Guids.ValueTrackingToolWindowIdString)]
internal class ValueTrackingToolWindow : ToolWindowPane
{
private readonly ValueTrackingRoot _root = new();
public static ValueTrackingToolWindow? Instance { get; set; }
private ValueTrackingTreeViewModel? _viewModel;
public ValueTrackingTreeViewModel? ViewModel
{
get => _viewModel;
set
{
if (value is null)
{
throw new ArgumentNullException(nameof(ViewModel));
}
_viewModel = value;
_root.SetChild(new ValueTrackingTree(_viewModel));
}
}
/// <summary>
/// This paramterless constructor is used when
/// the tool window is initialized on open without any
/// context. If the tool window is left open across shutdown/restart
/// of VS for example, then this gets called.
/// </summary>
public ValueTrackingToolWindow() : base(null)
{
Caption = ServicesVSResources.Value_Tracking;
Content = _root;
}
public ValueTrackingToolWindow(ValueTrackingTreeViewModel viewModel)
: base(null)
{
Caption = ServicesVSResources.Value_Tracking;
Content = _root;
ViewModel = viewModel;
}
public TreeItemViewModel? Root
{
get => ViewModel?.Roots.Single();
set
{
if (value is null)
{
return;
}
Contract.ThrowIfNull(ViewModel);
ViewModel.Roots.Clear();
ViewModel.Roots.Add(value);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Windows.Controls;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
namespace Microsoft.VisualStudio.LanguageServices.ValueTracking
{
[Guid(Guids.ValueTrackingToolWindowIdString)]
internal class ValueTrackingToolWindow : ToolWindowPane
{
private readonly ValueTrackingRoot _root = new();
public static ValueTrackingToolWindow? Instance { get; set; }
private ValueTrackingTreeViewModel? _viewModel;
public ValueTrackingTreeViewModel? ViewModel
{
get => _viewModel;
set
{
if (value is null)
{
throw new ArgumentNullException(nameof(ViewModel));
}
_viewModel = value;
_root.SetChild(new ValueTrackingTree(_viewModel));
}
}
/// <summary>
/// This paramterless constructor is used when
/// the tool window is initialized on open without any
/// context. If the tool window is left open across shutdown/restart
/// of VS for example, then this gets called.
/// </summary>
public ValueTrackingToolWindow() : base(null)
{
Caption = ServicesVSResources.Value_Tracking;
Content = _root;
}
public ValueTrackingToolWindow(ValueTrackingTreeViewModel viewModel)
: base(null)
{
Caption = ServicesVSResources.Value_Tracking;
Content = _root;
ViewModel = viewModel;
}
public TreeItemViewModel? Root
{
get => ViewModel?.Roots.Single();
set
{
if (value is null)
{
return;
}
Contract.ThrowIfNull(ViewModel);
ViewModel.Roots.Clear();
ViewModel.Roots.Add(value);
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Core/CodeAnalysisTest/Collections/ImmutableSegmentedDictionaryTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/ImmutableDictionaryTest.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.Collections;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
public partial class ImmutableSegmentedDictionaryTest : ImmutableDictionaryTestBase
{
[Fact]
public void AddExistingKeySameValueTest()
{
AddExistingKeySameValueTestHelper(Empty<string, string>(StringComparer.Ordinal), "Company", "Microsoft", "Microsoft");
}
[Fact]
public void AddExistingKeyDifferentValueTest()
{
AddExistingKeyDifferentValueTestHelper(Empty<string, string>(StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void UnorderedChangeTest()
{
var map = Empty<string, string>(StringComparer.Ordinal)
.Add("Johnny", "Appleseed")
.Add("JOHNNY", "Appleseed");
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("Johnny"));
Assert.False(map.ContainsKey("johnny"));
var newMap = map.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, newMap.Count);
Assert.True(newMap.ContainsKey("Johnny"));
Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive
}
[Fact]
public void ToSortedTest()
{
var map = Empty<string, string>(StringComparer.Ordinal)
.Add("Johnny", "Appleseed")
.Add("JOHNNY", "Appleseed");
var sortedMap = map.ToImmutableSortedDictionary(StringComparer.Ordinal);
Assert.Equal(sortedMap.Count, map.Count);
CollectionAssertAreEquivalent<KeyValuePair<string, string>>(sortedMap.ToList(), map.ToList());
}
[Fact]
public void SetItemUpdateEqualKeyTest()
{
var map = Empty<string, int>().WithComparer(StringComparer.OrdinalIgnoreCase)
.SetItem("A", 1);
map = map.SetItem("a", 2);
Assert.Equal("A", map.Keys.Single());
}
[Fact]
public void ContainsValueTest()
{
ContainsValueTestHelper(ImmutableSegmentedDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper());
}
[Fact]
public void ContainsValue_NoSuchValue_ReturnsFalse()
{
ImmutableSegmentedDictionary<int, string?> dictionary = new Dictionary<int, string?>
{
{ 1, "a" },
{ 2, "b" }
}.ToImmutableSegmentedDictionary();
Assert.False(dictionary.ContainsValue("c"));
Assert.False(dictionary.ContainsValue(null));
}
[Fact]
public void Create()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var dictionary = ImmutableSegmentedDictionary.Create<string, string>();
Assert.Equal(0, dictionary.Count);
Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer);
dictionary = ImmutableSegmentedDictionary.Create<string, string>(keyComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
dictionary = ImmutableSegmentedDictionary.CreateRange(pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer);
dictionary = ImmutableSegmentedDictionary.CreateRange(keyComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
}
[Fact]
public void ToImmutableDictionary()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
ImmutableSegmentedDictionary<string, string> dictionary = pairs.ToImmutableSegmentedDictionary();
Assert.Equal(1, dictionary.Count);
Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer);
dictionary = pairs.ToImmutableSegmentedDictionary(keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
dictionary = pairs.ToImmutableSegmentedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant());
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer);
dictionary = pairs.ToImmutableSegmentedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
var list = new int[] { 1, 2 };
var intDictionary = list.ToImmutableSegmentedDictionary(n => (double)n);
Assert.Equal(1, intDictionary[1.0]);
Assert.Equal(2, intDictionary[2.0]);
Assert.Equal(2, intDictionary.Count);
var stringIntDictionary = list.ToImmutableSegmentedDictionary(n => n.ToString(), StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, stringIntDictionary.KeyComparer);
Assert.Equal(1, stringIntDictionary["1"]);
Assert.Equal(2, stringIntDictionary["2"]);
Assert.Equal(2, intDictionary.Count);
Assert.Throws<ArgumentNullException>("keySelector", () => list.ToImmutableSegmentedDictionary<int, int>(null!));
Assert.Throws<ArgumentNullException>("keySelector", () => list.ToImmutableSegmentedDictionary<int, int, int>(null!, v => v));
Assert.Throws<ArgumentNullException>("elementSelector", () => list.ToImmutableSegmentedDictionary<int, int, int>(k => k, null!));
list.ToDictionary(k => k, v => v, null); // verifies BCL behavior is to not throw.
list.ToImmutableSegmentedDictionary(k => k, v => v, null);
}
[Fact]
public void ToImmutableDictionaryOptimized()
{
var dictionary = ImmutableSegmentedDictionary.Create<string, string>();
var result = dictionary.ToImmutableSegmentedDictionary();
Assert.True(IsSame(dictionary, result));
var cultureComparer = StringComparer.CurrentCulture;
result = dictionary.WithComparer(cultureComparer);
Assert.Same(cultureComparer, result.KeyComparer);
}
[Fact]
public void WithComparer()
{
var map = ImmutableSegmentedDictionary.Create<string, string>().Add("a", "1").Add("B", "1");
Assert.Same(EqualityComparer<string>.Default, map.KeyComparer);
Assert.True(map.ContainsKey("a"));
Assert.False(map.ContainsKey("A"));
map = map.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void WithComparerCollisions()
{
// First check where collisions have matching values.
var map = ImmutableSegmentedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "1");
map = map.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(1, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.Equal("1", map["a"]);
// Now check where collisions have conflicting values.
map = ImmutableSegmentedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "2").Add("b", "3");
Assert.Throws<ArgumentException>(null, () => map.WithComparer(StringComparer.OrdinalIgnoreCase));
}
[Fact]
public void CollisionExceptionMessageContainsKey()
{
var map = ImmutableSegmentedDictionary.Create<string, string>()
.Add("firstKey", "1").Add("secondKey", "2");
var exception = Assert.Throws<ArgumentException>(null, () => map.Add("firstKey", "3"));
Assert.Contains("firstKey", exception.Message);
}
[Fact]
public void WithComparerEmptyCollection()
{
var map = ImmutableSegmentedDictionary.Create<string, string>();
Assert.Same(EqualityComparer<string>.Default, map.KeyComparer);
map = map.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
}
[Fact]
public void GetValueOrDefaultOfIImmutableDictionary()
{
IImmutableDictionary<string, int> empty = ImmutableSegmentedDictionary.Create<string, int>();
IImmutableDictionary<string, int> populated = ImmutableSegmentedDictionary.Create<string, int>().Add("a", 5);
Assert.Equal(0, empty.GetValueOrDefault("a"));
Assert.Equal(1, empty.GetValueOrDefault("a", 1));
Assert.Equal(5, populated.GetValueOrDefault("a"));
Assert.Equal(5, populated.GetValueOrDefault("a", 1));
}
[Fact]
public void GetValueOrDefaultOfConcreteType()
{
var empty = ImmutableSegmentedDictionary.Create<string, int>();
var populated = ImmutableSegmentedDictionary.Create<string, int>().Add("a", 5);
Assert.Equal(0, empty.GetValueOrDefault("a"));
Assert.Equal(1, empty.GetValueOrDefault("a", 1));
Assert.Equal(5, populated.GetValueOrDefault("a"));
Assert.Equal(5, populated.GetValueOrDefault("a", 1));
}
[Fact(Skip = "Not implemented: https://github.com/dotnet/roslyn/issues/50657")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSegmentedDictionary.Create<int, int>());
ImmutableSegmentedDictionary<string, int> dict = ImmutableSegmentedDictionary.Create<string, int>().Add("One", 1).Add("Two", 2);
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(dict);
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableSegmentedDictionary.Create<string, string>(), "_root") ?? throw new InvalidOperationException();
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>()!.State == DebuggerBrowsableState.RootHidden);
KeyValuePair<string, int>[]? items = itemProperty.GetValue(info.Instance) as KeyValuePair<string, int>[];
Assert.Equal(dict, items);
}
[Fact(Skip = "Not implemented: https://github.com/dotnet/roslyn/issues/50657")]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableSegmentedDictionary.Create<string, int>());
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object?)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
[Fact]
public void Clear_NoComparer_ReturnsEmptyWithoutComparer()
{
ImmutableSegmentedDictionary<string, int> dictionary = new Dictionary<string, int>
{
{ "a", 1 }
}.ToImmutableSegmentedDictionary();
Assert.True(IsSame(ImmutableSegmentedDictionary<string, int>.Empty, dictionary.Clear()));
Assert.NotEmpty(dictionary);
}
[Fact]
public void Clear_HasComparer_ReturnsEmptyWithOriginalComparer()
{
ImmutableSegmentedDictionary<string, int> dictionary = new Dictionary<string, int>
{
{ "a", 1 }
}.ToImmutableSegmentedDictionary(StringComparer.OrdinalIgnoreCase);
ImmutableSegmentedDictionary<string, int> clearedDictionary = dictionary.Clear();
Assert.False(IsSame(ImmutableSegmentedDictionary<string, int>.Empty, clearedDictionary.Clear()));
Assert.NotEmpty(dictionary);
clearedDictionary = clearedDictionary.Add("a", 1);
Assert.True(clearedDictionary.ContainsKey("A"));
}
[Fact]
public void Indexer_KeyNotFoundException_ContainsKeyInMessage()
{
var map = ImmutableSegmentedDictionary.Create<string, string>()
.Add("a", "1").Add("b", "2");
var missingKey = "__ThisKeyDoesNotExist__";
var exception = Assert.Throws<KeyNotFoundException>(() => map[missingKey]);
Assert.Contains(missingKey, exception.Message);
}
protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>()
{
return ImmutableSegmentedDictionaryTest.Empty<TKey, TValue>();
}
protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer)
{
return ImmutableSegmentedDictionary.Create<string, TValue>(comparer);
}
protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
return EqualityComparer<TValue>.Default;
}
private protected static void ContainsValueTestHelper<TKey, TValue>(ImmutableSegmentedDictionary<TKey, TValue> map, TKey key, TValue value)
where TKey : notnull
{
Assert.False(map.ContainsValue(value));
Assert.True(map.Add(key, value).ContainsValue(value));
}
private static ImmutableSegmentedDictionary<TKey, TValue> Empty<TKey, TValue>(IEqualityComparer<TKey>? keyComparer = null)
where TKey : notnull
{
return ImmutableSegmentedDictionary<TKey, TValue>.Empty.WithComparer(keyComparer);
}
/// <summary>
/// An ordinal comparer for case-insensitive strings.
/// </summary>
private class MyStringOrdinalComparer : EqualityComparer<CaseInsensitiveString?>
{
public override bool Equals(CaseInsensitiveString? x, CaseInsensitiveString? y)
{
return StringComparer.Ordinal.Equals(x!.Value, y!.Value);
}
public override int GetHashCode(CaseInsensitiveString obj)
{
return StringComparer.Ordinal.GetHashCode(obj.Value);
}
}
/// <summary>
/// A string-wrapper that considers equality based on case insensitivity.
/// </summary>
private class CaseInsensitiveString
{
public CaseInsensitiveString(string value)
{
Value = value;
}
public string Value { get; private set; }
public override int GetHashCode()
{
return StringComparer.OrdinalIgnoreCase.GetHashCode(this.Value);
}
public override bool Equals(object? obj)
{
return StringComparer.OrdinalIgnoreCase.Equals(this.Value, ((CaseInsensitiveString?)obj)!.Value);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/ImmutableDictionaryTest.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.Collections;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
public partial class ImmutableSegmentedDictionaryTest : ImmutableDictionaryTestBase
{
[Fact]
public void AddExistingKeySameValueTest()
{
AddExistingKeySameValueTestHelper(Empty<string, string>(StringComparer.Ordinal), "Company", "Microsoft", "Microsoft");
}
[Fact]
public void AddExistingKeyDifferentValueTest()
{
AddExistingKeyDifferentValueTestHelper(Empty<string, string>(StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT");
}
[Fact]
public void UnorderedChangeTest()
{
var map = Empty<string, string>(StringComparer.Ordinal)
.Add("Johnny", "Appleseed")
.Add("JOHNNY", "Appleseed");
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("Johnny"));
Assert.False(map.ContainsKey("johnny"));
var newMap = map.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, newMap.Count);
Assert.True(newMap.ContainsKey("Johnny"));
Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive
}
[Fact]
public void ToSortedTest()
{
var map = Empty<string, string>(StringComparer.Ordinal)
.Add("Johnny", "Appleseed")
.Add("JOHNNY", "Appleseed");
var sortedMap = map.ToImmutableSortedDictionary(StringComparer.Ordinal);
Assert.Equal(sortedMap.Count, map.Count);
CollectionAssertAreEquivalent<KeyValuePair<string, string>>(sortedMap.ToList(), map.ToList());
}
[Fact]
public void SetItemUpdateEqualKeyTest()
{
var map = Empty<string, int>().WithComparer(StringComparer.OrdinalIgnoreCase)
.SetItem("A", 1);
map = map.SetItem("a", 2);
Assert.Equal("A", map.Keys.Single());
}
[Fact]
public void ContainsValueTest()
{
ContainsValueTestHelper(ImmutableSegmentedDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper());
}
[Fact]
public void ContainsValue_NoSuchValue_ReturnsFalse()
{
ImmutableSegmentedDictionary<int, string?> dictionary = new Dictionary<int, string?>
{
{ 1, "a" },
{ 2, "b" }
}.ToImmutableSegmentedDictionary();
Assert.False(dictionary.ContainsValue("c"));
Assert.False(dictionary.ContainsValue(null));
}
[Fact]
public void Create()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
var dictionary = ImmutableSegmentedDictionary.Create<string, string>();
Assert.Equal(0, dictionary.Count);
Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer);
dictionary = ImmutableSegmentedDictionary.Create<string, string>(keyComparer);
Assert.Equal(0, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
dictionary = ImmutableSegmentedDictionary.CreateRange(pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer);
dictionary = ImmutableSegmentedDictionary.CreateRange(keyComparer, pairs);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
}
[Fact]
public void ToImmutableDictionary()
{
IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } };
var keyComparer = StringComparer.OrdinalIgnoreCase;
ImmutableSegmentedDictionary<string, string> dictionary = pairs.ToImmutableSegmentedDictionary();
Assert.Equal(1, dictionary.Count);
Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer);
dictionary = pairs.ToImmutableSegmentedDictionary(keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Same(keyComparer, dictionary.KeyComparer);
dictionary = pairs.ToImmutableSegmentedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant());
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer);
dictionary = pairs.ToImmutableSegmentedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer);
Assert.Equal(1, dictionary.Count);
Assert.Equal("A", dictionary.Keys.Single());
Assert.Equal("b", dictionary.Values.Single());
Assert.Same(keyComparer, dictionary.KeyComparer);
var list = new int[] { 1, 2 };
var intDictionary = list.ToImmutableSegmentedDictionary(n => (double)n);
Assert.Equal(1, intDictionary[1.0]);
Assert.Equal(2, intDictionary[2.0]);
Assert.Equal(2, intDictionary.Count);
var stringIntDictionary = list.ToImmutableSegmentedDictionary(n => n.ToString(), StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, stringIntDictionary.KeyComparer);
Assert.Equal(1, stringIntDictionary["1"]);
Assert.Equal(2, stringIntDictionary["2"]);
Assert.Equal(2, intDictionary.Count);
Assert.Throws<ArgumentNullException>("keySelector", () => list.ToImmutableSegmentedDictionary<int, int>(null!));
Assert.Throws<ArgumentNullException>("keySelector", () => list.ToImmutableSegmentedDictionary<int, int, int>(null!, v => v));
Assert.Throws<ArgumentNullException>("elementSelector", () => list.ToImmutableSegmentedDictionary<int, int, int>(k => k, null!));
list.ToDictionary(k => k, v => v, null); // verifies BCL behavior is to not throw.
list.ToImmutableSegmentedDictionary(k => k, v => v, null);
}
[Fact]
public void ToImmutableDictionaryOptimized()
{
var dictionary = ImmutableSegmentedDictionary.Create<string, string>();
var result = dictionary.ToImmutableSegmentedDictionary();
Assert.True(IsSame(dictionary, result));
var cultureComparer = StringComparer.CurrentCulture;
result = dictionary.WithComparer(cultureComparer);
Assert.Same(cultureComparer, result.KeyComparer);
}
[Fact]
public void WithComparer()
{
var map = ImmutableSegmentedDictionary.Create<string, string>().Add("a", "1").Add("B", "1");
Assert.Same(EqualityComparer<string>.Default, map.KeyComparer);
Assert.True(map.ContainsKey("a"));
Assert.False(map.ContainsKey("A"));
map = map.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(2, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.True(map.ContainsKey("A"));
Assert.True(map.ContainsKey("b"));
}
[Fact]
public void WithComparerCollisions()
{
// First check where collisions have matching values.
var map = ImmutableSegmentedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "1");
map = map.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
Assert.Equal(1, map.Count);
Assert.True(map.ContainsKey("a"));
Assert.Equal("1", map["a"]);
// Now check where collisions have conflicting values.
map = ImmutableSegmentedDictionary.Create<string, string>()
.Add("a", "1").Add("A", "2").Add("b", "3");
Assert.Throws<ArgumentException>(null, () => map.WithComparer(StringComparer.OrdinalIgnoreCase));
}
[Fact]
public void CollisionExceptionMessageContainsKey()
{
var map = ImmutableSegmentedDictionary.Create<string, string>()
.Add("firstKey", "1").Add("secondKey", "2");
var exception = Assert.Throws<ArgumentException>(null, () => map.Add("firstKey", "3"));
Assert.Contains("firstKey", exception.Message);
}
[Fact]
public void WithComparerEmptyCollection()
{
var map = ImmutableSegmentedDictionary.Create<string, string>();
Assert.Same(EqualityComparer<string>.Default, map.KeyComparer);
map = map.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer);
}
[Fact]
public void GetValueOrDefaultOfIImmutableDictionary()
{
IImmutableDictionary<string, int> empty = ImmutableSegmentedDictionary.Create<string, int>();
IImmutableDictionary<string, int> populated = ImmutableSegmentedDictionary.Create<string, int>().Add("a", 5);
Assert.Equal(0, empty.GetValueOrDefault("a"));
Assert.Equal(1, empty.GetValueOrDefault("a", 1));
Assert.Equal(5, populated.GetValueOrDefault("a"));
Assert.Equal(5, populated.GetValueOrDefault("a", 1));
}
[Fact]
public void GetValueOrDefaultOfConcreteType()
{
var empty = ImmutableSegmentedDictionary.Create<string, int>();
var populated = ImmutableSegmentedDictionary.Create<string, int>().Add("a", 5);
Assert.Equal(0, empty.GetValueOrDefault("a"));
Assert.Equal(1, empty.GetValueOrDefault("a", 1));
Assert.Equal(5, populated.GetValueOrDefault("a"));
Assert.Equal(5, populated.GetValueOrDefault("a", 1));
}
[Fact(Skip = "Not implemented: https://github.com/dotnet/roslyn/issues/50657")]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSegmentedDictionary.Create<int, int>());
ImmutableSegmentedDictionary<string, int> dict = ImmutableSegmentedDictionary.Create<string, int>().Add("One", 1).Add("Two", 2);
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(dict);
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableSegmentedDictionary.Create<string, string>(), "_root") ?? throw new InvalidOperationException();
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>()!.State == DebuggerBrowsableState.RootHidden);
KeyValuePair<string, int>[]? items = itemProperty.GetValue(info.Instance) as KeyValuePair<string, int>[];
Assert.Equal(dict, items);
}
[Fact(Skip = "Not implemented: https://github.com/dotnet/roslyn/issues/50657")]
public static void TestDebuggerAttributes_Null()
{
Type proxyType = DebuggerAttributes.GetProxyType(ImmutableSegmentedDictionary.Create<string, int>());
TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object?)null));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
[Fact]
public void Clear_NoComparer_ReturnsEmptyWithoutComparer()
{
ImmutableSegmentedDictionary<string, int> dictionary = new Dictionary<string, int>
{
{ "a", 1 }
}.ToImmutableSegmentedDictionary();
Assert.True(IsSame(ImmutableSegmentedDictionary<string, int>.Empty, dictionary.Clear()));
Assert.NotEmpty(dictionary);
}
[Fact]
public void Clear_HasComparer_ReturnsEmptyWithOriginalComparer()
{
ImmutableSegmentedDictionary<string, int> dictionary = new Dictionary<string, int>
{
{ "a", 1 }
}.ToImmutableSegmentedDictionary(StringComparer.OrdinalIgnoreCase);
ImmutableSegmentedDictionary<string, int> clearedDictionary = dictionary.Clear();
Assert.False(IsSame(ImmutableSegmentedDictionary<string, int>.Empty, clearedDictionary.Clear()));
Assert.NotEmpty(dictionary);
clearedDictionary = clearedDictionary.Add("a", 1);
Assert.True(clearedDictionary.ContainsKey("A"));
}
[Fact]
public void Indexer_KeyNotFoundException_ContainsKeyInMessage()
{
var map = ImmutableSegmentedDictionary.Create<string, string>()
.Add("a", "1").Add("b", "2");
var missingKey = "__ThisKeyDoesNotExist__";
var exception = Assert.Throws<KeyNotFoundException>(() => map[missingKey]);
Assert.Contains(missingKey, exception.Message);
}
protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>()
{
return ImmutableSegmentedDictionaryTest.Empty<TKey, TValue>();
}
protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer)
{
return ImmutableSegmentedDictionary.Create<string, TValue>(comparer);
}
protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary)
{
return EqualityComparer<TValue>.Default;
}
private protected static void ContainsValueTestHelper<TKey, TValue>(ImmutableSegmentedDictionary<TKey, TValue> map, TKey key, TValue value)
where TKey : notnull
{
Assert.False(map.ContainsValue(value));
Assert.True(map.Add(key, value).ContainsValue(value));
}
private static ImmutableSegmentedDictionary<TKey, TValue> Empty<TKey, TValue>(IEqualityComparer<TKey>? keyComparer = null)
where TKey : notnull
{
return ImmutableSegmentedDictionary<TKey, TValue>.Empty.WithComparer(keyComparer);
}
/// <summary>
/// An ordinal comparer for case-insensitive strings.
/// </summary>
private class MyStringOrdinalComparer : EqualityComparer<CaseInsensitiveString?>
{
public override bool Equals(CaseInsensitiveString? x, CaseInsensitiveString? y)
{
return StringComparer.Ordinal.Equals(x!.Value, y!.Value);
}
public override int GetHashCode(CaseInsensitiveString obj)
{
return StringComparer.Ordinal.GetHashCode(obj.Value);
}
}
/// <summary>
/// A string-wrapper that considers equality based on case insensitivity.
/// </summary>
private class CaseInsensitiveString
{
public CaseInsensitiveString(string value)
{
Value = value;
}
public string Value { get; private set; }
public override int GetHashCode()
{
return StringComparer.OrdinalIgnoreCase.GetHashCode(this.Value);
}
public override bool Equals(object? obj)
{
return StringComparer.OrdinalIgnoreCase.Equals(this.Value, ((CaseInsensitiveString?)obj)!.Value);
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/xlf/VisualBasicCompilerExtensionsResources.pl.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pl" original="../VisualBasicCompilerExtensionsResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">Usuń tę wartość, gdy dodawana jest kolejna.</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pl" original="../VisualBasicCompilerExtensionsResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">Usuń tę wartość, gdy dodawana jest kolejna.</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxNodeStructureProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using Microsoft.CodeAnalysis.Shared.Collections;
namespace Microsoft.CodeAnalysis.Structure
{
internal abstract class AbstractSyntaxNodeStructureProvider<TSyntaxNode> : AbstractSyntaxStructureProvider
where TSyntaxNode : SyntaxNode
{
public sealed override void CollectBlockSpans(
SyntaxTrivia trivia,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
public sealed override void CollectBlockSpans(
SyntaxToken previousToken,
SyntaxNode node,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
if (node is TSyntaxNode tSyntax)
{
CollectBlockSpans(previousToken, tSyntax, ref spans, optionProvider, cancellationToken);
}
}
protected abstract void CollectBlockSpans(
SyntaxToken previousToken,
TSyntaxNode node, ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using Microsoft.CodeAnalysis.Shared.Collections;
namespace Microsoft.CodeAnalysis.Structure
{
internal abstract class AbstractSyntaxNodeStructureProvider<TSyntaxNode> : AbstractSyntaxStructureProvider
where TSyntaxNode : SyntaxNode
{
public sealed override void CollectBlockSpans(
SyntaxTrivia trivia,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
public sealed override void CollectBlockSpans(
SyntaxToken previousToken,
SyntaxNode node,
ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider,
CancellationToken cancellationToken)
{
if (node is TSyntaxNode tSyntax)
{
CollectBlockSpans(previousToken, tSyntax, ref spans, optionProvider, cancellationToken);
}
}
protected abstract void CollectBlockSpans(
SyntaxToken previousToken,
TSyntaxNode node, ref TemporaryArray<BlockSpan> spans,
BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Core/Portable/Operations/OperationVisitor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Operations
{
/// <summary>
/// Represents a <see cref="IOperation"/> visitor that visits only the single IOperation
/// passed into its Visit method.
/// </summary>
public abstract partial class OperationVisitor
{
// Make public after review: https://github.com/dotnet/roslyn/issues/21281
internal virtual void VisitFixed(IFixedOperation operation) =>
// https://github.com/dotnet/roslyn/issues/21281
//DefaultVisit(operation);
VisitNoneOperation(operation);
}
/// <summary>
/// Represents a <see cref="IOperation"/> visitor that visits only the single IOperation
/// passed into its Visit method with an additional argument of the type specified by the
/// <typeparamref name="TArgument"/> parameter and produces a value of the type specified by
/// the <typeparamref name="TResult"/> parameter.
/// </summary>
/// <typeparam name="TArgument">
/// The type of the additional argument passed to this visitor's Visit method.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the return value of this visitor's Visit method.
/// </typeparam>
public abstract partial class OperationVisitor<TArgument, TResult>
{
// Make public after review: https://github.com/dotnet/roslyn/issues/21281
internal virtual TResult? VisitFixed(IFixedOperation operation, TArgument argument) =>
// https://github.com/dotnet/roslyn/issues/21281
//return DefaultVisit(operation, argument);
VisitNoneOperation(operation, argument);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Operations
{
/// <summary>
/// Represents a <see cref="IOperation"/> visitor that visits only the single IOperation
/// passed into its Visit method.
/// </summary>
public abstract partial class OperationVisitor
{
// Make public after review: https://github.com/dotnet/roslyn/issues/21281
internal virtual void VisitFixed(IFixedOperation operation) =>
// https://github.com/dotnet/roslyn/issues/21281
//DefaultVisit(operation);
VisitNoneOperation(operation);
}
/// <summary>
/// Represents a <see cref="IOperation"/> visitor that visits only the single IOperation
/// passed into its Visit method with an additional argument of the type specified by the
/// <typeparamref name="TArgument"/> parameter and produces a value of the type specified by
/// the <typeparamref name="TResult"/> parameter.
/// </summary>
/// <typeparam name="TArgument">
/// The type of the additional argument passed to this visitor's Visit method.
/// </typeparam>
/// <typeparam name="TResult">
/// The type of the return value of this visitor's Visit method.
/// </typeparam>
public abstract partial class OperationVisitor<TArgument, TResult>
{
// Make public after review: https://github.com/dotnet/roslyn/issues/21281
internal virtual TResult? VisitFixed(IFixedOperation operation, TArgument argument) =>
// https://github.com/dotnet/roslyn/issues/21281
//return DefaultVisit(operation, argument);
VisitNoneOperation(operation, argument);
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpVarReducer.Rewriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
internal partial class CSharpVarReducer
{
private class Rewriter : AbstractReductionRewriter
{
public Rewriter(ObjectPool<IReductionRewriter> pool)
: base(pool)
{
}
private SyntaxNode ProcessTypeSyntax(TypeSyntax typeSyntax)
{
this.CancellationToken.ThrowIfCancellationRequested();
// Only simplify if us, or a parent, was marked as needing simplification.
if (!alwaysSimplify && !typeSyntax.HasAnnotation(Simplifier.Annotation))
{
return typeSyntax;
}
// Definitely do not simplify us if we were told to not simplify.
if (typeSyntax.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation))
{
return typeSyntax;
}
var typeStyle = CSharpUseImplicitTypeHelper.Instance.AnalyzeTypeName(
typeSyntax, this.SemanticModel, this.OptionSet, this.CancellationToken);
if (!typeStyle.IsStylePreferred || !typeStyle.CanConvert())
{
return typeSyntax;
}
return SyntaxFactory.IdentifierName("var")
.WithLeadingTrivia(typeSyntax.GetLeadingTrivia())
.WithTrailingTrivia(typeSyntax.GetTrailingTrivia());
}
public override SyntaxNode VisitAliasQualifiedName(AliasQualifiedNameSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitArrayType(ArrayTypeSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitGenericName(GenericNameSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitNullableType(NullableTypeSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitPointerType(PointerTypeSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitPredefinedType(PredefinedTypeSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitQualifiedName(QualifiedNameSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitTupleType(TupleTypeSyntax node) => ProcessTypeSyntax(node);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
internal partial class CSharpVarReducer
{
private class Rewriter : AbstractReductionRewriter
{
public Rewriter(ObjectPool<IReductionRewriter> pool)
: base(pool)
{
}
private SyntaxNode ProcessTypeSyntax(TypeSyntax typeSyntax)
{
this.CancellationToken.ThrowIfCancellationRequested();
// Only simplify if us, or a parent, was marked as needing simplification.
if (!alwaysSimplify && !typeSyntax.HasAnnotation(Simplifier.Annotation))
{
return typeSyntax;
}
// Definitely do not simplify us if we were told to not simplify.
if (typeSyntax.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation))
{
return typeSyntax;
}
var typeStyle = CSharpUseImplicitTypeHelper.Instance.AnalyzeTypeName(
typeSyntax, this.SemanticModel, this.OptionSet, this.CancellationToken);
if (!typeStyle.IsStylePreferred || !typeStyle.CanConvert())
{
return typeSyntax;
}
return SyntaxFactory.IdentifierName("var")
.WithLeadingTrivia(typeSyntax.GetLeadingTrivia())
.WithTrailingTrivia(typeSyntax.GetTrailingTrivia());
}
public override SyntaxNode VisitAliasQualifiedName(AliasQualifiedNameSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitArrayType(ArrayTypeSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitGenericName(GenericNameSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitNullableType(NullableTypeSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitPointerType(PointerTypeSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitPredefinedType(PredefinedTypeSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitQualifiedName(QualifiedNameSyntax node) => ProcessTypeSyntax(node);
public override SyntaxNode VisitTupleType(TupleTypeSyntax node) => ProcessTypeSyntax(node);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/Core.Wpf/Interactive/InteractiveCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using System.Threading;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
internal abstract class InteractiveCommandHandler :
ICommandHandler<ExecuteInInteractiveCommandArgs>,
ICommandHandler<CopyToInteractiveCommandArgs>
{
private readonly IContentTypeRegistryService _contentTypeRegistryService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;
protected InteractiveCommandHandler(
IContentTypeRegistryService contentTypeRegistryService,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEditorOperationsFactoryService editorOperationsFactoryService)
{
_contentTypeRegistryService = contentTypeRegistryService;
_editorOptionsFactoryService = editorOptionsFactoryService;
_editorOperationsFactoryService = editorOperationsFactoryService;
}
protected IContentTypeRegistryService ContentTypeRegistryService { get { return _contentTypeRegistryService; } }
protected abstract IInteractiveWindow OpenInteractiveWindow(bool focus);
protected abstract ISendToInteractiveSubmissionProvider SendToInteractiveSubmissionProvider { get; }
public string DisplayName => EditorFeaturesResources.Interactive;
private string GetSelectedText(EditorCommandArgs args, CancellationToken cancellationToken)
{
var editorOptions = _editorOptionsFactoryService.GetOptions(args.SubjectBuffer);
return SendToInteractiveSubmissionProvider.GetSelectedText(editorOptions, args, cancellationToken);
}
CommandState ICommandHandler<ExecuteInInteractiveCommandArgs>.GetCommandState(ExecuteInInteractiveCommandArgs args)
=> CommandState.Available;
bool ICommandHandler<ExecuteInInteractiveCommandArgs>.ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context)
{
var window = OpenInteractiveWindow(focus: false);
using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesWpfResources.Executing_selection_in_Interactive_Window))
{
var submission = GetSelectedText(args, context.OperationContext.UserCancellationToken);
if (!string.IsNullOrWhiteSpace(submission))
{
window.SubmitAsync(new string[] { submission });
}
}
return true;
}
CommandState ICommandHandler<CopyToInteractiveCommandArgs>.GetCommandState(CopyToInteractiveCommandArgs args)
=> CommandState.Available;
bool ICommandHandler<CopyToInteractiveCommandArgs>.ExecuteCommand(CopyToInteractiveCommandArgs args, CommandExecutionContext context)
{
var window = OpenInteractiveWindow(focus: true);
var buffer = window.CurrentLanguageBuffer;
if (buffer != null)
{
CopyToWindow(window, args, context);
}
else
{
Action action = null;
action = new Action(() =>
{
window.ReadyForInput -= action;
CopyToWindow(window, args, context);
});
window.ReadyForInput += action;
}
return true;
}
private void CopyToWindow(IInteractiveWindow window, CopyToInteractiveCommandArgs args, CommandExecutionContext context)
{
var buffer = window.CurrentLanguageBuffer;
Debug.Assert(buffer != null);
using (var edit = buffer.CreateEdit())
using (var waitScope = context.OperationContext.AddScope(allowCancellation: true,
EditorFeaturesWpfResources.Copying_selection_to_Interactive_Window))
{
var text = GetSelectedText(args, context.OperationContext.UserCancellationToken);
// If the last line isn't empty in the existing submission buffer, we will prepend a
// newline
var lastLine = buffer.CurrentSnapshot.GetLineFromLineNumber(buffer.CurrentSnapshot.LineCount - 1);
if (lastLine.Extent.Length > 0)
{
var editorOptions = _editorOptionsFactoryService.GetOptions(args.SubjectBuffer);
text = editorOptions.GetNewLineCharacter() + text;
}
edit.Insert(buffer.CurrentSnapshot.Length, text);
edit.Apply();
}
// Move the caret to the end
var editorOperations = _editorOperationsFactoryService.GetEditorOperations(window.TextView);
var endPoint = new VirtualSnapshotPoint(window.TextView.TextBuffer.CurrentSnapshot, window.TextView.TextBuffer.CurrentSnapshot.Length);
editorOperations.SelectAndMoveCaret(endPoint, endPoint);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using System.Threading;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
internal abstract class InteractiveCommandHandler :
ICommandHandler<ExecuteInInteractiveCommandArgs>,
ICommandHandler<CopyToInteractiveCommandArgs>
{
private readonly IContentTypeRegistryService _contentTypeRegistryService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;
protected InteractiveCommandHandler(
IContentTypeRegistryService contentTypeRegistryService,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEditorOperationsFactoryService editorOperationsFactoryService)
{
_contentTypeRegistryService = contentTypeRegistryService;
_editorOptionsFactoryService = editorOptionsFactoryService;
_editorOperationsFactoryService = editorOperationsFactoryService;
}
protected IContentTypeRegistryService ContentTypeRegistryService { get { return _contentTypeRegistryService; } }
protected abstract IInteractiveWindow OpenInteractiveWindow(bool focus);
protected abstract ISendToInteractiveSubmissionProvider SendToInteractiveSubmissionProvider { get; }
public string DisplayName => EditorFeaturesResources.Interactive;
private string GetSelectedText(EditorCommandArgs args, CancellationToken cancellationToken)
{
var editorOptions = _editorOptionsFactoryService.GetOptions(args.SubjectBuffer);
return SendToInteractiveSubmissionProvider.GetSelectedText(editorOptions, args, cancellationToken);
}
CommandState ICommandHandler<ExecuteInInteractiveCommandArgs>.GetCommandState(ExecuteInInteractiveCommandArgs args)
=> CommandState.Available;
bool ICommandHandler<ExecuteInInteractiveCommandArgs>.ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context)
{
var window = OpenInteractiveWindow(focus: false);
using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesWpfResources.Executing_selection_in_Interactive_Window))
{
var submission = GetSelectedText(args, context.OperationContext.UserCancellationToken);
if (!string.IsNullOrWhiteSpace(submission))
{
window.SubmitAsync(new string[] { submission });
}
}
return true;
}
CommandState ICommandHandler<CopyToInteractiveCommandArgs>.GetCommandState(CopyToInteractiveCommandArgs args)
=> CommandState.Available;
bool ICommandHandler<CopyToInteractiveCommandArgs>.ExecuteCommand(CopyToInteractiveCommandArgs args, CommandExecutionContext context)
{
var window = OpenInteractiveWindow(focus: true);
var buffer = window.CurrentLanguageBuffer;
if (buffer != null)
{
CopyToWindow(window, args, context);
}
else
{
Action action = null;
action = new Action(() =>
{
window.ReadyForInput -= action;
CopyToWindow(window, args, context);
});
window.ReadyForInput += action;
}
return true;
}
private void CopyToWindow(IInteractiveWindow window, CopyToInteractiveCommandArgs args, CommandExecutionContext context)
{
var buffer = window.CurrentLanguageBuffer;
Debug.Assert(buffer != null);
using (var edit = buffer.CreateEdit())
using (var waitScope = context.OperationContext.AddScope(allowCancellation: true,
EditorFeaturesWpfResources.Copying_selection_to_Interactive_Window))
{
var text = GetSelectedText(args, context.OperationContext.UserCancellationToken);
// If the last line isn't empty in the existing submission buffer, we will prepend a
// newline
var lastLine = buffer.CurrentSnapshot.GetLineFromLineNumber(buffer.CurrentSnapshot.LineCount - 1);
if (lastLine.Extent.Length > 0)
{
var editorOptions = _editorOptionsFactoryService.GetOptions(args.SubjectBuffer);
text = editorOptions.GetNewLineCharacter() + text;
}
edit.Insert(buffer.CurrentSnapshot.Length, text);
edit.Apply();
}
// Move the caret to the end
var editorOperations = _editorOperationsFactoryService.GetEditorOperations(window.TextView);
var endPoint = new VirtualSnapshotPoint(window.TextView.TextBuffer.CurrentSnapshot, window.TextView.TextBuffer.CurrentSnapshot.Length);
editorOperations.SelectAndMoveCaret(endPoint, endPoint);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Portable/Symbols/Wrapped/WrappedParameterSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.CSharp.Emit;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a parameter that is based on another parameter.
/// When inheriting from this class, one shouldn't assume that
/// the default behavior it has is appropriate for every case.
/// That behavior should be carefully reviewed and derived type
/// should override behavior as appropriate.
/// </summary>
internal abstract class WrappedParameterSymbol : ParameterSymbol
{
protected readonly ParameterSymbol _underlyingParameter;
protected WrappedParameterSymbol(ParameterSymbol underlyingParameter)
{
Debug.Assert((object)underlyingParameter != null);
this._underlyingParameter = underlyingParameter;
}
public ParameterSymbol UnderlyingParameter => _underlyingParameter;
public sealed override bool IsDiscard => _underlyingParameter.IsDiscard;
#region Forwarded
public override TypeWithAnnotations TypeWithAnnotations
{
get { return _underlyingParameter.TypeWithAnnotations; }
}
public sealed override RefKind RefKind
{
get { return _underlyingParameter.RefKind; }
}
internal sealed override bool IsMetadataIn
{
get { return _underlyingParameter.IsMetadataIn; }
}
internal sealed override bool IsMetadataOut
{
get { return _underlyingParameter.IsMetadataOut; }
}
public sealed override ImmutableArray<Location> Locations
{
get { return _underlyingParameter.Locations; }
}
public sealed override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { return _underlyingParameter.DeclaringSyntaxReferences; }
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return _underlyingParameter.GetAttributes();
}
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
_underlyingParameter.AddSynthesizedAttributes(moduleBuilder, ref attributes);
}
internal sealed override ConstantValue ExplicitDefaultConstantValue
{
get { return _underlyingParameter.ExplicitDefaultConstantValue; }
}
public override int Ordinal
{
get { return _underlyingParameter.Ordinal; }
}
public override bool IsParams
{
get { return _underlyingParameter.IsParams; }
}
internal override bool IsMetadataOptional
{
get { return _underlyingParameter.IsMetadataOptional; }
}
public override bool IsImplicitlyDeclared
{
get { return _underlyingParameter.IsImplicitlyDeclared; }
}
public sealed override string Name
{
get { return _underlyingParameter.Name; }
}
public sealed override string MetadataName
{
get { return _underlyingParameter.MetadataName; }
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return _underlyingParameter.RefCustomModifiers; }
}
internal override MarshalPseudoCustomAttributeData MarshallingInformation
{
get { return _underlyingParameter.MarshallingInformation; }
}
internal override UnmanagedType MarshallingType
{
get { return _underlyingParameter.MarshallingType; }
}
internal override bool IsIDispatchConstant
{
get { return _underlyingParameter.IsIDispatchConstant; }
}
internal override bool IsIUnknownConstant
{
get { return _underlyingParameter.IsIUnknownConstant; }
}
internal override FlowAnalysisAnnotations FlowAnalysisAnnotations
{
// https://github.com/dotnet/roslyn/issues/30073: Consider moving to leaf types
get { return _underlyingParameter.FlowAnalysisAnnotations; }
}
internal override ImmutableHashSet<string> NotNullIfParameterNotNull
{
get { return _underlyingParameter.NotNullIfParameterNotNull; }
}
public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default)
{
return _underlyingParameter.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken);
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.CSharp.Emit;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Represents a parameter that is based on another parameter.
/// When inheriting from this class, one shouldn't assume that
/// the default behavior it has is appropriate for every case.
/// That behavior should be carefully reviewed and derived type
/// should override behavior as appropriate.
/// </summary>
internal abstract class WrappedParameterSymbol : ParameterSymbol
{
protected readonly ParameterSymbol _underlyingParameter;
protected WrappedParameterSymbol(ParameterSymbol underlyingParameter)
{
Debug.Assert((object)underlyingParameter != null);
this._underlyingParameter = underlyingParameter;
}
public ParameterSymbol UnderlyingParameter => _underlyingParameter;
public sealed override bool IsDiscard => _underlyingParameter.IsDiscard;
#region Forwarded
public override TypeWithAnnotations TypeWithAnnotations
{
get { return _underlyingParameter.TypeWithAnnotations; }
}
public sealed override RefKind RefKind
{
get { return _underlyingParameter.RefKind; }
}
internal sealed override bool IsMetadataIn
{
get { return _underlyingParameter.IsMetadataIn; }
}
internal sealed override bool IsMetadataOut
{
get { return _underlyingParameter.IsMetadataOut; }
}
public sealed override ImmutableArray<Location> Locations
{
get { return _underlyingParameter.Locations; }
}
public sealed override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { return _underlyingParameter.DeclaringSyntaxReferences; }
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return _underlyingParameter.GetAttributes();
}
internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
{
_underlyingParameter.AddSynthesizedAttributes(moduleBuilder, ref attributes);
}
internal sealed override ConstantValue ExplicitDefaultConstantValue
{
get { return _underlyingParameter.ExplicitDefaultConstantValue; }
}
public override int Ordinal
{
get { return _underlyingParameter.Ordinal; }
}
public override bool IsParams
{
get { return _underlyingParameter.IsParams; }
}
internal override bool IsMetadataOptional
{
get { return _underlyingParameter.IsMetadataOptional; }
}
public override bool IsImplicitlyDeclared
{
get { return _underlyingParameter.IsImplicitlyDeclared; }
}
public sealed override string Name
{
get { return _underlyingParameter.Name; }
}
public sealed override string MetadataName
{
get { return _underlyingParameter.MetadataName; }
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return _underlyingParameter.RefCustomModifiers; }
}
internal override MarshalPseudoCustomAttributeData MarshallingInformation
{
get { return _underlyingParameter.MarshallingInformation; }
}
internal override UnmanagedType MarshallingType
{
get { return _underlyingParameter.MarshallingType; }
}
internal override bool IsIDispatchConstant
{
get { return _underlyingParameter.IsIDispatchConstant; }
}
internal override bool IsIUnknownConstant
{
get { return _underlyingParameter.IsIUnknownConstant; }
}
internal override FlowAnalysisAnnotations FlowAnalysisAnnotations
{
// https://github.com/dotnet/roslyn/issues/30073: Consider moving to leaf types
get { return _underlyingParameter.FlowAnalysisAnnotations; }
}
internal override ImmutableHashSet<string> NotNullIfParameterNotNull
{
get { return _underlyingParameter.NotNullIfParameterNotNull; }
}
public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default)
{
return _underlyingParameter.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/Core/Host/IPreviewPaneService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Editor.Host
{
internal interface IPreviewPaneService : IWorkspaceService
{
object GetPreviewPane(DiagnosticData diagnostic, IReadOnlyList<object> previewContent);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Editor.Host
{
internal interface IPreviewPaneService : IWorkspaceService
{
object GetPreviewPane(DiagnosticData diagnostic, IReadOnlyList<object> previewContent);
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/CSharp/Test/CodeModel/FileCodeClassTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using EnvDTE;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeClassTests : AbstractFileCodeElementTests
{
public FileCodeClassTests()
: base(@"using System;
public abstract class Goo : IDisposable, ICloneable
{
}
[Serializable]
public class Bar
{
int a;
public int A
{
get
{
return a;
}
}
public string WindowsUserID => ""Domain"";
}")
{
}
private CodeClass GetCodeClass(params object[] path)
{
return (CodeClass)GetCodeElement(path);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsAbstract()
{
var cc = GetCodeClass("Goo");
Assert.True(cc.IsAbstract);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Bases()
{
var cc = GetCodeClass("Goo");
var bases = cc.Bases;
Assert.Equal(1, bases.Count);
Assert.Equal(1, bases.Cast<CodeElement>().Count());
Assert.NotNull(bases.Parent);
var parentClass = bases.Parent as CodeClass;
Assert.NotNull(parentClass);
Assert.Equal("Goo", parentClass.FullName);
Assert.True(bases.Item("object") is CodeClass);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void ImplementedInterfaces()
{
var cc = GetCodeClass("Goo");
var interfaces = cc.ImplementedInterfaces;
Assert.Equal(2, interfaces.Count);
Assert.Equal(2, interfaces.Cast<CodeElement>().Count());
Assert.NotNull(interfaces.Parent);
var parentClass = interfaces.Parent as CodeClass;
Assert.NotNull(parentClass);
Assert.Equal("Goo", parentClass.FullName);
Assert.True(interfaces.Item("System.IDisposable") is CodeInterface);
Assert.True(interfaces.Item("ICloneable") is CodeInterface);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void KindTest()
{
var cc = GetCodeClass("Goo");
Assert.Equal(vsCMElement.vsCMElementClass, cc.Kind);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Attributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_AttributesWithDelimiter()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Body()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartBody);
Assert.Equal(10, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_BodyWithDelimiter()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Header()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartHeader);
Assert.Equal(8, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_HeaderWithAttributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Name()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Navigate()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(8, startPoint.Line);
Assert.Equal(14, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Whole()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_WholeWithAttributes()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Attributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_AttributesWithDelimiter()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(7, endPoint.Line);
Assert.Equal(15, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Body()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartBody);
Assert.Equal(21, endPoint.Line);
Assert.Equal(1, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_BodyWithDelimiter()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Header()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_HeaderWithAttributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Name()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Navigate()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(8, endPoint.Line);
Assert.Equal(17, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Whole()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_WholeWithAttributes()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(21, endPoint.Line);
Assert.Equal(2, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void StartPoint()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.StartPoint;
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void EndPoint()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.EndPoint;
Assert.Equal(21, endPoint.Line);
Assert.Equal(2, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Accessor()
{
var testObject = GetCodeClass("Bar");
var l = from p in testObject.Members.OfType<CodeProperty>() where vsCMAccess.vsCMAccessPublic == p.Access && p.Getter != null && !p.Getter.IsShared && vsCMAccess.vsCMAccessPublic == p.Getter.Access select p;
var z = l.ToList<CodeProperty>();
Assert.Equal(2, z.Count);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using EnvDTE;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeClassTests : AbstractFileCodeElementTests
{
public FileCodeClassTests()
: base(@"using System;
public abstract class Goo : IDisposable, ICloneable
{
}
[Serializable]
public class Bar
{
int a;
public int A
{
get
{
return a;
}
}
public string WindowsUserID => ""Domain"";
}")
{
}
private CodeClass GetCodeClass(params object[] path)
{
return (CodeClass)GetCodeElement(path);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsAbstract()
{
var cc = GetCodeClass("Goo");
Assert.True(cc.IsAbstract);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Bases()
{
var cc = GetCodeClass("Goo");
var bases = cc.Bases;
Assert.Equal(1, bases.Count);
Assert.Equal(1, bases.Cast<CodeElement>().Count());
Assert.NotNull(bases.Parent);
var parentClass = bases.Parent as CodeClass;
Assert.NotNull(parentClass);
Assert.Equal("Goo", parentClass.FullName);
Assert.True(bases.Item("object") is CodeClass);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void ImplementedInterfaces()
{
var cc = GetCodeClass("Goo");
var interfaces = cc.ImplementedInterfaces;
Assert.Equal(2, interfaces.Count);
Assert.Equal(2, interfaces.Cast<CodeElement>().Count());
Assert.NotNull(interfaces.Parent);
var parentClass = interfaces.Parent as CodeClass;
Assert.NotNull(parentClass);
Assert.Equal("Goo", parentClass.FullName);
Assert.True(interfaces.Item("System.IDisposable") is CodeInterface);
Assert.True(interfaces.Item("ICloneable") is CodeInterface);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void KindTest()
{
var cc = GetCodeClass("Goo");
Assert.Equal(vsCMElement.vsCMElementClass, cc.Kind);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Attributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_AttributesWithDelimiter()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Body()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartBody);
Assert.Equal(10, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_BodyWithDelimiter()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Header()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartHeader);
Assert.Equal(8, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_HeaderWithAttributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Name()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Navigate()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(8, startPoint.Line);
Assert.Equal(14, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Whole()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_WholeWithAttributes()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Attributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_AttributesWithDelimiter()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(7, endPoint.Line);
Assert.Equal(15, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Body()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartBody);
Assert.Equal(21, endPoint.Line);
Assert.Equal(1, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_BodyWithDelimiter()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Header()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_HeaderWithAttributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Name()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Navigate()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(8, endPoint.Line);
Assert.Equal(17, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Whole()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_WholeWithAttributes()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(21, endPoint.Line);
Assert.Equal(2, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void StartPoint()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.StartPoint;
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void EndPoint()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.EndPoint;
Assert.Equal(21, endPoint.Line);
Assert.Equal(2, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Accessor()
{
var testObject = GetCodeClass("Bar");
var l = from p in testObject.Members.OfType<CodeProperty>() where vsCMAccess.vsCMAccessPublic == p.Access && p.Getter != null && !p.Getter.IsShared && vsCMAccess.vsCMAccessPublic == p.Getter.Access select p;
var z = l.ToList<CodeProperty>();
Assert.Equal(2, z.Count);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/RQName/Nodes/RQType.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal abstract class RQType
{
public static readonly RQType ObjectType = new RQConstructedType(
new RQUnconstructedType(new[] { "System" }, new[] { new RQUnconstructedTypeInfo("Object", 0) }),
Array.Empty<RQType>());
public abstract SimpleTreeNode ToSimpleTree();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal abstract class RQType
{
public static readonly RQType ObjectType = new RQConstructedType(
new RQUnconstructedType(new[] { "System" }, new[] { new RQUnconstructedTypeInfo("Object", 0) }),
Array.Empty<RQType>());
public abstract SimpleTreeNode ToSimpleTree();
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/Core/Portable/Options/Option2`1_operators.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Options
{
internal partial class Option2<T>
{
[return: NotNullIfNotNull("option")]
public static explicit operator Option<T>?(Option2<T>? option)
{
if (option is null)
{
return null;
}
return new Option<T>(option.OptionDefinition, option.StorageLocations.As<OptionStorageLocation>());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Options
{
internal partial class Option2<T>
{
[return: NotNullIfNotNull("option")]
public static explicit operator Option<T>?(Option2<T>? option)
{
if (option is null)
{
return null;
}
return new Option<T>(option.OptionDefinition, option.StorageLocations.As<OptionStorageLocation>());
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/CSharp/Portable/ChangeSignature/CSharpChangeSignatureService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace Microsoft.CodeAnalysis.CSharp.ChangeSignature
{
[ExportLanguageService(typeof(AbstractChangeSignatureService), LanguageNames.CSharp), Shared]
internal sealed class CSharpChangeSignatureService : AbstractChangeSignatureService
{
protected override SyntaxGenerator Generator => CSharpSyntaxGenerator.Instance;
protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance;
private static readonly ImmutableArray<SyntaxKind> _declarationKinds = ImmutableArray.Create(
SyntaxKind.MethodDeclaration,
SyntaxKind.ConstructorDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.DelegateDeclaration,
SyntaxKind.SimpleLambdaExpression,
SyntaxKind.ParenthesizedLambdaExpression,
SyntaxKind.LocalFunctionStatement,
SyntaxKind.RecordStructDeclaration,
SyntaxKind.RecordDeclaration);
private static readonly ImmutableArray<SyntaxKind> _declarationAndInvocableKinds =
_declarationKinds.Concat(ImmutableArray.Create(
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.ThisConstructorInitializer,
SyntaxKind.BaseConstructorInitializer,
SyntaxKind.ObjectCreationExpression,
SyntaxKind.ImplicitObjectCreationExpression,
SyntaxKind.Attribute,
SyntaxKind.NameMemberCref));
private static readonly ImmutableArray<SyntaxKind> _updatableAncestorKinds = ImmutableArray.Create(
SyntaxKind.ConstructorDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.ThisConstructorInitializer,
SyntaxKind.BaseConstructorInitializer,
SyntaxKind.ObjectCreationExpression,
SyntaxKind.Attribute,
SyntaxKind.DelegateDeclaration,
SyntaxKind.SimpleLambdaExpression,
SyntaxKind.ParenthesizedLambdaExpression,
SyntaxKind.NameMemberCref);
private static readonly ImmutableArray<SyntaxKind> _updatableNodeKinds = ImmutableArray.Create(
SyntaxKind.MethodDeclaration,
SyntaxKind.LocalFunctionStatement,
SyntaxKind.ConstructorDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.ThisConstructorInitializer,
SyntaxKind.BaseConstructorInitializer,
SyntaxKind.ObjectCreationExpression,
SyntaxKind.ImplicitObjectCreationExpression,
SyntaxKind.Attribute,
SyntaxKind.DelegateDeclaration,
SyntaxKind.NameMemberCref,
SyntaxKind.AnonymousMethodExpression,
SyntaxKind.ParenthesizedLambdaExpression,
SyntaxKind.SimpleLambdaExpression,
SyntaxKind.RecordStructDeclaration,
SyntaxKind.RecordDeclaration);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpChangeSignatureService()
{
}
public override async Task<(ISymbol? symbol, int selectedIndex)> GetInvocationSymbolAsync(
Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(position != tree.Length ? position : Math.Max(0, position - 1));
// Allow the user to invoke Change-Sig if they've written: Goo(a, b, c);$$
if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent is StatementSyntax)
{
token = token.GetPreviousToken();
position = token.Span.End;
}
if (token.Parent == null)
{
return default;
}
var matchingNode = GetMatchingNode(token.Parent, restrictToDeclarations);
if (matchingNode == null)
{
return default;
}
// Don't show change-signature in the random whitespace/trivia for code.
if (!matchingNode.Span.IntersectsWith(position))
{
return default;
}
// If we're actually on the declaration of some symbol, ensure that we're
// in a good location for that symbol (i.e. not in the attributes/constraints).
if (!InSymbolHeader(matchingNode, position))
{
return default;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var symbol = semanticModel.GetDeclaredSymbol(matchingNode, cancellationToken);
if (symbol != null)
{
var selectedIndex = TryGetSelectedIndexFromDeclaration(position, matchingNode);
return (symbol, selectedIndex);
}
if (matchingNode.IsKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation) &&
token.Parent.AncestorsAndSelf().Any(a => a == objectCreation.Type))
{
var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol;
if (typeSymbol != null && typeSymbol.IsKind(SymbolKind.NamedType) && ((ITypeSymbol)typeSymbol).TypeKind == TypeKind.Delegate)
{
return (typeSymbol, 0);
}
}
var symbolInfo = semanticModel.GetSymbolInfo(matchingNode, cancellationToken);
return (symbolInfo.Symbol ?? symbolInfo.CandidateSymbols.FirstOrDefault(), 0);
}
private static int TryGetSelectedIndexFromDeclaration(int position, SyntaxNode matchingNode)
{
var parameters = matchingNode.ChildNodes().OfType<BaseParameterListSyntax>().SingleOrDefault();
return parameters != null ? GetParameterIndex(parameters.Parameters, position) : 0;
}
private static SyntaxNode? GetMatchingNode(SyntaxNode node, bool restrictToDeclarations)
{
var matchKinds = restrictToDeclarations
? _declarationKinds
: _declarationAndInvocableKinds;
for (var current = node; current != null; current = current.Parent)
{
if (restrictToDeclarations &&
current.Kind() == SyntaxKind.Block || current.Kind() == SyntaxKind.ArrowExpressionClause)
{
return null;
}
if (matchKinds.Contains(current.Kind()))
{
return current;
}
}
return null;
}
private static bool InSymbolHeader(SyntaxNode matchingNode, int position)
{
// Caret has to be after the attributes if the symbol has any.
var lastAttributes = matchingNode.ChildNodes().LastOrDefault(n => n is AttributeListSyntax);
var start = lastAttributes?.GetLastToken().GetNextToken().SpanStart ??
matchingNode.SpanStart;
if (position < start)
{
return false;
}
// If the symbol has a parameter list, then the caret shouldn't be past the end of it.
var parameterList = matchingNode.ChildNodes().LastOrDefault(n => n is ParameterListSyntax);
if (parameterList != null)
{
return position <= parameterList.FullSpan.End;
}
// Case we haven't handled yet. Just assume we're in the header.
return true;
}
public override SyntaxNode? FindNodeToUpdate(Document document, SyntaxNode node)
{
if (_updatableNodeKinds.Contains(node.Kind()))
{
return node;
}
// TODO: file bug about this: var invocation = csnode.Ancestors().FirstOrDefault(a => a.Kind == SyntaxKind.InvocationExpression);
var matchingNode = node.AncestorsAndSelf().FirstOrDefault(n => _updatableAncestorKinds.Contains(n.Kind()));
if (matchingNode == null)
{
return null;
}
var nodeContainingOriginal = GetNodeContainingTargetNode(matchingNode);
if (nodeContainingOriginal == null)
{
return null;
}
return node.AncestorsAndSelf().Any(n => n == nodeContainingOriginal) ? matchingNode : null;
}
private static SyntaxNode? GetNodeContainingTargetNode(SyntaxNode matchingNode)
{
switch (matchingNode.Kind())
{
case SyntaxKind.InvocationExpression:
return ((InvocationExpressionSyntax)matchingNode).Expression;
case SyntaxKind.ElementAccessExpression:
return ((ElementAccessExpressionSyntax)matchingNode).ArgumentList;
case SyntaxKind.ObjectCreationExpression:
return ((ObjectCreationExpressionSyntax)matchingNode).Type;
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.ThisConstructorInitializer:
case SyntaxKind.BaseConstructorInitializer:
case SyntaxKind.Attribute:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.NameMemberCref:
return matchingNode;
default:
return null;
}
}
public override async Task<SyntaxNode> ChangeSignatureAsync(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken)
{
var updatedNode = potentiallyUpdatedNode as CSharpSyntaxNode;
// Update <param> tags.
if (updatedNode.IsKind(SyntaxKind.MethodDeclaration) ||
updatedNode.IsKind(SyntaxKind.ConstructorDeclaration) ||
updatedNode.IsKind(SyntaxKind.IndexerDeclaration) ||
updatedNode.IsKind(SyntaxKind.DelegateDeclaration) ||
updatedNode.IsKind(SyntaxKind.RecordStructDeclaration) ||
updatedNode.IsKind(SyntaxKind.RecordDeclaration))
{
var updatedLeadingTrivia = UpdateParamTagsInLeadingTrivia(document, updatedNode, declarationSymbol, signaturePermutation);
if (updatedLeadingTrivia != default && !updatedLeadingTrivia.IsEmpty)
{
updatedNode = updatedNode.WithLeadingTrivia(updatedLeadingTrivia);
}
}
// Update declarations parameter lists
if (updatedNode.IsKind(SyntaxKind.MethodDeclaration, out MethodDeclarationSyntax? method))
{
var updatedParameters = UpdateDeclaration(method.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return method.WithParameterList(method.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode is RecordDeclarationSyntax { ParameterList: not null } record)
{
var updatedParameters = UpdateDeclaration(record.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return record.WithParameterList(record.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.LocalFunctionStatement, out LocalFunctionStatementSyntax? localFunction))
{
var updatedParameters = UpdateDeclaration(localFunction.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return localFunction.WithParameterList(localFunction.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax? constructor))
{
var updatedParameters = UpdateDeclaration(constructor.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return constructor.WithParameterList(constructor.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.IndexerDeclaration, out IndexerDeclarationSyntax? indexer))
{
var updatedParameters = UpdateDeclaration(indexer.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return indexer.WithParameterList(indexer.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDeclaration))
{
var updatedParameters = UpdateDeclaration(delegateDeclaration.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return delegateDeclaration.WithParameterList(delegateDeclaration.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.AnonymousMethodExpression, out AnonymousMethodExpressionSyntax? anonymousMethod))
{
// Delegates may omit parameters in C#
if (anonymousMethod.ParameterList == null)
{
return anonymousMethod;
}
var updatedParameters = UpdateDeclaration(anonymousMethod.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return anonymousMethod.WithParameterList(anonymousMethod.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.SimpleLambdaExpression, out SimpleLambdaExpressionSyntax? lambda))
{
if (signaturePermutation.UpdatedConfiguration.ToListOfParameters().Any())
{
var updatedParameters = UpdateDeclaration(SeparatedList(new[] { lambda.Parameter }), signaturePermutation, CreateNewParameterSyntax);
return ParenthesizedLambdaExpression(
lambda.AsyncKeyword,
ParameterList(updatedParameters),
lambda.ArrowToken,
lambda.Body);
}
else
{
// No parameters. Change to a parenthesized lambda expression
var emptyParameterList = ParameterList()
.WithLeadingTrivia(lambda.Parameter.GetLeadingTrivia())
.WithTrailingTrivia(lambda.Parameter.GetTrailingTrivia());
return ParenthesizedLambdaExpression(lambda.AsyncKeyword, emptyParameterList, lambda.ArrowToken, lambda.Body);
}
}
if (updatedNode.IsKind(SyntaxKind.ParenthesizedLambdaExpression, out ParenthesizedLambdaExpressionSyntax? parenLambda))
{
var doNotSkipParameterType = parenLambda.ParameterList.Parameters.FirstOrDefault()?.Type != null;
var updatedParameters = UpdateDeclaration(
parenLambda.ParameterList.Parameters,
signaturePermutation,
p => CreateNewParameterSyntax(p, !doNotSkipParameterType));
return parenLambda.WithParameterList(parenLambda.ParameterList.WithParameters(updatedParameters));
}
// Handle references in crefs
if (updatedNode.IsKind(SyntaxKind.NameMemberCref, out NameMemberCrefSyntax? nameMemberCref))
{
if (nameMemberCref.Parameters == null ||
!nameMemberCref.Parameters.Parameters.Any())
{
return nameMemberCref;
}
var newParameters = UpdateDeclaration(nameMemberCref.Parameters.Parameters, signaturePermutation, CreateNewCrefParameterSyntax);
var newCrefParameterList = nameMemberCref.Parameters.WithParameters(newParameters);
return nameMemberCref.WithParameters(newCrefParameterList);
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// Update reference site argument lists
if (updatedNode.IsKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax? invocation))
{
var symbolInfo = semanticModel.GetSymbolInfo((InvocationExpressionSyntax)originalNode, cancellationToken);
return invocation.WithArgumentList(
await UpdateArgumentListAsync(
declarationSymbol,
signaturePermutation,
invocation.ArgumentList,
symbolInfo.Symbol is IMethodSymbol { MethodKind: MethodKind.ReducedExtension },
IsParamsArrayExpanded(semanticModel, invocation, symbolInfo, cancellationToken),
document,
originalNode.SpanStart,
cancellationToken).ConfigureAwait(false));
}
// Handles both ObjectCreationExpressionSyntax and ImplicitObjectCreationExpressionSyntax
if (updatedNode is BaseObjectCreationExpressionSyntax objCreation)
{
if (objCreation.ArgumentList == null)
{
return updatedNode;
}
var symbolInfo = semanticModel.GetSymbolInfo((BaseObjectCreationExpressionSyntax)originalNode, cancellationToken);
return objCreation.WithArgumentList(
await UpdateArgumentListAsync(
declarationSymbol,
signaturePermutation,
objCreation.ArgumentList,
isReducedExtensionMethod: false,
IsParamsArrayExpanded(semanticModel, objCreation, symbolInfo, cancellationToken),
document,
originalNode.SpanStart,
cancellationToken).ConfigureAwait(false));
}
if (updatedNode.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) ||
updatedNode.IsKind(SyntaxKind.BaseConstructorInitializer, out constructorInit))
{
var symbolInfo = semanticModel.GetSymbolInfo((ConstructorInitializerSyntax)originalNode, cancellationToken);
return constructorInit.WithArgumentList(
await UpdateArgumentListAsync(
declarationSymbol,
signaturePermutation,
constructorInit.ArgumentList,
isReducedExtensionMethod: false,
IsParamsArrayExpanded(semanticModel, constructorInit, symbolInfo, cancellationToken),
document,
originalNode.SpanStart,
cancellationToken).ConfigureAwait(false));
}
if (updatedNode.IsKind(SyntaxKind.ElementAccessExpression, out ElementAccessExpressionSyntax? elementAccess))
{
var symbolInfo = semanticModel.GetSymbolInfo((ElementAccessExpressionSyntax)originalNode, cancellationToken);
return elementAccess.WithArgumentList(
await UpdateArgumentListAsync(
declarationSymbol,
signaturePermutation,
elementAccess.ArgumentList,
isReducedExtensionMethod: false,
IsParamsArrayExpanded(semanticModel, elementAccess, symbolInfo, cancellationToken),
document,
originalNode.SpanStart,
cancellationToken).ConfigureAwait(false));
}
if (updatedNode.IsKind(SyntaxKind.Attribute, out AttributeSyntax? attribute))
{
var symbolInfo = semanticModel.GetSymbolInfo((AttributeSyntax)originalNode, cancellationToken);
if (attribute.ArgumentList == null)
{
return updatedNode;
}
return attribute.WithArgumentList(
await UpdateAttributeArgumentListAsync(
declarationSymbol,
signaturePermutation,
attribute.ArgumentList,
isReducedExtensionMethod: false,
IsParamsArrayExpanded(semanticModel, attribute, symbolInfo, cancellationToken),
document,
originalNode.SpanStart,
cancellationToken).ConfigureAwait(false));
}
Debug.Assert(false, "Unknown reference location");
return null;
}
private async Task<T> UpdateArgumentListAsync<T>(
ISymbol declarationSymbol,
SignatureChange signaturePermutation,
T argumentList,
bool isReducedExtensionMethod,
bool isParamsArrayExpanded,
Document document,
int position,
CancellationToken cancellationToken) where T : BaseArgumentListSyntax
{
// Reorders and removes arguments
// e.g. P(a, b, c) ==> P(c, a)
var newArguments = PermuteArgumentList(
declarationSymbol,
argumentList.Arguments,
signaturePermutation.WithoutAddedParameters(),
isReducedExtensionMethod);
// Adds new arguments into the updated list
// e.g. P(c, a) ==> P(x, c, a, y)
newArguments = await AddNewArgumentsToListAsync(
declarationSymbol,
newArguments,
argumentList.Arguments,
signaturePermutation,
isReducedExtensionMethod,
isParamsArrayExpanded,
generateAttributeArguments: false,
document,
position,
cancellationToken).ConfigureAwait(false);
return (T)argumentList
.WithArguments(newArguments)
.WithAdditionalAnnotations(changeSignatureFormattingAnnotation);
}
private async Task<AttributeArgumentListSyntax> UpdateAttributeArgumentListAsync(
ISymbol declarationSymbol,
SignatureChange signaturePermutation,
AttributeArgumentListSyntax argumentList,
bool isReducedExtensionMethod,
bool isParamsArrayExpanded,
Document document,
int position,
CancellationToken cancellationToken)
{
var newArguments = PermuteAttributeArgumentList(
declarationSymbol,
argumentList.Arguments,
signaturePermutation.WithoutAddedParameters());
newArguments = await AddNewArgumentsToListAsync(
declarationSymbol,
newArguments,
argumentList.Arguments,
signaturePermutation,
isReducedExtensionMethod,
isParamsArrayExpanded,
generateAttributeArguments: true,
document,
position,
cancellationToken).ConfigureAwait(false);
return argumentList
.WithArguments(newArguments)
.WithAdditionalAnnotations(changeSignatureFormattingAnnotation);
}
private static bool IsParamsArrayExpanded(SemanticModel semanticModel, SyntaxNode node, SymbolInfo symbolInfo, CancellationToken cancellationToken)
{
if (symbolInfo.Symbol == null)
{
return false;
}
int argumentCount;
bool lastArgumentIsNamed;
ExpressionSyntax lastArgumentExpression;
if (node is AttributeSyntax attribute)
{
if (attribute.ArgumentList == null)
{
return false;
}
argumentCount = attribute.ArgumentList.Arguments.Count;
lastArgumentIsNamed = attribute.ArgumentList.Arguments.LastOrDefault()?.NameColon != null ||
attribute.ArgumentList.Arguments.LastOrDefault()?.NameEquals != null;
var lastArgument = attribute.ArgumentList.Arguments.LastOrDefault();
if (lastArgument == null)
{
return false;
}
lastArgumentExpression = lastArgument.Expression;
}
else
{
BaseArgumentListSyntax? argumentList = node switch
{
InvocationExpressionSyntax invocation => invocation.ArgumentList,
BaseObjectCreationExpressionSyntax objectCreation => objectCreation.ArgumentList,
ConstructorInitializerSyntax constructorInitializer => constructorInitializer.ArgumentList,
ElementAccessExpressionSyntax elementAccess => elementAccess.ArgumentList,
_ => throw ExceptionUtilities.UnexpectedValue(node.Kind())
};
if (argumentList == null)
{
return false;
}
argumentCount = argumentList.Arguments.Count;
lastArgumentIsNamed = argumentList.Arguments.LastOrDefault()?.NameColon != null;
var lastArgument = argumentList.Arguments.LastOrDefault();
if (lastArgument == null)
{
return false;
}
lastArgumentExpression = lastArgument.Expression;
}
return IsParamsArrayExpandedHelper(symbolInfo.Symbol, argumentCount, lastArgumentIsNamed, semanticModel, lastArgumentExpression, cancellationToken);
}
private static ParameterSyntax CreateNewParameterSyntax(AddedParameter addedParameter)
=> CreateNewParameterSyntax(addedParameter, skipParameterType: false);
private static ParameterSyntax CreateNewParameterSyntax(AddedParameter addedParameter, bool skipParameterType)
{
var equalsValueClause = addedParameter.HasDefaultValue
? EqualsValueClause(ParseExpression(addedParameter.DefaultValue))
: null;
return Parameter(
attributeLists: default,
modifiers: default,
type: skipParameterType
? null
: addedParameter.Type.GenerateTypeSyntax(),
Identifier(addedParameter.Name),
@default: equalsValueClause);
}
private static CrefParameterSyntax CreateNewCrefParameterSyntax(AddedParameter addedParameter)
=> CrefParameter(type: addedParameter.Type.GenerateTypeSyntax())
.WithLeadingTrivia(ElasticSpace);
private SeparatedSyntaxList<T> UpdateDeclaration<T>(
SeparatedSyntaxList<T> list,
SignatureChange updatedSignature,
Func<AddedParameter, T> createNewParameterMethod) where T : SyntaxNode
{
var (parameters, separators) = base.UpdateDeclarationBase<T>(list, updatedSignature, createNewParameterMethod);
return SeparatedList(parameters, separators);
}
protected override T TransferLeadingWhitespaceTrivia<T>(T newArgument, SyntaxNode oldArgument)
{
var oldTrivia = oldArgument.GetLeadingTrivia();
var oldOnlyHasWhitespaceTrivia = oldTrivia.All(t => t.IsKind(SyntaxKind.WhitespaceTrivia));
var newTrivia = newArgument.GetLeadingTrivia();
var newOnlyHasWhitespaceTrivia = newTrivia.All(t => t.IsKind(SyntaxKind.WhitespaceTrivia));
if (oldOnlyHasWhitespaceTrivia && newOnlyHasWhitespaceTrivia)
{
newArgument = newArgument.WithLeadingTrivia(oldTrivia);
}
return newArgument;
}
private async Task<SeparatedSyntaxList<SyntaxNode>> AddNewArgumentsToListAsync(
ISymbol declarationSymbol,
SeparatedSyntaxList<SyntaxNode> newArguments,
SeparatedSyntaxList<SyntaxNode> originalArguments,
SignatureChange signaturePermutation,
bool isReducedExtensionMethod,
bool isParamsArrayExpanded,
bool generateAttributeArguments,
Document document,
int position,
CancellationToken cancellationToken)
{
var newArgumentList = await AddNewArgumentsToListAsync(
declarationSymbol, newArguments,
signaturePermutation, isReducedExtensionMethod,
isParamsArrayExpanded, generateAttributeArguments,
document, position, cancellationToken).ConfigureAwait(false);
return SeparatedList(
TransferLeadingWhitespaceTrivia(newArgumentList, originalArguments),
newArgumentList.GetSeparators());
}
private SeparatedSyntaxList<AttributeArgumentSyntax> PermuteAttributeArgumentList(
ISymbol declarationSymbol,
SeparatedSyntaxList<AttributeArgumentSyntax> arguments,
SignatureChange updatedSignature)
{
var newArguments = PermuteArguments(declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToImmutableArray(),
updatedSignature);
var numSeparatorsToSkip = arguments.Count - newArguments.Length;
// copy whitespace trivia from original position
var newArgumentsWithTrivia = TransferLeadingWhitespaceTrivia(
newArguments.Select(a => (AttributeArgumentSyntax)(UnifiedArgumentSyntax)a), arguments);
return SeparatedList(newArgumentsWithTrivia, GetSeparators(arguments, numSeparatorsToSkip));
}
private SeparatedSyntaxList<ArgumentSyntax> PermuteArgumentList(
ISymbol declarationSymbol,
SeparatedSyntaxList<ArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
var newArguments = PermuteArguments(
declarationSymbol,
arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToImmutableArray(),
updatedSignature,
isReducedExtensionMethod);
// copy whitespace trivia from original position
var newArgumentsWithTrivia = TransferLeadingWhitespaceTrivia(
newArguments.Select(a => (ArgumentSyntax)(UnifiedArgumentSyntax)a), arguments);
var numSeparatorsToSkip = arguments.Count - newArguments.Length;
return SeparatedList(newArgumentsWithTrivia, GetSeparators(arguments, numSeparatorsToSkip));
}
private ImmutableArray<T> TransferLeadingWhitespaceTrivia<T, U>(IEnumerable<T> newArguments, SeparatedSyntaxList<U> oldArguments)
where T : SyntaxNode
where U : SyntaxNode
{
var result = ImmutableArray.CreateBuilder<T>();
var index = 0;
foreach (var newArgument in newArguments)
{
result.Add(index < oldArguments.Count
? TransferLeadingWhitespaceTrivia(newArgument, oldArguments[index])
: newArgument);
index++;
}
return result.ToImmutable();
}
private ImmutableArray<SyntaxTrivia> UpdateParamTagsInLeadingTrivia(Document document, CSharpSyntaxNode node, ISymbol declarationSymbol, SignatureChange updatedSignature)
{
if (!node.HasLeadingTrivia)
{
return ImmutableArray<SyntaxTrivia>.Empty;
}
var paramNodes = node
.DescendantNodes(descendIntoTrivia: true)
.OfType<XmlElementSyntax>()
.Where(e => e.StartTag.Name.ToString() == DocumentationCommentXmlNames.ParameterElementName);
var permutedParamNodes = VerifyAndPermuteParamNodes(paramNodes, declarationSymbol, updatedSignature);
if (permutedParamNodes.IsEmpty)
{
return ImmutableArray<SyntaxTrivia>.Empty;
}
return GetPermutedDocCommentTrivia(document, node, permutedParamNodes);
}
private ImmutableArray<SyntaxNode> VerifyAndPermuteParamNodes(IEnumerable<XmlElementSyntax> paramNodes, ISymbol declarationSymbol, SignatureChange updatedSignature)
{
// Only reorder if count and order match originally.
var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var declaredParameters = GetParameters(declarationSymbol);
if (paramNodes.Count() != declaredParameters.Length)
{
return ImmutableArray<SyntaxNode>.Empty;
}
// No parameters originally, so no param nodes to permute.
if (declaredParameters.Length == 0)
{
return ImmutableArray<SyntaxNode>.Empty;
}
var dictionary = new Dictionary<string, XmlElementSyntax>();
var i = 0;
foreach (var paramNode in paramNodes)
{
var nameAttribute = paramNode.StartTag.Attributes.FirstOrDefault(a => a.Name.ToString().Equals("name", StringComparison.OrdinalIgnoreCase));
if (nameAttribute == null)
{
return ImmutableArray<SyntaxNode>.Empty;
}
var identifier = nameAttribute.DescendantNodes(descendIntoTrivia: true).OfType<IdentifierNameSyntax>().FirstOrDefault();
if (identifier == null || identifier.ToString() != declaredParameters.ElementAt(i).Name)
{
return ImmutableArray<SyntaxNode>.Empty;
}
dictionary.Add(originalParameters[i].Name.ToString(), paramNode);
i++;
}
// Everything lines up, so permute them.
var permutedParams = ArrayBuilder<SyntaxNode>.GetInstance();
foreach (var parameter in reorderedParameters)
{
if (dictionary.TryGetValue(parameter.Name, out var permutedParam))
{
permutedParams.Add(permutedParam);
}
else
{
permutedParams.Add(XmlElement(
XmlElementStartTag(
XmlName("param"),
List<XmlAttributeSyntax>(new[] { XmlNameAttribute(parameter.Name) })),
XmlElementEndTag(XmlName("param"))));
}
}
return permutedParams.ToImmutableAndFree();
}
public override async Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsFromDelegateInvokeAsync(
IMethodSymbol symbol,
Document document,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var convertedMethodNodes);
foreach (var node in root.DescendantNodes())
{
if (!node.IsKind(SyntaxKind.IdentifierName) ||
!semanticModel.GetMemberGroup(node, cancellationToken).Any())
{
continue;
}
var convertedType = (ISymbol?)semanticModel.GetTypeInfo(node, cancellationToken).ConvertedType;
convertedType = convertedType?.OriginalDefinition;
if (convertedType != null)
{
convertedType = await SymbolFinder.FindSourceDefinitionAsync(convertedType, document.Project.Solution, cancellationToken).ConfigureAwait(false)
?? convertedType;
}
if (Equals(convertedType, symbol.ContainingType))
convertedMethodNodes.Add(node);
}
var convertedMethodGroups = convertedMethodNodes
.Select(n => semanticModel.GetSymbolInfo(n, cancellationToken).Symbol)
.WhereNotNull()
.ToImmutableArray();
return convertedMethodGroups;
}
protected override IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document)
=> Formatter.GetDefaultFormattingRules(document).Concat(new ChangeSignatureFormattingRule());
protected override SyntaxNode AddNameToArgument(SyntaxNode newArgument, string name)
{
return newArgument switch
{
ArgumentSyntax a => a.WithNameColon(NameColon(name)),
AttributeArgumentSyntax a => a.WithNameColon(NameColon(name)),
_ => throw ExceptionUtilities.UnexpectedValue(newArgument.Kind())
};
}
protected override SyntaxNode CreateExplicitParamsArrayFromIndividualArguments(SeparatedSyntaxList<SyntaxNode> newArguments, int indexInExistingList, IParameterSymbol parameterSymbol)
{
RoslynDebug.Assert(parameterSymbol.IsParams);
// These arguments are part of a params array, and should not have any modifiers, making it okay to just use their expressions.
var listOfArguments = SeparatedList(newArguments.Skip(indexInExistingList).Select(a => ((ArgumentSyntax)a).Expression), newArguments.GetSeparators().Skip(indexInExistingList));
var initializerExpression = InitializerExpression(SyntaxKind.ArrayInitializerExpression, listOfArguments);
var objectCreation = ArrayCreationExpression((ArrayTypeSyntax)parameterSymbol.Type.GenerateTypeSyntax(), initializerExpression);
return Argument(objectCreation);
}
protected override bool SupportsOptionalAndParamsArrayParametersSimultaneously()
{
return true;
}
protected override SyntaxToken CommaTokenWithElasticSpace()
=> Token(SyntaxKind.CommaToken).WithTrailingTrivia(ElasticSpace);
protected override bool TryGetRecordPrimaryConstructor(INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol? primaryConstructor)
=> typeSymbol.TryGetRecordPrimaryConstructor(out primaryConstructor);
protected override ImmutableArray<IParameterSymbol> GetParameters(ISymbol declarationSymbol)
{
var declaredParameters = declarationSymbol.GetParameters();
if (declarationSymbol is INamedTypeSymbol namedTypeSymbol &&
namedTypeSymbol.TryGetRecordPrimaryConstructor(out var primaryConstructor))
{
declaredParameters = primaryConstructor.Parameters;
}
return declaredParameters;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace Microsoft.CodeAnalysis.CSharp.ChangeSignature
{
[ExportLanguageService(typeof(AbstractChangeSignatureService), LanguageNames.CSharp), Shared]
internal sealed class CSharpChangeSignatureService : AbstractChangeSignatureService
{
protected override SyntaxGenerator Generator => CSharpSyntaxGenerator.Instance;
protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance;
private static readonly ImmutableArray<SyntaxKind> _declarationKinds = ImmutableArray.Create(
SyntaxKind.MethodDeclaration,
SyntaxKind.ConstructorDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.DelegateDeclaration,
SyntaxKind.SimpleLambdaExpression,
SyntaxKind.ParenthesizedLambdaExpression,
SyntaxKind.LocalFunctionStatement,
SyntaxKind.RecordStructDeclaration,
SyntaxKind.RecordDeclaration);
private static readonly ImmutableArray<SyntaxKind> _declarationAndInvocableKinds =
_declarationKinds.Concat(ImmutableArray.Create(
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.ThisConstructorInitializer,
SyntaxKind.BaseConstructorInitializer,
SyntaxKind.ObjectCreationExpression,
SyntaxKind.ImplicitObjectCreationExpression,
SyntaxKind.Attribute,
SyntaxKind.NameMemberCref));
private static readonly ImmutableArray<SyntaxKind> _updatableAncestorKinds = ImmutableArray.Create(
SyntaxKind.ConstructorDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.ThisConstructorInitializer,
SyntaxKind.BaseConstructorInitializer,
SyntaxKind.ObjectCreationExpression,
SyntaxKind.Attribute,
SyntaxKind.DelegateDeclaration,
SyntaxKind.SimpleLambdaExpression,
SyntaxKind.ParenthesizedLambdaExpression,
SyntaxKind.NameMemberCref);
private static readonly ImmutableArray<SyntaxKind> _updatableNodeKinds = ImmutableArray.Create(
SyntaxKind.MethodDeclaration,
SyntaxKind.LocalFunctionStatement,
SyntaxKind.ConstructorDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.ThisConstructorInitializer,
SyntaxKind.BaseConstructorInitializer,
SyntaxKind.ObjectCreationExpression,
SyntaxKind.ImplicitObjectCreationExpression,
SyntaxKind.Attribute,
SyntaxKind.DelegateDeclaration,
SyntaxKind.NameMemberCref,
SyntaxKind.AnonymousMethodExpression,
SyntaxKind.ParenthesizedLambdaExpression,
SyntaxKind.SimpleLambdaExpression,
SyntaxKind.RecordStructDeclaration,
SyntaxKind.RecordDeclaration);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpChangeSignatureService()
{
}
public override async Task<(ISymbol? symbol, int selectedIndex)> GetInvocationSymbolAsync(
Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(position != tree.Length ? position : Math.Max(0, position - 1));
// Allow the user to invoke Change-Sig if they've written: Goo(a, b, c);$$
if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent is StatementSyntax)
{
token = token.GetPreviousToken();
position = token.Span.End;
}
if (token.Parent == null)
{
return default;
}
var matchingNode = GetMatchingNode(token.Parent, restrictToDeclarations);
if (matchingNode == null)
{
return default;
}
// Don't show change-signature in the random whitespace/trivia for code.
if (!matchingNode.Span.IntersectsWith(position))
{
return default;
}
// If we're actually on the declaration of some symbol, ensure that we're
// in a good location for that symbol (i.e. not in the attributes/constraints).
if (!InSymbolHeader(matchingNode, position))
{
return default;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var symbol = semanticModel.GetDeclaredSymbol(matchingNode, cancellationToken);
if (symbol != null)
{
var selectedIndex = TryGetSelectedIndexFromDeclaration(position, matchingNode);
return (symbol, selectedIndex);
}
if (matchingNode.IsKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation) &&
token.Parent.AncestorsAndSelf().Any(a => a == objectCreation.Type))
{
var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol;
if (typeSymbol != null && typeSymbol.IsKind(SymbolKind.NamedType) && ((ITypeSymbol)typeSymbol).TypeKind == TypeKind.Delegate)
{
return (typeSymbol, 0);
}
}
var symbolInfo = semanticModel.GetSymbolInfo(matchingNode, cancellationToken);
return (symbolInfo.Symbol ?? symbolInfo.CandidateSymbols.FirstOrDefault(), 0);
}
private static int TryGetSelectedIndexFromDeclaration(int position, SyntaxNode matchingNode)
{
var parameters = matchingNode.ChildNodes().OfType<BaseParameterListSyntax>().SingleOrDefault();
return parameters != null ? GetParameterIndex(parameters.Parameters, position) : 0;
}
private static SyntaxNode? GetMatchingNode(SyntaxNode node, bool restrictToDeclarations)
{
var matchKinds = restrictToDeclarations
? _declarationKinds
: _declarationAndInvocableKinds;
for (var current = node; current != null; current = current.Parent)
{
if (restrictToDeclarations &&
current.Kind() == SyntaxKind.Block || current.Kind() == SyntaxKind.ArrowExpressionClause)
{
return null;
}
if (matchKinds.Contains(current.Kind()))
{
return current;
}
}
return null;
}
private static bool InSymbolHeader(SyntaxNode matchingNode, int position)
{
// Caret has to be after the attributes if the symbol has any.
var lastAttributes = matchingNode.ChildNodes().LastOrDefault(n => n is AttributeListSyntax);
var start = lastAttributes?.GetLastToken().GetNextToken().SpanStart ??
matchingNode.SpanStart;
if (position < start)
{
return false;
}
// If the symbol has a parameter list, then the caret shouldn't be past the end of it.
var parameterList = matchingNode.ChildNodes().LastOrDefault(n => n is ParameterListSyntax);
if (parameterList != null)
{
return position <= parameterList.FullSpan.End;
}
// Case we haven't handled yet. Just assume we're in the header.
return true;
}
public override SyntaxNode? FindNodeToUpdate(Document document, SyntaxNode node)
{
if (_updatableNodeKinds.Contains(node.Kind()))
{
return node;
}
// TODO: file bug about this: var invocation = csnode.Ancestors().FirstOrDefault(a => a.Kind == SyntaxKind.InvocationExpression);
var matchingNode = node.AncestorsAndSelf().FirstOrDefault(n => _updatableAncestorKinds.Contains(n.Kind()));
if (matchingNode == null)
{
return null;
}
var nodeContainingOriginal = GetNodeContainingTargetNode(matchingNode);
if (nodeContainingOriginal == null)
{
return null;
}
return node.AncestorsAndSelf().Any(n => n == nodeContainingOriginal) ? matchingNode : null;
}
private static SyntaxNode? GetNodeContainingTargetNode(SyntaxNode matchingNode)
{
switch (matchingNode.Kind())
{
case SyntaxKind.InvocationExpression:
return ((InvocationExpressionSyntax)matchingNode).Expression;
case SyntaxKind.ElementAccessExpression:
return ((ElementAccessExpressionSyntax)matchingNode).ArgumentList;
case SyntaxKind.ObjectCreationExpression:
return ((ObjectCreationExpressionSyntax)matchingNode).Type;
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.ThisConstructorInitializer:
case SyntaxKind.BaseConstructorInitializer:
case SyntaxKind.Attribute:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.NameMemberCref:
return matchingNode;
default:
return null;
}
}
public override async Task<SyntaxNode> ChangeSignatureAsync(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken)
{
var updatedNode = potentiallyUpdatedNode as CSharpSyntaxNode;
// Update <param> tags.
if (updatedNode.IsKind(SyntaxKind.MethodDeclaration) ||
updatedNode.IsKind(SyntaxKind.ConstructorDeclaration) ||
updatedNode.IsKind(SyntaxKind.IndexerDeclaration) ||
updatedNode.IsKind(SyntaxKind.DelegateDeclaration) ||
updatedNode.IsKind(SyntaxKind.RecordStructDeclaration) ||
updatedNode.IsKind(SyntaxKind.RecordDeclaration))
{
var updatedLeadingTrivia = UpdateParamTagsInLeadingTrivia(document, updatedNode, declarationSymbol, signaturePermutation);
if (updatedLeadingTrivia != default && !updatedLeadingTrivia.IsEmpty)
{
updatedNode = updatedNode.WithLeadingTrivia(updatedLeadingTrivia);
}
}
// Update declarations parameter lists
if (updatedNode.IsKind(SyntaxKind.MethodDeclaration, out MethodDeclarationSyntax? method))
{
var updatedParameters = UpdateDeclaration(method.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return method.WithParameterList(method.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode is RecordDeclarationSyntax { ParameterList: not null } record)
{
var updatedParameters = UpdateDeclaration(record.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return record.WithParameterList(record.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.LocalFunctionStatement, out LocalFunctionStatementSyntax? localFunction))
{
var updatedParameters = UpdateDeclaration(localFunction.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return localFunction.WithParameterList(localFunction.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax? constructor))
{
var updatedParameters = UpdateDeclaration(constructor.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return constructor.WithParameterList(constructor.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.IndexerDeclaration, out IndexerDeclarationSyntax? indexer))
{
var updatedParameters = UpdateDeclaration(indexer.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return indexer.WithParameterList(indexer.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDeclaration))
{
var updatedParameters = UpdateDeclaration(delegateDeclaration.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return delegateDeclaration.WithParameterList(delegateDeclaration.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.AnonymousMethodExpression, out AnonymousMethodExpressionSyntax? anonymousMethod))
{
// Delegates may omit parameters in C#
if (anonymousMethod.ParameterList == null)
{
return anonymousMethod;
}
var updatedParameters = UpdateDeclaration(anonymousMethod.ParameterList.Parameters, signaturePermutation, CreateNewParameterSyntax);
return anonymousMethod.WithParameterList(anonymousMethod.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.SimpleLambdaExpression, out SimpleLambdaExpressionSyntax? lambda))
{
if (signaturePermutation.UpdatedConfiguration.ToListOfParameters().Any())
{
var updatedParameters = UpdateDeclaration(SeparatedList(new[] { lambda.Parameter }), signaturePermutation, CreateNewParameterSyntax);
return ParenthesizedLambdaExpression(
lambda.AsyncKeyword,
ParameterList(updatedParameters),
lambda.ArrowToken,
lambda.Body);
}
else
{
// No parameters. Change to a parenthesized lambda expression
var emptyParameterList = ParameterList()
.WithLeadingTrivia(lambda.Parameter.GetLeadingTrivia())
.WithTrailingTrivia(lambda.Parameter.GetTrailingTrivia());
return ParenthesizedLambdaExpression(lambda.AsyncKeyword, emptyParameterList, lambda.ArrowToken, lambda.Body);
}
}
if (updatedNode.IsKind(SyntaxKind.ParenthesizedLambdaExpression, out ParenthesizedLambdaExpressionSyntax? parenLambda))
{
var doNotSkipParameterType = parenLambda.ParameterList.Parameters.FirstOrDefault()?.Type != null;
var updatedParameters = UpdateDeclaration(
parenLambda.ParameterList.Parameters,
signaturePermutation,
p => CreateNewParameterSyntax(p, !doNotSkipParameterType));
return parenLambda.WithParameterList(parenLambda.ParameterList.WithParameters(updatedParameters));
}
// Handle references in crefs
if (updatedNode.IsKind(SyntaxKind.NameMemberCref, out NameMemberCrefSyntax? nameMemberCref))
{
if (nameMemberCref.Parameters == null ||
!nameMemberCref.Parameters.Parameters.Any())
{
return nameMemberCref;
}
var newParameters = UpdateDeclaration(nameMemberCref.Parameters.Parameters, signaturePermutation, CreateNewCrefParameterSyntax);
var newCrefParameterList = nameMemberCref.Parameters.WithParameters(newParameters);
return nameMemberCref.WithParameters(newCrefParameterList);
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// Update reference site argument lists
if (updatedNode.IsKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax? invocation))
{
var symbolInfo = semanticModel.GetSymbolInfo((InvocationExpressionSyntax)originalNode, cancellationToken);
return invocation.WithArgumentList(
await UpdateArgumentListAsync(
declarationSymbol,
signaturePermutation,
invocation.ArgumentList,
symbolInfo.Symbol is IMethodSymbol { MethodKind: MethodKind.ReducedExtension },
IsParamsArrayExpanded(semanticModel, invocation, symbolInfo, cancellationToken),
document,
originalNode.SpanStart,
cancellationToken).ConfigureAwait(false));
}
// Handles both ObjectCreationExpressionSyntax and ImplicitObjectCreationExpressionSyntax
if (updatedNode is BaseObjectCreationExpressionSyntax objCreation)
{
if (objCreation.ArgumentList == null)
{
return updatedNode;
}
var symbolInfo = semanticModel.GetSymbolInfo((BaseObjectCreationExpressionSyntax)originalNode, cancellationToken);
return objCreation.WithArgumentList(
await UpdateArgumentListAsync(
declarationSymbol,
signaturePermutation,
objCreation.ArgumentList,
isReducedExtensionMethod: false,
IsParamsArrayExpanded(semanticModel, objCreation, symbolInfo, cancellationToken),
document,
originalNode.SpanStart,
cancellationToken).ConfigureAwait(false));
}
if (updatedNode.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) ||
updatedNode.IsKind(SyntaxKind.BaseConstructorInitializer, out constructorInit))
{
var symbolInfo = semanticModel.GetSymbolInfo((ConstructorInitializerSyntax)originalNode, cancellationToken);
return constructorInit.WithArgumentList(
await UpdateArgumentListAsync(
declarationSymbol,
signaturePermutation,
constructorInit.ArgumentList,
isReducedExtensionMethod: false,
IsParamsArrayExpanded(semanticModel, constructorInit, symbolInfo, cancellationToken),
document,
originalNode.SpanStart,
cancellationToken).ConfigureAwait(false));
}
if (updatedNode.IsKind(SyntaxKind.ElementAccessExpression, out ElementAccessExpressionSyntax? elementAccess))
{
var symbolInfo = semanticModel.GetSymbolInfo((ElementAccessExpressionSyntax)originalNode, cancellationToken);
return elementAccess.WithArgumentList(
await UpdateArgumentListAsync(
declarationSymbol,
signaturePermutation,
elementAccess.ArgumentList,
isReducedExtensionMethod: false,
IsParamsArrayExpanded(semanticModel, elementAccess, symbolInfo, cancellationToken),
document,
originalNode.SpanStart,
cancellationToken).ConfigureAwait(false));
}
if (updatedNode.IsKind(SyntaxKind.Attribute, out AttributeSyntax? attribute))
{
var symbolInfo = semanticModel.GetSymbolInfo((AttributeSyntax)originalNode, cancellationToken);
if (attribute.ArgumentList == null)
{
return updatedNode;
}
return attribute.WithArgumentList(
await UpdateAttributeArgumentListAsync(
declarationSymbol,
signaturePermutation,
attribute.ArgumentList,
isReducedExtensionMethod: false,
IsParamsArrayExpanded(semanticModel, attribute, symbolInfo, cancellationToken),
document,
originalNode.SpanStart,
cancellationToken).ConfigureAwait(false));
}
Debug.Assert(false, "Unknown reference location");
return null;
}
private async Task<T> UpdateArgumentListAsync<T>(
ISymbol declarationSymbol,
SignatureChange signaturePermutation,
T argumentList,
bool isReducedExtensionMethod,
bool isParamsArrayExpanded,
Document document,
int position,
CancellationToken cancellationToken) where T : BaseArgumentListSyntax
{
// Reorders and removes arguments
// e.g. P(a, b, c) ==> P(c, a)
var newArguments = PermuteArgumentList(
declarationSymbol,
argumentList.Arguments,
signaturePermutation.WithoutAddedParameters(),
isReducedExtensionMethod);
// Adds new arguments into the updated list
// e.g. P(c, a) ==> P(x, c, a, y)
newArguments = await AddNewArgumentsToListAsync(
declarationSymbol,
newArguments,
argumentList.Arguments,
signaturePermutation,
isReducedExtensionMethod,
isParamsArrayExpanded,
generateAttributeArguments: false,
document,
position,
cancellationToken).ConfigureAwait(false);
return (T)argumentList
.WithArguments(newArguments)
.WithAdditionalAnnotations(changeSignatureFormattingAnnotation);
}
private async Task<AttributeArgumentListSyntax> UpdateAttributeArgumentListAsync(
ISymbol declarationSymbol,
SignatureChange signaturePermutation,
AttributeArgumentListSyntax argumentList,
bool isReducedExtensionMethod,
bool isParamsArrayExpanded,
Document document,
int position,
CancellationToken cancellationToken)
{
var newArguments = PermuteAttributeArgumentList(
declarationSymbol,
argumentList.Arguments,
signaturePermutation.WithoutAddedParameters());
newArguments = await AddNewArgumentsToListAsync(
declarationSymbol,
newArguments,
argumentList.Arguments,
signaturePermutation,
isReducedExtensionMethod,
isParamsArrayExpanded,
generateAttributeArguments: true,
document,
position,
cancellationToken).ConfigureAwait(false);
return argumentList
.WithArguments(newArguments)
.WithAdditionalAnnotations(changeSignatureFormattingAnnotation);
}
private static bool IsParamsArrayExpanded(SemanticModel semanticModel, SyntaxNode node, SymbolInfo symbolInfo, CancellationToken cancellationToken)
{
if (symbolInfo.Symbol == null)
{
return false;
}
int argumentCount;
bool lastArgumentIsNamed;
ExpressionSyntax lastArgumentExpression;
if (node is AttributeSyntax attribute)
{
if (attribute.ArgumentList == null)
{
return false;
}
argumentCount = attribute.ArgumentList.Arguments.Count;
lastArgumentIsNamed = attribute.ArgumentList.Arguments.LastOrDefault()?.NameColon != null ||
attribute.ArgumentList.Arguments.LastOrDefault()?.NameEquals != null;
var lastArgument = attribute.ArgumentList.Arguments.LastOrDefault();
if (lastArgument == null)
{
return false;
}
lastArgumentExpression = lastArgument.Expression;
}
else
{
BaseArgumentListSyntax? argumentList = node switch
{
InvocationExpressionSyntax invocation => invocation.ArgumentList,
BaseObjectCreationExpressionSyntax objectCreation => objectCreation.ArgumentList,
ConstructorInitializerSyntax constructorInitializer => constructorInitializer.ArgumentList,
ElementAccessExpressionSyntax elementAccess => elementAccess.ArgumentList,
_ => throw ExceptionUtilities.UnexpectedValue(node.Kind())
};
if (argumentList == null)
{
return false;
}
argumentCount = argumentList.Arguments.Count;
lastArgumentIsNamed = argumentList.Arguments.LastOrDefault()?.NameColon != null;
var lastArgument = argumentList.Arguments.LastOrDefault();
if (lastArgument == null)
{
return false;
}
lastArgumentExpression = lastArgument.Expression;
}
return IsParamsArrayExpandedHelper(symbolInfo.Symbol, argumentCount, lastArgumentIsNamed, semanticModel, lastArgumentExpression, cancellationToken);
}
private static ParameterSyntax CreateNewParameterSyntax(AddedParameter addedParameter)
=> CreateNewParameterSyntax(addedParameter, skipParameterType: false);
private static ParameterSyntax CreateNewParameterSyntax(AddedParameter addedParameter, bool skipParameterType)
{
var equalsValueClause = addedParameter.HasDefaultValue
? EqualsValueClause(ParseExpression(addedParameter.DefaultValue))
: null;
return Parameter(
attributeLists: default,
modifiers: default,
type: skipParameterType
? null
: addedParameter.Type.GenerateTypeSyntax(),
Identifier(addedParameter.Name),
@default: equalsValueClause);
}
private static CrefParameterSyntax CreateNewCrefParameterSyntax(AddedParameter addedParameter)
=> CrefParameter(type: addedParameter.Type.GenerateTypeSyntax())
.WithLeadingTrivia(ElasticSpace);
private SeparatedSyntaxList<T> UpdateDeclaration<T>(
SeparatedSyntaxList<T> list,
SignatureChange updatedSignature,
Func<AddedParameter, T> createNewParameterMethod) where T : SyntaxNode
{
var (parameters, separators) = base.UpdateDeclarationBase<T>(list, updatedSignature, createNewParameterMethod);
return SeparatedList(parameters, separators);
}
protected override T TransferLeadingWhitespaceTrivia<T>(T newArgument, SyntaxNode oldArgument)
{
var oldTrivia = oldArgument.GetLeadingTrivia();
var oldOnlyHasWhitespaceTrivia = oldTrivia.All(t => t.IsKind(SyntaxKind.WhitespaceTrivia));
var newTrivia = newArgument.GetLeadingTrivia();
var newOnlyHasWhitespaceTrivia = newTrivia.All(t => t.IsKind(SyntaxKind.WhitespaceTrivia));
if (oldOnlyHasWhitespaceTrivia && newOnlyHasWhitespaceTrivia)
{
newArgument = newArgument.WithLeadingTrivia(oldTrivia);
}
return newArgument;
}
private async Task<SeparatedSyntaxList<SyntaxNode>> AddNewArgumentsToListAsync(
ISymbol declarationSymbol,
SeparatedSyntaxList<SyntaxNode> newArguments,
SeparatedSyntaxList<SyntaxNode> originalArguments,
SignatureChange signaturePermutation,
bool isReducedExtensionMethod,
bool isParamsArrayExpanded,
bool generateAttributeArguments,
Document document,
int position,
CancellationToken cancellationToken)
{
var newArgumentList = await AddNewArgumentsToListAsync(
declarationSymbol, newArguments,
signaturePermutation, isReducedExtensionMethod,
isParamsArrayExpanded, generateAttributeArguments,
document, position, cancellationToken).ConfigureAwait(false);
return SeparatedList(
TransferLeadingWhitespaceTrivia(newArgumentList, originalArguments),
newArgumentList.GetSeparators());
}
private SeparatedSyntaxList<AttributeArgumentSyntax> PermuteAttributeArgumentList(
ISymbol declarationSymbol,
SeparatedSyntaxList<AttributeArgumentSyntax> arguments,
SignatureChange updatedSignature)
{
var newArguments = PermuteArguments(declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToImmutableArray(),
updatedSignature);
var numSeparatorsToSkip = arguments.Count - newArguments.Length;
// copy whitespace trivia from original position
var newArgumentsWithTrivia = TransferLeadingWhitespaceTrivia(
newArguments.Select(a => (AttributeArgumentSyntax)(UnifiedArgumentSyntax)a), arguments);
return SeparatedList(newArgumentsWithTrivia, GetSeparators(arguments, numSeparatorsToSkip));
}
private SeparatedSyntaxList<ArgumentSyntax> PermuteArgumentList(
ISymbol declarationSymbol,
SeparatedSyntaxList<ArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
var newArguments = PermuteArguments(
declarationSymbol,
arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToImmutableArray(),
updatedSignature,
isReducedExtensionMethod);
// copy whitespace trivia from original position
var newArgumentsWithTrivia = TransferLeadingWhitespaceTrivia(
newArguments.Select(a => (ArgumentSyntax)(UnifiedArgumentSyntax)a), arguments);
var numSeparatorsToSkip = arguments.Count - newArguments.Length;
return SeparatedList(newArgumentsWithTrivia, GetSeparators(arguments, numSeparatorsToSkip));
}
private ImmutableArray<T> TransferLeadingWhitespaceTrivia<T, U>(IEnumerable<T> newArguments, SeparatedSyntaxList<U> oldArguments)
where T : SyntaxNode
where U : SyntaxNode
{
var result = ImmutableArray.CreateBuilder<T>();
var index = 0;
foreach (var newArgument in newArguments)
{
result.Add(index < oldArguments.Count
? TransferLeadingWhitespaceTrivia(newArgument, oldArguments[index])
: newArgument);
index++;
}
return result.ToImmutable();
}
private ImmutableArray<SyntaxTrivia> UpdateParamTagsInLeadingTrivia(Document document, CSharpSyntaxNode node, ISymbol declarationSymbol, SignatureChange updatedSignature)
{
if (!node.HasLeadingTrivia)
{
return ImmutableArray<SyntaxTrivia>.Empty;
}
var paramNodes = node
.DescendantNodes(descendIntoTrivia: true)
.OfType<XmlElementSyntax>()
.Where(e => e.StartTag.Name.ToString() == DocumentationCommentXmlNames.ParameterElementName);
var permutedParamNodes = VerifyAndPermuteParamNodes(paramNodes, declarationSymbol, updatedSignature);
if (permutedParamNodes.IsEmpty)
{
return ImmutableArray<SyntaxTrivia>.Empty;
}
return GetPermutedDocCommentTrivia(document, node, permutedParamNodes);
}
private ImmutableArray<SyntaxNode> VerifyAndPermuteParamNodes(IEnumerable<XmlElementSyntax> paramNodes, ISymbol declarationSymbol, SignatureChange updatedSignature)
{
// Only reorder if count and order match originally.
var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var declaredParameters = GetParameters(declarationSymbol);
if (paramNodes.Count() != declaredParameters.Length)
{
return ImmutableArray<SyntaxNode>.Empty;
}
// No parameters originally, so no param nodes to permute.
if (declaredParameters.Length == 0)
{
return ImmutableArray<SyntaxNode>.Empty;
}
var dictionary = new Dictionary<string, XmlElementSyntax>();
var i = 0;
foreach (var paramNode in paramNodes)
{
var nameAttribute = paramNode.StartTag.Attributes.FirstOrDefault(a => a.Name.ToString().Equals("name", StringComparison.OrdinalIgnoreCase));
if (nameAttribute == null)
{
return ImmutableArray<SyntaxNode>.Empty;
}
var identifier = nameAttribute.DescendantNodes(descendIntoTrivia: true).OfType<IdentifierNameSyntax>().FirstOrDefault();
if (identifier == null || identifier.ToString() != declaredParameters.ElementAt(i).Name)
{
return ImmutableArray<SyntaxNode>.Empty;
}
dictionary.Add(originalParameters[i].Name.ToString(), paramNode);
i++;
}
// Everything lines up, so permute them.
var permutedParams = ArrayBuilder<SyntaxNode>.GetInstance();
foreach (var parameter in reorderedParameters)
{
if (dictionary.TryGetValue(parameter.Name, out var permutedParam))
{
permutedParams.Add(permutedParam);
}
else
{
permutedParams.Add(XmlElement(
XmlElementStartTag(
XmlName("param"),
List<XmlAttributeSyntax>(new[] { XmlNameAttribute(parameter.Name) })),
XmlElementEndTag(XmlName("param"))));
}
}
return permutedParams.ToImmutableAndFree();
}
public override async Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsFromDelegateInvokeAsync(
IMethodSymbol symbol,
Document document,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<SyntaxNode>.GetInstance(out var convertedMethodNodes);
foreach (var node in root.DescendantNodes())
{
if (!node.IsKind(SyntaxKind.IdentifierName) ||
!semanticModel.GetMemberGroup(node, cancellationToken).Any())
{
continue;
}
var convertedType = (ISymbol?)semanticModel.GetTypeInfo(node, cancellationToken).ConvertedType;
convertedType = convertedType?.OriginalDefinition;
if (convertedType != null)
{
convertedType = await SymbolFinder.FindSourceDefinitionAsync(convertedType, document.Project.Solution, cancellationToken).ConfigureAwait(false)
?? convertedType;
}
if (Equals(convertedType, symbol.ContainingType))
convertedMethodNodes.Add(node);
}
var convertedMethodGroups = convertedMethodNodes
.Select(n => semanticModel.GetSymbolInfo(n, cancellationToken).Symbol)
.WhereNotNull()
.ToImmutableArray();
return convertedMethodGroups;
}
protected override IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document)
=> Formatter.GetDefaultFormattingRules(document).Concat(new ChangeSignatureFormattingRule());
protected override SyntaxNode AddNameToArgument(SyntaxNode newArgument, string name)
{
return newArgument switch
{
ArgumentSyntax a => a.WithNameColon(NameColon(name)),
AttributeArgumentSyntax a => a.WithNameColon(NameColon(name)),
_ => throw ExceptionUtilities.UnexpectedValue(newArgument.Kind())
};
}
protected override SyntaxNode CreateExplicitParamsArrayFromIndividualArguments(SeparatedSyntaxList<SyntaxNode> newArguments, int indexInExistingList, IParameterSymbol parameterSymbol)
{
RoslynDebug.Assert(parameterSymbol.IsParams);
// These arguments are part of a params array, and should not have any modifiers, making it okay to just use their expressions.
var listOfArguments = SeparatedList(newArguments.Skip(indexInExistingList).Select(a => ((ArgumentSyntax)a).Expression), newArguments.GetSeparators().Skip(indexInExistingList));
var initializerExpression = InitializerExpression(SyntaxKind.ArrayInitializerExpression, listOfArguments);
var objectCreation = ArrayCreationExpression((ArrayTypeSyntax)parameterSymbol.Type.GenerateTypeSyntax(), initializerExpression);
return Argument(objectCreation);
}
protected override bool SupportsOptionalAndParamsArrayParametersSimultaneously()
{
return true;
}
protected override SyntaxToken CommaTokenWithElasticSpace()
=> Token(SyntaxKind.CommaToken).WithTrailingTrivia(ElasticSpace);
protected override bool TryGetRecordPrimaryConstructor(INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol? primaryConstructor)
=> typeSymbol.TryGetRecordPrimaryConstructor(out primaryConstructor);
protected override ImmutableArray<IParameterSymbol> GetParameters(ISymbol declarationSymbol)
{
var declaredParameters = declarationSymbol.GetParameters();
if (declarationSymbol is INamedTypeSymbol namedTypeSymbol &&
namedTypeSymbol.TryGetRecordPrimaryConstructor(out var primaryConstructor))
{
declaredParameters = primaryConstructor.Parameters;
}
return declaredParameters;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.es.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="es" original="../CSharpAnalyzersResources.resx">
<body>
<trans-unit id="Add_braces">
<source>Add braces</source>
<target state="translated">Agregar llaves</target>
<note />
</trans-unit>
<trans-unit id="Add_braces_to_0_statement">
<source>Add braces to '{0}' statement.</source>
<target state="translated">Agregar llaves a la instrucción '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon">
<source>Blank line not allowed after constructor initializer colon</source>
<target state="translated">No se permite una línea en blanco después del signo de dos puntos del inicializador del constructor</target>
<note />
</trans-unit>
<trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them">
<source>Consecutive braces must not have blank line between them</source>
<target state="translated">Las llaves consecutivas no deben tener una línea en blanco entre ellas</target>
<note />
</trans-unit>
<trans-unit id="Convert_switch_statement_to_expression">
<source>Convert switch statement to expression</source>
<target state="translated">Convertir una instrucción switch en expresión</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_block_scoped_namespace">
<source>Convert to block scoped namespace</source>
<target state="new">Convert to block scoped namespace</target>
<note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Convert_to_file_scoped_namespace">
<source>Convert to file-scoped namespace</source>
<target state="new">Convert to file-scoped namespace</target>
<note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Deconstruct_variable_declaration">
<source>Deconstruct variable declaration</source>
<target state="translated">Desconstruir la declaración de variable</target>
<note />
</trans-unit>
<trans-unit id="Delegate_invocation_can_be_simplified">
<source>Delegate invocation can be simplified.</source>
<target state="translated">La invocación del delegado se puede simplificar.</target>
<note />
</trans-unit>
<trans-unit id="Discard_can_be_removed">
<source>Discard can be removed</source>
<target state="translated">El descarte se puede quitar.</target>
<note />
</trans-unit>
<trans-unit id="Embedded_statements_must_be_on_their_own_line">
<source>Embedded statements must be on their own line</source>
<target state="translated">Las instrucciones incrustadas deben estar en su propia línea</target>
<note />
</trans-unit>
<trans-unit id="Indexing_can_be_simplified">
<source>Indexing can be simplified</source>
<target state="translated">La indexación de direcciones se puede simplificar</target>
<note />
</trans-unit>
<trans-unit id="Inline_variable_declaration">
<source>Inline variable declaration</source>
<target state="translated">Declaración de variables alineada</target>
<note />
</trans-unit>
<trans-unit id="Misplaced_using_directive">
<source>Misplaced using directive</source>
<target state="translated">Directiva using mal colocada</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Move_misplaced_using_directives">
<source>Move misplaced using directives</source>
<target state="translated">Mover directivas using mal colocadas</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Make_readonly_fields_writable">
<source>Make readonly fields writable</source>
<target state="translated">Convertir en editables los campos readonly</target>
<note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Local_function_can_be_made_static">
<source>Local function can be made static</source>
<target state="translated">La función local se puede convertir en estática</target>
<note />
</trans-unit>
<trans-unit id="Make_local_function_static">
<source>Make local function 'static'</source>
<target state="translated">Convertir la función local "static"</target>
<note />
</trans-unit>
<trans-unit id="Negate_expression_changes_semantics">
<source>Negate expression (changes semantics)</source>
<target state="translated">Negar expresión (cambia la semántica)</target>
<note />
</trans-unit>
<trans-unit id="Null_check_can_be_clarified">
<source>Null check can be clarified</source>
<target state="new">Null check can be clarified</target>
<note />
</trans-unit>
<trans-unit id="Prefer_null_check_over_type_check">
<source>Prefer 'null' check over type check</source>
<target state="new">Prefer 'null' check over type check</target>
<note />
</trans-unit>
<trans-unit id="Remove_operator_preserves_semantics">
<source>Remove operator (preserves semantics)</source>
<target state="translated">Quitar operador (conserva la semántica)</target>
<note />
</trans-unit>
<trans-unit id="Remove_suppression_operators">
<source>Remove suppression operators</source>
<target state="translated">Quitar operadores de supresión</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnecessary_suppression_operator">
<source>Remove unnecessary suppression operator</source>
<target state="translated">Quitar operador de supresión innecesario</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnessary_discard">
<source>Remove unnecessary discard</source>
<target state="translated">Quitar un descarte innecesario</target>
<note />
</trans-unit>
<trans-unit id="Simplify_default_expression">
<source>Simplify 'default' expression</source>
<target state="translated">Simplificar la expresión "predeterminada"</target>
<note />
</trans-unit>
<trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable">
<source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source>
<target state="translated">Struct contiene una asignación a "this" fuera del constructor. Convierta en editables los campos de solo lectura.</target>
<note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note>
</trans-unit>
<trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted">
<source>Suppression operator has no effect and can be misinterpreted</source>
<target state="translated">El operador de supresión no tiene efecto y se puede interpretar incorrectamente</target>
<note />
</trans-unit>
<trans-unit id="Unreachable_code_detected">
<source>Unreachable code detected</source>
<target state="translated">Se detectó código inaccesible</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_accessors">
<source>Use block body for accessors</source>
<target state="translated">Usar cuerpo del bloque para los descriptores de acceso</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_constructors">
<source>Use block body for constructors</source>
<target state="translated">Usar cuerpo del bloque para los constructores</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_indexers">
<source>Use block body for indexers</source>
<target state="translated">Usar cuerpo del bloque para los indizadores</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_local_functions">
<source>Use block body for local functions</source>
<target state="translated">Usar cuerpo del bloque para las funciones locales</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_methods">
<source>Use block body for methods</source>
<target state="translated">Usar cuerpo del bloque para los métodos</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_operators">
<source>Use block body for operators</source>
<target state="translated">Usar cuerpo del bloque para los operadores</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_properties">
<source>Use block body for properties</source>
<target state="translated">Usar cuerpo del bloque para las propiedades</target>
<note />
</trans-unit>
<trans-unit id="Use_explicit_type">
<source>Use explicit type</source>
<target state="translated">Usar un tipo explícito</target>
<note />
</trans-unit>
<trans-unit id="Use_explicit_type_instead_of_var">
<source>Use explicit type instead of 'var'</source>
<target state="translated">Usar un tipo explícito en lugar de 'var'</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_accessors">
<source>Use expression body for accessors</source>
<target state="translated">Usar cuerpo de expresiones para los descriptores de acceso</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_constructors">
<source>Use expression body for constructors</source>
<target state="translated">Usar cuerpo de expresiones para los constructores</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_indexers">
<source>Use expression body for indexers</source>
<target state="translated">Usar cuerpo de expresiones para los indizadores</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_local_functions">
<source>Use expression body for local functions</source>
<target state="translated">Usar el cuerpo de la expresión para las funciones locales</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_methods">
<source>Use expression body for methods</source>
<target state="translated">Usar cuerpo de expresiones para los métodos</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_operators">
<source>Use expression body for operators</source>
<target state="translated">Usar cuerpo de expresiones para los operadores</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_properties">
<source>Use expression body for properties</source>
<target state="translated">Usar cuerpo de expresiones para las propiedades</target>
<note />
</trans-unit>
<trans-unit id="Use_implicit_type">
<source>Use implicit type</source>
<target state="translated">Usar un tipo implícito</target>
<note />
</trans-unit>
<trans-unit id="Use_index_operator">
<source>Use index operator</source>
<target state="translated">Usar operador de índice</target>
<note />
</trans-unit>
<trans-unit id="Use_is_null_check">
<source>Use 'is null' check</source>
<target state="translated">Usar comprobación "is null"</target>
<note />
</trans-unit>
<trans-unit id="Use_local_function">
<source>Use local function</source>
<target state="translated">Usar función local</target>
<note />
</trans-unit>
<trans-unit id="Use_new">
<source>Use 'new(...)'</source>
<target state="translated">Usar "new(...)"</target>
<note>{Locked="new(...)"} This is a C# construct and should not be localized.</note>
</trans-unit>
<trans-unit id="Use_pattern_matching">
<source>Use pattern matching</source>
<target state="translated">Usar coincidencia de patrones</target>
<note />
</trans-unit>
<trans-unit id="Use_pattern_matching_may_change_code_meaning">
<source>Use pattern matching (may change code meaning)</source>
<target state="new">Use pattern matching (may change code meaning)</target>
<note />
</trans-unit>
<trans-unit id="Use_range_operator">
<source>Use range operator</source>
<target state="translated">Usar el operador de intervalo</target>
<note />
</trans-unit>
<trans-unit id="Use_simple_using_statement">
<source>Use simple 'using' statement</source>
<target state="translated">Use la instrucción "using" simple</target>
<note />
</trans-unit>
<trans-unit id="Use_switch_expression">
<source>Use 'switch' expression</source>
<target state="translated">Usar la expresión "switch"</target>
<note />
</trans-unit>
<trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration">
<source>Using directives must be placed inside of a namespace declaration</source>
<target state="translated">Las directivas using deben colocarse dentro de una declaración de namespace</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration">
<source>Using directives must be placed outside of a namespace declaration</source>
<target state="translated">Las directivas using deben colocarse fuera de una declaración de namespace</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Variable_declaration_can_be_deconstructed">
<source>Variable declaration can be deconstructed</source>
<target state="translated">La declaración de variables se puede desconstruir.</target>
<note />
</trans-unit>
<trans-unit id="Variable_declaration_can_be_inlined">
<source>Variable declaration can be inlined</source>
<target state="translated">La declaración de variables se puede insertar</target>
<note />
</trans-unit>
<trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning">
<source>Warning: Moving using directives may change code meaning.</source>
<target state="translated">Advertencia: El movimiento de directivas using puede cambiar el significado del código.</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="_0_can_be_simplified">
<source>{0} can be simplified</source>
<target state="translated">{0} se puede simplificar.</target>
<note />
</trans-unit>
<trans-unit id="default_expression_can_be_simplified">
<source>'default' expression can be simplified</source>
<target state="translated">'La expresión "predeterminada" se puede simplificar</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">La instrucción "if" se puede simplificar</target>
<note />
</trans-unit>
<trans-unit id="new_expression_can_be_simplified">
<source>'new' expression can be simplified</source>
<target state="translated">La expresión "new" se puede simplificar.</target>
<note />
</trans-unit>
<trans-unit id="typeof_can_be_converted_ to_nameof">
<source>'typeof' can be converted to 'nameof'</source>
<target state="translated">"typeof" puede convertirse en "nameof"</target>
<note />
</trans-unit>
<trans-unit id="use_var_instead_of_explicit_type">
<source>use 'var' instead of explicit type</source>
<target state="translated">Usar 'var' en lugar de un tipo explícito</target>
<note />
</trans-unit>
<trans-unit id="Using_directive_is_unnecessary">
<source>Using directive is unnecessary.</source>
<target state="translated">El uso de la directiva no es necesario.</target>
<note />
</trans-unit>
<trans-unit id="using_statement_can_be_simplified">
<source>'using' statement can be simplified</source>
<target state="translated">La instrucción "using" se puede simplificar</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="es" original="../CSharpAnalyzersResources.resx">
<body>
<trans-unit id="Add_braces">
<source>Add braces</source>
<target state="translated">Agregar llaves</target>
<note />
</trans-unit>
<trans-unit id="Add_braces_to_0_statement">
<source>Add braces to '{0}' statement.</source>
<target state="translated">Agregar llaves a la instrucción '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon">
<source>Blank line not allowed after constructor initializer colon</source>
<target state="translated">No se permite una línea en blanco después del signo de dos puntos del inicializador del constructor</target>
<note />
</trans-unit>
<trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them">
<source>Consecutive braces must not have blank line between them</source>
<target state="translated">Las llaves consecutivas no deben tener una línea en blanco entre ellas</target>
<note />
</trans-unit>
<trans-unit id="Convert_switch_statement_to_expression">
<source>Convert switch statement to expression</source>
<target state="translated">Convertir una instrucción switch en expresión</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_block_scoped_namespace">
<source>Convert to block scoped namespace</source>
<target state="new">Convert to block scoped namespace</target>
<note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Convert_to_file_scoped_namespace">
<source>Convert to file-scoped namespace</source>
<target state="new">Convert to file-scoped namespace</target>
<note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Deconstruct_variable_declaration">
<source>Deconstruct variable declaration</source>
<target state="translated">Desconstruir la declaración de variable</target>
<note />
</trans-unit>
<trans-unit id="Delegate_invocation_can_be_simplified">
<source>Delegate invocation can be simplified.</source>
<target state="translated">La invocación del delegado se puede simplificar.</target>
<note />
</trans-unit>
<trans-unit id="Discard_can_be_removed">
<source>Discard can be removed</source>
<target state="translated">El descarte se puede quitar.</target>
<note />
</trans-unit>
<trans-unit id="Embedded_statements_must_be_on_their_own_line">
<source>Embedded statements must be on their own line</source>
<target state="translated">Las instrucciones incrustadas deben estar en su propia línea</target>
<note />
</trans-unit>
<trans-unit id="Indexing_can_be_simplified">
<source>Indexing can be simplified</source>
<target state="translated">La indexación de direcciones se puede simplificar</target>
<note />
</trans-unit>
<trans-unit id="Inline_variable_declaration">
<source>Inline variable declaration</source>
<target state="translated">Declaración de variables alineada</target>
<note />
</trans-unit>
<trans-unit id="Misplaced_using_directive">
<source>Misplaced using directive</source>
<target state="translated">Directiva using mal colocada</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Move_misplaced_using_directives">
<source>Move misplaced using directives</source>
<target state="translated">Mover directivas using mal colocadas</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Make_readonly_fields_writable">
<source>Make readonly fields writable</source>
<target state="translated">Convertir en editables los campos readonly</target>
<note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Local_function_can_be_made_static">
<source>Local function can be made static</source>
<target state="translated">La función local se puede convertir en estática</target>
<note />
</trans-unit>
<trans-unit id="Make_local_function_static">
<source>Make local function 'static'</source>
<target state="translated">Convertir la función local "static"</target>
<note />
</trans-unit>
<trans-unit id="Negate_expression_changes_semantics">
<source>Negate expression (changes semantics)</source>
<target state="translated">Negar expresión (cambia la semántica)</target>
<note />
</trans-unit>
<trans-unit id="Null_check_can_be_clarified">
<source>Null check can be clarified</source>
<target state="new">Null check can be clarified</target>
<note />
</trans-unit>
<trans-unit id="Prefer_null_check_over_type_check">
<source>Prefer 'null' check over type check</source>
<target state="new">Prefer 'null' check over type check</target>
<note />
</trans-unit>
<trans-unit id="Remove_operator_preserves_semantics">
<source>Remove operator (preserves semantics)</source>
<target state="translated">Quitar operador (conserva la semántica)</target>
<note />
</trans-unit>
<trans-unit id="Remove_suppression_operators">
<source>Remove suppression operators</source>
<target state="translated">Quitar operadores de supresión</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnecessary_suppression_operator">
<source>Remove unnecessary suppression operator</source>
<target state="translated">Quitar operador de supresión innecesario</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnessary_discard">
<source>Remove unnecessary discard</source>
<target state="translated">Quitar un descarte innecesario</target>
<note />
</trans-unit>
<trans-unit id="Simplify_default_expression">
<source>Simplify 'default' expression</source>
<target state="translated">Simplificar la expresión "predeterminada"</target>
<note />
</trans-unit>
<trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable">
<source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source>
<target state="translated">Struct contiene una asignación a "this" fuera del constructor. Convierta en editables los campos de solo lectura.</target>
<note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note>
</trans-unit>
<trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted">
<source>Suppression operator has no effect and can be misinterpreted</source>
<target state="translated">El operador de supresión no tiene efecto y se puede interpretar incorrectamente</target>
<note />
</trans-unit>
<trans-unit id="Unreachable_code_detected">
<source>Unreachable code detected</source>
<target state="translated">Se detectó código inaccesible</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_accessors">
<source>Use block body for accessors</source>
<target state="translated">Usar cuerpo del bloque para los descriptores de acceso</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_constructors">
<source>Use block body for constructors</source>
<target state="translated">Usar cuerpo del bloque para los constructores</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_indexers">
<source>Use block body for indexers</source>
<target state="translated">Usar cuerpo del bloque para los indizadores</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_local_functions">
<source>Use block body for local functions</source>
<target state="translated">Usar cuerpo del bloque para las funciones locales</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_methods">
<source>Use block body for methods</source>
<target state="translated">Usar cuerpo del bloque para los métodos</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_operators">
<source>Use block body for operators</source>
<target state="translated">Usar cuerpo del bloque para los operadores</target>
<note />
</trans-unit>
<trans-unit id="Use_block_body_for_properties">
<source>Use block body for properties</source>
<target state="translated">Usar cuerpo del bloque para las propiedades</target>
<note />
</trans-unit>
<trans-unit id="Use_explicit_type">
<source>Use explicit type</source>
<target state="translated">Usar un tipo explícito</target>
<note />
</trans-unit>
<trans-unit id="Use_explicit_type_instead_of_var">
<source>Use explicit type instead of 'var'</source>
<target state="translated">Usar un tipo explícito en lugar de 'var'</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_accessors">
<source>Use expression body for accessors</source>
<target state="translated">Usar cuerpo de expresiones para los descriptores de acceso</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_constructors">
<source>Use expression body for constructors</source>
<target state="translated">Usar cuerpo de expresiones para los constructores</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_indexers">
<source>Use expression body for indexers</source>
<target state="translated">Usar cuerpo de expresiones para los indizadores</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_local_functions">
<source>Use expression body for local functions</source>
<target state="translated">Usar el cuerpo de la expresión para las funciones locales</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_methods">
<source>Use expression body for methods</source>
<target state="translated">Usar cuerpo de expresiones para los métodos</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_operators">
<source>Use expression body for operators</source>
<target state="translated">Usar cuerpo de expresiones para los operadores</target>
<note />
</trans-unit>
<trans-unit id="Use_expression_body_for_properties">
<source>Use expression body for properties</source>
<target state="translated">Usar cuerpo de expresiones para las propiedades</target>
<note />
</trans-unit>
<trans-unit id="Use_implicit_type">
<source>Use implicit type</source>
<target state="translated">Usar un tipo implícito</target>
<note />
</trans-unit>
<trans-unit id="Use_index_operator">
<source>Use index operator</source>
<target state="translated">Usar operador de índice</target>
<note />
</trans-unit>
<trans-unit id="Use_is_null_check">
<source>Use 'is null' check</source>
<target state="translated">Usar comprobación "is null"</target>
<note />
</trans-unit>
<trans-unit id="Use_local_function">
<source>Use local function</source>
<target state="translated">Usar función local</target>
<note />
</trans-unit>
<trans-unit id="Use_new">
<source>Use 'new(...)'</source>
<target state="translated">Usar "new(...)"</target>
<note>{Locked="new(...)"} This is a C# construct and should not be localized.</note>
</trans-unit>
<trans-unit id="Use_pattern_matching">
<source>Use pattern matching</source>
<target state="translated">Usar coincidencia de patrones</target>
<note />
</trans-unit>
<trans-unit id="Use_pattern_matching_may_change_code_meaning">
<source>Use pattern matching (may change code meaning)</source>
<target state="new">Use pattern matching (may change code meaning)</target>
<note />
</trans-unit>
<trans-unit id="Use_range_operator">
<source>Use range operator</source>
<target state="translated">Usar el operador de intervalo</target>
<note />
</trans-unit>
<trans-unit id="Use_simple_using_statement">
<source>Use simple 'using' statement</source>
<target state="translated">Use la instrucción "using" simple</target>
<note />
</trans-unit>
<trans-unit id="Use_switch_expression">
<source>Use 'switch' expression</source>
<target state="translated">Usar la expresión "switch"</target>
<note />
</trans-unit>
<trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration">
<source>Using directives must be placed inside of a namespace declaration</source>
<target state="translated">Las directivas using deben colocarse dentro de una declaración de namespace</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration">
<source>Using directives must be placed outside of a namespace declaration</source>
<target state="translated">Las directivas using deben colocarse fuera de una declaración de namespace</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Variable_declaration_can_be_deconstructed">
<source>Variable declaration can be deconstructed</source>
<target state="translated">La declaración de variables se puede desconstruir.</target>
<note />
</trans-unit>
<trans-unit id="Variable_declaration_can_be_inlined">
<source>Variable declaration can be inlined</source>
<target state="translated">La declaración de variables se puede insertar</target>
<note />
</trans-unit>
<trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning">
<source>Warning: Moving using directives may change code meaning.</source>
<target state="translated">Advertencia: El movimiento de directivas using puede cambiar el significado del código.</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="_0_can_be_simplified">
<source>{0} can be simplified</source>
<target state="translated">{0} se puede simplificar.</target>
<note />
</trans-unit>
<trans-unit id="default_expression_can_be_simplified">
<source>'default' expression can be simplified</source>
<target state="translated">'La expresión "predeterminada" se puede simplificar</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">La instrucción "if" se puede simplificar</target>
<note />
</trans-unit>
<trans-unit id="new_expression_can_be_simplified">
<source>'new' expression can be simplified</source>
<target state="translated">La expresión "new" se puede simplificar.</target>
<note />
</trans-unit>
<trans-unit id="typeof_can_be_converted_ to_nameof">
<source>'typeof' can be converted to 'nameof'</source>
<target state="translated">"typeof" puede convertirse en "nameof"</target>
<note />
</trans-unit>
<trans-unit id="use_var_instead_of_explicit_type">
<source>use 'var' instead of explicit type</source>
<target state="translated">Usar 'var' en lugar de un tipo explícito</target>
<note />
</trans-unit>
<trans-unit id="Using_directive_is_unnecessary">
<source>Using directive is unnecessary.</source>
<target state="translated">El uso de la directiva no es necesario.</target>
<note />
</trans-unit>
<trans-unit id="using_statement_can_be_simplified">
<source>'using' statement can be simplified</source>
<target state="translated">La instrucción "using" se puede simplificar</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/CSharpTest2/Recommendations/StackAllocKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class StackAllocKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
// e.g. this is a valid statement
// stackalloc[] { 1, 2, 3 }.IndexOf(1);
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptySpaceAfterAssignment()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUnsafeEmptySpace()
{
await VerifyKeywordAsync(
@"unsafe class C {
void Goo() {
var v = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUnsafeEmptySpace_AfterNonPointer()
{
// There can be an implicit conversion to int
await VerifyKeywordAsync(
@"unsafe class C {
void Goo() {
int v = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUnsafeEmptySpace_AfterPointer()
{
await VerifyKeywordAsync(
@"unsafe class C {
void Goo() {
int* v = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInField()
{
// While assigning stackalloc'd value to a field is invalid,
// using one in the initializer is OK. e.g.
// int _f = stackalloc[] { 1, 2, 3 }.IndexOf(1);
await VerifyKeywordAsync(
@"class C {
int v = $$");
}
[WorkItem(544504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideForStatementVarDecl1()
{
await VerifyKeywordAsync(
@"class C
{
unsafe static void Main(string[] args)
{
for (var i = $$");
}
[WorkItem(544504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideForStatementVarDecl2()
{
await VerifyKeywordAsync(
@"class C
{
unsafe static void Main(string[] args)
{
for (int* i = $$");
}
[WorkItem(544504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideForStatementVarDecl3()
{
await VerifyKeywordAsync(
@"class C
{
unsafe static void Main(string[] args)
{
for (string i = $$");
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSOfAssignment_Span()
{
await VerifyKeywordAsync(AddInsideMethod(@"
Span<int> s = $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSOfAssignment_Pointer()
{
await VerifyKeywordAsync(AddInsideMethod(
@"int* v = $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSOfAssignment_ReAssignment()
{
await VerifyKeywordAsync(AddInsideMethod(
@"v = $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithCast()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = (Span<char>)$$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = (Span<char>)$$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_True()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value ? $$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value ? $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_True_WithCast()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value ? (Span<int>)$$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value ? (Span<int>)$$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_False()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value ? stackalloc int[10] : $$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value ? stackalloc int[10] : $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_False_WithCast()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value ? stackalloc int[10] : (Span<int>)$$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value ? stackalloc int[10] : (Span<int>)$$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_NestedConditional_True()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value1 ? value2 ? $$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value1 ? value2 ? $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_NestedConditional_WithCast_True()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value1 ? value2 ? (Span<int>)$$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value1 ? value2 ? (Span<int>)$$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_NestedConditional_False()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value1 ? value2 ? stackalloc int [10] : $$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value1 ? value2 ? stackalloc int [10] : $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_NestedConditional_WithCast_False()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value1 ? value2 ? stackalloc int [10] : (Span<int>)$$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value1 ? value2 ? stackalloc int [10] : (Span<int>)$$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInLHSOfAssignment()
{
await VerifyAbsenceAsync(AddInsideMethod(@"
var x $$ ="));
await VerifyAbsenceAsync(AddInsideMethod(@"
x $$ ="));
}
[WorkItem(41736, "https://github.com/dotnet/roslyn/issues/41736")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInArgument()
{
await VerifyKeywordAsync(@"
class Program
{
static void Method(System.Span<byte> span)
{
Method($$);
}
}");
await VerifyKeywordAsync(@"
class Program
{
static void Method(int x, System.Span<byte> span)
{
Method(1, $$);
}
}");
}
[WorkItem(41736, "https://github.com/dotnet/roslyn/issues/41736")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInConstFieldInitializer()
{
await VerifyAbsenceAsync(@"
class Program
{
private const int _f = $$
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class StackAllocKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
// e.g. this is a valid statement
// stackalloc[] { 1, 2, 3 }.IndexOf(1);
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptySpaceAfterAssignment()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUnsafeEmptySpace()
{
await VerifyKeywordAsync(
@"unsafe class C {
void Goo() {
var v = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUnsafeEmptySpace_AfterNonPointer()
{
// There can be an implicit conversion to int
await VerifyKeywordAsync(
@"unsafe class C {
void Goo() {
int v = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUnsafeEmptySpace_AfterPointer()
{
await VerifyKeywordAsync(
@"unsafe class C {
void Goo() {
int* v = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInField()
{
// While assigning stackalloc'd value to a field is invalid,
// using one in the initializer is OK. e.g.
// int _f = stackalloc[] { 1, 2, 3 }.IndexOf(1);
await VerifyKeywordAsync(
@"class C {
int v = $$");
}
[WorkItem(544504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideForStatementVarDecl1()
{
await VerifyKeywordAsync(
@"class C
{
unsafe static void Main(string[] args)
{
for (var i = $$");
}
[WorkItem(544504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideForStatementVarDecl2()
{
await VerifyKeywordAsync(
@"class C
{
unsafe static void Main(string[] args)
{
for (int* i = $$");
}
[WorkItem(544504, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544504")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideForStatementVarDecl3()
{
await VerifyKeywordAsync(
@"class C
{
unsafe static void Main(string[] args)
{
for (string i = $$");
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSOfAssignment_Span()
{
await VerifyKeywordAsync(AddInsideMethod(@"
Span<int> s = $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSOfAssignment_Pointer()
{
await VerifyKeywordAsync(AddInsideMethod(
@"int* v = $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSOfAssignment_ReAssignment()
{
await VerifyKeywordAsync(AddInsideMethod(
@"v = $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithCast()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = (Span<char>)$$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = (Span<char>)$$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_True()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value ? $$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value ? $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_True_WithCast()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value ? (Span<int>)$$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value ? (Span<int>)$$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_False()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value ? stackalloc int[10] : $$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value ? stackalloc int[10] : $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_False_WithCast()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value ? stackalloc int[10] : (Span<int>)$$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value ? stackalloc int[10] : (Span<int>)$$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_NestedConditional_True()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value1 ? value2 ? $$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value1 ? value2 ? $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_NestedConditional_WithCast_True()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value1 ? value2 ? (Span<int>)$$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value1 ? value2 ? (Span<int>)$$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_NestedConditional_False()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value1 ? value2 ? stackalloc int [10] : $$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value1 ? value2 ? stackalloc int [10] : $$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestOnRHSWithConditionalExpression_NestedConditional_WithCast_False()
{
await VerifyKeywordAsync(AddInsideMethod(@"
var s = value1 ? value2 ? stackalloc int [10] : (Span<int>)$$"));
await VerifyKeywordAsync(AddInsideMethod(@"
s = value1 ? value2 ? stackalloc int [10] : (Span<int>)$$"));
}
[WorkItem(23584, "https://github.com/dotnet/roslyn/issues/23584")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInLHSOfAssignment()
{
await VerifyAbsenceAsync(AddInsideMethod(@"
var x $$ ="));
await VerifyAbsenceAsync(AddInsideMethod(@"
x $$ ="));
}
[WorkItem(41736, "https://github.com/dotnet/roslyn/issues/41736")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInArgument()
{
await VerifyKeywordAsync(@"
class Program
{
static void Method(System.Span<byte> span)
{
Method($$);
}
}");
await VerifyKeywordAsync(@"
class Program
{
static void Method(int x, System.Span<byte> span)
{
Method(1, $$);
}
}");
}
[WorkItem(41736, "https://github.com/dotnet/roslyn/issues/41736")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInConstFieldInitializer()
{
await VerifyAbsenceAsync(@"
class Program
{
private const int _f = $$
}");
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/Core/Portable/Workspace/Host/Mef/ExportWorkspaceServiceAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis.Host.Mef
{
/// <summary>
/// Use this attribute to declare a <see cref="IWorkspaceService"/> implementation for inclusion in a MEF-based workspace.
/// </summary>
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public class ExportWorkspaceServiceAttribute : ExportAttribute
{
/// <summary>
/// The assembly qualified name of the service's type.
/// </summary>
public string ServiceType { get; }
/// <summary>
/// The layer that the service is specified for; ServiceLayer.Default, etc.
/// </summary>
public string Layer { get; }
/// <summary>
/// Declares a <see cref="IWorkspaceService"/> implementation for inclusion in a MEF-based workspace.
/// </summary>
/// <param name="serviceType">The type that will be used to retrieve the service from a <see cref="HostWorkspaceServices"/>.</param>
/// <param name="layer">The layer that the service is specified for; <see cref="ServiceLayer.Default" />, etc.</param>
public ExportWorkspaceServiceAttribute(Type serviceType, string layer = ServiceLayer.Default)
: base(typeof(IWorkspaceService))
{
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}
this.ServiceType = serviceType.AssemblyQualifiedName;
this.Layer = layer ?? throw new ArgumentNullException(nameof(layer));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis.Host.Mef
{
/// <summary>
/// Use this attribute to declare a <see cref="IWorkspaceService"/> implementation for inclusion in a MEF-based workspace.
/// </summary>
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
public class ExportWorkspaceServiceAttribute : ExportAttribute
{
/// <summary>
/// The assembly qualified name of the service's type.
/// </summary>
public string ServiceType { get; }
/// <summary>
/// The layer that the service is specified for; ServiceLayer.Default, etc.
/// </summary>
public string Layer { get; }
/// <summary>
/// Declares a <see cref="IWorkspaceService"/> implementation for inclusion in a MEF-based workspace.
/// </summary>
/// <param name="serviceType">The type that will be used to retrieve the service from a <see cref="HostWorkspaceServices"/>.</param>
/// <param name="layer">The layer that the service is specified for; <see cref="ServiceLayer.Default" />, etc.</param>
public ExportWorkspaceServiceAttribute(Type serviceType, string layer = ServiceLayer.Default)
: base(typeof(IWorkspaceService))
{
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}
this.ServiceType = serviceType.AssemblyQualifiedName;
this.Layer = layer ?? throw new ArgumentNullException(nameof(layer));
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/Core/Def/Implementation/Preview/ChangeList.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview
{
internal partial class ChangeList : IVsPreviewChangesList, IVsLiteTreeList
{
public static readonly ChangeList Empty = new(Array.Empty<AbstractChange>());
internal AbstractChange[] Changes { get; }
public ChangeList(AbstractChange[] changes)
=> this.Changes = changes;
public int GetDisplayData(uint index, VSTREEDISPLAYDATA[] pData)
{
pData[0].Mask = (uint)_VSTREEDISPLAYMASK.TDM_STATE | (uint)_VSTREEDISPLAYMASK.TDM_IMAGE | (uint)_VSTREEDISPLAYMASK.TDM_SELECTEDIMAGE;
// Set TDS_SELECTED and TDS_GRAYTEXT
pData[0].State = Changes[index].GetDisplayState();
Changes[index].GetDisplayData(pData);
return VSConstants.S_OK;
}
public int GetExpandable(uint index, out int pfExpandable)
{
pfExpandable = Changes[index].IsExpandable;
return VSConstants.S_OK;
}
public int GetExpandedList(uint index, out int pfCanRecurse, out IVsLiteTreeList pptlNode)
{
pfCanRecurse = Changes[index].CanRecurse;
pptlNode = (IVsLiteTreeList)Changes[index].GetChildren();
return VSConstants.S_OK;
}
public int GetFlags(out uint pFlags)
{
// The interface IVsSimplePreviewChangesList doesn't include this method.
// Setting flags to 0 is necessary to make the underlying treeview draw
// checkboxes and make them clickable.
pFlags = 0;
return VSConstants.S_OK;
}
public int GetItemCount(out uint pCount)
{
pCount = (uint)Changes.Length;
return VSConstants.S_OK;
}
public int GetListChanges(ref uint pcChanges, VSTREELISTITEMCHANGE[] prgListChanges)
=> VSConstants.E_FAIL;
public int GetText(uint index, VSTREETEXTOPTIONS tto, out string ppszText)
=> Changes[index].GetText(out _, out ppszText);
public int GetTipText(uint index, VSTREETOOLTIPTYPE eTipType, out string ppszText)
=> Changes[index].GetTipText(out _, out ppszText);
public int LocateExpandedList(IVsLiteTreeList child, out uint iIndex)
{
for (var i = 0; i < Changes.Length; i++)
{
if (Changes[i].GetChildren() == child)
{
iIndex = (uint)i;
return VSConstants.S_OK;
}
}
iIndex = 0;
return VSConstants.S_FALSE;
}
public int OnClose(VSTREECLOSEACTIONS[] ptca)
=> VSConstants.S_OK;
public int OnRequestSource(uint index, object pIUnknownTextView)
=> Changes[index].OnRequestSource(pIUnknownTextView);
public int ToggleState(uint index, out uint ptscr)
{
Changes[index].Toggle();
ptscr = (uint)_VSTREESTATECHANGEREFRESH.TSCR_ENTIRE;
Changes[index].OnRequestSource(null);
return VSConstants.S_OK;
}
public int UpdateCounter(out uint pCurUpdate, out uint pgrfChanges)
{
pCurUpdate = 0;
pgrfChanges = 0;
return VSConstants.S_OK;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview
{
internal partial class ChangeList : IVsPreviewChangesList, IVsLiteTreeList
{
public static readonly ChangeList Empty = new(Array.Empty<AbstractChange>());
internal AbstractChange[] Changes { get; }
public ChangeList(AbstractChange[] changes)
=> this.Changes = changes;
public int GetDisplayData(uint index, VSTREEDISPLAYDATA[] pData)
{
pData[0].Mask = (uint)_VSTREEDISPLAYMASK.TDM_STATE | (uint)_VSTREEDISPLAYMASK.TDM_IMAGE | (uint)_VSTREEDISPLAYMASK.TDM_SELECTEDIMAGE;
// Set TDS_SELECTED and TDS_GRAYTEXT
pData[0].State = Changes[index].GetDisplayState();
Changes[index].GetDisplayData(pData);
return VSConstants.S_OK;
}
public int GetExpandable(uint index, out int pfExpandable)
{
pfExpandable = Changes[index].IsExpandable;
return VSConstants.S_OK;
}
public int GetExpandedList(uint index, out int pfCanRecurse, out IVsLiteTreeList pptlNode)
{
pfCanRecurse = Changes[index].CanRecurse;
pptlNode = (IVsLiteTreeList)Changes[index].GetChildren();
return VSConstants.S_OK;
}
public int GetFlags(out uint pFlags)
{
// The interface IVsSimplePreviewChangesList doesn't include this method.
// Setting flags to 0 is necessary to make the underlying treeview draw
// checkboxes and make them clickable.
pFlags = 0;
return VSConstants.S_OK;
}
public int GetItemCount(out uint pCount)
{
pCount = (uint)Changes.Length;
return VSConstants.S_OK;
}
public int GetListChanges(ref uint pcChanges, VSTREELISTITEMCHANGE[] prgListChanges)
=> VSConstants.E_FAIL;
public int GetText(uint index, VSTREETEXTOPTIONS tto, out string ppszText)
=> Changes[index].GetText(out _, out ppszText);
public int GetTipText(uint index, VSTREETOOLTIPTYPE eTipType, out string ppszText)
=> Changes[index].GetTipText(out _, out ppszText);
public int LocateExpandedList(IVsLiteTreeList child, out uint iIndex)
{
for (var i = 0; i < Changes.Length; i++)
{
if (Changes[i].GetChildren() == child)
{
iIndex = (uint)i;
return VSConstants.S_OK;
}
}
iIndex = 0;
return VSConstants.S_FALSE;
}
public int OnClose(VSTREECLOSEACTIONS[] ptca)
=> VSConstants.S_OK;
public int OnRequestSource(uint index, object pIUnknownTextView)
=> Changes[index].OnRequestSource(pIUnknownTextView);
public int ToggleState(uint index, out uint ptscr)
{
Changes[index].Toggle();
ptscr = (uint)_VSTREESTATECHANGEREFRESH.TSCR_ENTIRE;
Changes[index].OnRequestSource(null);
return VSConstants.S_OK;
}
public int UpdateCounter(out uint pCurUpdate, out uint pgrfChanges)
{
pCurUpdate = 0;
pgrfChanges = 0;
return VSConstants.S_OK;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Portable/CommandLine/CSharpCommandLineArguments.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The command line arguments to a C# <see cref="CSharpCompiler"/>.
/// </summary>
public sealed class CSharpCommandLineArguments : CommandLineArguments
{
/// <summary>
/// Gets the compilation options for the C# <see cref="Compilation"/>
/// created from the <see cref="CSharpCompiler"/>.
/// </summary>
public new CSharpCompilationOptions CompilationOptions { get; internal set; }
/// <summary>
/// Gets the parse options for the C# <see cref="Compilation"/>.
/// </summary>
public new CSharpParseOptions ParseOptions { get; internal set; }
protected override ParseOptions ParseOptionsCore
{
get { return ParseOptions; }
}
protected override CompilationOptions CompilationOptionsCore
{
get { return CompilationOptions; }
}
/// <value>
/// Should the format of error messages include the line and column of
/// the end of the offending text.
/// </value>
internal bool ShouldIncludeErrorEndLocation { get; set; }
internal CSharpCommandLineArguments()
{
// Always initialized by CSharpCommandLineParser.Parse
CompilationOptions = null!;
ParseOptions = null!;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The command line arguments to a C# <see cref="CSharpCompiler"/>.
/// </summary>
public sealed class CSharpCommandLineArguments : CommandLineArguments
{
/// <summary>
/// Gets the compilation options for the C# <see cref="Compilation"/>
/// created from the <see cref="CSharpCompiler"/>.
/// </summary>
public new CSharpCompilationOptions CompilationOptions { get; internal set; }
/// <summary>
/// Gets the parse options for the C# <see cref="Compilation"/>.
/// </summary>
public new CSharpParseOptions ParseOptions { get; internal set; }
protected override ParseOptions ParseOptionsCore
{
get { return ParseOptions; }
}
protected override CompilationOptions CompilationOptionsCore
{
get { return CompilationOptions; }
}
/// <value>
/// Should the format of error messages include the line and column of
/// the end of the offending text.
/// </value>
internal bool ShouldIncludeErrorEndLocation { get; set; }
internal CSharpCommandLineArguments()
{
// Always initialized by CSharpCommandLineParser.Parse
CompilationOptions = null!;
ParseOptions = null!;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/Test/CodeRefactorings/ErrorCases/CodeRefactoringExceptionInComputeRefactorings.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeRefactoringService.ErrorCases
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Test")]
[Shared]
[PartNotDiscoverable]
internal class ExceptionInCodeActions : CodeRefactoringProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ExceptionInCodeActions()
{
}
public override Task ComputeRefactoringsAsync(CodeRefactoringContext context)
=> throw new Exception($"Exception thrown from ComputeRefactoringsAsync in {nameof(ExceptionInCodeActions)}");
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeRefactoringService.ErrorCases
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Test")]
[Shared]
[PartNotDiscoverable]
internal class ExceptionInCodeActions : CodeRefactoringProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ExceptionInCodeActions()
{
}
public override Task ComputeRefactoringsAsync(CodeRefactoringContext context)
=> throw new Exception($"Exception thrown from ComputeRefactoringsAsync in {nameof(ExceptionInCodeActions)}");
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Method.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.ImplementInterface
{
internal abstract partial class AbstractImplementInterfaceService
{
internal partial class ImplementInterfaceCodeAction
{
private ISymbol GenerateMethod(
Compilation compilation,
IMethodSymbol method,
Accessibility accessibility,
DeclarationModifiers modifiers,
bool generateAbstractly,
bool useExplicitInterfaceSymbol,
string memberName)
{
var syntaxFacts = Document.GetRequiredLanguageService<ISyntaxFactsService>();
var updatedMethod = method.EnsureNonConflictingNames(State.ClassOrStructType, syntaxFacts);
updatedMethod = updatedMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(
State.ClassOrStructType,
AttributesToRemove(compilation));
return CodeGenerationSymbolFactory.CreateMethodSymbol(
updatedMethod,
accessibility: accessibility,
modifiers: modifiers,
explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(updatedMethod) : default,
name: memberName,
statements: generateAbstractly
? default
: ImmutableArray.Create(CreateStatement(compilation, updatedMethod)));
}
private SyntaxNode CreateStatement(Compilation compilation, IMethodSymbol method)
{
var factory = Document.GetLanguageService<SyntaxGenerator>();
return ThroughMember == null
? factory.CreateThrowNotImplementedStatement(compilation)
: factory.GenerateDelegateThroughMemberStatement(method, ThroughMember);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.ImplementInterface
{
internal abstract partial class AbstractImplementInterfaceService
{
internal partial class ImplementInterfaceCodeAction
{
private ISymbol GenerateMethod(
Compilation compilation,
IMethodSymbol method,
Accessibility accessibility,
DeclarationModifiers modifiers,
bool generateAbstractly,
bool useExplicitInterfaceSymbol,
string memberName)
{
var syntaxFacts = Document.GetRequiredLanguageService<ISyntaxFactsService>();
var updatedMethod = method.EnsureNonConflictingNames(State.ClassOrStructType, syntaxFacts);
updatedMethod = updatedMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(
State.ClassOrStructType,
AttributesToRemove(compilation));
return CodeGenerationSymbolFactory.CreateMethodSymbol(
updatedMethod,
accessibility: accessibility,
modifiers: modifiers,
explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(updatedMethod) : default,
name: memberName,
statements: generateAbstractly
? default
: ImmutableArray.Create(CreateStatement(compilation, updatedMethod)));
}
private SyntaxNode CreateStatement(Compilation compilation, IMethodSymbol method)
{
var factory = Document.GetLanguageService<SyntaxGenerator>();
return ThroughMember == null
? factory.CreateThrowNotImplementedStatement(compilation)
: factory.GenerateDelegateThroughMemberStatement(method, ThroughMember);
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/TypeOfKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class TypeOfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public TypeOfKeywordRecommender()
: base(SyntaxKind.TypeOfKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
(context.IsAnyExpressionContext && !context.IsConstantExpressionContext) ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
IsAttributeArgumentContext(context);
}
private static bool IsAttributeArgumentContext(CSharpSyntaxContext context)
{
return
context.IsAnyExpressionContext &&
context.LeftToken.GetAncestor<AttributeSyntax>() != null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class TypeOfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public TypeOfKeywordRecommender()
: base(SyntaxKind.TypeOfKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
(context.IsAnyExpressionContext && !context.IsConstantExpressionContext) ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
IsAttributeArgumentContext(context);
}
private static bool IsAttributeArgumentContext(CSharpSyntaxContext context)
{
return
context.IsAnyExpressionContext &&
context.LeftToken.GetAncestor<AttributeSyntax>() != null;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeActionOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Packaging;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.AddPackage
{
/// <summary>
/// Operation responsible purely for installing a nuget package with a specific
/// version, or a the latest version of a nuget package. Is not responsible
/// for adding an import to user code.
/// </summary>
internal class InstallPackageDirectlyCodeActionOperation : CodeActionOperation
{
private readonly Document _document;
private readonly IPackageInstallerService _installerService;
private readonly string _source;
private readonly string _packageName;
private readonly string _versionOpt;
private readonly bool _includePrerelease;
private readonly bool _isLocal;
private readonly List<string> _projectsWithMatchingVersion;
public InstallPackageDirectlyCodeActionOperation(
IPackageInstallerService installerService,
Document document,
string source,
string packageName,
string versionOpt,
bool includePrerelease,
bool isLocal)
{
_installerService = installerService;
_document = document;
_source = source;
_packageName = packageName;
_versionOpt = versionOpt;
_includePrerelease = includePrerelease;
_isLocal = isLocal;
if (versionOpt != null)
{
const int projectsToShow = 5;
var otherProjects = installerService.GetProjectsWithInstalledPackage(
_document.Project.Solution, packageName, versionOpt).ToList();
_projectsWithMatchingVersion = otherProjects.Take(projectsToShow).Select(p => p.Name).ToList();
if (otherProjects.Count > projectsToShow)
{
_projectsWithMatchingVersion.Add("...");
}
}
}
public override string Title => _versionOpt == null
? string.Format(FeaturesResources.Find_and_install_latest_version_of_0, _packageName)
: _isLocal
? string.Format(FeaturesResources.Use_locally_installed_0_version_1_This_version_used_in_colon_2, _packageName, _versionOpt, string.Join(", ", _projectsWithMatchingVersion))
: string.Format(FeaturesResources.Install_0_1, _packageName, _versionOpt);
internal override bool ApplyDuringTests => true;
internal override bool TryApply(
Workspace workspace, IProgressTracker progressTracker, CancellationToken cancellationToken)
{
return _installerService.TryInstallPackage(
workspace, _document.Id, _source, _packageName,
_versionOpt, _includePrerelease,
progressTracker, cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Packaging;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.AddPackage
{
/// <summary>
/// Operation responsible purely for installing a nuget package with a specific
/// version, or a the latest version of a nuget package. Is not responsible
/// for adding an import to user code.
/// </summary>
internal class InstallPackageDirectlyCodeActionOperation : CodeActionOperation
{
private readonly Document _document;
private readonly IPackageInstallerService _installerService;
private readonly string _source;
private readonly string _packageName;
private readonly string _versionOpt;
private readonly bool _includePrerelease;
private readonly bool _isLocal;
private readonly List<string> _projectsWithMatchingVersion;
public InstallPackageDirectlyCodeActionOperation(
IPackageInstallerService installerService,
Document document,
string source,
string packageName,
string versionOpt,
bool includePrerelease,
bool isLocal)
{
_installerService = installerService;
_document = document;
_source = source;
_packageName = packageName;
_versionOpt = versionOpt;
_includePrerelease = includePrerelease;
_isLocal = isLocal;
if (versionOpt != null)
{
const int projectsToShow = 5;
var otherProjects = installerService.GetProjectsWithInstalledPackage(
_document.Project.Solution, packageName, versionOpt).ToList();
_projectsWithMatchingVersion = otherProjects.Take(projectsToShow).Select(p => p.Name).ToList();
if (otherProjects.Count > projectsToShow)
{
_projectsWithMatchingVersion.Add("...");
}
}
}
public override string Title => _versionOpt == null
? string.Format(FeaturesResources.Find_and_install_latest_version_of_0, _packageName)
: _isLocal
? string.Format(FeaturesResources.Use_locally_installed_0_version_1_This_version_used_in_colon_2, _packageName, _versionOpt, string.Join(", ", _projectsWithMatchingVersion))
: string.Format(FeaturesResources.Install_0_1, _packageName, _versionOpt);
internal override bool ApplyDuringTests => true;
internal override bool TryApply(
Workspace workspace, IProgressTracker progressTracker, CancellationToken cancellationToken)
{
return _installerService.TryInstallPackage(
workspace, _document.Id, _source, _packageName,
_versionOpt, _includePrerelease,
progressTracker, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ControlFlowRegionExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.FlowAnalysis
{
internal static partial class ControlFlowRegionExtensions
{
internal static bool ContainsBlock(this ControlFlowRegion region, int destinationOrdinal)
=> region.FirstBlockOrdinal <= destinationOrdinal && region.LastBlockOrdinal >= destinationOrdinal;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.FlowAnalysis
{
internal static partial class ControlFlowRegionExtensions
{
internal static bool ContainsBlock(this ControlFlowRegion region, int destinationOrdinal)
=> region.FirstBlockOrdinal <= destinationOrdinal && region.LastBlockOrdinal >= destinationOrdinal;
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/CSharp/Portable/Organizing/Organizers/RecordDeclarationOrganizer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Organizing.Organizers;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
[ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared]
internal class RecordDeclarationOrganizer : AbstractSyntaxNodeOrganizer<RecordDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RecordDeclarationOrganizer()
{
}
protected override RecordDeclarationSyntax Organize(
RecordDeclarationSyntax syntax,
CancellationToken cancellationToken)
{
return syntax.Update(
syntax.AttributeLists,
ModifiersOrganizer.Organize(syntax.Modifiers),
syntax.Keyword,
syntax.ClassOrStructKeyword,
syntax.Identifier,
syntax.TypeParameterList,
syntax.ParameterList,
syntax.BaseList,
syntax.ConstraintClauses,
syntax.OpenBraceToken,
MemberDeclarationsOrganizer.Organize(syntax.Members, cancellationToken),
syntax.CloseBraceToken,
syntax.SemicolonToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Organizing.Organizers;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
[ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared]
internal class RecordDeclarationOrganizer : AbstractSyntaxNodeOrganizer<RecordDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RecordDeclarationOrganizer()
{
}
protected override RecordDeclarationSyntax Organize(
RecordDeclarationSyntax syntax,
CancellationToken cancellationToken)
{
return syntax.Update(
syntax.AttributeLists,
ModifiersOrganizer.Organize(syntax.Modifiers),
syntax.Keyword,
syntax.ClassOrStructKeyword,
syntax.Identifier,
syntax.TypeParameterList,
syntax.ParameterList,
syntax.BaseList,
syntax.ConstraintClauses,
syntax.OpenBraceToken,
MemberDeclarationsOrganizer.Organize(syntax.Members, cancellationToken),
syntax.CloseBraceToken,
syntax.SemicolonToken);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/Core/Portable/Classification/SyntaxClassification/ISyntaxClassificationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification.Classifiers;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Classification
{
internal interface ISyntaxClassificationService : ILanguageService
{
ImmutableArray<ISyntaxClassifier> GetDefaultSyntaxClassifiers();
/// <inheritdoc cref="IClassificationService.AddLexicalClassifications"/>
void AddLexicalClassifications(SourceText text,
TextSpan textSpan,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken);
/// <inheritdoc cref="IClassificationService.AddSyntacticClassificationsAsync"/>
void AddSyntacticClassifications(
SyntaxNode root,
TextSpan textSpan,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken);
/// <inheritdoc cref="IClassificationService.AddSemanticClassificationsAsync"/>
Task AddSemanticClassificationsAsync(Document document,
TextSpan textSpan,
Func<SyntaxNode, ImmutableArray<ISyntaxClassifier>> getNodeClassifiers,
Func<SyntaxToken, ImmutableArray<ISyntaxClassifier>> getTokenClassifiers,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken);
/// <inheritdoc cref="AddSemanticClassificationsAsync"/>
void AddSemanticClassifications(
SemanticModel semanticModel,
TextSpan textSpan,
Workspace workspace,
Func<SyntaxNode, ImmutableArray<ISyntaxClassifier>> getNodeClassifiers,
Func<SyntaxToken, ImmutableArray<ISyntaxClassifier>> getTokenClassifiers,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken);
/// <inheritdoc cref="IClassificationService.AdjustStaleClassification"/>
ClassifiedSpan FixClassification(SourceText text, ClassifiedSpan classifiedSpan);
/// <inheritdoc cref="IClassificationService.ComputeSyntacticChangeRangeAsync"/>
TextChangeRange? ComputeSyntacticChangeRange(
SyntaxNode oldRoot, SyntaxNode newRoot, TimeSpan timeout, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification.Classifiers;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Classification
{
internal interface ISyntaxClassificationService : ILanguageService
{
ImmutableArray<ISyntaxClassifier> GetDefaultSyntaxClassifiers();
/// <inheritdoc cref="IClassificationService.AddLexicalClassifications"/>
void AddLexicalClassifications(SourceText text,
TextSpan textSpan,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken);
/// <inheritdoc cref="IClassificationService.AddSyntacticClassificationsAsync"/>
void AddSyntacticClassifications(
SyntaxNode root,
TextSpan textSpan,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken);
/// <inheritdoc cref="IClassificationService.AddSemanticClassificationsAsync"/>
Task AddSemanticClassificationsAsync(Document document,
TextSpan textSpan,
Func<SyntaxNode, ImmutableArray<ISyntaxClassifier>> getNodeClassifiers,
Func<SyntaxToken, ImmutableArray<ISyntaxClassifier>> getTokenClassifiers,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken);
/// <inheritdoc cref="AddSemanticClassificationsAsync"/>
void AddSemanticClassifications(
SemanticModel semanticModel,
TextSpan textSpan,
Workspace workspace,
Func<SyntaxNode, ImmutableArray<ISyntaxClassifier>> getNodeClassifiers,
Func<SyntaxToken, ImmutableArray<ISyntaxClassifier>> getTokenClassifiers,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken);
/// <inheritdoc cref="IClassificationService.AdjustStaleClassification"/>
ClassifiedSpan FixClassification(SourceText text, ClassifiedSpan classifiedSpan);
/// <inheritdoc cref="IClassificationService.ComputeSyntacticChangeRangeAsync"/>
TextChangeRange? ComputeSyntacticChangeRange(
SyntaxNode oldRoot, SyntaxNode newRoot, TimeSpan timeout, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.ja.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ja" original="../CodeStyleResources.resx">
<body>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">言語名は、このオプションでは指定できません。</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">このオプションの言語名を指定する必要があります。</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">複数の次元を持つ配列はシリアル化できません。</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">型 '{0}' をシリアル化できません。</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">'{0}' の逆シリアル化のリーダーが、正しくない数の値を読み取りました。</target>
<note />
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">エラー</target>
<note />
</trans-unit>
<trans-unit id="Fix_formatting">
<source>Fix formatting</source>
<target state="translated">書式設定を修正</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">インデントと間隔</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">改行設定</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">なし</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">リファクタリングのみ</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">ストリームが長すぎます。</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">提案事項</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">型 '{0}' がシリアル化バインダーで認識されません。</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">値が大きすぎるため、30 ビットの符号なし整数として表すことができません。</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">警告</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ja" original="../CodeStyleResources.resx">
<body>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">言語名は、このオプションでは指定できません。</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">このオプションの言語名を指定する必要があります。</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">複数の次元を持つ配列はシリアル化できません。</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">型 '{0}' をシリアル化できません。</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">'{0}' の逆シリアル化のリーダーが、正しくない数の値を読み取りました。</target>
<note />
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">エラー</target>
<note />
</trans-unit>
<trans-unit id="Fix_formatting">
<source>Fix formatting</source>
<target state="translated">書式設定を修正</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">インデントと間隔</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">改行設定</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">なし</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">リファクタリングのみ</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">ストリームが長すぎます。</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">提案事項</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">型 '{0}' がシリアル化バインダーで認識されません。</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">値が大きすぎるため、30 ビットの符号なし整数として表すことができません。</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">警告</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Test/Core/Assert/WorkItemAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Roslyn.Test.Utilities
{
/// <summary>
/// Used to tag test methods or types which are created for a given WorkItem
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class WorkItemAttribute : Attribute
{
public int Id
{
get;
}
public string Location
{
get;
}
/// <summary>
/// Initializes a new instance of the <see cref="WorkItemAttribute"/>.
/// </summary>
/// <param name="id">The ID of the issue in the original tracker where the work item was first reported. This
/// could be a GitHub issue or pull request number, or the number of a Microsoft-internal bug.</param>
/// <param name="issueUri">The URI where the work item can be viewed. This is a link to work item
/// <paramref name="id"/> in the original source.</param>
public WorkItemAttribute(int id, string issueUri)
{
Id = id;
Location = issueUri;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Roslyn.Test.Utilities
{
/// <summary>
/// Used to tag test methods or types which are created for a given WorkItem
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class WorkItemAttribute : Attribute
{
public int Id
{
get;
}
public string Location
{
get;
}
/// <summary>
/// Initializes a new instance of the <see cref="WorkItemAttribute"/>.
/// </summary>
/// <param name="id">The ID of the issue in the original tracker where the work item was first reported. This
/// could be a GitHub issue or pull request number, or the number of a Microsoft-internal bug.</param>
/// <param name="issueUri">The URI where the work item can be viewed. This is a link to work item
/// <paramref name="id"/> in the original source.</param>
public WorkItemAttribute(int id, string issueUri)
{
Id = id;
Location = issueUri;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/CSharp/Portable/ConvertForToForEach/CSharpConvertForToForEachCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.ConvertForToForEach;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.CSharp.ConvertForToForEach
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertForToForEach), Shared]
internal class CSharpConvertForToForEachCodeRefactoringProvider :
AbstractConvertForToForEachCodeRefactoringProvider<
StatementSyntax,
ForStatementSyntax,
ExpressionSyntax,
MemberAccessExpressionSyntax,
TypeSyntax,
VariableDeclaratorSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpConvertForToForEachCodeRefactoringProvider()
{
}
protected override string GetTitle()
=> CSharpFeaturesResources.Convert_to_foreach;
protected override SyntaxList<StatementSyntax> GetBodyStatements(ForStatementSyntax forStatement)
=> forStatement.Statement is BlockSyntax block
? block.Statements
: SyntaxFactory.SingletonList(forStatement.Statement);
protected override bool TryGetForStatementComponents(
ForStatementSyntax forStatement,
out SyntaxToken iterationVariable, out ExpressionSyntax initializer,
out MemberAccessExpressionSyntax memberAccess,
out ExpressionSyntax stepValueExpressionOpt,
CancellationToken cancellationToken)
{
// Look for very specific forms. Basically, only minor variations around:
// for (var i = 0; i < expr.Lenth; i++)
if (forStatement.Declaration != null &&
forStatement.Condition.IsKind(SyntaxKind.LessThanExpression) &&
forStatement.Incrementors.Count == 1)
{
var declaration = forStatement.Declaration;
if (declaration.Variables.Count == 1)
{
var declarator = declaration.Variables[0];
if (declarator.Initializer != null)
{
iterationVariable = declarator.Identifier;
initializer = declarator.Initializer.Value;
var binaryExpression = (BinaryExpressionSyntax)forStatement.Condition;
// Look for: i < expr.Length
if (binaryExpression.Left is IdentifierNameSyntax identifierName &&
identifierName.Identifier.ValueText == iterationVariable.ValueText &&
binaryExpression.Right is MemberAccessExpressionSyntax)
{
memberAccess = (MemberAccessExpressionSyntax)binaryExpression.Right;
var incrementor = forStatement.Incrementors[0];
return TryGetStepValue(iterationVariable, incrementor, out stepValueExpressionOpt);
}
}
}
}
iterationVariable = default;
memberAccess = null;
initializer = null;
stepValueExpressionOpt = null;
return false;
}
private static bool TryGetStepValue(
SyntaxToken iterationVariable, ExpressionSyntax incrementor, out ExpressionSyntax stepValue)
{
// support
// x++
// ++x
// x += constant_1
ExpressionSyntax operand;
switch (incrementor.Kind())
{
case SyntaxKind.PostIncrementExpression:
operand = ((PostfixUnaryExpressionSyntax)incrementor).Operand;
stepValue = null;
break;
case SyntaxKind.PreIncrementExpression:
operand = ((PrefixUnaryExpressionSyntax)incrementor).Operand;
stepValue = null;
break;
case SyntaxKind.AddAssignmentExpression:
var assignment = (AssignmentExpressionSyntax)incrementor;
operand = assignment.Left;
stepValue = assignment.Right;
break;
default:
stepValue = null;
return false;
}
return operand is IdentifierNameSyntax identifierName &&
identifierName.Identifier.ValueText == iterationVariable.ValueText;
}
protected override SyntaxNode ConvertForNode(
ForStatementSyntax forStatement, TypeSyntax typeNode,
SyntaxToken foreachIdentifier, ExpressionSyntax collectionExpression,
ITypeSymbol iterationVariableType, OptionSet optionSet)
{
typeNode ??= iterationVariableType.GenerateTypeSyntax();
return SyntaxFactory.ForEachStatement(
SyntaxFactory.Token(SyntaxKind.ForEachKeyword).WithTriviaFrom(forStatement.ForKeyword),
forStatement.OpenParenToken,
typeNode,
foreachIdentifier,
SyntaxFactory.Token(SyntaxKind.InKeyword),
collectionExpression,
forStatement.CloseParenToken,
forStatement.Statement);
}
// C# has no special variable declarator forms that would cause us to not be able to convert.
protected override bool IsValidVariableDeclarator(VariableDeclaratorSyntax firstVariable)
=> true;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.ConvertForToForEach;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.CSharp.ConvertForToForEach
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertForToForEach), Shared]
internal class CSharpConvertForToForEachCodeRefactoringProvider :
AbstractConvertForToForEachCodeRefactoringProvider<
StatementSyntax,
ForStatementSyntax,
ExpressionSyntax,
MemberAccessExpressionSyntax,
TypeSyntax,
VariableDeclaratorSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpConvertForToForEachCodeRefactoringProvider()
{
}
protected override string GetTitle()
=> CSharpFeaturesResources.Convert_to_foreach;
protected override SyntaxList<StatementSyntax> GetBodyStatements(ForStatementSyntax forStatement)
=> forStatement.Statement is BlockSyntax block
? block.Statements
: SyntaxFactory.SingletonList(forStatement.Statement);
protected override bool TryGetForStatementComponents(
ForStatementSyntax forStatement,
out SyntaxToken iterationVariable, out ExpressionSyntax initializer,
out MemberAccessExpressionSyntax memberAccess,
out ExpressionSyntax stepValueExpressionOpt,
CancellationToken cancellationToken)
{
// Look for very specific forms. Basically, only minor variations around:
// for (var i = 0; i < expr.Lenth; i++)
if (forStatement.Declaration != null &&
forStatement.Condition.IsKind(SyntaxKind.LessThanExpression) &&
forStatement.Incrementors.Count == 1)
{
var declaration = forStatement.Declaration;
if (declaration.Variables.Count == 1)
{
var declarator = declaration.Variables[0];
if (declarator.Initializer != null)
{
iterationVariable = declarator.Identifier;
initializer = declarator.Initializer.Value;
var binaryExpression = (BinaryExpressionSyntax)forStatement.Condition;
// Look for: i < expr.Length
if (binaryExpression.Left is IdentifierNameSyntax identifierName &&
identifierName.Identifier.ValueText == iterationVariable.ValueText &&
binaryExpression.Right is MemberAccessExpressionSyntax)
{
memberAccess = (MemberAccessExpressionSyntax)binaryExpression.Right;
var incrementor = forStatement.Incrementors[0];
return TryGetStepValue(iterationVariable, incrementor, out stepValueExpressionOpt);
}
}
}
}
iterationVariable = default;
memberAccess = null;
initializer = null;
stepValueExpressionOpt = null;
return false;
}
private static bool TryGetStepValue(
SyntaxToken iterationVariable, ExpressionSyntax incrementor, out ExpressionSyntax stepValue)
{
// support
// x++
// ++x
// x += constant_1
ExpressionSyntax operand;
switch (incrementor.Kind())
{
case SyntaxKind.PostIncrementExpression:
operand = ((PostfixUnaryExpressionSyntax)incrementor).Operand;
stepValue = null;
break;
case SyntaxKind.PreIncrementExpression:
operand = ((PrefixUnaryExpressionSyntax)incrementor).Operand;
stepValue = null;
break;
case SyntaxKind.AddAssignmentExpression:
var assignment = (AssignmentExpressionSyntax)incrementor;
operand = assignment.Left;
stepValue = assignment.Right;
break;
default:
stepValue = null;
return false;
}
return operand is IdentifierNameSyntax identifierName &&
identifierName.Identifier.ValueText == iterationVariable.ValueText;
}
protected override SyntaxNode ConvertForNode(
ForStatementSyntax forStatement, TypeSyntax typeNode,
SyntaxToken foreachIdentifier, ExpressionSyntax collectionExpression,
ITypeSymbol iterationVariableType, OptionSet optionSet)
{
typeNode ??= iterationVariableType.GenerateTypeSyntax();
return SyntaxFactory.ForEachStatement(
SyntaxFactory.Token(SyntaxKind.ForEachKeyword).WithTriviaFrom(forStatement.ForKeyword),
forStatement.OpenParenToken,
typeNode,
foreachIdentifier,
SyntaxFactory.Token(SyntaxKind.InKeyword),
collectionExpression,
forStatement.CloseParenToken,
forStatement.Statement);
}
// C# has no special variable declarator forms that would cause us to not be able to convert.
protected override bool IsValidVariableDeclarator(VariableDeclaratorSyntax firstVariable)
=> true;
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Portable/Emitter/Model/GenericNamespaceTypeInstanceReference.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
/// <summary>
/// Represents a reference to a generic type instantiation that is not nested.
/// e.g. MyNamespace.A{int}
/// </summary>
internal sealed class GenericNamespaceTypeInstanceReference : GenericTypeInstanceReference
{
public GenericNamespaceTypeInstanceReference(NamedTypeSymbol underlyingNamedType)
: base(underlyingNamedType)
{
}
public override Microsoft.Cci.IGenericTypeInstanceReference AsGenericTypeInstanceReference
{
get { return this; }
}
public override Microsoft.Cci.INamespaceTypeReference AsNamespaceTypeReference
{
get { return null; }
}
public override Microsoft.Cci.INestedTypeReference AsNestedTypeReference
{
get { return null; }
}
public override Microsoft.Cci.ISpecializedNestedTypeReference AsSpecializedNestedTypeReference
{
get { return null; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
/// <summary>
/// Represents a reference to a generic type instantiation that is not nested.
/// e.g. MyNamespace.A{int}
/// </summary>
internal sealed class GenericNamespaceTypeInstanceReference : GenericTypeInstanceReference
{
public GenericNamespaceTypeInstanceReference(NamedTypeSymbol underlyingNamedType)
: base(underlyingNamedType)
{
}
public override Microsoft.Cci.IGenericTypeInstanceReference AsGenericTypeInstanceReference
{
get { return this; }
}
public override Microsoft.Cci.INamespaceTypeReference AsNamespaceTypeReference
{
get { return null; }
}
public override Microsoft.Cci.INestedTypeReference AsNestedTypeReference
{
get { return null; }
}
public override Microsoft.Cci.ISpecializedNestedTypeReference AsSpecializedNestedTypeReference
{
get { return null; }
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/TestUtilities/ReassignedVariable/AbstractReassignedVariableTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ReassignedVariable;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReassignedVariable
{
[UseExportProvider]
public abstract class AbstractReassignedVariableTests
{
protected abstract TestWorkspace CreateWorkspace(string markup);
protected async Task TestAsync(string markup)
{
using var workspace = CreateWorkspace(markup);
var project = workspace.CurrentSolution.Projects.Single();
var language = project.Language;
var document = project.Documents.Single();
var text = await document.GetTextAsync();
var service = document.GetRequiredLanguageService<IReassignedVariableService>();
var result = await service.GetLocationsAsync(document, new TextSpan(0, text.Length), CancellationToken.None);
var expectedSpans = workspace.Documents.Single().SelectedSpans.OrderBy(s => s.Start);
var actualSpans = result.OrderBy(s => s.Start);
Assert.Equal(expectedSpans, actualSpans);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ReassignedVariable;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReassignedVariable
{
[UseExportProvider]
public abstract class AbstractReassignedVariableTests
{
protected abstract TestWorkspace CreateWorkspace(string markup);
protected async Task TestAsync(string markup)
{
using var workspace = CreateWorkspace(markup);
var project = workspace.CurrentSolution.Projects.Single();
var language = project.Language;
var document = project.Documents.Single();
var text = await document.GetTextAsync();
var service = document.GetRequiredLanguageService<IReassignedVariableService>();
var result = await service.GetLocationsAsync(document, new TextSpan(0, text.Length), CancellationToken.None);
var expectedSpans = workspace.Documents.Single().SelectedSpans.OrderBy(s => s.Start);
var actualSpans = result.OrderBy(s => s.Start);
Assert.Equal(expectedSpans, actualSpans);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Test/Core/Assert/DiffUtil.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class DiffUtil
{
private enum EditKind
{
/// <summary>
/// No change.
/// </summary>
None = 0,
/// <summary>
/// Node value was updated.
/// </summary>
Update = 1,
/// <summary>
/// Node was inserted.
/// </summary>
Insert = 2,
/// <summary>
/// Node was deleted.
/// </summary>
Delete = 3,
}
private class LCS<T> : LongestCommonSubsequence<IList<T>>
{
public static readonly LCS<T> Default = new LCS<T>(EqualityComparer<T>.Default);
private readonly IEqualityComparer<T> _comparer;
public LCS(IEqualityComparer<T> comparer)
{
_comparer = comparer;
}
protected override bool ItemsEqual(IList<T> sequenceA, int indexA, IList<T> sequenceB, int indexB)
{
return _comparer.Equals(sequenceA[indexA], sequenceB[indexB]);
}
public IEnumerable<string> CalculateDiff(IList<T> sequenceA, IList<T> sequenceB, Func<T, string> toString)
{
foreach (var edit in GetEdits(sequenceA, sequenceA.Count, sequenceB, sequenceB.Count).Reverse())
{
switch (edit.Kind)
{
case EditKind.Delete:
yield return "--> " + toString(sequenceA[edit.IndexA]);
break;
case EditKind.Insert:
yield return "++> " + toString(sequenceB[edit.IndexB]);
break;
case EditKind.Update:
yield return " " + toString(sequenceB[edit.IndexB]);
break;
}
}
}
}
public static string DiffReport<T>(IEnumerable<T> expected, IEnumerable<T> actual, string separator, IEqualityComparer<T> comparer = null, Func<T, string> toString = null)
{
var lcs = (comparer != null) ? new LCS<T>(comparer) : LCS<T>.Default;
toString = toString ?? new Func<T, string>(obj => obj.ToString());
IList<T> expectedList = expected as IList<T> ?? new List<T>(expected);
IList<T> actualList = actual as IList<T> ?? new List<T>(actual);
return string.Join(separator, lcs.CalculateDiff(expectedList, actualList, toString));
}
private static readonly char[] s_lineSplitChars = new[] { '\r', '\n' };
public static string[] Lines(string s)
{
return s.Split(s_lineSplitChars, StringSplitOptions.RemoveEmptyEntries);
}
public static string DiffReport(string expected, string actual)
{
var exlines = Lines(expected);
var aclines = Lines(actual);
return DiffReport(exlines, aclines, separator: Environment.NewLine);
}
/// <summary>
/// Calculates Longest Common Subsequence.
/// </summary>
private abstract class LongestCommonSubsequence<TSequence>
{
protected struct Edit
{
public readonly EditKind Kind;
public readonly int IndexA;
public readonly int IndexB;
internal Edit(EditKind kind, int indexA, int indexB)
{
this.Kind = kind;
this.IndexA = indexA;
this.IndexB = indexB;
}
}
private const int DeleteCost = 1;
private const int InsertCost = 1;
private const int UpdateCost = 2;
protected abstract bool ItemsEqual(TSequence sequenceA, int indexA, TSequence sequenceB, int indexB);
protected IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB);
int i = lengthA;
int j = lengthB;
while (i != 0 && j != 0)
{
if (d[i, j] == d[i - 1, j] + DeleteCost)
{
i--;
}
else if (d[i, j] == d[i, j - 1] + InsertCost)
{
j--;
}
else
{
i--;
j--;
yield return new KeyValuePair<int, int>(i, j);
}
}
}
protected IEnumerable<Edit> GetEdits(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB);
int i = lengthA;
int j = lengthB;
while (i != 0 && j != 0)
{
if (d[i, j] == d[i - 1, j] + DeleteCost)
{
i--;
yield return new Edit(EditKind.Delete, i, -1);
}
else if (d[i, j] == d[i, j - 1] + InsertCost)
{
j--;
yield return new Edit(EditKind.Insert, -1, j);
}
else
{
i--;
j--;
yield return new Edit(EditKind.Update, i, j);
}
}
while (i > 0)
{
i--;
yield return new Edit(EditKind.Delete, i, -1);
}
while (j > 0)
{
j--;
yield return new Edit(EditKind.Insert, -1, j);
}
}
/// <summary>
/// Returns a distance [0..1] of the specified sequences.
/// The smaller distance the more of their elements match.
/// </summary>
/// <summary>
/// Returns a distance [0..1] of the specified sequences.
/// The smaller distance the more of their elements match.
/// </summary>
protected double ComputeDistance(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
Debug.Assert(lengthA >= 0 && lengthB >= 0);
if (lengthA == 0 || lengthB == 0)
{
return (lengthA == lengthB) ? 0.0 : 1.0;
}
int lcsLength = 0;
foreach (var pair in GetMatchingPairs(sequenceA, lengthA, sequenceB, lengthB))
{
lcsLength++;
}
int max = Math.Max(lengthA, lengthB);
Debug.Assert(lcsLength <= max);
return 1.0 - (double)lcsLength / (double)max;
}
/// <summary>
/// Calculates costs of all paths in an edit graph starting from vertex (0,0) and ending in vertex (lengthA, lengthB).
/// </summary>
/// <remarks>
/// The edit graph for A and B has a vertex at each point in the grid (i,j), i in [0, lengthA] and j in [0, lengthB].
///
/// The vertices of the edit graph are connected by horizontal, vertical, and diagonal directed edges to form a directed acyclic graph.
/// Horizontal edges connect each vertex to its right neighbor.
/// Vertical edges connect each vertex to the neighbor below it.
/// Diagonal edges connect vertex (i,j) to vertex (i-1,j-1) if <see cref="ItemsEqual"/>(sequenceA[i-1],sequenceB[j-1]) is true.
///
/// Editing starts with S = [].
/// Move along horizontal edge (i-1,j)-(i,j) represents the fact that sequenceA[i-1] is not added to S.
/// Move along vertical edge (i,j-1)-(i,j) represents an insert of sequenceB[j-1] to S.
/// Move along diagonal edge (i-1,j-1)-(i,j) represents an addition of sequenceB[j-1] to S via an acceptable
/// change of sequenceA[i-1] to sequenceB[j-1].
///
/// In every vertex the cheapest outgoing edge is selected.
/// The number of diagonal edges on the path from (0,0) to (lengthA, lengthB) is the length of the longest common subsequence.
/// </remarks>
private int[,] ComputeCostMatrix(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
var la = lengthA + 1;
var lb = lengthB + 1;
// TODO: Optimization possible: O(ND) time, O(N) space
// EUGENE W. MYERS: An O(ND) Difference Algorithm and Its Variations
var d = new int[la, lb];
d[0, 0] = 0;
for (int i = 1; i <= lengthA; i++)
{
d[i, 0] = d[i - 1, 0] + DeleteCost;
}
for (int j = 1; j <= lengthB; j++)
{
d[0, j] = d[0, j - 1] + InsertCost;
}
for (int i = 1; i <= lengthA; i++)
{
for (int j = 1; j <= lengthB; j++)
{
int m1 = d[i - 1, j - 1] + (ItemsEqual(sequenceA, i - 1, sequenceB, j - 1) ? 0 : UpdateCost);
int m2 = d[i - 1, j] + DeleteCost;
int m3 = d[i, j - 1] + InsertCost;
d[i, j] = Math.Min(Math.Min(m1, m2), m3);
}
}
return d;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class DiffUtil
{
private enum EditKind
{
/// <summary>
/// No change.
/// </summary>
None = 0,
/// <summary>
/// Node value was updated.
/// </summary>
Update = 1,
/// <summary>
/// Node was inserted.
/// </summary>
Insert = 2,
/// <summary>
/// Node was deleted.
/// </summary>
Delete = 3,
}
private class LCS<T> : LongestCommonSubsequence<IList<T>>
{
public static readonly LCS<T> Default = new LCS<T>(EqualityComparer<T>.Default);
private readonly IEqualityComparer<T> _comparer;
public LCS(IEqualityComparer<T> comparer)
{
_comparer = comparer;
}
protected override bool ItemsEqual(IList<T> sequenceA, int indexA, IList<T> sequenceB, int indexB)
{
return _comparer.Equals(sequenceA[indexA], sequenceB[indexB]);
}
public IEnumerable<string> CalculateDiff(IList<T> sequenceA, IList<T> sequenceB, Func<T, string> toString)
{
foreach (var edit in GetEdits(sequenceA, sequenceA.Count, sequenceB, sequenceB.Count).Reverse())
{
switch (edit.Kind)
{
case EditKind.Delete:
yield return "--> " + toString(sequenceA[edit.IndexA]);
break;
case EditKind.Insert:
yield return "++> " + toString(sequenceB[edit.IndexB]);
break;
case EditKind.Update:
yield return " " + toString(sequenceB[edit.IndexB]);
break;
}
}
}
}
public static string DiffReport<T>(IEnumerable<T> expected, IEnumerable<T> actual, string separator, IEqualityComparer<T> comparer = null, Func<T, string> toString = null)
{
var lcs = (comparer != null) ? new LCS<T>(comparer) : LCS<T>.Default;
toString = toString ?? new Func<T, string>(obj => obj.ToString());
IList<T> expectedList = expected as IList<T> ?? new List<T>(expected);
IList<T> actualList = actual as IList<T> ?? new List<T>(actual);
return string.Join(separator, lcs.CalculateDiff(expectedList, actualList, toString));
}
private static readonly char[] s_lineSplitChars = new[] { '\r', '\n' };
public static string[] Lines(string s)
{
return s.Split(s_lineSplitChars, StringSplitOptions.RemoveEmptyEntries);
}
public static string DiffReport(string expected, string actual)
{
var exlines = Lines(expected);
var aclines = Lines(actual);
return DiffReport(exlines, aclines, separator: Environment.NewLine);
}
/// <summary>
/// Calculates Longest Common Subsequence.
/// </summary>
private abstract class LongestCommonSubsequence<TSequence>
{
protected struct Edit
{
public readonly EditKind Kind;
public readonly int IndexA;
public readonly int IndexB;
internal Edit(EditKind kind, int indexA, int indexB)
{
this.Kind = kind;
this.IndexA = indexA;
this.IndexB = indexB;
}
}
private const int DeleteCost = 1;
private const int InsertCost = 1;
private const int UpdateCost = 2;
protected abstract bool ItemsEqual(TSequence sequenceA, int indexA, TSequence sequenceB, int indexB);
protected IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB);
int i = lengthA;
int j = lengthB;
while (i != 0 && j != 0)
{
if (d[i, j] == d[i - 1, j] + DeleteCost)
{
i--;
}
else if (d[i, j] == d[i, j - 1] + InsertCost)
{
j--;
}
else
{
i--;
j--;
yield return new KeyValuePair<int, int>(i, j);
}
}
}
protected IEnumerable<Edit> GetEdits(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
int[,] d = ComputeCostMatrix(sequenceA, lengthA, sequenceB, lengthB);
int i = lengthA;
int j = lengthB;
while (i != 0 && j != 0)
{
if (d[i, j] == d[i - 1, j] + DeleteCost)
{
i--;
yield return new Edit(EditKind.Delete, i, -1);
}
else if (d[i, j] == d[i, j - 1] + InsertCost)
{
j--;
yield return new Edit(EditKind.Insert, -1, j);
}
else
{
i--;
j--;
yield return new Edit(EditKind.Update, i, j);
}
}
while (i > 0)
{
i--;
yield return new Edit(EditKind.Delete, i, -1);
}
while (j > 0)
{
j--;
yield return new Edit(EditKind.Insert, -1, j);
}
}
/// <summary>
/// Returns a distance [0..1] of the specified sequences.
/// The smaller distance the more of their elements match.
/// </summary>
/// <summary>
/// Returns a distance [0..1] of the specified sequences.
/// The smaller distance the more of their elements match.
/// </summary>
protected double ComputeDistance(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
Debug.Assert(lengthA >= 0 && lengthB >= 0);
if (lengthA == 0 || lengthB == 0)
{
return (lengthA == lengthB) ? 0.0 : 1.0;
}
int lcsLength = 0;
foreach (var pair in GetMatchingPairs(sequenceA, lengthA, sequenceB, lengthB))
{
lcsLength++;
}
int max = Math.Max(lengthA, lengthB);
Debug.Assert(lcsLength <= max);
return 1.0 - (double)lcsLength / (double)max;
}
/// <summary>
/// Calculates costs of all paths in an edit graph starting from vertex (0,0) and ending in vertex (lengthA, lengthB).
/// </summary>
/// <remarks>
/// The edit graph for A and B has a vertex at each point in the grid (i,j), i in [0, lengthA] and j in [0, lengthB].
///
/// The vertices of the edit graph are connected by horizontal, vertical, and diagonal directed edges to form a directed acyclic graph.
/// Horizontal edges connect each vertex to its right neighbor.
/// Vertical edges connect each vertex to the neighbor below it.
/// Diagonal edges connect vertex (i,j) to vertex (i-1,j-1) if <see cref="ItemsEqual"/>(sequenceA[i-1],sequenceB[j-1]) is true.
///
/// Editing starts with S = [].
/// Move along horizontal edge (i-1,j)-(i,j) represents the fact that sequenceA[i-1] is not added to S.
/// Move along vertical edge (i,j-1)-(i,j) represents an insert of sequenceB[j-1] to S.
/// Move along diagonal edge (i-1,j-1)-(i,j) represents an addition of sequenceB[j-1] to S via an acceptable
/// change of sequenceA[i-1] to sequenceB[j-1].
///
/// In every vertex the cheapest outgoing edge is selected.
/// The number of diagonal edges on the path from (0,0) to (lengthA, lengthB) is the length of the longest common subsequence.
/// </remarks>
private int[,] ComputeCostMatrix(TSequence sequenceA, int lengthA, TSequence sequenceB, int lengthB)
{
var la = lengthA + 1;
var lb = lengthB + 1;
// TODO: Optimization possible: O(ND) time, O(N) space
// EUGENE W. MYERS: An O(ND) Difference Algorithm and Its Variations
var d = new int[la, lb];
d[0, 0] = 0;
for (int i = 1; i <= lengthA; i++)
{
d[i, 0] = d[i - 1, 0] + DeleteCost;
}
for (int j = 1; j <= lengthB; j++)
{
d[0, j] = d[0, j - 1] + InsertCost;
}
for (int i = 1; i <= lengthA; i++)
{
for (int j = 1; j <= lengthB; j++)
{
int m1 = d[i - 1, j - 1] + (ItemsEqual(sequenceA, i - 1, sequenceB, j - 1) ? 0 : UpdateCost);
int m2 = d[i - 1, j] + DeleteCost;
int m3 = d[i, j - 1] + InsertCost;
d[i, j] = Math.Min(Math.Min(m1, m2), m3);
}
}
return d;
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/NamingStylePreferences.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.NamingStyles;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
/// <summary>
/// Contains all information related to Naming Style Preferences.
/// 1. Symbol Specifications
/// 2. Name Style
/// 3. Naming Rule (points to Symbol Specification IDs)
/// </summary>
internal sealed class NamingStylePreferences : IEquatable<NamingStylePreferences>, IObjectWritable
{
static NamingStylePreferences()
{
ObjectBinder.RegisterTypeReader(typeof(NamingStylePreferences), ReadFrom);
}
private const int s_serializationVersion = 5;
public readonly ImmutableArray<SymbolSpecification> SymbolSpecifications;
public readonly ImmutableArray<NamingStyle> NamingStyles;
public readonly ImmutableArray<SerializableNamingRule> NamingRules;
private readonly Lazy<NamingStyleRules> _lazyRules;
internal NamingStylePreferences(
ImmutableArray<SymbolSpecification> symbolSpecifications,
ImmutableArray<NamingStyle> namingStyles,
ImmutableArray<SerializableNamingRule> namingRules)
{
SymbolSpecifications = symbolSpecifications;
NamingStyles = namingStyles;
NamingRules = namingRules;
_lazyRules = new Lazy<NamingStyleRules>(CreateRules, isThreadSafe: true);
}
public static NamingStylePreferences Default => FromXElement(XElement.Parse(DefaultNamingPreferencesString));
public static string DefaultNamingPreferencesString => _defaultNamingPreferencesString;
internal NamingStyle GetNamingStyle(Guid namingStyleID)
=> NamingStyles.Single(s => s.ID == namingStyleID);
internal SymbolSpecification GetSymbolSpecification(Guid symbolSpecificationID)
=> SymbolSpecifications.Single(s => s.ID == symbolSpecificationID);
public NamingStyleRules Rules => _lazyRules.Value;
public NamingStyleRules CreateRules()
=> new(NamingRules.Select(r => r.GetRule(this)).ToImmutableArray());
internal XElement CreateXElement()
{
return new XElement("NamingPreferencesInfo",
new XAttribute("SerializationVersion", s_serializationVersion),
new XElement(nameof(SymbolSpecifications), SymbolSpecifications.Select(s => s.CreateXElement())),
new XElement(nameof(NamingStyles), NamingStyles.Select(n => n.CreateXElement())),
new XElement(nameof(NamingRules), NamingRules.Select(n => n.CreateXElement())));
}
internal static NamingStylePreferences FromXElement(XElement element)
{
element = GetUpgradedSerializationIfNecessary(element);
return new NamingStylePreferences(
element.Element(nameof(SymbolSpecifications)).Elements(nameof(SymbolSpecification))
.Select(SymbolSpecification.FromXElement).ToImmutableArray(),
element.Element(nameof(NamingStyles)).Elements(nameof(NamingStyle))
.Select(NamingStyle.FromXElement).ToImmutableArray(),
element.Element(nameof(NamingRules)).Elements(nameof(SerializableNamingRule))
.Select(SerializableNamingRule.FromXElement).ToImmutableArray());
}
public bool ShouldReuseInSerialization => false;
public void WriteTo(ObjectWriter writer)
{
writer.WriteArray(SymbolSpecifications, (w, v) => v.WriteTo(w));
writer.WriteArray(NamingStyles, (w, v) => v.WriteTo(w));
writer.WriteArray(NamingRules, (w, v) => v.WriteTo(w));
}
public static NamingStylePreferences ReadFrom(ObjectReader reader)
{
return new NamingStylePreferences(
reader.ReadArray(r => SymbolSpecification.ReadFrom(r)),
reader.ReadArray(r => NamingStyle.ReadFrom(r)),
reader.ReadArray(r => SerializableNamingRule.ReadFrom(r)));
}
public override bool Equals(object obj)
=> Equals(obj as NamingStylePreferences);
public bool Equals(NamingStylePreferences other)
{
if (other is null)
return false;
return SymbolSpecifications.SequenceEqual(other.SymbolSpecifications)
&& NamingStyles.SequenceEqual(other.NamingStyles)
&& NamingRules.SequenceEqual(other.NamingRules);
}
public static bool operator ==(NamingStylePreferences left, NamingStylePreferences right)
{
if (left is null && right is null)
{
return true;
}
else if (left is null || right is null)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(NamingStylePreferences left, NamingStylePreferences right)
=> !(left == right);
public override int GetHashCode()
{
return Hash.Combine(Hash.CombineValues(SymbolSpecifications),
Hash.Combine(Hash.CombineValues(NamingStyles),
Hash.CombineValues(NamingRules)));
}
private static readonly string _defaultNamingPreferencesString = $@"
<NamingPreferencesInfo SerializationVersion=""{s_serializationVersion}"">
<SymbolSpecifications>
<SymbolSpecification ID=""5c545a62-b14d-460a-88d8-e936c0a39316"" Name=""{CompilerExtensionsResources.Class}"">
<ApplicableSymbolKindList>
<TypeKind>Class</TypeKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""23d856b4-5089-4405-83ce-749aada99153"" Name=""{CompilerExtensionsResources.Interface}"">
<ApplicableSymbolKindList>
<TypeKind>Interface</TypeKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""d1796e78-ff66-463f-8576-eb46416060c0"" Name=""{CompilerExtensionsResources.Struct}"">
<ApplicableSymbolKindList>
<TypeKind>Struct</TypeKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""d8af8dc6-1ade-441d-9947-8946922e198a"" Name=""{CompilerExtensionsResources.Enum}"">
<ApplicableSymbolKindList>
<TypeKind>Enum</TypeKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""408a3347-b908-4b54-a954-1355e64c1de3"" Name=""{CompilerExtensionsResources.Delegate}"">
<ApplicableSymbolKindList>
<TypeKind>Delegate</TypeKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""830657f6-e7e5-4830-b328-f109d3b6c165"" Name=""{CompilerExtensionsResources.Event}"">
<ApplicableSymbolKindList>
<SymbolKind>Event</SymbolKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""390caed4-f0a9-42bb-adbb-b44c4a302a22"" Name=""{CompilerExtensionsResources.Method}"">
<ApplicableSymbolKindList>
<MethodKind>Ordinary</MethodKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""af410767-f189-47c6-b140-aeccf1ff242e"" Name=""{CompilerExtensionsResources.Private_Method}"">
<ApplicableSymbolKindList>
<MethodKind>Ordinary</MethodKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Private</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""8076757e-6a4a-47f1-9b4b-ae8a3284e987"" Name=""{CompilerExtensionsResources.Abstract_Method}"">
<ApplicableSymbolKindList>
<MethodKind>Ordinary</MethodKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList>
<ModifierKind>IsAbstract</ModifierKind>
</RequiredModifierList>
</SymbolSpecification>
<SymbolSpecification ID=""16133061-a8e7-4392-92c3-1d93cd54c218"" Name=""{CompilerExtensionsResources.Static_Method}"">
<ApplicableSymbolKindList>
<MethodKind>Ordinary</MethodKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList>
<ModifierKind>IsStatic</ModifierKind>
</RequiredModifierList>
</SymbolSpecification>
<SymbolSpecification ID=""da6a2919-5aa6-4ad1-a24d-576776ed3974"" Name=""{CompilerExtensionsResources.Property}"">
<ApplicableSymbolKindList>
<SymbolKind>Property</SymbolKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""b24a91ce-3501-4799-b6df-baf044156c83"" Name=""{CompilerExtensionsResources.Public_or_Protected_Field}"">
<ApplicableSymbolKindList>
<SymbolKind>Field</SymbolKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""70af42cb-1741-4027-969c-9edc4877d965"" Name=""{CompilerExtensionsResources.Static_Field}"">
<ApplicableSymbolKindList>
<SymbolKind>Field</SymbolKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList>
<ModifierKind>IsStatic</ModifierKind>
</RequiredModifierList>
</SymbolSpecification>
<SymbolSpecification ID=""10790aa6-0a0b-432d-a52d-d252ca92302b"" Name=""{CompilerExtensionsResources.Private_or_Internal_Field}"">
<ApplicableSymbolKindList>
<SymbolKind>Field</SymbolKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""ac995be4-88de-4771-9dcc-a456a7c02d89"" Name=""{CompilerExtensionsResources.Private_or_Internal_Static_Field}"">
<ApplicableSymbolKindList>
<SymbolKind>Field</SymbolKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList>
<ModifierKind>IsStatic</ModifierKind>
</RequiredModifierList>
</SymbolSpecification>
<SymbolSpecification ID=""2c07f5bf-bc81-4c2b-82b4-ae9b3ffd0ba4"" Name=""{CompilerExtensionsResources.Types}"">
<ApplicableSymbolKindList>
<TypeKind>Class</TypeKind>
<TypeKind>Struct</TypeKind>
<TypeKind>Interface</TypeKind>
<TypeKind>Enum</TypeKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""5f3ddba1-279f-486c-801e-5c097c36dd85"" Name=""{CompilerExtensionsResources.Non_Field_Members}"">
<ApplicableSymbolKindList>
<SymbolKind>Property</SymbolKind>
<SymbolKind>Event</SymbolKind>
<MethodKind>Ordinary</MethodKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
</SymbolSpecifications>
<NamingStyles>
<NamingStyle ID=""87e7c501-9948-4b53-b1eb-a6cbe918feee"" Name=""{CompilerExtensionsResources.Pascal_Case}"" Prefix="""" Suffix="""" WordSeparator="""" CapitalizationScheme=""PascalCase"" />
<NamingStyle ID=""1ecc5eb6-b5fc-49a5-a9f1-a980f3e48c92"" Name=""{CompilerExtensionsResources.Begins_with_I}"" Prefix=""I"" Suffix="""" WordSeparator="""" CapitalizationScheme=""PascalCase"" />
</NamingStyles>
<NamingRules>
<SerializableNamingRule SymbolSpecificationID=""23d856b4-5089-4405-83ce-749aada99153"" NamingStyleID=""1ecc5eb6-b5fc-49a5-a9f1-a980f3e48c92"" EnforcementLevel=""Info"" />
<SerializableNamingRule SymbolSpecificationID=""2c07f5bf-bc81-4c2b-82b4-ae9b3ffd0ba4"" NamingStyleID=""87e7c501-9948-4b53-b1eb-a6cbe918feee"" EnforcementLevel=""Info"" />
<SerializableNamingRule SymbolSpecificationID=""5f3ddba1-279f-486c-801e-5c097c36dd85"" NamingStyleID=""87e7c501-9948-4b53-b1eb-a6cbe918feee"" EnforcementLevel=""Info"" />
</NamingRules>
</NamingPreferencesInfo>
";
private static XElement GetUpgradedSerializationIfNecessary(XElement rootElement)
{
var serializationVersion = int.Parse(rootElement.Attribute("SerializationVersion").Value);
if (serializationVersion == 4)
{
UpgradeSerialization_4To5(rootElement = new XElement(rootElement));
serializationVersion = 5;
}
// Add future version checks here. If the version is off by more than 1, these upgrades will run in sequence.
// The next one should check serializationVersion == 5 and update it to 6.
// It is also important to create a new roaming location in NamingStyleOptions.NamingPreferences
// so that we never store the new format in an older version.
Debug.Assert(s_serializationVersion == 5, "After increasing the serialization version, add an upgrade path here.");
return serializationVersion == s_serializationVersion
? rootElement
: XElement.Parse(DefaultNamingPreferencesString);
}
private static void UpgradeSerialization_4To5(XElement rootElement)
{
var methodElements = rootElement
.Descendants()
.Where(e => e.Name.LocalName == "SymbolKind" && e.Value == "Method").ToList();
foreach (var element in methodElements)
{
element.ReplaceWith(XElement.Parse("<MethodKind>Ordinary</MethodKind>"));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.NamingStyles;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
/// <summary>
/// Contains all information related to Naming Style Preferences.
/// 1. Symbol Specifications
/// 2. Name Style
/// 3. Naming Rule (points to Symbol Specification IDs)
/// </summary>
internal sealed class NamingStylePreferences : IEquatable<NamingStylePreferences>, IObjectWritable
{
static NamingStylePreferences()
{
ObjectBinder.RegisterTypeReader(typeof(NamingStylePreferences), ReadFrom);
}
private const int s_serializationVersion = 5;
public readonly ImmutableArray<SymbolSpecification> SymbolSpecifications;
public readonly ImmutableArray<NamingStyle> NamingStyles;
public readonly ImmutableArray<SerializableNamingRule> NamingRules;
private readonly Lazy<NamingStyleRules> _lazyRules;
internal NamingStylePreferences(
ImmutableArray<SymbolSpecification> symbolSpecifications,
ImmutableArray<NamingStyle> namingStyles,
ImmutableArray<SerializableNamingRule> namingRules)
{
SymbolSpecifications = symbolSpecifications;
NamingStyles = namingStyles;
NamingRules = namingRules;
_lazyRules = new Lazy<NamingStyleRules>(CreateRules, isThreadSafe: true);
}
public static NamingStylePreferences Default => FromXElement(XElement.Parse(DefaultNamingPreferencesString));
public static string DefaultNamingPreferencesString => _defaultNamingPreferencesString;
internal NamingStyle GetNamingStyle(Guid namingStyleID)
=> NamingStyles.Single(s => s.ID == namingStyleID);
internal SymbolSpecification GetSymbolSpecification(Guid symbolSpecificationID)
=> SymbolSpecifications.Single(s => s.ID == symbolSpecificationID);
public NamingStyleRules Rules => _lazyRules.Value;
public NamingStyleRules CreateRules()
=> new(NamingRules.Select(r => r.GetRule(this)).ToImmutableArray());
internal XElement CreateXElement()
{
return new XElement("NamingPreferencesInfo",
new XAttribute("SerializationVersion", s_serializationVersion),
new XElement(nameof(SymbolSpecifications), SymbolSpecifications.Select(s => s.CreateXElement())),
new XElement(nameof(NamingStyles), NamingStyles.Select(n => n.CreateXElement())),
new XElement(nameof(NamingRules), NamingRules.Select(n => n.CreateXElement())));
}
internal static NamingStylePreferences FromXElement(XElement element)
{
element = GetUpgradedSerializationIfNecessary(element);
return new NamingStylePreferences(
element.Element(nameof(SymbolSpecifications)).Elements(nameof(SymbolSpecification))
.Select(SymbolSpecification.FromXElement).ToImmutableArray(),
element.Element(nameof(NamingStyles)).Elements(nameof(NamingStyle))
.Select(NamingStyle.FromXElement).ToImmutableArray(),
element.Element(nameof(NamingRules)).Elements(nameof(SerializableNamingRule))
.Select(SerializableNamingRule.FromXElement).ToImmutableArray());
}
public bool ShouldReuseInSerialization => false;
public void WriteTo(ObjectWriter writer)
{
writer.WriteArray(SymbolSpecifications, (w, v) => v.WriteTo(w));
writer.WriteArray(NamingStyles, (w, v) => v.WriteTo(w));
writer.WriteArray(NamingRules, (w, v) => v.WriteTo(w));
}
public static NamingStylePreferences ReadFrom(ObjectReader reader)
{
return new NamingStylePreferences(
reader.ReadArray(r => SymbolSpecification.ReadFrom(r)),
reader.ReadArray(r => NamingStyle.ReadFrom(r)),
reader.ReadArray(r => SerializableNamingRule.ReadFrom(r)));
}
public override bool Equals(object obj)
=> Equals(obj as NamingStylePreferences);
public bool Equals(NamingStylePreferences other)
{
if (other is null)
return false;
return SymbolSpecifications.SequenceEqual(other.SymbolSpecifications)
&& NamingStyles.SequenceEqual(other.NamingStyles)
&& NamingRules.SequenceEqual(other.NamingRules);
}
public static bool operator ==(NamingStylePreferences left, NamingStylePreferences right)
{
if (left is null && right is null)
{
return true;
}
else if (left is null || right is null)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(NamingStylePreferences left, NamingStylePreferences right)
=> !(left == right);
public override int GetHashCode()
{
return Hash.Combine(Hash.CombineValues(SymbolSpecifications),
Hash.Combine(Hash.CombineValues(NamingStyles),
Hash.CombineValues(NamingRules)));
}
private static readonly string _defaultNamingPreferencesString = $@"
<NamingPreferencesInfo SerializationVersion=""{s_serializationVersion}"">
<SymbolSpecifications>
<SymbolSpecification ID=""5c545a62-b14d-460a-88d8-e936c0a39316"" Name=""{CompilerExtensionsResources.Class}"">
<ApplicableSymbolKindList>
<TypeKind>Class</TypeKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""23d856b4-5089-4405-83ce-749aada99153"" Name=""{CompilerExtensionsResources.Interface}"">
<ApplicableSymbolKindList>
<TypeKind>Interface</TypeKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""d1796e78-ff66-463f-8576-eb46416060c0"" Name=""{CompilerExtensionsResources.Struct}"">
<ApplicableSymbolKindList>
<TypeKind>Struct</TypeKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""d8af8dc6-1ade-441d-9947-8946922e198a"" Name=""{CompilerExtensionsResources.Enum}"">
<ApplicableSymbolKindList>
<TypeKind>Enum</TypeKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""408a3347-b908-4b54-a954-1355e64c1de3"" Name=""{CompilerExtensionsResources.Delegate}"">
<ApplicableSymbolKindList>
<TypeKind>Delegate</TypeKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""830657f6-e7e5-4830-b328-f109d3b6c165"" Name=""{CompilerExtensionsResources.Event}"">
<ApplicableSymbolKindList>
<SymbolKind>Event</SymbolKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""390caed4-f0a9-42bb-adbb-b44c4a302a22"" Name=""{CompilerExtensionsResources.Method}"">
<ApplicableSymbolKindList>
<MethodKind>Ordinary</MethodKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""af410767-f189-47c6-b140-aeccf1ff242e"" Name=""{CompilerExtensionsResources.Private_Method}"">
<ApplicableSymbolKindList>
<MethodKind>Ordinary</MethodKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Private</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""8076757e-6a4a-47f1-9b4b-ae8a3284e987"" Name=""{CompilerExtensionsResources.Abstract_Method}"">
<ApplicableSymbolKindList>
<MethodKind>Ordinary</MethodKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList>
<ModifierKind>IsAbstract</ModifierKind>
</RequiredModifierList>
</SymbolSpecification>
<SymbolSpecification ID=""16133061-a8e7-4392-92c3-1d93cd54c218"" Name=""{CompilerExtensionsResources.Static_Method}"">
<ApplicableSymbolKindList>
<MethodKind>Ordinary</MethodKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList>
<ModifierKind>IsStatic</ModifierKind>
</RequiredModifierList>
</SymbolSpecification>
<SymbolSpecification ID=""da6a2919-5aa6-4ad1-a24d-576776ed3974"" Name=""{CompilerExtensionsResources.Property}"">
<ApplicableSymbolKindList>
<SymbolKind>Property</SymbolKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""b24a91ce-3501-4799-b6df-baf044156c83"" Name=""{CompilerExtensionsResources.Public_or_Protected_Field}"">
<ApplicableSymbolKindList>
<SymbolKind>Field</SymbolKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""70af42cb-1741-4027-969c-9edc4877d965"" Name=""{CompilerExtensionsResources.Static_Field}"">
<ApplicableSymbolKindList>
<SymbolKind>Field</SymbolKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList>
<ModifierKind>IsStatic</ModifierKind>
</RequiredModifierList>
</SymbolSpecification>
<SymbolSpecification ID=""10790aa6-0a0b-432d-a52d-d252ca92302b"" Name=""{CompilerExtensionsResources.Private_or_Internal_Field}"">
<ApplicableSymbolKindList>
<SymbolKind>Field</SymbolKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""ac995be4-88de-4771-9dcc-a456a7c02d89"" Name=""{CompilerExtensionsResources.Private_or_Internal_Static_Field}"">
<ApplicableSymbolKindList>
<SymbolKind>Field</SymbolKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList>
<ModifierKind>IsStatic</ModifierKind>
</RequiredModifierList>
</SymbolSpecification>
<SymbolSpecification ID=""2c07f5bf-bc81-4c2b-82b4-ae9b3ffd0ba4"" Name=""{CompilerExtensionsResources.Types}"">
<ApplicableSymbolKindList>
<TypeKind>Class</TypeKind>
<TypeKind>Struct</TypeKind>
<TypeKind>Interface</TypeKind>
<TypeKind>Enum</TypeKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
<SymbolSpecification ID=""5f3ddba1-279f-486c-801e-5c097c36dd85"" Name=""{CompilerExtensionsResources.Non_Field_Members}"">
<ApplicableSymbolKindList>
<SymbolKind>Property</SymbolKind>
<SymbolKind>Event</SymbolKind>
<MethodKind>Ordinary</MethodKind>
</ApplicableSymbolKindList>
<ApplicableAccessibilityList>
<AccessibilityKind>Public</AccessibilityKind>
<AccessibilityKind>Internal</AccessibilityKind>
<AccessibilityKind>Private</AccessibilityKind>
<AccessibilityKind>Protected</AccessibilityKind>
<AccessibilityKind>ProtectedOrInternal</AccessibilityKind>
<AccessibilityKind>ProtectedAndInternal</AccessibilityKind>
</ApplicableAccessibilityList>
<RequiredModifierList />
</SymbolSpecification>
</SymbolSpecifications>
<NamingStyles>
<NamingStyle ID=""87e7c501-9948-4b53-b1eb-a6cbe918feee"" Name=""{CompilerExtensionsResources.Pascal_Case}"" Prefix="""" Suffix="""" WordSeparator="""" CapitalizationScheme=""PascalCase"" />
<NamingStyle ID=""1ecc5eb6-b5fc-49a5-a9f1-a980f3e48c92"" Name=""{CompilerExtensionsResources.Begins_with_I}"" Prefix=""I"" Suffix="""" WordSeparator="""" CapitalizationScheme=""PascalCase"" />
</NamingStyles>
<NamingRules>
<SerializableNamingRule SymbolSpecificationID=""23d856b4-5089-4405-83ce-749aada99153"" NamingStyleID=""1ecc5eb6-b5fc-49a5-a9f1-a980f3e48c92"" EnforcementLevel=""Info"" />
<SerializableNamingRule SymbolSpecificationID=""2c07f5bf-bc81-4c2b-82b4-ae9b3ffd0ba4"" NamingStyleID=""87e7c501-9948-4b53-b1eb-a6cbe918feee"" EnforcementLevel=""Info"" />
<SerializableNamingRule SymbolSpecificationID=""5f3ddba1-279f-486c-801e-5c097c36dd85"" NamingStyleID=""87e7c501-9948-4b53-b1eb-a6cbe918feee"" EnforcementLevel=""Info"" />
</NamingRules>
</NamingPreferencesInfo>
";
private static XElement GetUpgradedSerializationIfNecessary(XElement rootElement)
{
var serializationVersion = int.Parse(rootElement.Attribute("SerializationVersion").Value);
if (serializationVersion == 4)
{
UpgradeSerialization_4To5(rootElement = new XElement(rootElement));
serializationVersion = 5;
}
// Add future version checks here. If the version is off by more than 1, these upgrades will run in sequence.
// The next one should check serializationVersion == 5 and update it to 6.
// It is also important to create a new roaming location in NamingStyleOptions.NamingPreferences
// so that we never store the new format in an older version.
Debug.Assert(s_serializationVersion == 5, "After increasing the serialization version, add an upgrade path here.");
return serializationVersion == s_serializationVersion
? rootElement
: XElement.Parse(DefaultNamingPreferencesString);
}
private static void UpgradeSerialization_4To5(XElement rootElement)
{
var methodElements = rootElement
.Descendants()
.Where(e => e.Name.LocalName == "SymbolKind" && e.Value == "Method").ToList();
foreach (var element in methodElements)
{
element.ReplaceWith(XElement.Parse("<MethodKind>Ordinary</MethodKind>"));
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractFormattingResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
internal abstract class AbstractFormattingResult : IFormattingResult
{
protected readonly TreeData TreeInfo;
protected readonly TokenStream TokenStream;
private readonly CancellableLazy<IList<TextChange>> _lazyChanges;
private readonly CancellableLazy<SyntaxNode> _lazyNode;
/// <summary>
/// span in the tree to format
/// </summary>
public readonly TextSpan FormattedSpan;
internal AbstractFormattingResult(
TreeData treeInfo,
TokenStream tokenStream,
TextSpan formattedSpan)
{
this.TreeInfo = treeInfo;
this.TokenStream = tokenStream;
this.FormattedSpan = formattedSpan;
_lazyChanges = new CancellableLazy<IList<TextChange>>(CreateTextChanges);
_lazyNode = new CancellableLazy<SyntaxNode>(CreateFormattedRoot);
}
/// <summary>
/// rewrite the tree info root node with the trivia information in the map
/// </summary>
protected abstract SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> map, CancellationToken cancellationToken);
#region IFormattingResult implementation
public IList<TextChange> GetTextChanges(CancellationToken cancellationToken)
=> _lazyChanges.GetValue(cancellationToken);
public SyntaxNode GetFormattedRoot(CancellationToken cancellationToken)
=> _lazyNode.GetValue(cancellationToken);
private IList<TextChange> CreateTextChanges(CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Formatting_CreateTextChanges, cancellationToken))
{
var data = this.TokenStream.GetTriviaDataWithTokenPair(cancellationToken);
var result = new List<TextChange>();
foreach (var f in data)
{
if (!f.Item2.ContainsChanges)
{
continue;
}
cancellationToken.ThrowIfCancellationRequested();
AddTextChanges(result, f.Item1.Item1, f.Item1.Item2, f.Item2);
}
return result;
}
}
private void AddTextChanges(List<TextChange> list, SyntaxToken token1, SyntaxToken token2, TriviaData data)
{
var span = TextSpan.FromBounds(token1.RawKind == 0 ? this.TreeInfo.StartPosition : token1.Span.End, token2.RawKind == 0 ? this.TreeInfo.EndPosition : token2.SpanStart);
var originalString = this.TreeInfo.GetTextBetween(token1, token2);
foreach (var change in data.GetTextChanges(span))
{
var oldText = (change.Span == span) ? originalString : originalString.Substring(change.Span.Start - span.Start, change.Span.Length);
list.Add(change.SimpleDiff(oldText));
}
}
private SyntaxNode CreateFormattedRoot(CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Formatting_CreateFormattedRoot, cancellationToken))
{
var changes = GetChanges(cancellationToken);
// create a map
using var pooledObject = SharedPools.Default<Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData>>().GetPooledObject();
var map = pooledObject.Object;
changes.Do(change => map.Add(change.Item1, change.Item2));
// no changes, return as it is.
if (map.Count == 0)
{
return this.TreeInfo.Root;
}
return Rewriter(map, cancellationToken);
}
}
internal IEnumerable<ValueTuple<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData>> GetChanges(CancellationToken cancellationToken)
=> TokenStream.GetTriviaDataWithTokenPair(cancellationToken).Where(d => d.Item2.ContainsChanges);
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
internal abstract class AbstractFormattingResult : IFormattingResult
{
protected readonly TreeData TreeInfo;
protected readonly TokenStream TokenStream;
private readonly CancellableLazy<IList<TextChange>> _lazyChanges;
private readonly CancellableLazy<SyntaxNode> _lazyNode;
/// <summary>
/// span in the tree to format
/// </summary>
public readonly TextSpan FormattedSpan;
internal AbstractFormattingResult(
TreeData treeInfo,
TokenStream tokenStream,
TextSpan formattedSpan)
{
this.TreeInfo = treeInfo;
this.TokenStream = tokenStream;
this.FormattedSpan = formattedSpan;
_lazyChanges = new CancellableLazy<IList<TextChange>>(CreateTextChanges);
_lazyNode = new CancellableLazy<SyntaxNode>(CreateFormattedRoot);
}
/// <summary>
/// rewrite the tree info root node with the trivia information in the map
/// </summary>
protected abstract SyntaxNode Rewriter(Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData> map, CancellationToken cancellationToken);
#region IFormattingResult implementation
public IList<TextChange> GetTextChanges(CancellationToken cancellationToken)
=> _lazyChanges.GetValue(cancellationToken);
public SyntaxNode GetFormattedRoot(CancellationToken cancellationToken)
=> _lazyNode.GetValue(cancellationToken);
private IList<TextChange> CreateTextChanges(CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Formatting_CreateTextChanges, cancellationToken))
{
var data = this.TokenStream.GetTriviaDataWithTokenPair(cancellationToken);
var result = new List<TextChange>();
foreach (var f in data)
{
if (!f.Item2.ContainsChanges)
{
continue;
}
cancellationToken.ThrowIfCancellationRequested();
AddTextChanges(result, f.Item1.Item1, f.Item1.Item2, f.Item2);
}
return result;
}
}
private void AddTextChanges(List<TextChange> list, SyntaxToken token1, SyntaxToken token2, TriviaData data)
{
var span = TextSpan.FromBounds(token1.RawKind == 0 ? this.TreeInfo.StartPosition : token1.Span.End, token2.RawKind == 0 ? this.TreeInfo.EndPosition : token2.SpanStart);
var originalString = this.TreeInfo.GetTextBetween(token1, token2);
foreach (var change in data.GetTextChanges(span))
{
var oldText = (change.Span == span) ? originalString : originalString.Substring(change.Span.Start - span.Start, change.Span.Length);
list.Add(change.SimpleDiff(oldText));
}
}
private SyntaxNode CreateFormattedRoot(CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Formatting_CreateFormattedRoot, cancellationToken))
{
var changes = GetChanges(cancellationToken);
// create a map
using var pooledObject = SharedPools.Default<Dictionary<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData>>().GetPooledObject();
var map = pooledObject.Object;
changes.Do(change => map.Add(change.Item1, change.Item2));
// no changes, return as it is.
if (map.Count == 0)
{
return this.TreeInfo.Root;
}
return Rewriter(map, cancellationToken);
}
}
internal IEnumerable<ValueTuple<ValueTuple<SyntaxToken, SyntaxToken>, TriviaData>> GetChanges(CancellationToken cancellationToken)
=> TokenStream.GetTriviaDataWithTokenPair(cancellationToken).Where(d => d.Item2.ContainsChanges);
#endregion
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IReturnStatement.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IReturnStatement : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void SimpleReturnFromRegularMethod()
{
string source = @"
class C
{
static void Method()
{
/*<bind>*/return;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return;')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ReturnStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ReturnWithValueFromRegularMethod()
{
string source = @"
class C
{
static bool Method()
{
/*<bind>*/return true;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return true;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ReturnStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void YieldReturnFromRegularMethod()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> Method()
{
/*<bind>*/yield return 0;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 0;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<YieldStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void YieldBreakFromRegularMethod()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> Method()
{
yield return 0;
/*<bind>*/yield break;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IReturnOperation (OperationKind.YieldBreak, Type: null) (Syntax: 'yield break;')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<YieldStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(7299, "https://github.com/dotnet/roslyn/issues/7299")]
public void Return_ConstantConversions_01()
{
string source = @"
class C
{
static float Method()
{
/*<bind>*/return 0.0;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return 0.0;')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Single, Constant: 0, IsInvalid, IsImplicit) (Syntax: '0.0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsInvalid) (Syntax: '0.0')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// (6,26): error CS0664: Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type
// /*<bind>*/return 0.0;/*</bind>*/
Diagnostic(ErrorCode.ERR_LiteralDoubleCast, "0.0").WithArguments("F", "float").WithLocation(6, 26)
};
VerifyOperationTreeAndDiagnosticsForTest<ReturnStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_01()
{
var source = @"
class C
{
void F()
/*<bind>*/{
return;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Exit
Predecessors: [B0]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_02()
{
var source = @"
class C
{
int F()
/*<bind>*/{
return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Return) Block[B2]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_03()
{
var source = @"
class C
{
void F(bool a)
/*<bind>*/{
return;
a = true;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,9): warning CS0162: Unreachable code detected
// a = true;
Diagnostic(ErrorCode.WRN_UnreachableCode, "a").WithLocation(7, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
Block[B1] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B0] [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_04()
{
var source = @"
class C
{
int F(bool a)
/*<bind>*/{
return 1;
a = true;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,9): warning CS0162: Unreachable code detected
// a = true;
Diagnostic(ErrorCode.WRN_UnreachableCode, "a").WithLocation(7, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Return) Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_05()
{
var source = @"
class C
{
object F(object a, object b)
/*<bind>*/{
return a ?? b;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'a')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'a')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'a')
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Next (Return) Block[B5]
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'a ?? b')
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_06()
{
var source = @"
class C
{
int F(bool a)
/*<bind>*/{
if (a)
{
return 1;
}
else
{
return 2;
}
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_07()
{
var source = @"
class C
{
void F(bool a)
/*<bind>*/{
if (a)
{
return;
}
else
{
a = true;
}
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_08()
{
var source = @"
class C
{
void F(bool a)
/*<bind>*/{
if (a)
{
a = false;
}
else
{
return;
}
a = true;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = false')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_09()
{
var source = @"
class C
{
int F(bool a, bool b)
/*<bind>*/{
if (a)
{
b = false;
}
else
{
b = true;
}
return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = false')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Next (Return) Block[B5]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_10()
{
var source = @"
class C
{
int F()
/*<bind>*/{
return 1;
return 2;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,9): warning CS0162: Unreachable code detected
// return 2;
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(7, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Return) Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (0)
Next (Return) Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_11()
{
var source = @"
class C
{
void F()
/*<bind>*/{
return;
return;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,9): warning CS0162: Unreachable code detected
// return;
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(7, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Exit
Predecessors: [B0]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_12()
{
var source = @"
class C
{
int F(int a)
/*<bind>*/{
{
int b = 0;
a = b;
}
return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 b]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 0')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = b;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = b')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'b')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_13()
{
var source = @"
class C
{
int F(int a)
/*<bind>*/{
a = 0;
try
{
return 1;
}
finally
{
a = 2;
}
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 0;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = 0')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R1} {R2}
.try {R1, R2}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Finalizing: {R3}
Leaving: {R2} {R1}
}
.finally {R3}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = 2')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (StructuredExceptionHandling) Block[null]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_14()
{
var source = @"
class C
{
int F(int a)
/*<bind>*/{
try
{
a = 2;
}
catch
{
}
return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.try {R1, R2}
{
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = 2')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B3]
Leaving: {R2} {R1}
}
.catch {R3} (System.Object)
{
Block[B2] - Block
Predecessors (0)
Statements (0)
Next (Regular) Block[B3]
Leaving: {R3} {R1}
}
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B4] - Exit
Predecessors: [B3]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_15()
{
var source = @"
class C
{
int F(int a)
/*<bind>*/{
try
{
a = 2;
}
finally
{
a = 3;
}
return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.try {R1, R2}
{
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = 2')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B3]
Finalizing: {R3}
Leaving: {R2} {R1}
}
.finally {R3}
{
Block[B2] - Block
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 3;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = 3')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (StructuredExceptionHandling) Block[null]
}
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B4] - Exit
Predecessors: [B3]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_16()
{
var source = @"
class C
{
int F(bool a)
/*<bind>*/{
do
{
}
while (a);
return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B1]
Statements (0)
Jump if True (Regular) to Block[B1]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_17()
{
var source = @"
class C
{
int F(bool a)
/*<bind>*/{
if (a) return 1;
goto label1;
label1:
goto label2;
label2:
return 2;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_18()
{
var source = @"
class C
{
int F(bool a)
/*<bind>*/{
a = true;
goto label1;
label2:
if (a) return 1;
return 2;
label1:
goto label2;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_01()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F()
/*<bind>*/{
yield break;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Exit
Predecessors: [B0]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_02()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F()
/*<bind>*/{
yield return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 1;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_03()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F(bool a)
/*<bind>*/{
yield break;
a = true;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,9): warning CS0162: Unreachable code detected
// a = true;
Diagnostic(ErrorCode.WRN_UnreachableCode, "a").WithLocation(7, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
Block[B1] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B0] [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_04()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F(bool a)
/*<bind>*/{
yield return 1;
a = true;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 1;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_05()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<object> F(object a, object b)
/*<bind>*/{
yield return a ?? b;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'a')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'a')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'a')
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return a ?? b;')
ReturnedValue:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'a ?? b')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_06()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F(bool a)
/*<bind>*/{
if (a)
{
yield return 1;
}
else
{
yield return 2;
}
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 1;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 2;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_07()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F(bool a)
/*<bind>*/{
if (a)
{
yield break;
}
else
{
a = true;
}
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_08()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F(bool a)
/*<bind>*/{
if (a)
{
a = false;
}
else
{
yield break;
}
a = true;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = false')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_09()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F()
/*<bind>*/{
yield return 1;
yield return 2;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 1;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 2;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_10()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F()
/*<bind>*/{
yield break;
yield break;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,9): warning CS0162: Unreachable code detected
// yield break;
Diagnostic(ErrorCode.WRN_UnreachableCode, "yield").WithLocation(7, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Exit
Predecessors: [B0]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IReturnStatement : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void SimpleReturnFromRegularMethod()
{
string source = @"
class C
{
static void Method()
{
/*<bind>*/return;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return;')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ReturnStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ReturnWithValueFromRegularMethod()
{
string source = @"
class C
{
static bool Method()
{
/*<bind>*/return true;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return true;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<ReturnStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void YieldReturnFromRegularMethod()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> Method()
{
/*<bind>*/yield return 0;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 0;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<YieldStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void YieldBreakFromRegularMethod()
{
string source = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> Method()
{
yield return 0;
/*<bind>*/yield break;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IReturnOperation (OperationKind.YieldBreak, Type: null) (Syntax: 'yield break;')
ReturnedValue:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<YieldStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(7299, "https://github.com/dotnet/roslyn/issues/7299")]
public void Return_ConstantConversions_01()
{
string source = @"
class C
{
static float Method()
{
/*<bind>*/return 0.0;/*</bind>*/
}
}
";
string expectedOperationTree = @"
IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return 0.0;')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Single, Constant: 0, IsInvalid, IsImplicit) (Syntax: '0.0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsInvalid) (Syntax: '0.0')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// (6,26): error CS0664: Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type
// /*<bind>*/return 0.0;/*</bind>*/
Diagnostic(ErrorCode.ERR_LiteralDoubleCast, "0.0").WithArguments("F", "float").WithLocation(6, 26)
};
VerifyOperationTreeAndDiagnosticsForTest<ReturnStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_01()
{
var source = @"
class C
{
void F()
/*<bind>*/{
return;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Exit
Predecessors: [B0]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_02()
{
var source = @"
class C
{
int F()
/*<bind>*/{
return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Return) Block[B2]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_03()
{
var source = @"
class C
{
void F(bool a)
/*<bind>*/{
return;
a = true;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,9): warning CS0162: Unreachable code detected
// a = true;
Diagnostic(ErrorCode.WRN_UnreachableCode, "a").WithLocation(7, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
Block[B1] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B0] [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_04()
{
var source = @"
class C
{
int F(bool a)
/*<bind>*/{
return 1;
a = true;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,9): warning CS0162: Unreachable code detected
// a = true;
Diagnostic(ErrorCode.WRN_UnreachableCode, "a").WithLocation(7, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Return) Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_05()
{
var source = @"
class C
{
object F(object a, object b)
/*<bind>*/{
return a ?? b;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'a')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'a')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'a')
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Next (Return) Block[B5]
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'a ?? b')
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_06()
{
var source = @"
class C
{
int F(bool a)
/*<bind>*/{
if (a)
{
return 1;
}
else
{
return 2;
}
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_07()
{
var source = @"
class C
{
void F(bool a)
/*<bind>*/{
if (a)
{
return;
}
else
{
a = true;
}
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_08()
{
var source = @"
class C
{
void F(bool a)
/*<bind>*/{
if (a)
{
a = false;
}
else
{
return;
}
a = true;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = false')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_09()
{
var source = @"
class C
{
int F(bool a, bool b)
/*<bind>*/{
if (a)
{
b = false;
}
else
{
b = true;
}
return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = false')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = true')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Next (Return) Block[B5]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_10()
{
var source = @"
class C
{
int F()
/*<bind>*/{
return 1;
return 2;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,9): warning CS0162: Unreachable code detected
// return 2;
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(7, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Return) Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (0)
Next (Return) Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_11()
{
var source = @"
class C
{
void F()
/*<bind>*/{
return;
return;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,9): warning CS0162: Unreachable code detected
// return;
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(7, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Exit
Predecessors: [B0]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_12()
{
var source = @"
class C
{
int F(int a)
/*<bind>*/{
{
int b = 0;
a = b;
}
return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 b]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'b = 0')
Left:
ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'b = 0')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = b;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = b')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'b')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_13()
{
var source = @"
class C
{
int F(int a)
/*<bind>*/{
a = 0;
try
{
return 1;
}
finally
{
a = 2;
}
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 0;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = 0')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
Next (Regular) Block[B2]
Entering: {R1} {R2}
.try {R1, R2}
{
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Finalizing: {R3}
Leaving: {R2} {R1}
}
.finally {R3}
{
Block[B3] - Block
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = 2')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (StructuredExceptionHandling) Block[null]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_14()
{
var source = @"
class C
{
int F(int a)
/*<bind>*/{
try
{
a = 2;
}
catch
{
}
return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.try {R1, R2}
{
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = 2')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B3]
Leaving: {R2} {R1}
}
.catch {R3} (System.Object)
{
Block[B2] - Block
Predecessors (0)
Statements (0)
Next (Regular) Block[B3]
Leaving: {R3} {R1}
}
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B4] - Exit
Predecessors: [B3]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_15()
{
var source = @"
class C
{
int F(int a)
/*<bind>*/{
try
{
a = 2;
}
finally
{
a = 3;
}
return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.try {R1, R2}
{
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 2;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = 2')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B3]
Finalizing: {R3}
Leaving: {R2} {R1}
}
.finally {R3}
{
Block[B2] - Block
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = 3;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'a = 3')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (StructuredExceptionHandling) Block[null]
}
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B4] - Exit
Predecessors: [B3]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_16()
{
var source = @"
class C
{
int F(bool a)
/*<bind>*/{
do
{
}
while (a);
return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B1]
Statements (0)
Jump if True (Regular) to Block[B1]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_17()
{
var source = @"
class C
{
int F(bool a)
/*<bind>*/{
if (a) return 1;
goto label1;
label1:
goto label2;
label2:
return 2;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void ReturnFlow_18()
{
var source = @"
class C
{
int F(bool a)
/*<bind>*/{
a = true;
goto label1;
label2:
if (a) return 1;
return 2;
label1:
goto label2;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Block[B3] - Block
Predecessors: [B1]
Statements (0)
Next (Return) Block[B4]
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_01()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F()
/*<bind>*/{
yield break;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Exit
Predecessors: [B0]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_02()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F()
/*<bind>*/{
yield return 1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 1;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_03()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F(bool a)
/*<bind>*/{
yield break;
a = true;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,9): warning CS0162: Unreachable code detected
// a = true;
Diagnostic(ErrorCode.WRN_UnreachableCode, "a").WithLocation(7, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
Block[B1] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B0] [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_04()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F(bool a)
/*<bind>*/{
yield return 1;
a = true;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 1;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_05()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<object> F(object a, object b)
/*<bind>*/{
yield return a ?? b;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'a')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'a')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'a')
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return a ?? b;')
ReturnedValue:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'a ?? b')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_06()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F(bool a)
/*<bind>*/{
if (a)
{
yield return 1;
}
else
{
yield return 2;
}
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 1;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 2;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B4] - Exit
Predecessors: [B2] [B3]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_07()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F(bool a)
/*<bind>*/{
if (a)
{
yield break;
}
else
{
a = true;
}
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_08()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F(bool a)
/*<bind>*/{
if (a)
{
a = false;
}
else
{
yield break;
}
a = true;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = false')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_09()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F()
/*<bind>*/{
yield return 1;
yield return 2;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 1;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IReturnOperation (OperationKind.YieldReturn, Type: null) (Syntax: 'yield return 2;')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void YieldFlow_10()
{
var source = @"
class C
{
System.Collections.Generic.IEnumerable<int> F()
/*<bind>*/{
yield break;
yield break;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,9): warning CS0162: Unreachable code detected
// yield break;
Diagnostic(ErrorCode.WRN_UnreachableCode, "yield").WithLocation(7, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Exit
Predecessors: [B0]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.pt-BR.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pt-BR" original="../CodeStyleResources.resx">
<body>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Um nome de idioma não pode ser especificado para essa opção.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">Um nome de idioma deve ser especificado para esta opção.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">As matrizes com mais de uma dimensão não podem ser serializadas.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Não é possível serializar o tipo '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">O leitor de desserialização para '{0}' lê o número incorreto de valores.</target>
<note />
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Erro</target>
<note />
</trans-unit>
<trans-unit id="Fix_formatting">
<source>Fix formatting</source>
<target state="translated">Corrigir a formatação</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Recuo e espaçamento</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Preferências de nova linha</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">NENHUM</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Somente Refatoração</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">O fluxo é muito longo.</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Sugestão</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">O tipo '{0}' não é compreendido pelo associador de serialização.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">Valor muito grande para ser representado como um inteiro não assinado de 30 bits.</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Aviso</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pt-BR" original="../CodeStyleResources.resx">
<body>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Um nome de idioma não pode ser especificado para essa opção.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">Um nome de idioma deve ser especificado para esta opção.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">As matrizes com mais de uma dimensão não podem ser serializadas.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Não é possível serializar o tipo '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">O leitor de desserialização para '{0}' lê o número incorreto de valores.</target>
<note />
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Erro</target>
<note />
</trans-unit>
<trans-unit id="Fix_formatting">
<source>Fix formatting</source>
<target state="translated">Corrigir a formatação</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Recuo e espaçamento</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Preferências de nova linha</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">NENHUM</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Somente Refatoração</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">O fluxo é muito longo.</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Sugestão</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">O tipo '{0}' não é compreendido pelo associador de serialização.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">Valor muito grande para ser representado como um inteiro não assinado de 30 bits.</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Aviso</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpRename.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpRename : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
private InlineRenameDialog_OutOfProc InlineRenameDialog => VisualStudio.InlineRenameDialog;
public CSharpRename(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpRename))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyLocalVariableRename()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int [|x|]$$ = 0;
[|x|] = 5;
TestMethod([|x|]);
}
static void TestMethod(int y)
{
}
}";
using (var telemetry = VisualStudio.EnableTestTelemetryChannel())
{
SetUpEditor(markup);
InlineRenameDialog.Invoke();
MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray<TextSpan> renameSpans);
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int y = 0;
y = 5;
TestMethod(y);
}
static void TestMethod(int y)
{
}
}");
telemetry.VerifyFired("vs/ide/vbcs/rename/inlinesession/session", "vs/ide/vbcs/rename/commitcore");
}
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public void VerifyAttributeRename()
{
var markup = @"
using System;
class [|$$ustom|]Attribute : Attribute
{
}
";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray<TextSpan> renameSpans);
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys("Custom", VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
using System;
class CustomAttribute : Attribute
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public void VerifyAttributeRenameWhileRenameClasss()
{
var markup = @"
using System;
class [|$$stom|]Attribute : Attribute
{
}
";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray<TextSpan> renameSpans);
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys("Custom");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Custom$$Attribute : Attribute
{
}
", true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public void VerifyAttributeRenameWhileRenameAttribute()
{
var markup = @"
using System;
[[|$$stom|]]
class Bar
{
}
class stomAttribute : Attribute
{
}
";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
MarkupTestFile.GetSpans(markup, out _, out ImmutableArray<TextSpan> _);
_ = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
VisualStudio.Editor.SendKeys("Custom");
VisualStudio.Editor.Verify.TextContains(@"
using System;
[Custom$$]
class Bar
{
}
class CustomAttribute : Attribute
{
}
", true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public void VerifyAttributeRenameWhileRenameAttributeClass()
{
var markup = @"
using System;
[stom]
class Bar
{
}
class [|$$stom|]Attribute : Attribute
{
}
";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
MarkupTestFile.GetSpans(markup, out _, out ImmutableArray<TextSpan> _);
_ = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
VisualStudio.Editor.SendKeys("Custom");
VisualStudio.Editor.Verify.TextContains(@"
using System;
[Custom]
class Bar
{
}
class Custom$$Attribute : Attribute
{
}
", true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyLocalVariableRenameWithCommentsUpdated()
{
// "variable" is intentionally misspelled as "varixable" and "this" is misspelled as
// "thix" below to ensure we don't change instances of "x" in comments that are part of
// larger words
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
/// <summary>
/// creates a varixable named [|x|] xx
/// </summary>
/// <param name=""args""></param>
static void Main(string[] args)
{
// thix varixable is named [|x|] xx
int [|x|]$$ = 0;
[|x|] = 5;
TestMethod([|x|]);
}
static void TestMethod(int y)
{
/*
* [|x|]
* xx
*/
}
}";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
InlineRenameDialog.ToggleIncludeComments();
MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray<TextSpan> renameSpans);
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
/// <summary>
/// creates a varixable named y xx
/// </summary>
/// <param name=""args""></param>
static void Main(string[] args)
{
// thix varixable is named y xx
int y = 0;
y = 5;
TestMethod(y);
}
static void TestMethod(int y)
{
/*
* y
* xx
*/
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyLocalVariableRenameWithStringsUpdated()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
int [|x|]$$ = 0;
[|x|] = 5;
var s = ""[|x|] xx [|x|]"";
var sLiteral =
@""
[|x|]
xx
[|x|]
"";
char c = 'x';
char cUnit = '\u0078';
}
}";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
InlineRenameDialog.ToggleIncludeStrings();
MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray<TextSpan> renameSpans);
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
class Program
{
static void Main(string[] args)
{
int y = 0;
y = 5;
var s = ""y xx y"";
var sLiteral =
@""
y
xx
y
"";
char c = 'x';
char cUnit = '\u0078';
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyOverloadsUpdated()
{
var markup = @"
interface I
{
void [|TestMethod|]$$(int y);
void [|TestMethod|](string y);
}
class B : I
{
public virtual void [|TestMethod|](int y)
{ }
public virtual void [|TestMethod|](string y)
{ }
}";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
InlineRenameDialog.ToggleIncludeOverloads();
MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray<TextSpan> renameSpans);
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
interface I
{
void y(int y);
void y(string y);
}
class B : I
{
public virtual void y(int y)
{ }
public virtual void y(string y)
{ }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyMultiFileRename()
{
SetUpEditor(@"
class $$Program
{
}");
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Class2.cs", @"");
VisualStudio.SolutionExplorer.OpenFile(project, "Class2.cs");
const string class2Markup = @"
class SomeOtherClass
{
void M()
{
[|Program|] p = new [|Program|]();
}
}";
MarkupTestFile.GetSpans(class2Markup, out var code, out ImmutableArray<TextSpan> renameSpans);
VisualStudio.Editor.SetText(code);
VisualStudio.Editor.PlaceCaret("Program");
InlineRenameDialog.Invoke();
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
class SomeOtherClass
{
void M()
{
y p = new y();
}
}");
VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs");
VisualStudio.Editor.Verify.TextContains(@"
class y
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyRenameCancellation()
{
SetUpEditor(@"
class $$Program
{
}");
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Class2.cs", @"");
VisualStudio.SolutionExplorer.OpenFile(project, "Class2.cs");
VisualStudio.Editor.SetText(@"
class SomeOtherClass
{
void M()
{
Program p = new Program();
}
}");
VisualStudio.Editor.PlaceCaret("Program");
InlineRenameDialog.Invoke();
VisualStudio.Editor.SendKeys(VirtualKey.Y);
VisualStudio.Editor.Verify.TextContains(@"class SomeOtherClass
{
void M()
{
y p = new y();
}
}");
VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs");
VisualStudio.Editor.Verify.TextContains(@"
class y
{
}");
VisualStudio.Editor.SendKeys(VirtualKey.Escape);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Rename);
VisualStudio.Editor.Verify.TextContains(@"
class Program
{
}");
VisualStudio.SolutionExplorer.OpenFile(project, "Class2.cs");
VisualStudio.Editor.Verify.TextContains(@"
class SomeOtherClass
{
void M()
{
Program p = new Program();
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyCrossProjectRename()
{
SetUpEditor(@"
$$class RenameRocks
{
static void Main(string[] args)
{
Class2 c = null;
c.ToString();
}
}");
var project1 = new ProjectUtils.Project(ProjectName);
var project2 = new ProjectUtils.Project("Project2");
VisualStudio.SolutionExplorer.AddProject(project2, WellKnownProjectTemplates.ClassLibrary, LanguageName);
VisualStudio.SolutionExplorer.AddProjectReference(fromProjectName: project1, toProjectName: new ProjectUtils.ProjectReference("Project2"));
VisualStudio.SolutionExplorer.AddFile(project2, "Class2.cs", @"");
VisualStudio.SolutionExplorer.OpenFile(project2, "Class2.cs");
VisualStudio.Editor.SetText(@"
public class Class2 { static void Main(string [] args) { } }");
VisualStudio.SolutionExplorer.OpenFile(project1, "Class1.cs");
VisualStudio.Editor.PlaceCaret("Class2");
InlineRenameDialog.Invoke();
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
class RenameRocks
{
static void Main(string[] args)
{
y c = null;
c.ToString();
}
}");
VisualStudio.SolutionExplorer.OpenFile(project2, "y.cs");
VisualStudio.Editor.Verify.TextContains(@"
public class y { static void Main(string [] args) { } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyRenameUndo()
{
VerifyCrossProjectRename();
VisualStudio.Editor.SendKeys(Ctrl(VirtualKey.Z));
VisualStudio.Editor.Verify.TextContains(@"
public class Class2 { static void Main(string [] args) { } }");
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs");
VisualStudio.Editor.Verify.TextContains(@"
class RenameRocks
{
static void Main(string[] args)
{
Class2 c = null;
c.ToString();
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyRenameInStandaloneFiles()
{
VisualStudio.SolutionExplorer.CloseSolution();
VisualStudio.SolutionExplorer.AddStandaloneFile("StandaloneFile1.cs");
VisualStudio.Editor.SetText(@"
class Program
{
void Goo()
{
var ids = 1;
ids = 2;
}
}");
VisualStudio.Editor.PlaceCaret("ids");
InlineRenameDialog.Invoke();
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
class Program
{
void Goo()
{
var y = 1;
y = 2;
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
[WorkItem(39617, "https://github.com/dotnet/roslyn/issues/39617")]
public void VerifyRenameCaseChange()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Program.cs",
@"
class Program
{
static void Main(string[] args)
{
}
}");
VisualStudio.SolutionExplorer.OpenFile(project, "Program.cs");
VisualStudio.Editor.PlaceCaret("Program");
InlineRenameDialog.Invoke();
VisualStudio.Editor.SendKeys(VirtualKey.Home, VirtualKey.Delete, VirtualKey.P, VirtualKey.Enter);
VisualStudio.SolutionExplorer.Verify.FileContents(project, "program.cs",
@"
class program
{
static void Main(string[] args)
{
}
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpRename : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
private InlineRenameDialog_OutOfProc InlineRenameDialog => VisualStudio.InlineRenameDialog;
public CSharpRename(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpRename))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyLocalVariableRename()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int [|x|]$$ = 0;
[|x|] = 5;
TestMethod([|x|]);
}
static void TestMethod(int y)
{
}
}";
using (var telemetry = VisualStudio.EnableTestTelemetryChannel())
{
SetUpEditor(markup);
InlineRenameDialog.Invoke();
MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray<TextSpan> renameSpans);
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int y = 0;
y = 5;
TestMethod(y);
}
static void TestMethod(int y)
{
}
}");
telemetry.VerifyFired("vs/ide/vbcs/rename/inlinesession/session", "vs/ide/vbcs/rename/commitcore");
}
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public void VerifyAttributeRename()
{
var markup = @"
using System;
class [|$$ustom|]Attribute : Attribute
{
}
";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray<TextSpan> renameSpans);
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys("Custom", VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
using System;
class CustomAttribute : Attribute
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public void VerifyAttributeRenameWhileRenameClasss()
{
var markup = @"
using System;
class [|$$stom|]Attribute : Attribute
{
}
";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray<TextSpan> renameSpans);
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys("Custom");
VisualStudio.Editor.Verify.TextContains(@"
using System;
class Custom$$Attribute : Attribute
{
}
", true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public void VerifyAttributeRenameWhileRenameAttribute()
{
var markup = @"
using System;
[[|$$stom|]]
class Bar
{
}
class stomAttribute : Attribute
{
}
";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
MarkupTestFile.GetSpans(markup, out _, out ImmutableArray<TextSpan> _);
_ = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
VisualStudio.Editor.SendKeys("Custom");
VisualStudio.Editor.Verify.TextContains(@"
using System;
[Custom$$]
class Bar
{
}
class CustomAttribute : Attribute
{
}
", true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public void VerifyAttributeRenameWhileRenameAttributeClass()
{
var markup = @"
using System;
[stom]
class Bar
{
}
class [|$$stom|]Attribute : Attribute
{
}
";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
MarkupTestFile.GetSpans(markup, out _, out ImmutableArray<TextSpan> _);
_ = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
VisualStudio.Editor.SendKeys("Custom");
VisualStudio.Editor.Verify.TextContains(@"
using System;
[Custom]
class Bar
{
}
class Custom$$Attribute : Attribute
{
}
", true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyLocalVariableRenameWithCommentsUpdated()
{
// "variable" is intentionally misspelled as "varixable" and "this" is misspelled as
// "thix" below to ensure we don't change instances of "x" in comments that are part of
// larger words
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
/// <summary>
/// creates a varixable named [|x|] xx
/// </summary>
/// <param name=""args""></param>
static void Main(string[] args)
{
// thix varixable is named [|x|] xx
int [|x|]$$ = 0;
[|x|] = 5;
TestMethod([|x|]);
}
static void TestMethod(int y)
{
/*
* [|x|]
* xx
*/
}
}";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
InlineRenameDialog.ToggleIncludeComments();
MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray<TextSpan> renameSpans);
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
/// <summary>
/// creates a varixable named y xx
/// </summary>
/// <param name=""args""></param>
static void Main(string[] args)
{
// thix varixable is named y xx
int y = 0;
y = 5;
TestMethod(y);
}
static void TestMethod(int y)
{
/*
* y
* xx
*/
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyLocalVariableRenameWithStringsUpdated()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
int [|x|]$$ = 0;
[|x|] = 5;
var s = ""[|x|] xx [|x|]"";
var sLiteral =
@""
[|x|]
xx
[|x|]
"";
char c = 'x';
char cUnit = '\u0078';
}
}";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
InlineRenameDialog.ToggleIncludeStrings();
MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray<TextSpan> renameSpans);
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
class Program
{
static void Main(string[] args)
{
int y = 0;
y = 5;
var s = ""y xx y"";
var sLiteral =
@""
y
xx
y
"";
char c = 'x';
char cUnit = '\u0078';
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyOverloadsUpdated()
{
var markup = @"
interface I
{
void [|TestMethod|]$$(int y);
void [|TestMethod|](string y);
}
class B : I
{
public virtual void [|TestMethod|](int y)
{ }
public virtual void [|TestMethod|](string y)
{ }
}";
SetUpEditor(markup);
InlineRenameDialog.Invoke();
InlineRenameDialog.ToggleIncludeOverloads();
MarkupTestFile.GetSpans(markup, out var _, out ImmutableArray<TextSpan> renameSpans);
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
interface I
{
void y(int y);
void y(string y);
}
class B : I
{
public virtual void y(int y)
{ }
public virtual void y(string y)
{ }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyMultiFileRename()
{
SetUpEditor(@"
class $$Program
{
}");
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Class2.cs", @"");
VisualStudio.SolutionExplorer.OpenFile(project, "Class2.cs");
const string class2Markup = @"
class SomeOtherClass
{
void M()
{
[|Program|] p = new [|Program|]();
}
}";
MarkupTestFile.GetSpans(class2Markup, out var code, out ImmutableArray<TextSpan> renameSpans);
VisualStudio.Editor.SetText(code);
VisualStudio.Editor.PlaceCaret("Program");
InlineRenameDialog.Invoke();
var tags = VisualStudio.Editor.GetTagSpans(InlineRenameDialog.ValidRenameTag);
AssertEx.SetEqual(renameSpans, tags);
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
class SomeOtherClass
{
void M()
{
y p = new y();
}
}");
VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs");
VisualStudio.Editor.Verify.TextContains(@"
class y
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyRenameCancellation()
{
SetUpEditor(@"
class $$Program
{
}");
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Class2.cs", @"");
VisualStudio.SolutionExplorer.OpenFile(project, "Class2.cs");
VisualStudio.Editor.SetText(@"
class SomeOtherClass
{
void M()
{
Program p = new Program();
}
}");
VisualStudio.Editor.PlaceCaret("Program");
InlineRenameDialog.Invoke();
VisualStudio.Editor.SendKeys(VirtualKey.Y);
VisualStudio.Editor.Verify.TextContains(@"class SomeOtherClass
{
void M()
{
y p = new y();
}
}");
VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs");
VisualStudio.Editor.Verify.TextContains(@"
class y
{
}");
VisualStudio.Editor.SendKeys(VirtualKey.Escape);
VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Rename);
VisualStudio.Editor.Verify.TextContains(@"
class Program
{
}");
VisualStudio.SolutionExplorer.OpenFile(project, "Class2.cs");
VisualStudio.Editor.Verify.TextContains(@"
class SomeOtherClass
{
void M()
{
Program p = new Program();
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyCrossProjectRename()
{
SetUpEditor(@"
$$class RenameRocks
{
static void Main(string[] args)
{
Class2 c = null;
c.ToString();
}
}");
var project1 = new ProjectUtils.Project(ProjectName);
var project2 = new ProjectUtils.Project("Project2");
VisualStudio.SolutionExplorer.AddProject(project2, WellKnownProjectTemplates.ClassLibrary, LanguageName);
VisualStudio.SolutionExplorer.AddProjectReference(fromProjectName: project1, toProjectName: new ProjectUtils.ProjectReference("Project2"));
VisualStudio.SolutionExplorer.AddFile(project2, "Class2.cs", @"");
VisualStudio.SolutionExplorer.OpenFile(project2, "Class2.cs");
VisualStudio.Editor.SetText(@"
public class Class2 { static void Main(string [] args) { } }");
VisualStudio.SolutionExplorer.OpenFile(project1, "Class1.cs");
VisualStudio.Editor.PlaceCaret("Class2");
InlineRenameDialog.Invoke();
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
class RenameRocks
{
static void Main(string[] args)
{
y c = null;
c.ToString();
}
}");
VisualStudio.SolutionExplorer.OpenFile(project2, "y.cs");
VisualStudio.Editor.Verify.TextContains(@"
public class y { static void Main(string [] args) { } }");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyRenameUndo()
{
VerifyCrossProjectRename();
VisualStudio.Editor.SendKeys(Ctrl(VirtualKey.Z));
VisualStudio.Editor.Verify.TextContains(@"
public class Class2 { static void Main(string [] args) { } }");
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs");
VisualStudio.Editor.Verify.TextContains(@"
class RenameRocks
{
static void Main(string[] args)
{
Class2 c = null;
c.ToString();
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
public void VerifyRenameInStandaloneFiles()
{
VisualStudio.SolutionExplorer.CloseSolution();
VisualStudio.SolutionExplorer.AddStandaloneFile("StandaloneFile1.cs");
VisualStudio.Editor.SetText(@"
class Program
{
void Goo()
{
var ids = 1;
ids = 2;
}
}");
VisualStudio.Editor.PlaceCaret("ids");
InlineRenameDialog.Invoke();
VisualStudio.Editor.SendKeys(VirtualKey.Y, VirtualKey.Enter);
VisualStudio.Editor.Verify.TextContains(@"
class Program
{
void Goo()
{
var y = 1;
y = 2;
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Rename)]
[WorkItem(39617, "https://github.com/dotnet/roslyn/issues/39617")]
public void VerifyRenameCaseChange()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Program.cs",
@"
class Program
{
static void Main(string[] args)
{
}
}");
VisualStudio.SolutionExplorer.OpenFile(project, "Program.cs");
VisualStudio.Editor.PlaceCaret("Program");
InlineRenameDialog.Invoke();
VisualStudio.Editor.SendKeys(VirtualKey.Home, VirtualKey.Delete, VirtualKey.P, VirtualKey.Enter);
VisualStudio.SolutionExplorer.Verify.FileContents(project, "program.cs",
@"
class program
{
static void Main(string[] args)
{
}
}");
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/QuickInfo/CommonQuickInfoProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.QuickInfo
{
internal abstract class CommonQuickInfoProvider : QuickInfoProvider
{
protected abstract Task<QuickInfoItem?> BuildQuickInfoAsync(QuickInfoContext context, SyntaxToken token);
protected abstract Task<QuickInfoItem?> BuildQuickInfoAsync(CommonQuickInfoContext context, SyntaxToken token);
public override async Task<QuickInfoItem?> GetQuickInfoAsync(QuickInfoContext context)
{
var cancellationToken = context.CancellationToken;
var tree = await context.Document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var tokens = await GetTokensAsync(tree, context.Position, context.CancellationToken).ConfigureAwait(false);
foreach (var token in tokens)
{
var info = await GetQuickInfoAsync(context, token).ConfigureAwait(false);
if (info != null)
return info;
}
return null;
}
public async Task<QuickInfoItem?> GetQuickInfoAsync(CommonQuickInfoContext context)
{
var tokens = await GetTokensAsync(context.SemanticModel.SyntaxTree, context.Position, context.CancellationToken).ConfigureAwait(false);
foreach (var token in tokens)
{
var info = await GetQuickInfoAsync(context, token).ConfigureAwait(false);
if (info != null)
return info;
}
return null;
}
protected async Task<ImmutableArray<SyntaxToken>> GetTokensAsync(SyntaxTree tree, int position, System.Threading.CancellationToken cancellationToken)
{
using var result = TemporaryArray<SyntaxToken>.Empty;
var token = await tree.GetTouchingTokenAsync(position, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
if (token != default)
{
result.Add(token);
if (ShouldCheckPreviousToken(token))
{
token = token.GetPreviousToken();
if (token != default && token.Span.IntersectsWith(position))
result.Add(token);
}
}
return result.ToImmutableAndClear();
}
protected virtual bool ShouldCheckPreviousToken(SyntaxToken token)
=> true;
private async Task<QuickInfoItem?> GetQuickInfoAsync(
QuickInfoContext context,
SyntaxToken token)
{
if (token != default &&
token.Span.IntersectsWith(context.Position))
{
return await BuildQuickInfoAsync(context, token).ConfigureAwait(false);
}
return null;
}
private async Task<QuickInfoItem?> GetQuickInfoAsync(
CommonQuickInfoContext context,
SyntaxToken token)
{
if (token != default &&
token.Span.IntersectsWith(context.Position))
{
return await BuildQuickInfoAsync(context, token).ConfigureAwait(false);
}
return null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.QuickInfo
{
internal abstract class CommonQuickInfoProvider : QuickInfoProvider
{
protected abstract Task<QuickInfoItem?> BuildQuickInfoAsync(QuickInfoContext context, SyntaxToken token);
protected abstract Task<QuickInfoItem?> BuildQuickInfoAsync(CommonQuickInfoContext context, SyntaxToken token);
public override async Task<QuickInfoItem?> GetQuickInfoAsync(QuickInfoContext context)
{
var cancellationToken = context.CancellationToken;
var tree = await context.Document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var tokens = await GetTokensAsync(tree, context.Position, context.CancellationToken).ConfigureAwait(false);
foreach (var token in tokens)
{
var info = await GetQuickInfoAsync(context, token).ConfigureAwait(false);
if (info != null)
return info;
}
return null;
}
public async Task<QuickInfoItem?> GetQuickInfoAsync(CommonQuickInfoContext context)
{
var tokens = await GetTokensAsync(context.SemanticModel.SyntaxTree, context.Position, context.CancellationToken).ConfigureAwait(false);
foreach (var token in tokens)
{
var info = await GetQuickInfoAsync(context, token).ConfigureAwait(false);
if (info != null)
return info;
}
return null;
}
protected async Task<ImmutableArray<SyntaxToken>> GetTokensAsync(SyntaxTree tree, int position, System.Threading.CancellationToken cancellationToken)
{
using var result = TemporaryArray<SyntaxToken>.Empty;
var token = await tree.GetTouchingTokenAsync(position, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
if (token != default)
{
result.Add(token);
if (ShouldCheckPreviousToken(token))
{
token = token.GetPreviousToken();
if (token != default && token.Span.IntersectsWith(position))
result.Add(token);
}
}
return result.ToImmutableAndClear();
}
protected virtual bool ShouldCheckPreviousToken(SyntaxToken token)
=> true;
private async Task<QuickInfoItem?> GetQuickInfoAsync(
QuickInfoContext context,
SyntaxToken token)
{
if (token != default &&
token.Span.IntersectsWith(context.Position))
{
return await BuildQuickInfoAsync(context, token).ConfigureAwait(false);
}
return null;
}
private async Task<QuickInfoItem?> GetQuickInfoAsync(
CommonQuickInfoContext context,
SyntaxToken token)
{
if (token != default &&
token.Span.IntersectsWith(context.Position))
{
return await BuildQuickInfoAsync(context, token).ConfigureAwait(false);
}
return null;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/Core/Implementation/IntelliSense/AbstractController.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense
{
internal abstract class AbstractController<TSession, TModel, TPresenterSession, TEditorSession> : ForegroundThreadAffinitizedObject, IController<TModel>
where TSession : class, ISession<TModel>
where TPresenterSession : IIntelliSensePresenterSession
{
protected readonly ITextView TextView;
protected readonly ITextBuffer SubjectBuffer;
protected readonly IIntelliSensePresenter<TPresenterSession, TEditorSession> Presenter;
protected readonly IDocumentProvider DocumentProvider;
private readonly IAsynchronousOperationListener _asyncListener;
private readonly string _asyncOperationId;
// Null when we absolutely know we don't have any sort of item computation going on. Non
// null the moment we think we start computing state. Null again once we decide we can
// stop.
protected TSession sessionOpt;
protected bool IsSessionActive => sessionOpt != null;
protected AbstractController(IThreadingContext threadingContext, ITextView textView, ITextBuffer subjectBuffer, IIntelliSensePresenter<TPresenterSession, TEditorSession> presenter, IAsynchronousOperationListener asyncListener, IDocumentProvider documentProvider, string asyncOperationId)
: base(threadingContext)
{
this.TextView = textView;
this.SubjectBuffer = subjectBuffer;
this.Presenter = presenter;
_asyncListener = asyncListener;
this.DocumentProvider = documentProvider;
_asyncOperationId = asyncOperationId;
this.TextView.Closed += OnTextViewClosed;
// Caret position changed only fires if the caret is explicitly moved. It doesn't fire
// when the caret is moved because of text change events.
this.TextView.Caret.PositionChanged += this.OnCaretPositionChanged;
this.TextView.TextBuffer.PostChanged += this.OnTextViewBufferPostChanged;
}
internal abstract void OnModelUpdated(TModel result, bool updateController);
internal abstract void OnTextViewBufferPostChanged(object sender, EventArgs e);
internal abstract void OnCaretPositionChanged(object sender, EventArgs e);
private void OnTextViewClosed(object sender, EventArgs e)
{
AssertIsForeground();
DismissSessionIfActive();
this.TextView.Closed -= OnTextViewClosed;
this.TextView.Caret.PositionChanged -= this.OnCaretPositionChanged;
this.TextView.TextBuffer.PostChanged -= this.OnTextViewBufferPostChanged;
}
public TModel WaitForController()
{
AssertIsForeground();
VerifySessionIsActive();
return sessionOpt.WaitForController();
}
void IController<TModel>.OnModelUpdated(TModel result, bool updateController)
{
// This is only called from the model computation if it was not cancelled. And if it was
// not cancelled then we must have a pointer to it (as well as the presenter session).
AssertIsForeground();
VerifySessionIsActive();
this.OnModelUpdated(result, updateController);
}
IAsyncToken IController<TModel>.BeginAsyncOperation(string name, object tag, string filePath, int lineNumber)
{
AssertIsForeground();
VerifySessionIsActive();
name = String.IsNullOrEmpty(name)
? _asyncOperationId
: $"{_asyncOperationId} - {name}";
return _asyncListener.BeginAsyncOperation(name, tag, filePath: filePath, lineNumber: lineNumber);
}
protected void VerifySessionIsActive()
{
AssertIsForeground();
Contract.ThrowIfFalse(IsSessionActive);
}
protected void VerifySessionIsInactive()
{
AssertIsForeground();
Contract.ThrowIfTrue(IsSessionActive);
}
protected void DismissSessionIfActive()
{
AssertIsForeground();
if (IsSessionActive)
{
this.StopModelComputation();
}
}
public void StopModelComputation()
{
AssertIsForeground();
VerifySessionIsActive();
// Make a local copy so that we won't do anything that causes us to recurse and try to
// dismiss this again.
var localSession = sessionOpt;
sessionOpt = null;
localSession.Stop();
}
public bool TryHandleEscapeKey()
{
AssertIsForeground();
// Escape simply dismissed a session if it's up. Otherwise let the next thing in the
// chain handle us.
if (!IsSessionActive)
{
return false;
}
// If we haven't even computed a model yet, then also send this command to anyone
// listening. It's unlikely that the command was intended for us (as we wouldn't
// have even shown ui yet.
var handledCommand = sessionOpt.InitialUnfilteredModel != null;
// In the presence of an escape, we always stop what we're doing.
this.StopModelComputation();
return handledCommand;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense
{
internal abstract class AbstractController<TSession, TModel, TPresenterSession, TEditorSession> : ForegroundThreadAffinitizedObject, IController<TModel>
where TSession : class, ISession<TModel>
where TPresenterSession : IIntelliSensePresenterSession
{
protected readonly ITextView TextView;
protected readonly ITextBuffer SubjectBuffer;
protected readonly IIntelliSensePresenter<TPresenterSession, TEditorSession> Presenter;
protected readonly IDocumentProvider DocumentProvider;
private readonly IAsynchronousOperationListener _asyncListener;
private readonly string _asyncOperationId;
// Null when we absolutely know we don't have any sort of item computation going on. Non
// null the moment we think we start computing state. Null again once we decide we can
// stop.
protected TSession sessionOpt;
protected bool IsSessionActive => sessionOpt != null;
protected AbstractController(IThreadingContext threadingContext, ITextView textView, ITextBuffer subjectBuffer, IIntelliSensePresenter<TPresenterSession, TEditorSession> presenter, IAsynchronousOperationListener asyncListener, IDocumentProvider documentProvider, string asyncOperationId)
: base(threadingContext)
{
this.TextView = textView;
this.SubjectBuffer = subjectBuffer;
this.Presenter = presenter;
_asyncListener = asyncListener;
this.DocumentProvider = documentProvider;
_asyncOperationId = asyncOperationId;
this.TextView.Closed += OnTextViewClosed;
// Caret position changed only fires if the caret is explicitly moved. It doesn't fire
// when the caret is moved because of text change events.
this.TextView.Caret.PositionChanged += this.OnCaretPositionChanged;
this.TextView.TextBuffer.PostChanged += this.OnTextViewBufferPostChanged;
}
internal abstract void OnModelUpdated(TModel result, bool updateController);
internal abstract void OnTextViewBufferPostChanged(object sender, EventArgs e);
internal abstract void OnCaretPositionChanged(object sender, EventArgs e);
private void OnTextViewClosed(object sender, EventArgs e)
{
AssertIsForeground();
DismissSessionIfActive();
this.TextView.Closed -= OnTextViewClosed;
this.TextView.Caret.PositionChanged -= this.OnCaretPositionChanged;
this.TextView.TextBuffer.PostChanged -= this.OnTextViewBufferPostChanged;
}
public TModel WaitForController()
{
AssertIsForeground();
VerifySessionIsActive();
return sessionOpt.WaitForController();
}
void IController<TModel>.OnModelUpdated(TModel result, bool updateController)
{
// This is only called from the model computation if it was not cancelled. And if it was
// not cancelled then we must have a pointer to it (as well as the presenter session).
AssertIsForeground();
VerifySessionIsActive();
this.OnModelUpdated(result, updateController);
}
IAsyncToken IController<TModel>.BeginAsyncOperation(string name, object tag, string filePath, int lineNumber)
{
AssertIsForeground();
VerifySessionIsActive();
name = String.IsNullOrEmpty(name)
? _asyncOperationId
: $"{_asyncOperationId} - {name}";
return _asyncListener.BeginAsyncOperation(name, tag, filePath: filePath, lineNumber: lineNumber);
}
protected void VerifySessionIsActive()
{
AssertIsForeground();
Contract.ThrowIfFalse(IsSessionActive);
}
protected void VerifySessionIsInactive()
{
AssertIsForeground();
Contract.ThrowIfTrue(IsSessionActive);
}
protected void DismissSessionIfActive()
{
AssertIsForeground();
if (IsSessionActive)
{
this.StopModelComputation();
}
}
public void StopModelComputation()
{
AssertIsForeground();
VerifySessionIsActive();
// Make a local copy so that we won't do anything that causes us to recurse and try to
// dismiss this again.
var localSession = sessionOpt;
sessionOpt = null;
localSession.Stop();
}
public bool TryHandleEscapeKey()
{
AssertIsForeground();
// Escape simply dismissed a session if it's up. Otherwise let the next thing in the
// chain handle us.
if (!IsSessionActive)
{
return false;
}
// If we haven't even computed a model yet, then also send this command to anyone
// listening. It's unlikely that the command was intended for us (as we wouldn't
// have even shown ui yet.
var handledCommand = sessionOpt.InitialUnfilteredModel != null;
// In the presence of an escape, we always stop what we're doing.
this.StopModelComputation();
return handledCommand;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/Core/EditorConfigSettings/Aggregator/ISettingsAggregator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings
{
internal interface ISettingsAggregator : IWorkspaceService
{
ISettingsProvider<TData>? GetSettingsProvider<TData>(string fileName);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings
{
internal interface ISettingsAggregator : IWorkspaceService
{
ISettingsProvider<TData>? GetSettingsProvider<TData>(string fileName);
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_ExternalErrorReporting.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS
{
internal sealed partial class CPSProject : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2
{
private ProjectExternalErrorReporter GetExternalErrorReporter()
{
var errorReporter = _externalErrorReporter.Value;
if (errorReporter == null)
{
throw new InvalidOperationException("The language of the project doesn't support external errors.");
}
return errorReporter;
}
public int ClearAllErrors()
=> GetExternalErrorReporter().ClearAllErrors();
public int AddNewErrors(IVsEnumExternalErrors pErrors)
=> GetExternalErrorReporter().AddNewErrors(pErrors);
public int GetErrors(out IVsEnumExternalErrors pErrors)
=> GetExternalErrorReporter().GetErrors(out pErrors);
public int ReportError(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName)
=> GetExternalErrorReporter().ReportError(bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName);
public int ClearErrors()
=> GetExternalErrorReporter().ClearErrors();
public void ReportError2(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName)
=> GetExternalErrorReporter().ReportError2(bstrErrorMessage, bstrErrorId, nPriority, iStartLine, iStartColumn, iEndLine, iEndColumn, bstrFileName);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS
{
internal sealed partial class CPSProject : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2
{
private ProjectExternalErrorReporter GetExternalErrorReporter()
{
var errorReporter = _externalErrorReporter.Value;
if (errorReporter == null)
{
throw new InvalidOperationException("The language of the project doesn't support external errors.");
}
return errorReporter;
}
public int ClearAllErrors()
=> GetExternalErrorReporter().ClearAllErrors();
public int AddNewErrors(IVsEnumExternalErrors pErrors)
=> GetExternalErrorReporter().AddNewErrors(pErrors);
public int GetErrors(out IVsEnumExternalErrors pErrors)
=> GetExternalErrorReporter().GetErrors(out pErrors);
public int ReportError(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName)
=> GetExternalErrorReporter().ReportError(bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName);
public int ClearErrors()
=> GetExternalErrorReporter().ClearErrors();
public void ReportError2(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName)
=> GetExternalErrorReporter().ReportError2(bstrErrorMessage, bstrErrorId, nPriority, iStartLine, iStartColumn, iEndLine, iEndColumn, bstrFileName);
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/Core/Def/Shared/LogicalStringComparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal class LogicalStringComparer : IComparer<string>
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
public static readonly IComparer<string> Instance = new LogicalStringComparer();
private LogicalStringComparer()
{
}
public int Compare(string x, string y)
=> StrCmpLogicalW(x, y);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal class LogicalStringComparer : IComparer<string>
{
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
public static readonly IComparer<string> Instance = new LogicalStringComparer();
private LogicalStringComparer()
{
}
public int Compare(string x, string y)
=> StrCmpLogicalW(x, y);
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeRefactoringVerifier`1.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Testing;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
{
public static partial class VisualBasicCodeRefactoringVerifier<TCodeRefactoring>
where TCodeRefactoring : CodeRefactoringProvider, new()
{
/// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, string)"/>
public static Task VerifyRefactoringAsync(string source, string fixedSource)
{
return VerifyRefactoringAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource);
}
/// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, DiagnosticResult, string)"/>
public static Task VerifyRefactoringAsync(string source, DiagnosticResult expected, string fixedSource)
{
return VerifyRefactoringAsync(source, new[] { expected }, fixedSource);
}
/// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, DiagnosticResult[], string)"/>
public static Task VerifyRefactoringAsync(string source, DiagnosticResult[] expected, string fixedSource)
{
var test = new Test
{
TestCode = source,
FixedCode = fixedSource
};
test.ExpectedDiagnostics.AddRange(expected);
return test.RunAsync(CancellationToken.None);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Testing;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
{
public static partial class VisualBasicCodeRefactoringVerifier<TCodeRefactoring>
where TCodeRefactoring : CodeRefactoringProvider, new()
{
/// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, string)"/>
public static Task VerifyRefactoringAsync(string source, string fixedSource)
{
return VerifyRefactoringAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource);
}
/// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, DiagnosticResult, string)"/>
public static Task VerifyRefactoringAsync(string source, DiagnosticResult expected, string fixedSource)
{
return VerifyRefactoringAsync(source, new[] { expected }, fixedSource);
}
/// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, DiagnosticResult[], string)"/>
public static Task VerifyRefactoringAsync(string source, DiagnosticResult[] expected, string fixedSource)
{
var test = new Test
{
TestCode = source,
FixedCode = fixedSource
};
test.ExpectedDiagnostics.AddRange(expected);
return test.RunAsync(CancellationToken.None);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractSyncNamespaceCodeRefactoringProvider.MoveFileCodeAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace
{
internal abstract partial class AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax>
: CodeRefactoringProvider
where TNamespaceDeclarationSyntax : SyntaxNode
where TCompilationUnitSyntax : SyntaxNode
where TMemberDeclarationSyntax : SyntaxNode
{
private class MoveFileCodeAction : CodeAction
{
private readonly State _state;
private readonly ImmutableArray<string> _newfolders;
public override string Title
=> _newfolders.Length > 0
? string.Format(FeaturesResources.Move_file_to_0, string.Join(PathUtilities.DirectorySeparatorStr, _newfolders))
: FeaturesResources.Move_file_to_project_root_folder;
public MoveFileCodeAction(State state, ImmutableArray<string> newFolders)
{
_state = state;
_newfolders = newFolders;
}
protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
{
var id = _state.Document.Id;
var solution = _state.Document.Project.Solution;
var document = solution.GetDocument(id);
var newDocumentId = DocumentId.CreateNewId(document.Project.Id, document.Name);
solution = solution.RemoveDocument(id);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
solution = solution.AddDocument(newDocumentId, document.Name, text, folders: _newfolders);
return ImmutableArray.Create<CodeActionOperation>(
new ApplyChangesOperation(solution),
new OpenDocumentOperation(newDocumentId, activateIfAlreadyOpen: true));
}
public static ImmutableArray<MoveFileCodeAction> Create(State state)
{
Debug.Assert(state.RelativeDeclaredNamespace != null);
// Since all documents have identical folder structure, we can do the computation on any of them.
var document = state.Document;
// In case the relative namespace is "", the file should be moved to project root,
// set `parts` to empty to indicate that.
var parts = state.RelativeDeclaredNamespace.Length == 0
? ImmutableArray<string>.Empty
: state.RelativeDeclaredNamespace.Split(new[] { '.' }).ToImmutableArray();
// Invalid char can only appear in namespace name when there's error,
// which we have checked before creating any code actions.
Debug.Assert(parts.IsEmpty || parts.Any(s => s.IndexOfAny(Path.GetInvalidPathChars()) < 0));
var projectRootFolder = FolderInfo.CreateFolderHierarchyForProject(document.Project);
var candidateFolders = FindCandidateFolders(projectRootFolder, parts, ImmutableArray<string>.Empty);
return candidateFolders.SelectAsArray(folders => new MoveFileCodeAction(state, folders));
}
/// <summary>
/// We try to provide additional "move file" options if we can find existing folders that matches target namespace.
/// For example, if the target namespace is 'DefaultNamesapce.A.B.C', and there's a folder 'ProjectRoot\A.B\' already
/// exists, then will provide two actions, "move file to ProjectRoot\A.B\C\" and "move file to ProjectRoot\A\B\C\".
/// </summary>
private static ImmutableArray<ImmutableArray<string>> FindCandidateFolders(
FolderInfo currentFolderInfo,
ImmutableArray<string> parts,
ImmutableArray<string> currentFolder)
{
if (parts.IsEmpty)
{
return ImmutableArray.Create(currentFolder);
}
// Try to figure out all possible folder names that can match the target namespace.
// For example, if the target is "A.B.C", then the matching folder names include
// "A", "A.B" and "A.B.C". The item "index" in the result tuple is the number
// of items in namespace parts used to construct iten "foldername".
var candidates = Enumerable.Range(1, parts.Length)
.Select(i => (foldername: string.Join(".", parts.Take(i)), index: i))
.ToImmutableDictionary(t => t.foldername, t => t.index, PathUtilities.Comparer);
var subFolders = currentFolderInfo.ChildFolders;
var builder = ArrayBuilder<ImmutableArray<string>>.GetInstance();
foreach (var (folderName, index) in candidates)
{
if (subFolders.TryGetValue(folderName, out var matchingFolderInfo))
{
var newParts = index >= parts.Length
? ImmutableArray<string>.Empty
: ImmutableArray.Create(parts, index, parts.Length - index);
var newCurrentFolder = currentFolder.Add(matchingFolderInfo.Name);
builder.AddRange(FindCandidateFolders(matchingFolderInfo, newParts, newCurrentFolder));
}
}
// Make sure we always have the default path as an available option to the user
// (which might have been found by the search above, therefore the check here)
// For example, if the target namespace is "A.B.C.D", and there's folder <ROOT>\A.B\,
// the search above would only return "<ROOT>\A.B\C\D". We'd want to provide
// "<ROOT>\A\B\C\D" as the default path.
var defaultPathBasedOnCurrentFolder = currentFolder.AddRange(parts);
if (builder.All(folders => !folders.SequenceEqual(defaultPathBasedOnCurrentFolder, PathUtilities.Comparer)))
{
builder.Add(defaultPathBasedOnCurrentFolder);
}
return builder.ToImmutableAndFree();
}
private class FolderInfo
{
private readonly Dictionary<string, FolderInfo> _childFolders;
public string Name { get; }
public IReadOnlyDictionary<string, FolderInfo> ChildFolders => _childFolders;
private FolderInfo(string name)
{
Name = name;
_childFolders = new Dictionary<string, FolderInfo>(StringComparer.Ordinal);
}
private void AddFolder(IEnumerable<string> folder)
{
if (!folder.Any())
{
return;
}
var firstFolder = folder.First();
if (!_childFolders.TryGetValue(firstFolder, out var firstFolderInfo))
{
firstFolderInfo = new FolderInfo(firstFolder);
_childFolders[firstFolder] = firstFolderInfo;
}
firstFolderInfo.AddFolder(folder.Skip(1));
}
// TODO:
// Since we are getting folder data from documents, only non-empty folders
// in the project are discovered. It's possible to get complete folder structure
// from VS but it requires UI thread to do so. We might want to revisit this later.
public static FolderInfo CreateFolderHierarchyForProject(Project project)
{
var handledFolders = new HashSet<string>(StringComparer.Ordinal);
var rootFolderInfo = new FolderInfo("<ROOT>");
foreach (var document in project.Documents)
{
var folders = document.Folders;
if (handledFolders.Add(string.Join(PathUtilities.DirectorySeparatorStr, folders)))
{
rootFolderInfo.AddFolder(folders);
}
}
return rootFolderInfo;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace
{
internal abstract partial class AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax>
: CodeRefactoringProvider
where TNamespaceDeclarationSyntax : SyntaxNode
where TCompilationUnitSyntax : SyntaxNode
where TMemberDeclarationSyntax : SyntaxNode
{
private class MoveFileCodeAction : CodeAction
{
private readonly State _state;
private readonly ImmutableArray<string> _newfolders;
public override string Title
=> _newfolders.Length > 0
? string.Format(FeaturesResources.Move_file_to_0, string.Join(PathUtilities.DirectorySeparatorStr, _newfolders))
: FeaturesResources.Move_file_to_project_root_folder;
public MoveFileCodeAction(State state, ImmutableArray<string> newFolders)
{
_state = state;
_newfolders = newFolders;
}
protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken)
{
var id = _state.Document.Id;
var solution = _state.Document.Project.Solution;
var document = solution.GetDocument(id);
var newDocumentId = DocumentId.CreateNewId(document.Project.Id, document.Name);
solution = solution.RemoveDocument(id);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
solution = solution.AddDocument(newDocumentId, document.Name, text, folders: _newfolders);
return ImmutableArray.Create<CodeActionOperation>(
new ApplyChangesOperation(solution),
new OpenDocumentOperation(newDocumentId, activateIfAlreadyOpen: true));
}
public static ImmutableArray<MoveFileCodeAction> Create(State state)
{
Debug.Assert(state.RelativeDeclaredNamespace != null);
// Since all documents have identical folder structure, we can do the computation on any of them.
var document = state.Document;
// In case the relative namespace is "", the file should be moved to project root,
// set `parts` to empty to indicate that.
var parts = state.RelativeDeclaredNamespace.Length == 0
? ImmutableArray<string>.Empty
: state.RelativeDeclaredNamespace.Split(new[] { '.' }).ToImmutableArray();
// Invalid char can only appear in namespace name when there's error,
// which we have checked before creating any code actions.
Debug.Assert(parts.IsEmpty || parts.Any(s => s.IndexOfAny(Path.GetInvalidPathChars()) < 0));
var projectRootFolder = FolderInfo.CreateFolderHierarchyForProject(document.Project);
var candidateFolders = FindCandidateFolders(projectRootFolder, parts, ImmutableArray<string>.Empty);
return candidateFolders.SelectAsArray(folders => new MoveFileCodeAction(state, folders));
}
/// <summary>
/// We try to provide additional "move file" options if we can find existing folders that matches target namespace.
/// For example, if the target namespace is 'DefaultNamesapce.A.B.C', and there's a folder 'ProjectRoot\A.B\' already
/// exists, then will provide two actions, "move file to ProjectRoot\A.B\C\" and "move file to ProjectRoot\A\B\C\".
/// </summary>
private static ImmutableArray<ImmutableArray<string>> FindCandidateFolders(
FolderInfo currentFolderInfo,
ImmutableArray<string> parts,
ImmutableArray<string> currentFolder)
{
if (parts.IsEmpty)
{
return ImmutableArray.Create(currentFolder);
}
// Try to figure out all possible folder names that can match the target namespace.
// For example, if the target is "A.B.C", then the matching folder names include
// "A", "A.B" and "A.B.C". The item "index" in the result tuple is the number
// of items in namespace parts used to construct iten "foldername".
var candidates = Enumerable.Range(1, parts.Length)
.Select(i => (foldername: string.Join(".", parts.Take(i)), index: i))
.ToImmutableDictionary(t => t.foldername, t => t.index, PathUtilities.Comparer);
var subFolders = currentFolderInfo.ChildFolders;
var builder = ArrayBuilder<ImmutableArray<string>>.GetInstance();
foreach (var (folderName, index) in candidates)
{
if (subFolders.TryGetValue(folderName, out var matchingFolderInfo))
{
var newParts = index >= parts.Length
? ImmutableArray<string>.Empty
: ImmutableArray.Create(parts, index, parts.Length - index);
var newCurrentFolder = currentFolder.Add(matchingFolderInfo.Name);
builder.AddRange(FindCandidateFolders(matchingFolderInfo, newParts, newCurrentFolder));
}
}
// Make sure we always have the default path as an available option to the user
// (which might have been found by the search above, therefore the check here)
// For example, if the target namespace is "A.B.C.D", and there's folder <ROOT>\A.B\,
// the search above would only return "<ROOT>\A.B\C\D". We'd want to provide
// "<ROOT>\A\B\C\D" as the default path.
var defaultPathBasedOnCurrentFolder = currentFolder.AddRange(parts);
if (builder.All(folders => !folders.SequenceEqual(defaultPathBasedOnCurrentFolder, PathUtilities.Comparer)))
{
builder.Add(defaultPathBasedOnCurrentFolder);
}
return builder.ToImmutableAndFree();
}
private class FolderInfo
{
private readonly Dictionary<string, FolderInfo> _childFolders;
public string Name { get; }
public IReadOnlyDictionary<string, FolderInfo> ChildFolders => _childFolders;
private FolderInfo(string name)
{
Name = name;
_childFolders = new Dictionary<string, FolderInfo>(StringComparer.Ordinal);
}
private void AddFolder(IEnumerable<string> folder)
{
if (!folder.Any())
{
return;
}
var firstFolder = folder.First();
if (!_childFolders.TryGetValue(firstFolder, out var firstFolderInfo))
{
firstFolderInfo = new FolderInfo(firstFolder);
_childFolders[firstFolder] = firstFolderInfo;
}
firstFolderInfo.AddFolder(folder.Skip(1));
}
// TODO:
// Since we are getting folder data from documents, only non-empty folders
// in the project are discovered. It's possible to get complete folder structure
// from VS but it requires UI thread to do so. We might want to revisit this later.
public static FolderInfo CreateFolderHierarchyForProject(Project project)
{
var handledFolders = new HashSet<string>(StringComparer.Ordinal);
var rootFolderInfo = new FolderInfo("<ROOT>");
foreach (var document in project.Documents)
{
var folders = document.Folders;
if (handledFolders.Add(string.Join(PathUtilities.DirectorySeparatorStr, folders)))
{
rootFolderInfo.AddFolder(folders);
}
}
return rootFolderInfo;
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_UsingStatement.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
/// <summary>
/// Rewrite a using statement into a try finally statement. Four forms are possible:
/// 1) using (expr) stmt
/// 2) await using (expr) stmt
/// 3) using (C c = expr) stmt
/// 4) await using (C c = expr) stmt
///
/// The first two are handled by RewriteExpressionUsingStatement and the latter two are handled by
/// RewriteDeclarationUsingStatement (called in a loop, once for each local declared).
///
/// For the async variants, `IAsyncDisposable` is used instead of `IDisposable` and we produce
/// `... await expr.DisposeAsync() ...` instead of `... expr.Dispose() ...`.
/// </summary>
/// <remarks>
/// It would be more in line with our usual pattern to rewrite using to try-finally
/// in the ControlFlowRewriter, but if we don't do it here the BoundMultipleLocalDeclarations
/// will be rewritten into a form that makes them harder to separate.
/// </remarks>
public override BoundNode VisitUsingStatement(BoundUsingStatement node)
{
BoundStatement? rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
BoundBlock tryBlock = rewrittenBody.Kind == BoundKind.Block
? (BoundBlock)rewrittenBody
: BoundBlock.SynthesizedNoLocals(node.Syntax, rewrittenBody);
if (node.ExpressionOpt != null)
{
return MakeExpressionUsingStatement(node, tryBlock);
}
else
{
Debug.Assert(node.DeclarationsOpt is { });
SyntaxToken awaitKeyword = node.Syntax.Kind() == SyntaxKind.UsingStatement ? ((UsingStatementSyntax)node.Syntax).AwaitKeyword : default;
return MakeDeclarationUsingStatement(node.Syntax,
tryBlock,
node.Locals,
node.DeclarationsOpt.LocalDeclarations,
node.IDisposableConversion,
node.PatternDisposeInfoOpt,
node.AwaitOpt,
awaitKeyword);
}
}
private BoundStatement MakeDeclarationUsingStatement(SyntaxNode syntax,
BoundBlock body,
ImmutableArray<LocalSymbol> locals,
ImmutableArray<BoundLocalDeclaration> declarations,
Conversion iDisposableConversion,
MethodArgumentInfo? patternDisposeInfo,
BoundAwaitableInfo? awaitOpt,
SyntaxToken awaitKeyword)
{
Debug.Assert(declarations != null);
BoundBlock result = body;
for (int i = declarations.Length - 1; i >= 0; i--) //NB: inner-to-outer = right-to-left
{
result = RewriteDeclarationUsingStatement(syntax, declarations[i], result, iDisposableConversion, awaitKeyword, awaitOpt, patternDisposeInfo);
}
// Declare all locals in a single, top-level block so that the scope is correct in the debugger
// (Dev10 has them all come into scope at once, not per-declaration.)
return new BoundBlock(
syntax,
locals,
ImmutableArray.Create<BoundStatement>(result));
}
/// <summary>
/// Lower "[await] using var x = (expression)" to a try-finally block.
/// </summary>
private BoundStatement MakeLocalUsingDeclarationStatement(BoundUsingLocalDeclarations usingDeclarations, ImmutableArray<BoundStatement> statements)
{
LocalDeclarationStatementSyntax syntax = (LocalDeclarationStatementSyntax)usingDeclarations.Syntax;
BoundBlock body = new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements);
var usingStatement = MakeDeclarationUsingStatement(syntax,
body,
ImmutableArray<LocalSymbol>.Empty,
usingDeclarations.LocalDeclarations,
usingDeclarations.IDisposableConversion,
usingDeclarations.PatternDisposeInfoOpt,
awaitOpt: usingDeclarations.AwaitOpt,
awaitKeyword: syntax.AwaitKeyword);
return usingStatement;
}
/// <summary>
/// Lower "using [await] (expression) statement" to a try-finally block.
/// </summary>
private BoundBlock MakeExpressionUsingStatement(BoundUsingStatement node, BoundBlock tryBlock)
{
Debug.Assert(node.ExpressionOpt != null);
Debug.Assert(node.DeclarationsOpt == null);
// See comments in BuildUsingTryFinally for the details of the lowering to try-finally.
//
// SPEC: A using statement of the form "using (expression) statement; " has the
// SPEC: same three possible expansions [ as "using (ResourceType r = expression) statement; ]
// SPEC: but in this case ResourceType is implicitly the compile-time type of the expression,
// SPEC: and the resource variable is inaccessible to and invisible to the embedded statement.
//
// DELIBERATE SPEC VIOLATION:
//
// The spec quote above implies that the expression must have a type; in fact we allow
// the expression to be null.
//
// If expr is the constant null then we can elide the whole thing and simply generate the statement.
BoundExpression rewrittenExpression = VisitExpression(node.ExpressionOpt);
if (rewrittenExpression.ConstantValue == ConstantValue.Null)
{
Debug.Assert(node.Locals.IsEmpty); // TODO: This might not be a valid assumption in presence of semicolon operator.
return tryBlock;
}
// Otherwise, we lower "using(expression) statement;" as follows:
//
// * If the expression is of type dynamic then we lower as though the user had written
//
// using(IDisposable temp = (IDisposable)expression) statement;
//
// Note that we have to do the conversion early, not in the finally block, because
// if the conversion fails at runtime with an exception then the exception must happen
// before the statement runs.
//
// * Otherwise we lower as though the user had written
//
// using(ResourceType temp = expression) statement;
//
Debug.Assert(rewrittenExpression.Type is { });
TypeSymbol expressionType = rewrittenExpression.Type;
SyntaxNode expressionSyntax = rewrittenExpression.Syntax;
UsingStatementSyntax usingSyntax = (UsingStatementSyntax)node.Syntax;
BoundAssignmentOperator tempAssignment;
BoundLocal boundTemp;
if (expressionType is null || expressionType.IsDynamic())
{
// IDisposable temp = (IDisposable) expr;
// or
// IAsyncDisposable temp = (IAsyncDisposable) expr;
TypeSymbol iDisposableType = node.AwaitOpt is null ?
_compilation.GetSpecialType(SpecialType.System_IDisposable) :
_compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable);
_diagnostics.ReportUseSite(iDisposableType, usingSyntax);
BoundExpression tempInit = MakeConversionNode(
expressionSyntax,
rewrittenExpression,
Conversion.GetTrivialConversion(node.IDisposableConversion.Kind),
iDisposableType,
@checked: false,
constantValueOpt: rewrittenExpression.ConstantValue);
boundTemp = _factory.StoreToTemp(tempInit, out tempAssignment, kind: SynthesizedLocalKind.Using);
}
else
{
// ResourceType temp = expr;
boundTemp = _factory.StoreToTemp(rewrittenExpression, out tempAssignment, syntaxOpt: usingSyntax, kind: SynthesizedLocalKind.Using);
}
BoundStatement expressionStatement = new BoundExpressionStatement(expressionSyntax, tempAssignment);
if (this.Instrument)
{
expressionStatement = _instrumenter.InstrumentUsingTargetCapture(node, expressionStatement);
}
BoundStatement tryFinally = RewriteUsingStatementTryFinally(usingSyntax, tryBlock, boundTemp, usingSyntax.AwaitKeyword, node.AwaitOpt, node.PatternDisposeInfoOpt);
// { ResourceType temp = expr; try { ... } finally { ... } }
return new BoundBlock(
syntax: usingSyntax,
locals: node.Locals.Add(boundTemp.LocalSymbol),
statements: ImmutableArray.Create<BoundStatement>(expressionStatement, tryFinally));
}
/// <summary>
/// Lower "using [await] (ResourceType resource = expression) statement" to a try-finally block.
/// </summary>
/// <remarks>
/// Assumes that the local symbol will be declared (i.e. in the LocalsOpt array) of an enclosing block.
/// Assumes that using statements with multiple locals have already been split up into multiple using statements.
/// </remarks>
private BoundBlock RewriteDeclarationUsingStatement(
SyntaxNode usingSyntax,
BoundLocalDeclaration localDeclaration,
BoundBlock tryBlock,
Conversion iDisposableConversion,
SyntaxToken awaitKeywordOpt,
BoundAwaitableInfo? awaitOpt,
MethodArgumentInfo? patternDisposeInfo)
{
Debug.Assert(localDeclaration.InitializerOpt is { });
SyntaxNode declarationSyntax = localDeclaration.Syntax;
LocalSymbol localSymbol = localDeclaration.LocalSymbol;
TypeSymbol localType = localSymbol.Type;
Debug.Assert((object)localType != null); //otherwise, there wouldn't be a conversion to IDisposable
BoundLocal boundLocal = new BoundLocal(declarationSyntax, localSymbol, localDeclaration.InitializerOpt.ConstantValue, localType);
BoundStatement? rewrittenDeclaration = VisitStatement(localDeclaration);
Debug.Assert(rewrittenDeclaration is { });
// If we know that the expression is null, then we know that the null check in the finally block
// will fail, and the Dispose call will never happen. That is, the finally block will have no effect.
// Consequently, we can simply skip the whole try-finally construct and just create a block containing
// the new declaration.
if (boundLocal.ConstantValue == ConstantValue.Null)
{
//localSymbol will be declared by an enclosing block
return BoundBlock.SynthesizedNoLocals(usingSyntax, rewrittenDeclaration, tryBlock);
}
if (localType.IsDynamic())
{
TypeSymbol iDisposableType = awaitOpt is null ?
_compilation.GetSpecialType(SpecialType.System_IDisposable) :
_compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable);
_diagnostics.ReportUseSite(iDisposableType, usingSyntax);
BoundExpression tempInit = MakeConversionNode(
declarationSyntax,
boundLocal,
iDisposableConversion,
iDisposableType,
@checked: false);
BoundAssignmentOperator tempAssignment;
BoundLocal boundTemp = _factory.StoreToTemp(tempInit, out tempAssignment, kind: SynthesizedLocalKind.Using);
BoundStatement tryFinally = RewriteUsingStatementTryFinally(usingSyntax, tryBlock, boundTemp, awaitKeywordOpt, awaitOpt, patternDisposeInfo);
return new BoundBlock(
syntax: usingSyntax,
locals: ImmutableArray.Create<LocalSymbol>(boundTemp.LocalSymbol), //localSymbol will be declared by an enclosing block
statements: ImmutableArray.Create<BoundStatement>(
rewrittenDeclaration,
new BoundExpressionStatement(declarationSyntax, tempAssignment),
tryFinally));
}
else
{
BoundStatement tryFinally = RewriteUsingStatementTryFinally(usingSyntax, tryBlock, boundLocal, awaitKeywordOpt, awaitOpt, patternDisposeInfo);
// localSymbol will be declared by an enclosing block
return BoundBlock.SynthesizedNoLocals(usingSyntax, rewrittenDeclaration, tryFinally);
}
}
private BoundStatement RewriteUsingStatementTryFinally(
SyntaxNode syntax,
BoundBlock tryBlock,
BoundLocal local,
SyntaxToken awaitKeywordOpt,
BoundAwaitableInfo? awaitOpt,
MethodArgumentInfo? patternDisposeInfo)
{
// SPEC: When ResourceType is a non-nullable value type, the expansion is:
// SPEC:
// SPEC: {
// SPEC: ResourceType resource = expr;
// SPEC: try { statement; }
// SPEC: finally { ((IDisposable)resource).Dispose(); }
// SPEC: }
// SPEC:
// SPEC: Otherwise, when Resource type is a nullable value type or
// SPEC: a reference type other than dynamic, the expansion is:
// SPEC:
// SPEC: {
// SPEC: ResourceType resource = expr;
// SPEC: try { statement; }
// SPEC: finally { if (resource != null) ((IDisposable)resource).Dispose(); }
// SPEC: }
// SPEC:
// SPEC: Otherwise, when ResourceType is dynamic, the expansion is:
// SPEC: {
// SPEC: dynamic resource = expr;
// SPEC: IDisposable d = (IDisposable)resource;
// SPEC: try { statement; }
// SPEC: finally { if (d != null) d.Dispose(); }
// SPEC: }
// SPEC:
// SPEC: An implementation is permitted to implement a given using statement
// SPEC: differently -- for example, for performance reasons -- as long as the
// SPEC: behavior is consistent with the above expansion.
//
// In the case of using-await statement, we'll use "IAsyncDisposable" instead of "IDisposable", "await DisposeAsync()" instead of "Dispose()"
//
// And we do in fact generate the code slightly differently than precisely how it is
// described above.
//
// First: if the type is a non-nullable value type then we do not do the
// *boxing conversion* from the resource to IDisposable. Rather, we do
// a *constrained virtual call* that elides the boxing if possible.
//
// Now, you might wonder if that is legal; isn't skipping the boxing producing
// an observable difference? Because if the value type is mutable and the Dispose
// mutates it, then skipping the boxing means that we are now mutating the original,
// not the boxed copy. But this is never observable. Either (1) we have "using(R r = x){}"
// and r is out of scope after the finally, so it is not possible to observe the mutation,
// or (2) we have "using(x) {}". But that has the semantics of "using(R temp = x){}",
// so again, we are not mutating x to begin with; we're always mutating a copy. Therefore
// it doesn't matter if we skip making *a copy of the copy*.
//
// This is what the dev10 compiler does, and we do so as well.
//
// Second: if the type is a nullable value type then we can similarly elide the boxing.
// We can generate
//
// {
// ResourceType resource = expr;
// try { statement; }
// finally { if (resource.HasValue) resource.GetValueOrDefault().Dispose(); }
// }
//
// Where again we do a constrained virtual call to Dispose, rather than boxing
// the value to IDisposable.
//
// Note that this optimization is *not* what the native compiler does; in this case
// the native compiler behavior is to test for HasValue, then *box* and convert
// the boxed value to IDisposable. There's no need to do that.
//
// Third: if we have "using(x)" and x is dynamic then obviously we need not generate
// "{ dynamic temp1 = x; IDisposable temp2 = (IDisposable) temp1; ... }". Rather, we elide
// the completely unnecessary first temporary.
Debug.Assert((awaitKeywordOpt == default) == (awaitOpt is null));
BoundExpression disposedExpression;
bool isNullableValueType = local.Type.IsNullableType();
if (isNullableValueType)
{
MethodSymbol getValueOrDefault = UnsafeGetNullableMethod(syntax, local.Type, SpecialMember.System_Nullable_T_GetValueOrDefault);
// local.GetValueOrDefault()
disposedExpression = BoundCall.Synthesized(syntax, local, getValueOrDefault);
}
else
{
// local
disposedExpression = local;
}
BoundExpression disposeCall = GenerateDisposeCall(syntax, disposedExpression, patternDisposeInfo, awaitOpt, awaitKeywordOpt);
// local.Dispose(); or await variant
BoundStatement disposeStatement = new BoundExpressionStatement(syntax, disposeCall);
BoundExpression? ifCondition;
if (isNullableValueType)
{
// local.HasValue
ifCondition = MakeNullableHasValue(syntax, local);
}
else if (local.Type.IsValueType)
{
ifCondition = null;
}
else
{
// local != null
ifCondition = MakeNullCheck(syntax, local, BinaryOperatorKind.NotEqual);
}
BoundStatement finallyStatement;
if (ifCondition == null)
{
// local.Dispose(); or await variant
finallyStatement = disposeStatement;
}
else
{
// if (local != null) local.Dispose();
// or
// if (local.HasValue) local.GetValueOrDefault().Dispose();
// or
// await variants
finallyStatement = RewriteIfStatement(
syntax: syntax,
rewrittenCondition: ifCondition,
rewrittenConsequence: disposeStatement,
rewrittenAlternativeOpt: null,
hasErrors: false);
}
// try { ... } finally { if (local != null) local.Dispose(); }
// or
// nullable or await variants
BoundStatement tryFinally = new BoundTryStatement(
syntax: syntax,
tryBlock: tryBlock,
catchBlocks: ImmutableArray<BoundCatchBlock>.Empty,
finallyBlockOpt: BoundBlock.SynthesizedNoLocals(syntax, finallyStatement));
return tryFinally;
}
private BoundExpression GenerateDisposeCall(
SyntaxNode syntax,
BoundExpression disposedExpression,
MethodArgumentInfo? disposeInfo,
BoundAwaitableInfo? awaitOpt,
SyntaxToken awaitKeyword)
{
Debug.Assert(awaitOpt is null || awaitKeyword != default);
// If we don't have an explicit dispose method, try and get the special member for IDisposable/IAsyncDisposable
MethodSymbol? disposeMethod = disposeInfo?.Method;
if (disposeMethod is null)
{
if (awaitOpt is null)
{
// IDisposable.Dispose()
Binder.TryGetSpecialTypeMember(_compilation, SpecialMember.System_IDisposable__Dispose, syntax, _diagnostics, out disposeMethod);
}
else
{
// IAsyncDisposable.DisposeAsync()
TryGetWellKnownTypeMember<MethodSymbol>(syntax: null, WellKnownMember.System_IAsyncDisposable__DisposeAsync, out disposeMethod, location: awaitKeyword.GetLocation());
}
}
BoundExpression disposeCall;
if (disposeMethod is null)
{
disposeCall = new BoundBadExpression(syntax, LookupResultKind.NotInvocable, ImmutableArray<Symbol?>.Empty, ImmutableArray.Create(disposedExpression), ErrorTypeSymbol.UnknownResultType);
}
else
{
if (disposeInfo is null)
{
// Generate the info for IDisposable.Dispose(). We know it has no arguments.
disposeInfo = MethodArgumentInfo.CreateParameterlessMethod(disposeMethod);
}
disposeCall = MakeCallWithNoExplicitArgument(disposeInfo, syntax, disposedExpression);
if (awaitOpt is object)
{
// await local.DisposeAsync()
_sawAwaitInExceptionHandler = true;
TypeSymbol awaitExpressionType = awaitOpt.GetResult?.ReturnType ?? _compilation.DynamicType;
disposeCall = RewriteAwaitExpression(syntax, disposeCall, awaitOpt, awaitExpressionType, false);
}
}
return disposeCall;
}
/// <summary>
/// Synthesize a call `expression.Method()`, but with some extra smarts to handle extension methods, and to fill-in optional and params parameters. This call expects that the
/// receiver parameter has already been visited.
/// </summary>
private BoundExpression MakeCallWithNoExplicitArgument(MethodArgumentInfo methodArgumentInfo, SyntaxNode syntax, BoundExpression? expression, bool assertParametersAreOptional = true)
{
MethodSymbol method = methodArgumentInfo.Method;
#if DEBUG
if (method.IsExtensionMethod)
{
Debug.Assert(expression == null);
Debug.Assert(method.Parameters.AsSpan()[1..].All(assertParametersAreOptional, (p, assertOptional) => (p.IsOptional || p.IsParams || !assertOptional) && p.RefKind == RefKind.None));
Debug.Assert(method.ParameterRefKinds.IsDefaultOrEmpty || method.ParameterRefKinds[0] is RefKind.In or RefKind.None);
}
else
{
Debug.Assert(!assertParametersAreOptional || method.Parameters.All(p => p.IsOptional || p.IsParams));
Debug.Assert(method.ParameterRefKinds.IsDefaultOrEmpty);
}
Debug.Assert(methodArgumentInfo.Arguments.All(arg => arg is not BoundConversion { ConversionKind: ConversionKind.InterpolatedStringHandler }));
#endif
return MakeArgumentsAndCall(
syntax,
expression,
method,
methodArgumentInfo.Arguments,
argumentRefKindsOpt: default,
expanded: methodArgumentInfo.Expanded,
invokedAsExtensionMethod: method.IsExtensionMethod,
methodArgumentInfo.ArgsToParamsOpt,
resultKind: LookupResultKind.Viable,
type: method.ReturnType,
temps: null);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
/// <summary>
/// Rewrite a using statement into a try finally statement. Four forms are possible:
/// 1) using (expr) stmt
/// 2) await using (expr) stmt
/// 3) using (C c = expr) stmt
/// 4) await using (C c = expr) stmt
///
/// The first two are handled by RewriteExpressionUsingStatement and the latter two are handled by
/// RewriteDeclarationUsingStatement (called in a loop, once for each local declared).
///
/// For the async variants, `IAsyncDisposable` is used instead of `IDisposable` and we produce
/// `... await expr.DisposeAsync() ...` instead of `... expr.Dispose() ...`.
/// </summary>
/// <remarks>
/// It would be more in line with our usual pattern to rewrite using to try-finally
/// in the ControlFlowRewriter, but if we don't do it here the BoundMultipleLocalDeclarations
/// will be rewritten into a form that makes them harder to separate.
/// </remarks>
public override BoundNode VisitUsingStatement(BoundUsingStatement node)
{
BoundStatement? rewrittenBody = VisitStatement(node.Body);
Debug.Assert(rewrittenBody is { });
BoundBlock tryBlock = rewrittenBody.Kind == BoundKind.Block
? (BoundBlock)rewrittenBody
: BoundBlock.SynthesizedNoLocals(node.Syntax, rewrittenBody);
if (node.ExpressionOpt != null)
{
return MakeExpressionUsingStatement(node, tryBlock);
}
else
{
Debug.Assert(node.DeclarationsOpt is { });
SyntaxToken awaitKeyword = node.Syntax.Kind() == SyntaxKind.UsingStatement ? ((UsingStatementSyntax)node.Syntax).AwaitKeyword : default;
return MakeDeclarationUsingStatement(node.Syntax,
tryBlock,
node.Locals,
node.DeclarationsOpt.LocalDeclarations,
node.IDisposableConversion,
node.PatternDisposeInfoOpt,
node.AwaitOpt,
awaitKeyword);
}
}
private BoundStatement MakeDeclarationUsingStatement(SyntaxNode syntax,
BoundBlock body,
ImmutableArray<LocalSymbol> locals,
ImmutableArray<BoundLocalDeclaration> declarations,
Conversion iDisposableConversion,
MethodArgumentInfo? patternDisposeInfo,
BoundAwaitableInfo? awaitOpt,
SyntaxToken awaitKeyword)
{
Debug.Assert(declarations != null);
BoundBlock result = body;
for (int i = declarations.Length - 1; i >= 0; i--) //NB: inner-to-outer = right-to-left
{
result = RewriteDeclarationUsingStatement(syntax, declarations[i], result, iDisposableConversion, awaitKeyword, awaitOpt, patternDisposeInfo);
}
// Declare all locals in a single, top-level block so that the scope is correct in the debugger
// (Dev10 has them all come into scope at once, not per-declaration.)
return new BoundBlock(
syntax,
locals,
ImmutableArray.Create<BoundStatement>(result));
}
/// <summary>
/// Lower "[await] using var x = (expression)" to a try-finally block.
/// </summary>
private BoundStatement MakeLocalUsingDeclarationStatement(BoundUsingLocalDeclarations usingDeclarations, ImmutableArray<BoundStatement> statements)
{
LocalDeclarationStatementSyntax syntax = (LocalDeclarationStatementSyntax)usingDeclarations.Syntax;
BoundBlock body = new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements);
var usingStatement = MakeDeclarationUsingStatement(syntax,
body,
ImmutableArray<LocalSymbol>.Empty,
usingDeclarations.LocalDeclarations,
usingDeclarations.IDisposableConversion,
usingDeclarations.PatternDisposeInfoOpt,
awaitOpt: usingDeclarations.AwaitOpt,
awaitKeyword: syntax.AwaitKeyword);
return usingStatement;
}
/// <summary>
/// Lower "using [await] (expression) statement" to a try-finally block.
/// </summary>
private BoundBlock MakeExpressionUsingStatement(BoundUsingStatement node, BoundBlock tryBlock)
{
Debug.Assert(node.ExpressionOpt != null);
Debug.Assert(node.DeclarationsOpt == null);
// See comments in BuildUsingTryFinally for the details of the lowering to try-finally.
//
// SPEC: A using statement of the form "using (expression) statement; " has the
// SPEC: same three possible expansions [ as "using (ResourceType r = expression) statement; ]
// SPEC: but in this case ResourceType is implicitly the compile-time type of the expression,
// SPEC: and the resource variable is inaccessible to and invisible to the embedded statement.
//
// DELIBERATE SPEC VIOLATION:
//
// The spec quote above implies that the expression must have a type; in fact we allow
// the expression to be null.
//
// If expr is the constant null then we can elide the whole thing and simply generate the statement.
BoundExpression rewrittenExpression = VisitExpression(node.ExpressionOpt);
if (rewrittenExpression.ConstantValue == ConstantValue.Null)
{
Debug.Assert(node.Locals.IsEmpty); // TODO: This might not be a valid assumption in presence of semicolon operator.
return tryBlock;
}
// Otherwise, we lower "using(expression) statement;" as follows:
//
// * If the expression is of type dynamic then we lower as though the user had written
//
// using(IDisposable temp = (IDisposable)expression) statement;
//
// Note that we have to do the conversion early, not in the finally block, because
// if the conversion fails at runtime with an exception then the exception must happen
// before the statement runs.
//
// * Otherwise we lower as though the user had written
//
// using(ResourceType temp = expression) statement;
//
Debug.Assert(rewrittenExpression.Type is { });
TypeSymbol expressionType = rewrittenExpression.Type;
SyntaxNode expressionSyntax = rewrittenExpression.Syntax;
UsingStatementSyntax usingSyntax = (UsingStatementSyntax)node.Syntax;
BoundAssignmentOperator tempAssignment;
BoundLocal boundTemp;
if (expressionType is null || expressionType.IsDynamic())
{
// IDisposable temp = (IDisposable) expr;
// or
// IAsyncDisposable temp = (IAsyncDisposable) expr;
TypeSymbol iDisposableType = node.AwaitOpt is null ?
_compilation.GetSpecialType(SpecialType.System_IDisposable) :
_compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable);
_diagnostics.ReportUseSite(iDisposableType, usingSyntax);
BoundExpression tempInit = MakeConversionNode(
expressionSyntax,
rewrittenExpression,
Conversion.GetTrivialConversion(node.IDisposableConversion.Kind),
iDisposableType,
@checked: false,
constantValueOpt: rewrittenExpression.ConstantValue);
boundTemp = _factory.StoreToTemp(tempInit, out tempAssignment, kind: SynthesizedLocalKind.Using);
}
else
{
// ResourceType temp = expr;
boundTemp = _factory.StoreToTemp(rewrittenExpression, out tempAssignment, syntaxOpt: usingSyntax, kind: SynthesizedLocalKind.Using);
}
BoundStatement expressionStatement = new BoundExpressionStatement(expressionSyntax, tempAssignment);
if (this.Instrument)
{
expressionStatement = _instrumenter.InstrumentUsingTargetCapture(node, expressionStatement);
}
BoundStatement tryFinally = RewriteUsingStatementTryFinally(usingSyntax, tryBlock, boundTemp, usingSyntax.AwaitKeyword, node.AwaitOpt, node.PatternDisposeInfoOpt);
// { ResourceType temp = expr; try { ... } finally { ... } }
return new BoundBlock(
syntax: usingSyntax,
locals: node.Locals.Add(boundTemp.LocalSymbol),
statements: ImmutableArray.Create<BoundStatement>(expressionStatement, tryFinally));
}
/// <summary>
/// Lower "using [await] (ResourceType resource = expression) statement" to a try-finally block.
/// </summary>
/// <remarks>
/// Assumes that the local symbol will be declared (i.e. in the LocalsOpt array) of an enclosing block.
/// Assumes that using statements with multiple locals have already been split up into multiple using statements.
/// </remarks>
private BoundBlock RewriteDeclarationUsingStatement(
SyntaxNode usingSyntax,
BoundLocalDeclaration localDeclaration,
BoundBlock tryBlock,
Conversion iDisposableConversion,
SyntaxToken awaitKeywordOpt,
BoundAwaitableInfo? awaitOpt,
MethodArgumentInfo? patternDisposeInfo)
{
Debug.Assert(localDeclaration.InitializerOpt is { });
SyntaxNode declarationSyntax = localDeclaration.Syntax;
LocalSymbol localSymbol = localDeclaration.LocalSymbol;
TypeSymbol localType = localSymbol.Type;
Debug.Assert((object)localType != null); //otherwise, there wouldn't be a conversion to IDisposable
BoundLocal boundLocal = new BoundLocal(declarationSyntax, localSymbol, localDeclaration.InitializerOpt.ConstantValue, localType);
BoundStatement? rewrittenDeclaration = VisitStatement(localDeclaration);
Debug.Assert(rewrittenDeclaration is { });
// If we know that the expression is null, then we know that the null check in the finally block
// will fail, and the Dispose call will never happen. That is, the finally block will have no effect.
// Consequently, we can simply skip the whole try-finally construct and just create a block containing
// the new declaration.
if (boundLocal.ConstantValue == ConstantValue.Null)
{
//localSymbol will be declared by an enclosing block
return BoundBlock.SynthesizedNoLocals(usingSyntax, rewrittenDeclaration, tryBlock);
}
if (localType.IsDynamic())
{
TypeSymbol iDisposableType = awaitOpt is null ?
_compilation.GetSpecialType(SpecialType.System_IDisposable) :
_compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable);
_diagnostics.ReportUseSite(iDisposableType, usingSyntax);
BoundExpression tempInit = MakeConversionNode(
declarationSyntax,
boundLocal,
iDisposableConversion,
iDisposableType,
@checked: false);
BoundAssignmentOperator tempAssignment;
BoundLocal boundTemp = _factory.StoreToTemp(tempInit, out tempAssignment, kind: SynthesizedLocalKind.Using);
BoundStatement tryFinally = RewriteUsingStatementTryFinally(usingSyntax, tryBlock, boundTemp, awaitKeywordOpt, awaitOpt, patternDisposeInfo);
return new BoundBlock(
syntax: usingSyntax,
locals: ImmutableArray.Create<LocalSymbol>(boundTemp.LocalSymbol), //localSymbol will be declared by an enclosing block
statements: ImmutableArray.Create<BoundStatement>(
rewrittenDeclaration,
new BoundExpressionStatement(declarationSyntax, tempAssignment),
tryFinally));
}
else
{
BoundStatement tryFinally = RewriteUsingStatementTryFinally(usingSyntax, tryBlock, boundLocal, awaitKeywordOpt, awaitOpt, patternDisposeInfo);
// localSymbol will be declared by an enclosing block
return BoundBlock.SynthesizedNoLocals(usingSyntax, rewrittenDeclaration, tryFinally);
}
}
private BoundStatement RewriteUsingStatementTryFinally(
SyntaxNode syntax,
BoundBlock tryBlock,
BoundLocal local,
SyntaxToken awaitKeywordOpt,
BoundAwaitableInfo? awaitOpt,
MethodArgumentInfo? patternDisposeInfo)
{
// SPEC: When ResourceType is a non-nullable value type, the expansion is:
// SPEC:
// SPEC: {
// SPEC: ResourceType resource = expr;
// SPEC: try { statement; }
// SPEC: finally { ((IDisposable)resource).Dispose(); }
// SPEC: }
// SPEC:
// SPEC: Otherwise, when Resource type is a nullable value type or
// SPEC: a reference type other than dynamic, the expansion is:
// SPEC:
// SPEC: {
// SPEC: ResourceType resource = expr;
// SPEC: try { statement; }
// SPEC: finally { if (resource != null) ((IDisposable)resource).Dispose(); }
// SPEC: }
// SPEC:
// SPEC: Otherwise, when ResourceType is dynamic, the expansion is:
// SPEC: {
// SPEC: dynamic resource = expr;
// SPEC: IDisposable d = (IDisposable)resource;
// SPEC: try { statement; }
// SPEC: finally { if (d != null) d.Dispose(); }
// SPEC: }
// SPEC:
// SPEC: An implementation is permitted to implement a given using statement
// SPEC: differently -- for example, for performance reasons -- as long as the
// SPEC: behavior is consistent with the above expansion.
//
// In the case of using-await statement, we'll use "IAsyncDisposable" instead of "IDisposable", "await DisposeAsync()" instead of "Dispose()"
//
// And we do in fact generate the code slightly differently than precisely how it is
// described above.
//
// First: if the type is a non-nullable value type then we do not do the
// *boxing conversion* from the resource to IDisposable. Rather, we do
// a *constrained virtual call* that elides the boxing if possible.
//
// Now, you might wonder if that is legal; isn't skipping the boxing producing
// an observable difference? Because if the value type is mutable and the Dispose
// mutates it, then skipping the boxing means that we are now mutating the original,
// not the boxed copy. But this is never observable. Either (1) we have "using(R r = x){}"
// and r is out of scope after the finally, so it is not possible to observe the mutation,
// or (2) we have "using(x) {}". But that has the semantics of "using(R temp = x){}",
// so again, we are not mutating x to begin with; we're always mutating a copy. Therefore
// it doesn't matter if we skip making *a copy of the copy*.
//
// This is what the dev10 compiler does, and we do so as well.
//
// Second: if the type is a nullable value type then we can similarly elide the boxing.
// We can generate
//
// {
// ResourceType resource = expr;
// try { statement; }
// finally { if (resource.HasValue) resource.GetValueOrDefault().Dispose(); }
// }
//
// Where again we do a constrained virtual call to Dispose, rather than boxing
// the value to IDisposable.
//
// Note that this optimization is *not* what the native compiler does; in this case
// the native compiler behavior is to test for HasValue, then *box* and convert
// the boxed value to IDisposable. There's no need to do that.
//
// Third: if we have "using(x)" and x is dynamic then obviously we need not generate
// "{ dynamic temp1 = x; IDisposable temp2 = (IDisposable) temp1; ... }". Rather, we elide
// the completely unnecessary first temporary.
Debug.Assert((awaitKeywordOpt == default) == (awaitOpt is null));
BoundExpression disposedExpression;
bool isNullableValueType = local.Type.IsNullableType();
if (isNullableValueType)
{
MethodSymbol getValueOrDefault = UnsafeGetNullableMethod(syntax, local.Type, SpecialMember.System_Nullable_T_GetValueOrDefault);
// local.GetValueOrDefault()
disposedExpression = BoundCall.Synthesized(syntax, local, getValueOrDefault);
}
else
{
// local
disposedExpression = local;
}
BoundExpression disposeCall = GenerateDisposeCall(syntax, disposedExpression, patternDisposeInfo, awaitOpt, awaitKeywordOpt);
// local.Dispose(); or await variant
BoundStatement disposeStatement = new BoundExpressionStatement(syntax, disposeCall);
BoundExpression? ifCondition;
if (isNullableValueType)
{
// local.HasValue
ifCondition = MakeNullableHasValue(syntax, local);
}
else if (local.Type.IsValueType)
{
ifCondition = null;
}
else
{
// local != null
ifCondition = MakeNullCheck(syntax, local, BinaryOperatorKind.NotEqual);
}
BoundStatement finallyStatement;
if (ifCondition == null)
{
// local.Dispose(); or await variant
finallyStatement = disposeStatement;
}
else
{
// if (local != null) local.Dispose();
// or
// if (local.HasValue) local.GetValueOrDefault().Dispose();
// or
// await variants
finallyStatement = RewriteIfStatement(
syntax: syntax,
rewrittenCondition: ifCondition,
rewrittenConsequence: disposeStatement,
rewrittenAlternativeOpt: null,
hasErrors: false);
}
// try { ... } finally { if (local != null) local.Dispose(); }
// or
// nullable or await variants
BoundStatement tryFinally = new BoundTryStatement(
syntax: syntax,
tryBlock: tryBlock,
catchBlocks: ImmutableArray<BoundCatchBlock>.Empty,
finallyBlockOpt: BoundBlock.SynthesizedNoLocals(syntax, finallyStatement));
return tryFinally;
}
private BoundExpression GenerateDisposeCall(
SyntaxNode syntax,
BoundExpression disposedExpression,
MethodArgumentInfo? disposeInfo,
BoundAwaitableInfo? awaitOpt,
SyntaxToken awaitKeyword)
{
Debug.Assert(awaitOpt is null || awaitKeyword != default);
// If we don't have an explicit dispose method, try and get the special member for IDisposable/IAsyncDisposable
MethodSymbol? disposeMethod = disposeInfo?.Method;
if (disposeMethod is null)
{
if (awaitOpt is null)
{
// IDisposable.Dispose()
Binder.TryGetSpecialTypeMember(_compilation, SpecialMember.System_IDisposable__Dispose, syntax, _diagnostics, out disposeMethod);
}
else
{
// IAsyncDisposable.DisposeAsync()
TryGetWellKnownTypeMember<MethodSymbol>(syntax: null, WellKnownMember.System_IAsyncDisposable__DisposeAsync, out disposeMethod, location: awaitKeyword.GetLocation());
}
}
BoundExpression disposeCall;
if (disposeMethod is null)
{
disposeCall = new BoundBadExpression(syntax, LookupResultKind.NotInvocable, ImmutableArray<Symbol?>.Empty, ImmutableArray.Create(disposedExpression), ErrorTypeSymbol.UnknownResultType);
}
else
{
if (disposeInfo is null)
{
// Generate the info for IDisposable.Dispose(). We know it has no arguments.
disposeInfo = MethodArgumentInfo.CreateParameterlessMethod(disposeMethod);
}
disposeCall = MakeCallWithNoExplicitArgument(disposeInfo, syntax, disposedExpression);
if (awaitOpt is object)
{
// await local.DisposeAsync()
_sawAwaitInExceptionHandler = true;
TypeSymbol awaitExpressionType = awaitOpt.GetResult?.ReturnType ?? _compilation.DynamicType;
disposeCall = RewriteAwaitExpression(syntax, disposeCall, awaitOpt, awaitExpressionType, false);
}
}
return disposeCall;
}
/// <summary>
/// Synthesize a call `expression.Method()`, but with some extra smarts to handle extension methods, and to fill-in optional and params parameters. This call expects that the
/// receiver parameter has already been visited.
/// </summary>
private BoundExpression MakeCallWithNoExplicitArgument(MethodArgumentInfo methodArgumentInfo, SyntaxNode syntax, BoundExpression? expression, bool assertParametersAreOptional = true)
{
MethodSymbol method = methodArgumentInfo.Method;
#if DEBUG
if (method.IsExtensionMethod)
{
Debug.Assert(expression == null);
Debug.Assert(method.Parameters.AsSpan()[1..].All(assertParametersAreOptional, (p, assertOptional) => (p.IsOptional || p.IsParams || !assertOptional) && p.RefKind == RefKind.None));
Debug.Assert(method.ParameterRefKinds.IsDefaultOrEmpty || method.ParameterRefKinds[0] is RefKind.In or RefKind.None);
}
else
{
Debug.Assert(!assertParametersAreOptional || method.Parameters.All(p => p.IsOptional || p.IsParams));
Debug.Assert(method.ParameterRefKinds.IsDefaultOrEmpty);
}
Debug.Assert(methodArgumentInfo.Arguments.All(arg => arg is not BoundConversion { ConversionKind: ConversionKind.InterpolatedStringHandler }));
#endif
return MakeArgumentsAndCall(
syntax,
expression,
method,
methodArgumentInfo.Arguments,
argumentRefKindsOpt: default,
expanded: methodArgumentInfo.Expanded,
invokedAsExtensionMethod: method.IsExtensionMethod,
methodArgumentInfo.ArgsToParamsOpt,
resultKind: LookupResultKind.Viable,
type: method.ReturnType,
temps: null);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicGenerateFromUsage.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicGenerateFromUsage : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicGenerateFromUsage(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicGenerateFromUsage))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateLocal)]
public void GenerateLocal()
{
SetUpEditor(
@"Module Program
Sub Main(args As String())
Dim x As String = $$xyz
End Sub
End Module");
VisualStudio.Editor.Verify.CodeAction("Generate local 'xyz'", applyFix: true);
VisualStudio.Editor.Verify.TextContains(
@"Module Program
Sub Main(args As String())
Dim xyz As String = Nothing
Dim x As String = xyz
End Sub
End Module");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public void GenerateTypeInNewFile()
{
SetUpEditor(
@"Module Program
Sub Main(args As String())
Dim x As New $$ClassInNewFile()
End Sub
End Module");
VisualStudio.Editor.Verify.CodeAction("Generate class 'ClassInNewFile' in new file", applyFix: true);
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "ClassInNewFile.vb");
VisualStudio.Editor.Verify.TextContains(
@"Friend Class ClassInNewFile
Public Sub New()
End Sub
End Class");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicGenerateFromUsage : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicGenerateFromUsage(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicGenerateFromUsage))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateLocal)]
public void GenerateLocal()
{
SetUpEditor(
@"Module Program
Sub Main(args As String())
Dim x As String = $$xyz
End Sub
End Module");
VisualStudio.Editor.Verify.CodeAction("Generate local 'xyz'", applyFix: true);
VisualStudio.Editor.Verify.TextContains(
@"Module Program
Sub Main(args As String())
Dim xyz As String = Nothing
Dim x As String = xyz
End Sub
End Module");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public void GenerateTypeInNewFile()
{
SetUpEditor(
@"Module Program
Sub Main(args As String())
Dim x As New $$ClassInNewFile()
End Sub
End Module");
VisualStudio.Editor.Verify.CodeAction("Generate class 'ClassInNewFile' in new file", applyFix: true);
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "ClassInNewFile.vb");
VisualStudio.Editor.Verify.TextContains(
@"Friend Class ClassInNewFile
Public Sub New()
End Sub
End Class");
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/CSharp/Test/ProjectSystemShim/CPS/CSharpCompilerOptionsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.LanguageServices.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS
{
[UseExportProvider]
public class CSharpCompilerOptionsTests : TestBase
{
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task DocumentationModeSetToDiagnoseIfProducingDocFile_CPS()
{
using var environment = new TestEnvironment();
using var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", commandLineArguments: @"/doc:DocFile.xml");
var parseOptions = environment.Workspace.CurrentSolution.Projects.Single().ParseOptions;
Assert.Equal(DocumentationMode.Diagnose, parseOptions.DocumentationMode);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task DocumentationModeSetToParseIfNotProducingDocFile_CPS()
{
using var environment = new TestEnvironment();
using var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", commandLineArguments: @"/doc:");
var parseOptions = environment.Workspace.CurrentSolution.Projects.Single().ParseOptions;
Assert.Equal(DocumentationMode.Parse, parseOptions.DocumentationMode);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task ProjectSettingsOptionAddAndRemove_CPS()
{
using var environment = new TestEnvironment();
using var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", commandLineArguments: @"/warnaserror:CS1111");
var options = environment.GetUpdatedCompilationOptionOfSingleProject();
Assert.Equal(expected: ReportDiagnostic.Error, actual: options.SpecificDiagnosticOptions["CS1111"]);
project.SetOptions(ImmutableArray.Create(@"/warnaserror"));
options = environment.GetUpdatedCompilationOptionOfSingleProject();
Assert.False(options.SpecificDiagnosticOptions.ContainsKey("CS1111"));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task ProjectOutputBinPathChange_CPS()
{
var initialObjPath = @"C:\test.dll";
var initialBinPath = initialObjPath;
using var environment = new TestEnvironment();
using var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", commandLineArguments: $"/out:{initialObjPath}");
Assert.Equal(initialObjPath, project.CompilationOutputAssemblyFilePath);
Assert.Equal(initialBinPath, project.BinOutputPath);
// Change obj output folder from command line arguments - verify that objOutputPath changes, but binOutputPath is the same.
var newObjPath = @"C:\NewFolder\test.dll";
project.SetOptions(ImmutableArray.Create($"/out:{newObjPath}"));
Assert.Equal(newObjPath, project.CompilationOutputAssemblyFilePath);
Assert.Equal(initialBinPath, project.BinOutputPath);
// Change output file name - verify that objOutputPath changes, but binOutputPath is the same.
newObjPath = @"C:\NewFolder\test2.dll";
project.SetOptions(ImmutableArray.Create($"/out:{newObjPath}"));
Assert.Equal(newObjPath, project.CompilationOutputAssemblyFilePath);
Assert.Equal(initialBinPath, project.BinOutputPath);
// Change output file name and folder - verify that objOutputPath changes, but binOutputPath is the same.
newObjPath = @"C:\NewFolder3\test3.dll";
project.SetOptions(ImmutableArray.Create($"/out:{newObjPath}"));
Assert.Equal(newObjPath, project.CompilationOutputAssemblyFilePath);
Assert.Equal(initialBinPath, project.BinOutputPath);
// Change bin output folder - verify that binOutputPath changes, but objOutputPath is the same.
var newBinPath = @"C:\NewFolder4\test.dll";
project.BinOutputPath = newBinPath;
Assert.Equal(newObjPath, project.CompilationOutputAssemblyFilePath);
Assert.Equal(newBinPath, project.BinOutputPath);
// Change bin output folder to non-normalized path - verify that binOutputPath changes to normalized path, but objOutputPath is the same.
newBinPath = @"test.dll";
var expectedNewBinPath = Path.Combine(Path.GetTempPath(), newBinPath);
project.BinOutputPath = newBinPath;
Assert.Equal(newObjPath, project.CompilationOutputAssemblyFilePath);
Assert.Equal(expectedNewBinPath, project.BinOutputPath);
}
[WpfFact, WorkItem(14520, "https://github.com/dotnet/roslyn/issues/14520")]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task InvalidProjectOutputBinPaths_CPS1()
{
using var environment = new TestEnvironment();
using var project1 = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", binOutputPath: null);
// Null output path is allowed.
Assert.Null(project1.BinOutputPath);
}
[WpfFact, WorkItem(14520, "https://github.com/dotnet/roslyn/issues/14520")]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task InvalidProjectOutputBinPaths_CPS2()
{
using var environment = new TestEnvironment();
using var project2 = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test2", binOutputPath: String.Empty);
// Empty output path is not allowed, it gets reset to null.
Assert.Null(project2.BinOutputPath);
}
[WpfFact, WorkItem(14520, "https://github.com/dotnet/roslyn/issues/14520")]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task InvalidProjectOutputBinPaths_CPS3()
{
using var environment = new TestEnvironment();
using var project3 = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test3", binOutputPath: "Test.dll");
// Non-rooted output path is not allowed, it gets reset to a temp rooted path.
Assert.Equal(Path.Combine(Path.GetTempPath(), "Test.dll"), project3.BinOutputPath);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task ProjectGuidSetter_CPS()
{
var initialGuid = Guid.NewGuid();
using var environment = new TestEnvironment();
using IWorkspaceProjectContext projectContext = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", initialGuid);
Assert.Equal(initialGuid, projectContext.Guid);
var newGuid = Guid.NewGuid();
projectContext.Guid = newGuid;
Assert.Equal(newGuid, projectContext.Guid);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task ProjectLastDesignTimeBuildSucceededSetter_CPS()
{
using var environment = new TestEnvironment();
using IWorkspaceProjectContext projectContext = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test");
Assert.True(projectContext.LastDesignTimeBuildSucceeded);
projectContext.LastDesignTimeBuildSucceeded = false;
Assert.False(projectContext.LastDesignTimeBuildSucceeded);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task ProjectDisplayNameSetter_CPS()
{
using var environment = new TestEnvironment();
using IWorkspaceProjectContext project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test");
Assert.Equal("Test", project.DisplayName);
var initialProjectFilePath = project.ProjectFilePath;
var newProjectDisplayName = "Test2";
project.DisplayName = newProjectDisplayName;
Assert.Equal(newProjectDisplayName, project.DisplayName);
Assert.Equal(initialProjectFilePath, project.ProjectFilePath);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task ProjectFilePathSetter_CPS()
{
using var environment = new TestEnvironment();
using IWorkspaceProjectContext project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test");
var initialProjectDisplayName = project.DisplayName;
var initialProjectFilePath = project.ProjectFilePath;
var newFilePath = Temp.CreateFile().Path;
var extension = PathUtilities.GetExtension(initialProjectFilePath);
if (!string.IsNullOrEmpty(extension))
{
newFilePath = PathUtilities.ChangeExtension(newFilePath, extension);
}
project.ProjectFilePath = newFilePath;
Assert.Equal(newFilePath, project.ProjectFilePath);
Assert.Equal(initialProjectDisplayName, project.DisplayName);
SharedResourceHelpers.CleanupAllGeneratedFiles(newFilePath);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.LanguageServices.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS
{
[UseExportProvider]
public class CSharpCompilerOptionsTests : TestBase
{
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task DocumentationModeSetToDiagnoseIfProducingDocFile_CPS()
{
using var environment = new TestEnvironment();
using var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", commandLineArguments: @"/doc:DocFile.xml");
var parseOptions = environment.Workspace.CurrentSolution.Projects.Single().ParseOptions;
Assert.Equal(DocumentationMode.Diagnose, parseOptions.DocumentationMode);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task DocumentationModeSetToParseIfNotProducingDocFile_CPS()
{
using var environment = new TestEnvironment();
using var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", commandLineArguments: @"/doc:");
var parseOptions = environment.Workspace.CurrentSolution.Projects.Single().ParseOptions;
Assert.Equal(DocumentationMode.Parse, parseOptions.DocumentationMode);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task ProjectSettingsOptionAddAndRemove_CPS()
{
using var environment = new TestEnvironment();
using var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", commandLineArguments: @"/warnaserror:CS1111");
var options = environment.GetUpdatedCompilationOptionOfSingleProject();
Assert.Equal(expected: ReportDiagnostic.Error, actual: options.SpecificDiagnosticOptions["CS1111"]);
project.SetOptions(ImmutableArray.Create(@"/warnaserror"));
options = environment.GetUpdatedCompilationOptionOfSingleProject();
Assert.False(options.SpecificDiagnosticOptions.ContainsKey("CS1111"));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task ProjectOutputBinPathChange_CPS()
{
var initialObjPath = @"C:\test.dll";
var initialBinPath = initialObjPath;
using var environment = new TestEnvironment();
using var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", commandLineArguments: $"/out:{initialObjPath}");
Assert.Equal(initialObjPath, project.CompilationOutputAssemblyFilePath);
Assert.Equal(initialBinPath, project.BinOutputPath);
// Change obj output folder from command line arguments - verify that objOutputPath changes, but binOutputPath is the same.
var newObjPath = @"C:\NewFolder\test.dll";
project.SetOptions(ImmutableArray.Create($"/out:{newObjPath}"));
Assert.Equal(newObjPath, project.CompilationOutputAssemblyFilePath);
Assert.Equal(initialBinPath, project.BinOutputPath);
// Change output file name - verify that objOutputPath changes, but binOutputPath is the same.
newObjPath = @"C:\NewFolder\test2.dll";
project.SetOptions(ImmutableArray.Create($"/out:{newObjPath}"));
Assert.Equal(newObjPath, project.CompilationOutputAssemblyFilePath);
Assert.Equal(initialBinPath, project.BinOutputPath);
// Change output file name and folder - verify that objOutputPath changes, but binOutputPath is the same.
newObjPath = @"C:\NewFolder3\test3.dll";
project.SetOptions(ImmutableArray.Create($"/out:{newObjPath}"));
Assert.Equal(newObjPath, project.CompilationOutputAssemblyFilePath);
Assert.Equal(initialBinPath, project.BinOutputPath);
// Change bin output folder - verify that binOutputPath changes, but objOutputPath is the same.
var newBinPath = @"C:\NewFolder4\test.dll";
project.BinOutputPath = newBinPath;
Assert.Equal(newObjPath, project.CompilationOutputAssemblyFilePath);
Assert.Equal(newBinPath, project.BinOutputPath);
// Change bin output folder to non-normalized path - verify that binOutputPath changes to normalized path, but objOutputPath is the same.
newBinPath = @"test.dll";
var expectedNewBinPath = Path.Combine(Path.GetTempPath(), newBinPath);
project.BinOutputPath = newBinPath;
Assert.Equal(newObjPath, project.CompilationOutputAssemblyFilePath);
Assert.Equal(expectedNewBinPath, project.BinOutputPath);
}
[WpfFact, WorkItem(14520, "https://github.com/dotnet/roslyn/issues/14520")]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task InvalidProjectOutputBinPaths_CPS1()
{
using var environment = new TestEnvironment();
using var project1 = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", binOutputPath: null);
// Null output path is allowed.
Assert.Null(project1.BinOutputPath);
}
[WpfFact, WorkItem(14520, "https://github.com/dotnet/roslyn/issues/14520")]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task InvalidProjectOutputBinPaths_CPS2()
{
using var environment = new TestEnvironment();
using var project2 = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test2", binOutputPath: String.Empty);
// Empty output path is not allowed, it gets reset to null.
Assert.Null(project2.BinOutputPath);
}
[WpfFact, WorkItem(14520, "https://github.com/dotnet/roslyn/issues/14520")]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task InvalidProjectOutputBinPaths_CPS3()
{
using var environment = new TestEnvironment();
using var project3 = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test3", binOutputPath: "Test.dll");
// Non-rooted output path is not allowed, it gets reset to a temp rooted path.
Assert.Equal(Path.Combine(Path.GetTempPath(), "Test.dll"), project3.BinOutputPath);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task ProjectGuidSetter_CPS()
{
var initialGuid = Guid.NewGuid();
using var environment = new TestEnvironment();
using IWorkspaceProjectContext projectContext = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", initialGuid);
Assert.Equal(initialGuid, projectContext.Guid);
var newGuid = Guid.NewGuid();
projectContext.Guid = newGuid;
Assert.Equal(newGuid, projectContext.Guid);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task ProjectLastDesignTimeBuildSucceededSetter_CPS()
{
using var environment = new TestEnvironment();
using IWorkspaceProjectContext projectContext = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test");
Assert.True(projectContext.LastDesignTimeBuildSucceeded);
projectContext.LastDesignTimeBuildSucceeded = false;
Assert.False(projectContext.LastDesignTimeBuildSucceeded);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task ProjectDisplayNameSetter_CPS()
{
using var environment = new TestEnvironment();
using IWorkspaceProjectContext project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test");
Assert.Equal("Test", project.DisplayName);
var initialProjectFilePath = project.ProjectFilePath;
var newProjectDisplayName = "Test2";
project.DisplayName = newProjectDisplayName;
Assert.Equal(newProjectDisplayName, project.DisplayName);
Assert.Equal(initialProjectFilePath, project.ProjectFilePath);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.ProjectSystemShims)]
public async Task ProjectFilePathSetter_CPS()
{
using var environment = new TestEnvironment();
using IWorkspaceProjectContext project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test");
var initialProjectDisplayName = project.DisplayName;
var initialProjectFilePath = project.ProjectFilePath;
var newFilePath = Temp.CreateFile().Path;
var extension = PathUtilities.GetExtension(initialProjectFilePath);
if (!string.IsNullOrEmpty(extension))
{
newFilePath = PathUtilities.ChangeExtension(newFilePath, extension);
}
project.ProjectFilePath = newFilePath;
Assert.Equal(newFilePath, project.ProjectFilePath);
Assert.Equal(initialProjectDisplayName, project.DisplayName);
SharedResourceHelpers.CleanupAllGeneratedFiles(newFilePath);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Test/Syntax/IncrementalParsing/ChangingAsync.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.IncrementalParsing
{
// These tests handle changing between asynchronous and synchronous parsing contexts as the 'async' modifier is added / removed.
public class ChangingAsync
{
[Fact]
public void AddAsync()
{
string oldText =
@"class Test
{
public static void F()
{
await t;
}
}";
ParseAndVerify(oldText, validator: oldTree =>
{
var newTree = oldTree.WithInsertBefore("public", "async ");
Assert.Equal(default(SyntaxNodeOrToken), oldTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
Assert.NotEqual(default(SyntaxNodeOrToken), newTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
});
}
[Fact]
public void RemoveAsync()
{
string oldText =
@"class Test
{
async public static void F()
{
await t;
}
}";
ParseAndVerify(oldText, validator: oldTree =>
{
var newTree = oldTree.WithRemoveFirst("async");
Assert.NotEqual(default(SyntaxNodeOrToken), oldTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
Assert.Equal(default(SyntaxNodeOrToken), newTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
});
}
#region Helpers
private static void ParseAndVerify(string text, Action<SyntaxTree> validator)
{
ParseAndValidate(text, validator, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5));
ParseAndValidate(text, validator, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp5));
}
private static void ParseAndValidate(string text, Action<SyntaxTree> validator, CSharpParseOptions options = null)
{
var oldTree = SyntaxFactory.ParseSyntaxTree(text);
validator(oldTree);
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.IncrementalParsing
{
// These tests handle changing between asynchronous and synchronous parsing contexts as the 'async' modifier is added / removed.
public class ChangingAsync
{
[Fact]
public void AddAsync()
{
string oldText =
@"class Test
{
public static void F()
{
await t;
}
}";
ParseAndVerify(oldText, validator: oldTree =>
{
var newTree = oldTree.WithInsertBefore("public", "async ");
Assert.Equal(default(SyntaxNodeOrToken), oldTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
Assert.NotEqual(default(SyntaxNodeOrToken), newTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
});
}
[Fact]
public void RemoveAsync()
{
string oldText =
@"class Test
{
async public static void F()
{
await t;
}
}";
ParseAndVerify(oldText, validator: oldTree =>
{
var newTree = oldTree.WithRemoveFirst("async");
Assert.NotEqual(default(SyntaxNodeOrToken), oldTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
Assert.Equal(default(SyntaxNodeOrToken), newTree.FindNodeOrTokenByKind(SyntaxKind.AwaitExpression));
});
}
#region Helpers
private static void ParseAndVerify(string text, Action<SyntaxTree> validator)
{
ParseAndValidate(text, validator, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5));
ParseAndValidate(text, validator, TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp5));
}
private static void ParseAndValidate(string text, Action<SyntaxTree> validator, CSharpParseOptions options = null)
{
var oldTree = SyntaxFactory.ParseSyntaxTree(text);
validator(oldTree);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/Remote/ServiceHub/Host/RemoteAnalyzerAssemblyLoaderService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Remote.Diagnostics
{
/// <summary>
/// Customizes the path where to store shadow-copies of analyzer assemblies.
/// </summary>
[ExportWorkspaceService(typeof(IAnalyzerAssemblyLoaderProvider), WorkspaceKind.RemoteWorkspace), Shared]
internal sealed class RemoteAnalyzerAssemblyLoaderService : IAnalyzerAssemblyLoaderProvider
{
private readonly RemoteAnalyzerAssemblyLoader _loader;
private readonly ShadowCopyAnalyzerAssemblyLoader _shadowCopyLoader;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RemoteAnalyzerAssemblyLoaderService()
{
var baseDirectory = Path.GetDirectoryName(Path.GetFullPath(typeof(RemoteAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location));
Debug.Assert(baseDirectory != null);
_loader = new(baseDirectory);
_shadowCopyLoader = new(Path.Combine(Path.GetTempPath(), "VS", "AnalyzerAssemblyLoader"));
}
public IAnalyzerAssemblyLoader GetLoader(in AnalyzerAssemblyLoaderOptions options)
=> options.ShadowCopy ? _shadowCopyLoader : _loader;
// For analyzers shipped in Roslyn, different set of assemblies might be used when running
// in-proc and OOP e.g. in-proc (VS) running on desktop clr and OOP running on ServiceHub .Net6
// host. We need to make sure to use the ones from the same location as the remote.
private sealed class RemoteAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader
{
private readonly string _baseDirectory;
public RemoteAnalyzerAssemblyLoader(string baseDirectory)
{
_baseDirectory = baseDirectory;
}
protected override string GetPathToLoad(string fullPath)
{
var fixedPath = Path.GetFullPath(Path.Combine(_baseDirectory, Path.GetFileName(fullPath)));
return File.Exists(fixedPath) ? fixedPath : fullPath;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Remote.Diagnostics
{
/// <summary>
/// Customizes the path where to store shadow-copies of analyzer assemblies.
/// </summary>
[ExportWorkspaceService(typeof(IAnalyzerAssemblyLoaderProvider), WorkspaceKind.RemoteWorkspace), Shared]
internal sealed class RemoteAnalyzerAssemblyLoaderService : IAnalyzerAssemblyLoaderProvider
{
private readonly RemoteAnalyzerAssemblyLoader _loader;
private readonly ShadowCopyAnalyzerAssemblyLoader _shadowCopyLoader;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RemoteAnalyzerAssemblyLoaderService()
{
var baseDirectory = Path.GetDirectoryName(Path.GetFullPath(typeof(RemoteAnalyzerAssemblyLoader).GetTypeInfo().Assembly.Location));
Debug.Assert(baseDirectory != null);
_loader = new(baseDirectory);
_shadowCopyLoader = new(Path.Combine(Path.GetTempPath(), "VS", "AnalyzerAssemblyLoader"));
}
public IAnalyzerAssemblyLoader GetLoader(in AnalyzerAssemblyLoaderOptions options)
=> options.ShadowCopy ? _shadowCopyLoader : _loader;
// For analyzers shipped in Roslyn, different set of assemblies might be used when running
// in-proc and OOP e.g. in-proc (VS) running on desktop clr and OOP running on ServiceHub .Net6
// host. We need to make sure to use the ones from the same location as the remote.
private sealed class RemoteAnalyzerAssemblyLoader : DefaultAnalyzerAssemblyLoader
{
private readonly string _baseDirectory;
public RemoteAnalyzerAssemblyLoader(string baseDirectory)
{
_baseDirectory = baseDirectory;
}
protected override string GetPathToLoad(string fullPath)
{
var fixedPath = Path.GetFullPath(Path.Combine(_baseDirectory, Path.GetFileName(fullPath)));
return File.Exists(fixedPath) ? fixedPath : fullPath;
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerService_UpdateSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class DiagnosticAnalyzerService : IDiagnosticUpdateSource
{
public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated
{
add
{
_eventMap.AddEventHandler(DiagnosticsUpdatedEventName, value);
}
remove
{
_eventMap.RemoveEventHandler(DiagnosticsUpdatedEventName, value);
}
}
public event EventHandler DiagnosticsCleared
{
add
{
// don't do anything. this update source doesn't use cleared event
}
remove
{
// don't do anything. this update source doesn't use cleared event
}
}
internal void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs args)
{
// all diagnostics events are serialized.
var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName);
if (ev.HasHandlers)
{
_eventQueue.ScheduleTask(nameof(RaiseDiagnosticsUpdated), () => ev.RaiseEvent(handler => handler(this, args)), CancellationToken.None);
}
}
internal void RaiseBulkDiagnosticsUpdated(Action<Action<DiagnosticsUpdatedArgs>> eventAction)
{
// all diagnostics events are serialized.
var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName);
if (ev.HasHandlers)
{
// we do this bulk update to reduce number of tasks (with captured data) enqueued.
// we saw some "out of memory" due to us having long list of pending tasks in memory.
// this is to reduce for such case to happen.
void raiseEvents(DiagnosticsUpdatedArgs args) => ev.RaiseEvent(handler => handler(this, args));
_eventQueue.ScheduleTask(nameof(RaiseDiagnosticsUpdated), () => eventAction(raiseEvents), CancellationToken.None);
}
}
internal void RaiseBulkDiagnosticsUpdated(Func<Action<DiagnosticsUpdatedArgs>, Task> eventActionAsync)
{
// all diagnostics events are serialized.
var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName);
if (ev.HasHandlers)
{
// we do this bulk update to reduce number of tasks (with captured data) enqueued.
// we saw some "out of memory" due to us having long list of pending tasks in memory.
// this is to reduce for such case to happen.
void raiseEvents(DiagnosticsUpdatedArgs args) => ev.RaiseEvent(handler => handler(this, args));
_eventQueue.ScheduleTask(nameof(RaiseDiagnosticsUpdated), () => eventActionAsync(raiseEvents), CancellationToken.None);
}
}
bool IDiagnosticUpdateSource.SupportGetDiagnostics => true;
ValueTask<ImmutableArray<DiagnosticData>> IDiagnosticUpdateSource.GetDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken)
{
if (id != null)
{
return new ValueTask<ImmutableArray<DiagnosticData>>(GetSpecificCachedDiagnosticsAsync(workspace, id, includeSuppressedDiagnostics, cancellationToken));
}
return new ValueTask<ImmutableArray<DiagnosticData>>(GetCachedDiagnosticsAsync(workspace, projectId, documentId, includeSuppressedDiagnostics, cancellationToken));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class DiagnosticAnalyzerService : IDiagnosticUpdateSource
{
public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated
{
add
{
_eventMap.AddEventHandler(DiagnosticsUpdatedEventName, value);
}
remove
{
_eventMap.RemoveEventHandler(DiagnosticsUpdatedEventName, value);
}
}
public event EventHandler DiagnosticsCleared
{
add
{
// don't do anything. this update source doesn't use cleared event
}
remove
{
// don't do anything. this update source doesn't use cleared event
}
}
internal void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs args)
{
// all diagnostics events are serialized.
var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName);
if (ev.HasHandlers)
{
_eventQueue.ScheduleTask(nameof(RaiseDiagnosticsUpdated), () => ev.RaiseEvent(handler => handler(this, args)), CancellationToken.None);
}
}
internal void RaiseBulkDiagnosticsUpdated(Action<Action<DiagnosticsUpdatedArgs>> eventAction)
{
// all diagnostics events are serialized.
var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName);
if (ev.HasHandlers)
{
// we do this bulk update to reduce number of tasks (with captured data) enqueued.
// we saw some "out of memory" due to us having long list of pending tasks in memory.
// this is to reduce for such case to happen.
void raiseEvents(DiagnosticsUpdatedArgs args) => ev.RaiseEvent(handler => handler(this, args));
_eventQueue.ScheduleTask(nameof(RaiseDiagnosticsUpdated), () => eventAction(raiseEvents), CancellationToken.None);
}
}
internal void RaiseBulkDiagnosticsUpdated(Func<Action<DiagnosticsUpdatedArgs>, Task> eventActionAsync)
{
// all diagnostics events are serialized.
var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName);
if (ev.HasHandlers)
{
// we do this bulk update to reduce number of tasks (with captured data) enqueued.
// we saw some "out of memory" due to us having long list of pending tasks in memory.
// this is to reduce for such case to happen.
void raiseEvents(DiagnosticsUpdatedArgs args) => ev.RaiseEvent(handler => handler(this, args));
_eventQueue.ScheduleTask(nameof(RaiseDiagnosticsUpdated), () => eventActionAsync(raiseEvents), CancellationToken.None);
}
}
bool IDiagnosticUpdateSource.SupportGetDiagnostics => true;
ValueTask<ImmutableArray<DiagnosticData>> IDiagnosticUpdateSource.GetDiagnosticsAsync(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken)
{
if (id != null)
{
return new ValueTask<ImmutableArray<DiagnosticData>>(GetSpecificCachedDiagnosticsAsync(workspace, id, includeSuppressedDiagnostics, cancellationToken));
}
return new ValueTask<ImmutableArray<DiagnosticData>>(GetCachedDiagnosticsAsync(workspace, projectId, documentId, includeSuppressedDiagnostics, cancellationToken));
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/LanguageServer/Protocol/Handler/DocumentChanges/DidChangeHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges
{
[ExportRoslynLanguagesLspRequestHandlerProvider, Shared]
[ProvidesMethod(LSP.Methods.TextDocumentDidChangeName)]
internal class DidChangeHandler : AbstractStatelessRequestHandler<LSP.DidChangeTextDocumentParams, object?>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DidChangeHandler()
{
}
public override string Method => LSP.Methods.TextDocumentDidChangeName;
public override bool MutatesSolutionState => true;
public override bool RequiresLSPSolution => false;
public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.DidChangeTextDocumentParams request) => request.TextDocument;
public override Task<object?> HandleRequestAsync(LSP.DidChangeTextDocumentParams request, RequestContext context, CancellationToken cancellationToken)
{
var text = context.GetTrackedDocumentSourceText(request.TextDocument.Uri);
// Per the LSP spec, each text change builds upon the previous, so we don't need to translate
// any text positions between changes, which makes this quite easy.
var changes = request.ContentChanges.Select(change => ProtocolConversions.ContentChangeEventToTextChange(change, text));
text = text.WithChanges(changes);
context.UpdateTrackedDocument(request.TextDocument.Uri, text);
return SpecializedTasks.Default<object>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges
{
[ExportRoslynLanguagesLspRequestHandlerProvider, Shared]
[ProvidesMethod(LSP.Methods.TextDocumentDidChangeName)]
internal class DidChangeHandler : AbstractStatelessRequestHandler<LSP.DidChangeTextDocumentParams, object?>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DidChangeHandler()
{
}
public override string Method => LSP.Methods.TextDocumentDidChangeName;
public override bool MutatesSolutionState => true;
public override bool RequiresLSPSolution => false;
public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.DidChangeTextDocumentParams request) => request.TextDocument;
public override Task<object?> HandleRequestAsync(LSP.DidChangeTextDocumentParams request, RequestContext context, CancellationToken cancellationToken)
{
var text = context.GetTrackedDocumentSourceText(request.TextDocument.Uri);
// Per the LSP spec, each text change builds upon the previous, so we don't need to translate
// any text positions between changes, which makes this quite easy.
var changes = request.ContentChanges.Select(change => ProtocolConversions.ContentChangeEventToTextChange(change, text));
text = text.WithChanges(changes);
context.UpdateTrackedDocument(request.TextDocument.Uri, text);
return SpecializedTasks.Default<object>();
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Core/Portable/Emit/EmitOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
/// <summary>
/// Represents compilation emit options.
/// </summary>
public sealed class EmitOptions : IEquatable<EmitOptions>
{
internal static readonly EmitOptions Default = PlatformInformation.IsWindows
? new EmitOptions()
: new EmitOptions().WithDebugInformationFormat(DebugInformationFormat.PortablePdb);
/// <summary>
/// True to emit an assembly excluding executable code such as method bodies.
/// </summary>
public bool EmitMetadataOnly { get; private set; }
/// <summary>
/// Tolerate errors, producing a PE stream and a success result even in the presence of (some) errors.
/// </summary>
public bool TolerateErrors { get; private set; }
/// <summary>
/// Unless set (private) members that don't affect the language semantics of the resulting assembly will be excluded
/// when emitting metadata-only assemblies as primary output (with <see cref="EmitMetadataOnly"/> on).
/// If emitting a secondary output, this flag is required to be false.
/// </summary>
public bool IncludePrivateMembers { get; private set; }
/// <summary>
/// Type of instrumentation that should be added to the output binary.
/// </summary>
public ImmutableArray<InstrumentationKind> InstrumentationKinds { get; private set; }
/// <summary>
/// Subsystem version
/// </summary>
public SubsystemVersion SubsystemVersion { get; private set; }
/// <summary>
/// Specifies the size of sections in the output file.
/// </summary>
/// <remarks>
/// Valid values are 0, 512, 1024, 2048, 4096 and 8192.
/// If the value is 0 the file alignment is determined based upon the value of <see cref="Platform"/>.
/// </remarks>
public int FileAlignment { get; private set; }
/// <summary>
/// True to enable high entropy virtual address space for the output binary.
/// </summary>
public bool HighEntropyVirtualAddressSpace { get; private set; }
/// <summary>
/// Specifies the preferred base address at which to load the output DLL.
/// </summary>
public ulong BaseAddress { get; private set; }
/// <summary>
/// Debug information format.
/// </summary>
public DebugInformationFormat DebugInformationFormat { get; private set; }
/// <summary>
/// Assembly name override - file name and extension. If not specified the compilation name is used.
/// </summary>
/// <remarks>
/// By default the name of the output assembly is <see cref="Compilation.AssemblyName"/>. Only in rare cases it is necessary
/// to override the name.
///
/// CAUTION: If this is set to a (non-null) value other than the existing compilation output name, then internals-visible-to
/// and assembly references may not work as expected. In particular, things that were visible at bind time, based on the
/// name of the compilation, may not be visible at runtime and vice-versa.
/// </remarks>
public string? OutputNameOverride { get; private set; }
/// <summary>
/// The name of the PDB file to be embedded in the PE image, or null to use the default.
/// </summary>
/// <remarks>
/// If not specified the file name of the source module with an extension changed to "pdb" is used.
/// </remarks>
public string? PdbFilePath { get; private set; }
/// <summary>
/// A crypto hash algorithm used to calculate PDB Checksum stored in the PE/COFF File.
/// If not specified (the value is <c>default(HashAlgorithmName)</c>) the checksum is not calculated.
/// </summary>
public HashAlgorithmName PdbChecksumAlgorithm { get; private set; }
/// <summary>
/// Runtime metadata version.
/// </summary>
public string? RuntimeMetadataVersion { get; private set; }
/// <summary>
/// The encoding used to parse source files that do not have a Byte Order Mark. If specified,
/// is stored in the emitted PDB in order to allow recreating the original compilation.
/// </summary>
public Encoding? DefaultSourceFileEncoding { get; private set; }
/// <summary>
/// If <see cref="DefaultSourceFileEncoding"/> is not specified, the encoding used to parse source files
/// that do not declare their encoding via Byte Order Mark and are not UTF8-encoded.
/// </summary>
public Encoding? FallbackSourceFileEncoding { get; private set; }
// 1.2 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string pdbFilePath,
string outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds: ImmutableArray<InstrumentationKind>.Empty)
{
}
// 2.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string pdbFilePath,
string outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers,
ImmutableArray<InstrumentationKind> instrumentationKinds)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds,
pdbChecksumAlgorithm: null)
{
}
// 3.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string? pdbFilePath,
string? outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string? runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers,
ImmutableArray<InstrumentationKind> instrumentationKinds,
HashAlgorithmName? pdbChecksumAlgorithm)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds,
pdbChecksumAlgorithm,
defaultSourceFileEncoding: null,
fallbackSourceFileEncoding: null)
{
}
public EmitOptions(
bool metadataOnly = false,
DebugInformationFormat debugInformationFormat = 0,
string? pdbFilePath = null,
string? outputNameOverride = null,
int fileAlignment = 0,
ulong baseAddress = 0,
bool highEntropyVirtualAddressSpace = false,
SubsystemVersion subsystemVersion = default,
string? runtimeMetadataVersion = null,
bool tolerateErrors = false,
bool includePrivateMembers = true,
ImmutableArray<InstrumentationKind> instrumentationKinds = default,
HashAlgorithmName? pdbChecksumAlgorithm = null,
Encoding? defaultSourceFileEncoding = null,
Encoding? fallbackSourceFileEncoding = null)
{
EmitMetadataOnly = metadataOnly;
DebugInformationFormat = (debugInformationFormat == 0) ? DebugInformationFormat.Pdb : debugInformationFormat;
PdbFilePath = pdbFilePath;
OutputNameOverride = outputNameOverride;
FileAlignment = fileAlignment;
BaseAddress = baseAddress;
HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace;
SubsystemVersion = subsystemVersion;
RuntimeMetadataVersion = runtimeMetadataVersion;
TolerateErrors = tolerateErrors;
IncludePrivateMembers = includePrivateMembers;
InstrumentationKinds = instrumentationKinds.NullToEmpty();
PdbChecksumAlgorithm = pdbChecksumAlgorithm ?? HashAlgorithmName.SHA256;
DefaultSourceFileEncoding = defaultSourceFileEncoding;
FallbackSourceFileEncoding = fallbackSourceFileEncoding;
}
private EmitOptions(EmitOptions other) : this(
other.EmitMetadataOnly,
other.DebugInformationFormat,
other.PdbFilePath,
other.OutputNameOverride,
other.FileAlignment,
other.BaseAddress,
other.HighEntropyVirtualAddressSpace,
other.SubsystemVersion,
other.RuntimeMetadataVersion,
other.TolerateErrors,
other.IncludePrivateMembers,
other.InstrumentationKinds,
other.PdbChecksumAlgorithm,
other.DefaultSourceFileEncoding,
other.FallbackSourceFileEncoding)
{
}
public override bool Equals(object? obj)
{
return Equals(obj as EmitOptions);
}
public bool Equals(EmitOptions? other)
{
if (ReferenceEquals(other, null))
{
return false;
}
return
EmitMetadataOnly == other.EmitMetadataOnly &&
BaseAddress == other.BaseAddress &&
FileAlignment == other.FileAlignment &&
HighEntropyVirtualAddressSpace == other.HighEntropyVirtualAddressSpace &&
SubsystemVersion.Equals(other.SubsystemVersion) &&
DebugInformationFormat == other.DebugInformationFormat &&
PdbFilePath == other.PdbFilePath &&
PdbChecksumAlgorithm == other.PdbChecksumAlgorithm &&
OutputNameOverride == other.OutputNameOverride &&
RuntimeMetadataVersion == other.RuntimeMetadataVersion &&
TolerateErrors == other.TolerateErrors &&
IncludePrivateMembers == other.IncludePrivateMembers &&
InstrumentationKinds.NullToEmpty().SequenceEqual(other.InstrumentationKinds.NullToEmpty(), (a, b) => a == b) &&
DefaultSourceFileEncoding == other.DefaultSourceFileEncoding &&
FallbackSourceFileEncoding == other.FallbackSourceFileEncoding;
}
public override int GetHashCode()
{
return Hash.Combine(EmitMetadataOnly,
Hash.Combine(BaseAddress.GetHashCode(),
Hash.Combine(FileAlignment,
Hash.Combine(HighEntropyVirtualAddressSpace,
Hash.Combine(SubsystemVersion.GetHashCode(),
Hash.Combine((int)DebugInformationFormat,
Hash.Combine(PdbFilePath,
Hash.Combine(PdbChecksumAlgorithm.GetHashCode(),
Hash.Combine(OutputNameOverride,
Hash.Combine(RuntimeMetadataVersion,
Hash.Combine(TolerateErrors,
Hash.Combine(IncludePrivateMembers,
Hash.Combine(Hash.CombineValues(InstrumentationKinds),
Hash.Combine(DefaultSourceFileEncoding,
Hash.Combine(FallbackSourceFileEncoding, 0)))))))))))))));
}
public static bool operator ==(EmitOptions? left, EmitOptions? right)
{
return object.Equals(left, right);
}
public static bool operator !=(EmitOptions? left, EmitOptions? right)
{
return !object.Equals(left, right);
}
internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider, bool isDeterministic)
{
if (!DebugInformationFormat.IsValid())
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat));
}
foreach (var instrumentationKind in InstrumentationKinds)
{
if (!instrumentationKind.IsValid())
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)instrumentationKind));
}
}
if (OutputNameOverride != null)
{
MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics);
}
if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment))
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment));
}
if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString()));
}
if (PdbChecksumAlgorithm.Name != null)
{
try
{
IncrementalHash.CreateHash(PdbChecksumAlgorithm).Dispose();
}
catch
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, PdbChecksumAlgorithm.ToString()));
}
}
else if (isDeterministic)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, ""));
}
}
internal bool EmitTestCoverageData => InstrumentationKinds.Contains(InstrumentationKind.TestCoverage);
internal static bool IsValidFileAlignment(int value)
{
switch (value)
{
case 512:
case 1024:
case 2048:
case 4096:
case 8192:
return true;
default:
return false;
}
}
public EmitOptions WithEmitMetadataOnly(bool value)
{
if (EmitMetadataOnly == value)
{
return this;
}
return new EmitOptions(this) { EmitMetadataOnly = value };
}
public EmitOptions WithPdbFilePath(string path)
{
if (PdbFilePath == path)
{
return this;
}
return new EmitOptions(this) { PdbFilePath = path };
}
public EmitOptions WithPdbChecksumAlgorithm(HashAlgorithmName name)
{
if (PdbChecksumAlgorithm == name)
{
return this;
}
return new EmitOptions(this) { PdbChecksumAlgorithm = name };
}
public EmitOptions WithOutputNameOverride(string outputName)
{
if (OutputNameOverride == outputName)
{
return this;
}
return new EmitOptions(this) { OutputNameOverride = outputName };
}
public EmitOptions WithDebugInformationFormat(DebugInformationFormat format)
{
if (DebugInformationFormat == format)
{
return this;
}
return new EmitOptions(this) { DebugInformationFormat = format };
}
/// <summary>
/// Sets the byte alignment for portable executable file sections.
/// </summary>
/// <param name="value">Can be one of the following values: 0, 512, 1024, 2048, 4096, 8192</param>
public EmitOptions WithFileAlignment(int value)
{
if (FileAlignment == value)
{
return this;
}
return new EmitOptions(this) { FileAlignment = value };
}
public EmitOptions WithBaseAddress(ulong value)
{
if (BaseAddress == value)
{
return this;
}
return new EmitOptions(this) { BaseAddress = value };
}
public EmitOptions WithHighEntropyVirtualAddressSpace(bool value)
{
if (HighEntropyVirtualAddressSpace == value)
{
return this;
}
return new EmitOptions(this) { HighEntropyVirtualAddressSpace = value };
}
public EmitOptions WithSubsystemVersion(SubsystemVersion subsystemVersion)
{
if (subsystemVersion.Equals(SubsystemVersion))
{
return this;
}
return new EmitOptions(this) { SubsystemVersion = subsystemVersion };
}
public EmitOptions WithRuntimeMetadataVersion(string version)
{
if (RuntimeMetadataVersion == version)
{
return this;
}
return new EmitOptions(this) { RuntimeMetadataVersion = version };
}
public EmitOptions WithTolerateErrors(bool value)
{
if (TolerateErrors == value)
{
return this;
}
return new EmitOptions(this) { TolerateErrors = value };
}
public EmitOptions WithIncludePrivateMembers(bool value)
{
if (IncludePrivateMembers == value)
{
return this;
}
return new EmitOptions(this) { IncludePrivateMembers = value };
}
public EmitOptions WithInstrumentationKinds(ImmutableArray<InstrumentationKind> instrumentationKinds)
{
if (InstrumentationKinds == instrumentationKinds)
{
return this;
}
return new EmitOptions(this) { InstrumentationKinds = instrumentationKinds };
}
public EmitOptions WithDefaultSourceFileEncoding(Encoding? defaultSourceFileEncoding)
{
if (DefaultSourceFileEncoding == defaultSourceFileEncoding)
{
return this;
}
return new EmitOptions(this) { DefaultSourceFileEncoding = defaultSourceFileEncoding };
}
public EmitOptions WithFallbackSourceFileEncoding(Encoding? fallbackSourceFileEncoding)
{
if (FallbackSourceFileEncoding == fallbackSourceFileEncoding)
{
return this;
}
return new EmitOptions(this) { FallbackSourceFileEncoding = fallbackSourceFileEncoding };
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
/// <summary>
/// Represents compilation emit options.
/// </summary>
public sealed class EmitOptions : IEquatable<EmitOptions>
{
internal static readonly EmitOptions Default = PlatformInformation.IsWindows
? new EmitOptions()
: new EmitOptions().WithDebugInformationFormat(DebugInformationFormat.PortablePdb);
/// <summary>
/// True to emit an assembly excluding executable code such as method bodies.
/// </summary>
public bool EmitMetadataOnly { get; private set; }
/// <summary>
/// Tolerate errors, producing a PE stream and a success result even in the presence of (some) errors.
/// </summary>
public bool TolerateErrors { get; private set; }
/// <summary>
/// Unless set (private) members that don't affect the language semantics of the resulting assembly will be excluded
/// when emitting metadata-only assemblies as primary output (with <see cref="EmitMetadataOnly"/> on).
/// If emitting a secondary output, this flag is required to be false.
/// </summary>
public bool IncludePrivateMembers { get; private set; }
/// <summary>
/// Type of instrumentation that should be added to the output binary.
/// </summary>
public ImmutableArray<InstrumentationKind> InstrumentationKinds { get; private set; }
/// <summary>
/// Subsystem version
/// </summary>
public SubsystemVersion SubsystemVersion { get; private set; }
/// <summary>
/// Specifies the size of sections in the output file.
/// </summary>
/// <remarks>
/// Valid values are 0, 512, 1024, 2048, 4096 and 8192.
/// If the value is 0 the file alignment is determined based upon the value of <see cref="Platform"/>.
/// </remarks>
public int FileAlignment { get; private set; }
/// <summary>
/// True to enable high entropy virtual address space for the output binary.
/// </summary>
public bool HighEntropyVirtualAddressSpace { get; private set; }
/// <summary>
/// Specifies the preferred base address at which to load the output DLL.
/// </summary>
public ulong BaseAddress { get; private set; }
/// <summary>
/// Debug information format.
/// </summary>
public DebugInformationFormat DebugInformationFormat { get; private set; }
/// <summary>
/// Assembly name override - file name and extension. If not specified the compilation name is used.
/// </summary>
/// <remarks>
/// By default the name of the output assembly is <see cref="Compilation.AssemblyName"/>. Only in rare cases it is necessary
/// to override the name.
///
/// CAUTION: If this is set to a (non-null) value other than the existing compilation output name, then internals-visible-to
/// and assembly references may not work as expected. In particular, things that were visible at bind time, based on the
/// name of the compilation, may not be visible at runtime and vice-versa.
/// </remarks>
public string? OutputNameOverride { get; private set; }
/// <summary>
/// The name of the PDB file to be embedded in the PE image, or null to use the default.
/// </summary>
/// <remarks>
/// If not specified the file name of the source module with an extension changed to "pdb" is used.
/// </remarks>
public string? PdbFilePath { get; private set; }
/// <summary>
/// A crypto hash algorithm used to calculate PDB Checksum stored in the PE/COFF File.
/// If not specified (the value is <c>default(HashAlgorithmName)</c>) the checksum is not calculated.
/// </summary>
public HashAlgorithmName PdbChecksumAlgorithm { get; private set; }
/// <summary>
/// Runtime metadata version.
/// </summary>
public string? RuntimeMetadataVersion { get; private set; }
/// <summary>
/// The encoding used to parse source files that do not have a Byte Order Mark. If specified,
/// is stored in the emitted PDB in order to allow recreating the original compilation.
/// </summary>
public Encoding? DefaultSourceFileEncoding { get; private set; }
/// <summary>
/// If <see cref="DefaultSourceFileEncoding"/> is not specified, the encoding used to parse source files
/// that do not declare their encoding via Byte Order Mark and are not UTF8-encoded.
/// </summary>
public Encoding? FallbackSourceFileEncoding { get; private set; }
// 1.2 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string pdbFilePath,
string outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds: ImmutableArray<InstrumentationKind>.Empty)
{
}
// 2.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string pdbFilePath,
string outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers,
ImmutableArray<InstrumentationKind> instrumentationKinds)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds,
pdbChecksumAlgorithm: null)
{
}
// 3.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitOptions(
bool metadataOnly,
DebugInformationFormat debugInformationFormat,
string? pdbFilePath,
string? outputNameOverride,
int fileAlignment,
ulong baseAddress,
bool highEntropyVirtualAddressSpace,
SubsystemVersion subsystemVersion,
string? runtimeMetadataVersion,
bool tolerateErrors,
bool includePrivateMembers,
ImmutableArray<InstrumentationKind> instrumentationKinds,
HashAlgorithmName? pdbChecksumAlgorithm)
: this(
metadataOnly,
debugInformationFormat,
pdbFilePath,
outputNameOverride,
fileAlignment,
baseAddress,
highEntropyVirtualAddressSpace,
subsystemVersion,
runtimeMetadataVersion,
tolerateErrors,
includePrivateMembers,
instrumentationKinds,
pdbChecksumAlgorithm,
defaultSourceFileEncoding: null,
fallbackSourceFileEncoding: null)
{
}
public EmitOptions(
bool metadataOnly = false,
DebugInformationFormat debugInformationFormat = 0,
string? pdbFilePath = null,
string? outputNameOverride = null,
int fileAlignment = 0,
ulong baseAddress = 0,
bool highEntropyVirtualAddressSpace = false,
SubsystemVersion subsystemVersion = default,
string? runtimeMetadataVersion = null,
bool tolerateErrors = false,
bool includePrivateMembers = true,
ImmutableArray<InstrumentationKind> instrumentationKinds = default,
HashAlgorithmName? pdbChecksumAlgorithm = null,
Encoding? defaultSourceFileEncoding = null,
Encoding? fallbackSourceFileEncoding = null)
{
EmitMetadataOnly = metadataOnly;
DebugInformationFormat = (debugInformationFormat == 0) ? DebugInformationFormat.Pdb : debugInformationFormat;
PdbFilePath = pdbFilePath;
OutputNameOverride = outputNameOverride;
FileAlignment = fileAlignment;
BaseAddress = baseAddress;
HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace;
SubsystemVersion = subsystemVersion;
RuntimeMetadataVersion = runtimeMetadataVersion;
TolerateErrors = tolerateErrors;
IncludePrivateMembers = includePrivateMembers;
InstrumentationKinds = instrumentationKinds.NullToEmpty();
PdbChecksumAlgorithm = pdbChecksumAlgorithm ?? HashAlgorithmName.SHA256;
DefaultSourceFileEncoding = defaultSourceFileEncoding;
FallbackSourceFileEncoding = fallbackSourceFileEncoding;
}
private EmitOptions(EmitOptions other) : this(
other.EmitMetadataOnly,
other.DebugInformationFormat,
other.PdbFilePath,
other.OutputNameOverride,
other.FileAlignment,
other.BaseAddress,
other.HighEntropyVirtualAddressSpace,
other.SubsystemVersion,
other.RuntimeMetadataVersion,
other.TolerateErrors,
other.IncludePrivateMembers,
other.InstrumentationKinds,
other.PdbChecksumAlgorithm,
other.DefaultSourceFileEncoding,
other.FallbackSourceFileEncoding)
{
}
public override bool Equals(object? obj)
{
return Equals(obj as EmitOptions);
}
public bool Equals(EmitOptions? other)
{
if (ReferenceEquals(other, null))
{
return false;
}
return
EmitMetadataOnly == other.EmitMetadataOnly &&
BaseAddress == other.BaseAddress &&
FileAlignment == other.FileAlignment &&
HighEntropyVirtualAddressSpace == other.HighEntropyVirtualAddressSpace &&
SubsystemVersion.Equals(other.SubsystemVersion) &&
DebugInformationFormat == other.DebugInformationFormat &&
PdbFilePath == other.PdbFilePath &&
PdbChecksumAlgorithm == other.PdbChecksumAlgorithm &&
OutputNameOverride == other.OutputNameOverride &&
RuntimeMetadataVersion == other.RuntimeMetadataVersion &&
TolerateErrors == other.TolerateErrors &&
IncludePrivateMembers == other.IncludePrivateMembers &&
InstrumentationKinds.NullToEmpty().SequenceEqual(other.InstrumentationKinds.NullToEmpty(), (a, b) => a == b) &&
DefaultSourceFileEncoding == other.DefaultSourceFileEncoding &&
FallbackSourceFileEncoding == other.FallbackSourceFileEncoding;
}
public override int GetHashCode()
{
return Hash.Combine(EmitMetadataOnly,
Hash.Combine(BaseAddress.GetHashCode(),
Hash.Combine(FileAlignment,
Hash.Combine(HighEntropyVirtualAddressSpace,
Hash.Combine(SubsystemVersion.GetHashCode(),
Hash.Combine((int)DebugInformationFormat,
Hash.Combine(PdbFilePath,
Hash.Combine(PdbChecksumAlgorithm.GetHashCode(),
Hash.Combine(OutputNameOverride,
Hash.Combine(RuntimeMetadataVersion,
Hash.Combine(TolerateErrors,
Hash.Combine(IncludePrivateMembers,
Hash.Combine(Hash.CombineValues(InstrumentationKinds),
Hash.Combine(DefaultSourceFileEncoding,
Hash.Combine(FallbackSourceFileEncoding, 0)))))))))))))));
}
public static bool operator ==(EmitOptions? left, EmitOptions? right)
{
return object.Equals(left, right);
}
public static bool operator !=(EmitOptions? left, EmitOptions? right)
{
return !object.Equals(left, right);
}
internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider, bool isDeterministic)
{
if (!DebugInformationFormat.IsValid())
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat));
}
foreach (var instrumentationKind in InstrumentationKinds)
{
if (!instrumentationKind.IsValid())
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)instrumentationKind));
}
}
if (OutputNameOverride != null)
{
MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics);
}
if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment))
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment));
}
if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString()));
}
if (PdbChecksumAlgorithm.Name != null)
{
try
{
IncrementalHash.CreateHash(PdbChecksumAlgorithm).Dispose();
}
catch
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, PdbChecksumAlgorithm.ToString()));
}
}
else if (isDeterministic)
{
diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, ""));
}
}
internal bool EmitTestCoverageData => InstrumentationKinds.Contains(InstrumentationKind.TestCoverage);
internal static bool IsValidFileAlignment(int value)
{
switch (value)
{
case 512:
case 1024:
case 2048:
case 4096:
case 8192:
return true;
default:
return false;
}
}
public EmitOptions WithEmitMetadataOnly(bool value)
{
if (EmitMetadataOnly == value)
{
return this;
}
return new EmitOptions(this) { EmitMetadataOnly = value };
}
public EmitOptions WithPdbFilePath(string path)
{
if (PdbFilePath == path)
{
return this;
}
return new EmitOptions(this) { PdbFilePath = path };
}
public EmitOptions WithPdbChecksumAlgorithm(HashAlgorithmName name)
{
if (PdbChecksumAlgorithm == name)
{
return this;
}
return new EmitOptions(this) { PdbChecksumAlgorithm = name };
}
public EmitOptions WithOutputNameOverride(string outputName)
{
if (OutputNameOverride == outputName)
{
return this;
}
return new EmitOptions(this) { OutputNameOverride = outputName };
}
public EmitOptions WithDebugInformationFormat(DebugInformationFormat format)
{
if (DebugInformationFormat == format)
{
return this;
}
return new EmitOptions(this) { DebugInformationFormat = format };
}
/// <summary>
/// Sets the byte alignment for portable executable file sections.
/// </summary>
/// <param name="value">Can be one of the following values: 0, 512, 1024, 2048, 4096, 8192</param>
public EmitOptions WithFileAlignment(int value)
{
if (FileAlignment == value)
{
return this;
}
return new EmitOptions(this) { FileAlignment = value };
}
public EmitOptions WithBaseAddress(ulong value)
{
if (BaseAddress == value)
{
return this;
}
return new EmitOptions(this) { BaseAddress = value };
}
public EmitOptions WithHighEntropyVirtualAddressSpace(bool value)
{
if (HighEntropyVirtualAddressSpace == value)
{
return this;
}
return new EmitOptions(this) { HighEntropyVirtualAddressSpace = value };
}
public EmitOptions WithSubsystemVersion(SubsystemVersion subsystemVersion)
{
if (subsystemVersion.Equals(SubsystemVersion))
{
return this;
}
return new EmitOptions(this) { SubsystemVersion = subsystemVersion };
}
public EmitOptions WithRuntimeMetadataVersion(string version)
{
if (RuntimeMetadataVersion == version)
{
return this;
}
return new EmitOptions(this) { RuntimeMetadataVersion = version };
}
public EmitOptions WithTolerateErrors(bool value)
{
if (TolerateErrors == value)
{
return this;
}
return new EmitOptions(this) { TolerateErrors = value };
}
public EmitOptions WithIncludePrivateMembers(bool value)
{
if (IncludePrivateMembers == value)
{
return this;
}
return new EmitOptions(this) { IncludePrivateMembers = value };
}
public EmitOptions WithInstrumentationKinds(ImmutableArray<InstrumentationKind> instrumentationKinds)
{
if (InstrumentationKinds == instrumentationKinds)
{
return this;
}
return new EmitOptions(this) { InstrumentationKinds = instrumentationKinds };
}
public EmitOptions WithDefaultSourceFileEncoding(Encoding? defaultSourceFileEncoding)
{
if (DefaultSourceFileEncoding == defaultSourceFileEncoding)
{
return this;
}
return new EmitOptions(this) { DefaultSourceFileEncoding = defaultSourceFileEncoding };
}
public EmitOptions WithFallbackSourceFileEncoding(Encoding? fallbackSourceFileEncoding)
{
if (FallbackSourceFileEncoding == fallbackSourceFileEncoding)
{
return this;
}
return new EmitOptions(this) { FallbackSourceFileEncoding = fallbackSourceFileEncoding };
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenOptimizedNullableOperators.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public partial class CodeGenOptimizedNullableOperatorTests : CSharpTestBase
{
[Fact]
public void TestNullableBoxingConversionsAlwaysNull()
{
// The native compiler does not optimize this case; Roslyn does. We know
// that the result of boxing default(int?) to object is the same as casting
// literal null to object, so we do not need to allocate space on the stack
// for the nullable int, initialize it, and then box that to a null ref.
string[] sources = {
@"class Program
{
static void Main()
{
System.Console.WriteLine((object)default(int?));
}
}
",
@"class Program
{
static void Main()
{
System.Console.WriteLine((object)(new int?()));
}
}
",
@"class Program
{
static void Main()
{
System.Console.WriteLine((object)(int?)null);
}
}
"};
string expectedOutput = "";
string expectedIL = @"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldnull
IL_0001: call ""void System.Console.WriteLine(object)""
IL_0006: ret
}";
foreach (string source in sources)
{
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", expectedIL);
}
}
[Fact]
public void TestNullableBoxingConversionNeverNull()
{
// The native compiler does not optimize this case; Roslyn does. We know
// that the result of boxing default(int?) to object is the same as casting
// literal null to object, so we do not need to allocate space on the stack
// for the nullable int, initialize it, and then box that to a null ref.
string[] sources = {
@"class Program
{
static void Main()
{
System.Console.WriteLine((object)new int?(123));
}
}
",
@"class Program
{
static void Main()
{
System.Console.WriteLine((object)(int?)123);
}
}
"};
string expectedOutput = "123";
string expectedIL = @"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldc.i4.s 123
IL_0002: box ""int""
IL_0007: call ""void System.Console.WriteLine(object)""
IL_000c: ret
}";
foreach (string source in sources)
{
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", expectedIL);
}
}
[Fact]
public void TestNullableConversionAlwaysNull()
{
// A built-in nullable conversion whose argument is known to always be null
// can simply be optimized away to be the null result.
string source = @"
class Program
{
static long? M()
{
return new int?();
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 10 (0xa)
.maxstack 1
.locals init (long? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""long?""
IL_0008: ldloc.0
IL_0009: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestNullableConversionNeverNull()
{
// A built-in nullable conversion whose argument is known to be non-null
// can be generated by converting the value to the underlying target type,
// and then converting that to nullable, without generating the nullable source
// or checking to see if it has a value.
string source = @"
class Program
{
static long? M(int x)
{
return new int?(x);
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: newobj ""long?..ctor(long)""
IL_0007: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestLiftedUserDefinedConversionAlwaysNull()
{
// A user-defined nullable conversion whose argument is known to always be null
// can simply be optimized away to be the null result.
string source = @"
struct S
{
public static implicit operator S(int x) { return new S(); }
}
class Program
{
static S? M()
{
return new int?();
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 10 (0xa)
.maxstack 1
.locals init (S? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S?""
IL_0008: ldloc.0
IL_0009: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestLiftedUserDefinedConversionNeverNull()
{
// A user-defined nullable conversion whose argument is known to never be null
// can have the nullable ctor, temporary store and value test optimized away.
string source = @"
struct S
{
public static implicit operator S(int x) { return new S(); }
public static implicit operator string(S s) { return s.ToString(); }
}
class Program
{
static S? M1(int x)
{
return new int?(x);
}
static S M2(int x)
{
return (S)(new int?(x));
}
static string M3(int x)
{
// The non-null conversion optimizer should chain well. That is,
// we first optimize (string)(S?)(new int?(x)) to (string)(new S?((S)x)), and then
// to (string)(S)x.
return (string)(S?)(new int?(x));
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""S S.op_Implicit(int)""
IL_0006: newobj ""S?..ctor(S)""
IL_000b: ret
}";
string expectedIL2 = @"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""S S.op_Implicit(int)""
IL_0006: ret
}";
string expectedIL3 = @"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""S S.op_Implicit(int)""
IL_0006: call ""string S.op_Implicit(S)""
IL_000b: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
}
[Fact]
public void TestNullableUnaryOpsAlwaysNull()
{
// A unary operator whose argument is known to always be null
// can simply be optimized away to be the null result.
string source = @"
class Program
{
static int? M()
{
return ~(new int?());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 10 (0xa)
.maxstack 1
.locals init (int? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""int?""
IL_0008: ldloc.0
IL_0009: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (6,16): warning CS0458: The result of the expression is always 'null' of type 'int?'
// return ~(new int?());
Diagnostic(ErrorCode.WRN_AlwaysNull, "~(new int?())").WithArguments("int?"));
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestNullableUnaryOpsAlwaysNullChained()
{
// A unary operator whose argument is known to always be null
// can simply be optimized away to be the null result. These
// optimizations should "chain" naturally. Here we combine
// a built-in conversion, two unary operations, and a boxing.
// The net result should simply be a null reference.
//
// The native compiler does not handle these "chained" optimizations,
// interestingly enough; the native compiler will optimize away only the
// innermost one; it is then not treated as "always null" and is checked
// for nullity unnecessarily.
//
// Fortunately, the warning logic does not do a deep analysis; it only
// reports a single warning.
string source = @"
class Program
{
static object M()
{
return ~-(new short?());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (6,17): warning CS0458: The result of the expression is always 'null' of type 'int?'
// return ~-(new short?());
Diagnostic(ErrorCode.WRN_AlwaysNull, "-(new short?())").WithArguments("int?"));
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestNullableUnaryOpsNeverNull()
{
// A unary operator whose argument is known to never be null
// can be optimized to avoid the null check.
string source = @"
class Program
{
static int N() { return 123; }
static int? M()
{
// This can be optimized to new int?(~N())
return ~(new int?(N()));
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: call ""int Program.N()""
IL_0005: not
IL_0006: newobj ""int?..ctor(int)""
IL_000b: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestNullableUnaryOpsNeverNullChained()
{
// A unary operator whose argument is known to never be null
// can simply be optimized away to be the null result. These
// optimizations should "chain" naturally. Here we combine
// two unary operations and a boxing. As you can see, we eliminate
// all the null checks and the "new S?" ctor.
string source = @"
struct S
{
public static S operator +(S s) { return s; }
public static S operator -(S s) { return s; }
public static S operator ~(S s) { return s; }
}
class Program
{
static object M(S s)
{
return ~-(new S?(s));
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""S S.op_UnaryNegation(S)""
IL_0006: call ""S S.op_OnesComplement(S)""
IL_000b: box ""S""
IL_0010: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestLiftedUnaryOpOnTopOfLifted()
{
// Here's an optimization that the dev10 compiler does not do. If we have a
// lifted unary operator "on top" of another lifted operation, then the unary
// operation can be "distributed" to both branches of the underlying lifted operation.
//
// For example, suppose we have
//
// return -(N1() + N2());
//
// Where N1() and N2() return int?. The dev10 compiler does this in two steps: first it
// computes the int? result of the addition, and then it does a fully lifted negation:
//
// int? t1 = N1();
// int? t2 = N2();
// int? t3 = t1.HasValue && t2.HasValue ? new int?(t1.Value + t2.Value) : new int?();
// return t3.HasValue ? new int?(-t3.Value)) : new int?();
//
// But t3 is completely unnecessary here. We could realize this as:
//
// return -(t1.HasValue && t2.HasValue ? new int?(t1.Value + t2.Value) : new int?())
//
// which is the same as distributing the conversion to the consequence and alternative:
//
// return (t1.HasValue && t2.HasValue ? - new int?(t1.Value + t2.Value) ): - ( new int?() ) )
//
// and now we can optimize the consequence and alternative down to
//
// return (t1.HasValue && t2.HasValue ? new int?(-(t1.Value + t2.Value) ): new int?() )
//
// And the int? t3 disappears entirely.
//
// This optimization has the nice property that it composes well with itself, as we'll see.
string source = @"
struct S
{
public static S operator -(S s) { return s; }
public static S operator ~(S s) { return s; }
public static S operator +(S s1, S s2) { return s1; }
}
class Program
{
static int? N1() { return 1; }
static int? N2() { return 2; }
static S? N3() { return null; }
static S? N4() { return null; }
static int? M1()
{
return -(N1() + N2());
}
static S? M2()
{
return -~(N3() + N4());
}
static void Main() { }
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 61 (0x3d)
.maxstack 2
.locals init (int? V_0,
int? V_1,
int? V_2)
IL_0000: call ""int? Program.N1()""
IL_0005: stloc.0
IL_0006: call ""int? Program.N2()""
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call ""bool int?.HasValue.get""
IL_0013: ldloca.s V_1
IL_0015: call ""bool int?.HasValue.get""
IL_001a: and
IL_001b: brtrue.s IL_0027
IL_001d: ldloca.s V_2
IL_001f: initobj ""int?""
IL_0025: ldloc.2
IL_0026: ret
IL_0027: ldloca.s V_0
IL_0029: call ""int int?.GetValueOrDefault()""
IL_002e: ldloca.s V_1
IL_0030: call ""int int?.GetValueOrDefault()""
IL_0035: add
IL_0036: neg
IL_0037: newobj ""int?..ctor(int)""
IL_003c: ret
}
";
string expectedIL2 = @"{
// Code size 74 (0x4a)
.maxstack 2
.locals init (S? V_0,
S? V_1,
S? V_2)
IL_0000: call ""S? Program.N3()""
IL_0005: stloc.0
IL_0006: call ""S? Program.N4()""
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call ""bool S?.HasValue.get""
IL_0013: ldloca.s V_1
IL_0015: call ""bool S?.HasValue.get""
IL_001a: and
IL_001b: brtrue.s IL_0027
IL_001d: ldloca.s V_2
IL_001f: initobj ""S?""
IL_0025: ldloc.2
IL_0026: ret
IL_0027: ldloca.s V_0
IL_0029: call ""S S?.GetValueOrDefault()""
IL_002e: ldloca.s V_1
IL_0030: call ""S S?.GetValueOrDefault()""
IL_0035: call ""S S.op_Addition(S, S)""
IL_003a: call ""S S.op_OnesComplement(S)""
IL_003f: call ""S S.op_UnaryNegation(S)""
IL_0044: newobj ""S?..ctor(S)""
IL_0049: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
}
[Fact]
public void TestLiftedBinaryOpWithConstantOnTopOfLifted()
{
// If we have a lifted binary operation "on top" of a lifted operation,
// and the right side of the outer operation is a constant, then we
// can eliminate several temporaries.
//
// For example, suppose we have
//
// return N1() * N2() + 1;
//
// Where N1() and N2() return int?. We could do this the obvious way:
//
// int? n1 = N1();
// int? n2 = N2();
// int? r = n1.HasValue && n2.HasValue ? new int?(n1.Value * n2.Value) : new int?();
// int v = 1;
// return r.HasValue ? new int?(r.Value + v)) : new int?();
//
// But r and v are both unnecessary. We could instead realize this as:
//
// int? n1 = N1();
// int? n2 = N2();
// return n1.HasValue && n2.HasValue ? new int?(n1.Value * n2.Value + 1) : new int?();
//
// We want to do this optimization in particular because it makes codegen for i++
// and i+=1 better.
//
// The dev10 compiler does this optimization *only* on i++ and not on expressions
// like N1() * N2() + 1 or sh+=1;
string source = @"
class Program
{
static int? N1() { return 1; }
static int? N2() { return 2; }
static short? sh;
static int? M1()
{
return N1() * N2() + 1;
}
static short? M2()
{
return sh++;
}
static short? M3()
{
return ++sh;
}
static short? M4()
{
return sh += 1;
}
static void Main() { }
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 62 (0x3e)
.maxstack 2
.locals init (int? V_0,
int? V_1,
int? V_2)
IL_0000: call ""int? Program.N1()""
IL_0005: stloc.0
IL_0006: call ""int? Program.N2()""
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call ""bool int?.HasValue.get""
IL_0013: ldloca.s V_1
IL_0015: call ""bool int?.HasValue.get""
IL_001a: and
IL_001b: brtrue.s IL_0027
IL_001d: ldloca.s V_2
IL_001f: initobj ""int?""
IL_0025: ldloc.2
IL_0026: ret
IL_0027: ldloca.s V_0
IL_0029: call ""int int?.GetValueOrDefault()""
IL_002e: ldloca.s V_1
IL_0030: call ""int int?.GetValueOrDefault()""
IL_0035: mul
IL_0036: ldc.i4.1
IL_0037: add
IL_0038: newobj ""int?..ctor(int)""
IL_003d: ret
}";
string expectedIL2 = @"{
// Code size 48 (0x30)
.maxstack 3
.locals init (short? V_0,
short? V_1)
IL_0000: ldsfld ""short? Program.sh""
IL_0005: dup
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""bool short?.HasValue.get""
IL_000e: brtrue.s IL_001b
IL_0010: ldloca.s V_1
IL_0012: initobj ""short?""
IL_0018: ldloc.1
IL_0019: br.s IL_002a
IL_001b: ldloca.s V_0
IL_001d: call ""short short?.GetValueOrDefault()""
IL_0022: ldc.i4.1
IL_0023: add
IL_0024: conv.i2
IL_0025: newobj ""short?..ctor(short)""
IL_002a: stsfld ""short? Program.sh""
IL_002f: ret
}";
string expectedIL3 = @"{
// Code size 48 (0x30)
.maxstack 2
.locals init (short? V_0,
short? V_1)
IL_0000: ldsfld ""short? Program.sh""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool short?.HasValue.get""
IL_000d: brtrue.s IL_001a
IL_000f: ldloca.s V_1
IL_0011: initobj ""short?""
IL_0017: ldloc.1
IL_0018: br.s IL_0029
IL_001a: ldloca.s V_0
IL_001c: call ""short short?.GetValueOrDefault()""
IL_0021: ldc.i4.1
IL_0022: add
IL_0023: conv.i2
IL_0024: newobj ""short?..ctor(short)""
IL_0029: dup
IL_002a: stsfld ""short? Program.sh""
IL_002f: ret
}";
string expectedIL4 = @"{
// Code size 48 (0x30)
.maxstack 2
.locals init (short? V_0,
short? V_1)
IL_0000: ldsfld ""short? Program.sh""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool short?.HasValue.get""
IL_000d: brtrue.s IL_001a
IL_000f: ldloca.s V_1
IL_0011: initobj ""short?""
IL_0017: ldloc.1
IL_0018: br.s IL_0029
IL_001a: ldloca.s V_0
IL_001c: call ""short short?.GetValueOrDefault()""
IL_0021: ldc.i4.1
IL_0022: add
IL_0023: conv.i2
IL_0024: newobj ""short?..ctor(short)""
IL_0029: dup
IL_002a: stsfld ""short? Program.sh""
IL_002f: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
}
[Fact]
public void TestNullableComparisonOpsBothAlwaysNull()
{
// An ==, !=, <, >, <= or >= operation where both operands
// are null is always true for equality, and always false otherwise.
// Note that the native compiler has a bug; it does not produce the warning
// "comparing null with S? always produces false" -- it incorrectly warns
// that it produces a null of type bool? ! Roslyn does not reproduce this bug.
string source = @"
struct S // User-defined relational ops
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return true; }
public static bool operator <(S x, S y) { return true; }
public static bool operator >(S x, S y) { return true; }
public static bool operator <=(S x, S y) { return true; }
public static bool operator >=(S x, S y) { return true; }
public override bool Equals(object x) { return true; }
public override int GetHashCode() { return 0; }
}
struct T // no user-defined relational ops
{
}
class Program
{
static bool M1()
{
return new int?() == new short?();
}
static bool M2()
{
return default(double?) != new short?();
}
static bool M3()
{
return ((int?)null) < new decimal?();
}
static bool M4()
{
return new S?() == new S?();
}
static bool M5()
{
return default(S?) != new S?();
}
static bool M6()
{
return ((S?)null) < new S?();
}
static bool M7() // Special case for equality with null literal and no overloaded operators.
{
return default(T?) == null;
}
static bool M8()
{
return null != new T?();
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedILTrue = @"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: ret
}";
string expectedILFalse = @"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (25,16): warning CS0464: Comparing with null of type 'decimal?' always produces 'false'
// return ((int?)null) < new decimal?();
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((int?)null) < new decimal?()").WithArguments("decimal?"),
// (37,16): warning CS0464: Comparing with null of type 'S?' always produces 'false'
// return ((S?)null) < new S?();
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((S?)null) < new S?()").WithArguments("S?"));
comp.VerifyIL("Program.M1", expectedILTrue);
comp.VerifyIL("Program.M2", expectedILFalse);
comp.VerifyIL("Program.M3", expectedILFalse);
comp.VerifyIL("Program.M4", expectedILTrue);
comp.VerifyIL("Program.M5", expectedILFalse);
comp.VerifyIL("Program.M6", expectedILFalse);
comp.VerifyIL("Program.M7", expectedILTrue);
comp.VerifyIL("Program.M8", expectedILFalse);
}
[Fact]
public void TestNullableComparisonNonNullWithLiteralNull()
{
// We can optimize this away to simply evaluating N() for its side effects
// and returning false.
string source = @"
struct S {}
class Program
{
static S N() { System.Console.WriteLine(123); return new S(); }
static bool M()
{
return new S?(N()) == null;
}
static void Main() {M();}
}
";
string expectedOutput = "123";
string expectedIL = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""S Program.N()""
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestNullableComparisonOpsBothNeverNull()
{
// An ==, !=, <, >, <= or >= operation where both operands
// are not null simply drops the lifting logic entirely.
string source = @"
struct S // User-defined relational ops
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return true; }
public static bool operator <(S x, S y) { return true; }
public static bool operator >(S x, S y) { return true; }
public static bool operator <=(S x, S y) { return true; }
public static bool operator >=(S x, S y) { return true; }
public override bool Equals(object x) { return true; }
public override int GetHashCode() { return 0; }
}
class Program
{
static int N1() { return 123; }
static short N2() { return 123; }
static double N3() { return 123; }
static decimal N4() { return 123; }
static S N5() { return new S(); }
static bool M1()
{
// Notice that there are two optimizations here and in the next few cases.
// First we optimize the conversion from short? to int? so that the right
// hand side is new int?((int)N2()). Second, we optimize the comparison to
// N1() == (int)N2(), eliminating all the lifting.
return new int?(N1()) == new short?(N2());
}
static bool M2()
{
return new double?(N3()) != new short?(N2());
}
static bool M3()
{
return new int?(N1()) < new decimal?(N4());
}
static bool M4()
{
return new S?(N5()) == new S?(N5());
}
static bool M5()
{
return new S?(N5()) != new S?(N5());
}
static bool M6()
{
return new S?(N5()) < new S?(N5());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 13 (0xd)
.maxstack 2
IL_0000: call ""int Program.N1()""
IL_0005: call ""short Program.N2()""
IL_000a: ceq
IL_000c: ret
}";
string expectedIL2 = @"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: call ""double Program.N3()""
IL_0005: call ""short Program.N2()""
IL_000a: conv.r8
IL_000b: ceq
IL_000d: ldc.i4.0
IL_000e: ceq
IL_0010: ret
}";
string expectedIL3 = @"{
// Code size 21 (0x15)
.maxstack 2
IL_0000: call ""int Program.N1()""
IL_0005: call ""decimal decimal.op_Implicit(int)""
IL_000a: call ""decimal Program.N4()""
IL_000f: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_0014: ret
}
";
string expectedIL4 = @"{
// Code size 16 (0x10)
.maxstack 2
IL_0000: call ""S Program.N5()""
IL_0005: call ""S Program.N5()""
IL_000a: call ""bool S.op_Equality(S, S)""
IL_000f: ret
}";
string expectedIL5 = @"{
// Code size 16 (0x10)
.maxstack 2
IL_0000: call ""S Program.N5()""
IL_0005: call ""S Program.N5()""
IL_000a: call ""bool S.op_Inequality(S, S)""
IL_000f: ret
}";
string expectedIL6 = @"{
// Code size 16 (0x10)
.maxstack 2
IL_0000: call ""S Program.N5()""
IL_0005: call ""S Program.N5()""
IL_000a: call ""bool S.op_LessThan(S, S)""
IL_000f: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
comp.VerifyIL("Program.M5", expectedIL5);
comp.VerifyIL("Program.M6", expectedIL6);
}
[Fact, WorkItem(663, "https://github.com/dotnet/roslyn/issues/663")]
public void TestNullableComparisonOpsOneNullOneNonNull()
{
// An ==, !=, <, >, <= or >= operation where one operand is null and the
// other is non-null is always false except for inequality, which is true.
// We can skip the lifting and just generate the side effect.
// Note that Roslyn produces considerably more warnings here than the
// native compiler; the native compiler only produces warnings for
// "((int?)null) < new decimal?(N3())" and "((S?)null) < new S?(N4())".
// For compatibility Roslyn reports the same diagnostics by default,
// but in "strict" mode (which will be part of the "warning waves" once
// we do that) Roslyn will report warnings for
// new S() == null and new S() != null.
string source = @"
struct S // User-defined relational ops
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return true; }
public static bool operator <(S x, S y) { return true; }
public static bool operator >(S x, S y) { return true; }
public static bool operator <=(S x, S y) { return true; }
public static bool operator >=(S x, S y) { return true; }
public override bool Equals(object x) { return true; }
public override int GetHashCode() { return 0; }
}
class Program
{
static int N1() { return 1; }
static short N2() { return 1; }
static decimal N3() { return 1; }
static S N4() { return new S(); }
static bool M1()
{
return new int?(N1()) == new short?();
}
static bool M2()
{
return default(double?) != new short?(N2());
}
static bool M3()
{
return ((int?)null) < new decimal?(N3());
}
static bool M4()
{
return new S?() == new S?(N4());
}
static bool M5()
{
return default(S?) != new S?(N4());
}
static bool M6()
{
return ((S?)null) < new S?(N4());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""int Program.N1()""
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
}";
string expectedIL2 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""short Program.N2()""
IL_0005: pop
IL_0006: ldc.i4.1
IL_0007: ret
}";
string expectedIL3 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""decimal Program.N3()""
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
}";
string expectedIL4 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""S Program.N4()""
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
}";
string expectedIL5 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""S Program.N4()""
IL_0005: pop
IL_0006: ldc.i4.1
IL_0007: ret
}";
string expectedIL6 = expectedIL4;
CompileAndVerify(source, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe.WithWarningLevel(4)).VerifyDiagnostics(
// (21,16): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'short?'
// return new int?(N1()) == new short?();
Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "new int?(N1()) == new short?()").WithArguments("false", "int", "short?").WithLocation(21, 16),
// (25,16): warning CS0472: The result of the expression is always 'true' since a value of type 'double' is never equal to 'null' of type 'double?'
// return default(double?) != new short?(N2());
Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "default(double?) != new short?(N2())").WithArguments("true", "double", "double?").WithLocation(25, 16),
// (29,16): warning CS0464: Comparing with null of type 'int?' always produces 'false'
// return ((int?)null) < new decimal?(N3());
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((int?)null) < new decimal?(N3())").WithArguments("int?").WithLocation(29, 16),
// (41,16): warning CS0464: Comparing with null of type 'S?' always produces 'false'
// return ((S?)null) < new S?(N4());
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((S?)null) < new S?(N4())").WithArguments("S?").WithLocation(41, 16)
);
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (21,16): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'short?'
// return new int?(N1()) == new short?();
Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "new int?(N1()) == new short?()").WithArguments("false", "int", "short?").WithLocation(21, 16),
// (25,16): warning CS0472: The result of the expression is always 'true' since a value of type 'double' is never equal to 'null' of type 'double?'
// return default(double?) != new short?(N2());
Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "default(double?) != new short?(N2())").WithArguments("true", "double", "double?").WithLocation(25, 16),
// (29,16): warning CS0464: Comparing with null of type 'int?' always produces 'false'
// return ((int?)null) < new decimal?(N3());
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((int?)null) < new decimal?(N3())").WithArguments("int?").WithLocation(29, 16),
// (33,16): warning CS8073: The result of the expression is always 'false' since a value of type 'S' is never equal to 'null' of type 'S?'
// return new S?() == new S?(N4());
Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "new S?() == new S?(N4())").WithArguments("false", "S", "S?").WithLocation(33, 16),
// (37,16): warning CS8073: The result of the expression is always 'true' since a value of type 'S' is never equal to 'null' of type 'S?'
// return default(S?) != new S?(N4());
Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "default(S?) != new S?(N4())").WithArguments("true", "S", "S?").WithLocation(37, 16),
// (41,16): warning CS0464: Comparing with null of type 'S?' always produces 'false'
// return ((S?)null) < new S?(N4());
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((S?)null) < new S?(N4())").WithArguments("S?").WithLocation(41, 16)
);
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
comp.VerifyIL("Program.M5", expectedIL5);
comp.VerifyIL("Program.M6", expectedIL6);
}
[Fact]
public void TestNullableComparisonOpsOneNullOneUnknown()
{
// An <, >, <= or >= operation where one operand is null and the
// other is unknown is always false; we can skip the lifting and
// generate the side effect.
//
// An == or != operation where one operand is null and the other is
// unknown turns into a call to HasValue.
//
// As mentioned above, the native compiler gets one of the warnings wrong;
// Roslyn gets it right.
string source = @"
struct S // User-defined relational ops
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return true; }
public static bool operator <(S x, S y) { return true; }
public static bool operator >(S x, S y) { return true; }
public static bool operator <=(S x, S y) { return true; }
public static bool operator >=(S x, S y) { return true; }
public override bool Equals(object x) { return true; }
public override int GetHashCode() { return 0; }
}
class Program
{
static int? N1() { return 1; }
static short? N2() { return 1; }
static decimal? N3() { return 1; }
static S? N4() { return new S(); }
static bool M1()
{
return N1() == new short?();
}
static bool M2()
{
return default(double?) != N2();
}
static bool M3()
{
return ((int?)null) < N3();
}
static bool M4()
{
return new S?() == N4();
}
static bool M5()
{
return default(S?) != N4();
}
static bool M6()
{
return ((S?)null) < N4();
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 17 (0x11)
.maxstack 2
.locals init (int? V_0)
IL_0000: call ""int? Program.N1()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool int?.HasValue.get""
IL_000d: ldc.i4.0
IL_000e: ceq
IL_0010: ret
}";
// TODO: Roslyn and the native compiler both produce this sub-optimal code for
// TODO: "default(double?) != N2()". We are essentially generating:
// TODO:
// TODO: short? temp1 = N2();
// TODO: double? temp2 = temp1.HasValue ? new double?((double)temp1.GetValueOrDefault()) : new double?();
// TODO: return temp2.HasValue;
// TODO:
// TODO: We could be instead simply generating
// TODO:
// TODO: return N2().HasValue();
string expectedIL2 = @"{
// Code size 48 (0x30)
.maxstack 1
.locals init (short? V_0,
double? V_1)
IL_0000: call ""short? Program.N2()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool short?.HasValue.get""
IL_000d: brtrue.s IL_001a
IL_000f: ldloca.s V_1
IL_0011: initobj ""double?""
IL_0017: ldloc.1
IL_0018: br.s IL_0027
IL_001a: ldloca.s V_0
IL_001c: call ""short short?.GetValueOrDefault()""
IL_0021: conv.r8
IL_0022: newobj ""double?..ctor(double)""
IL_0027: stloc.1
IL_0028: ldloca.s V_1
IL_002a: call ""bool double?.HasValue.get""
IL_002f: ret
}";
string expectedIL3 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""decimal? Program.N3()""
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
}";
string expectedIL4 = @"{
// Code size 17 (0x11)
.maxstack 2
.locals init (S? V_0)
IL_0000: call ""S? Program.N4()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool S?.HasValue.get""
IL_000d: ldc.i4.0
IL_000e: ceq
IL_0010: ret
}";
string expectedIL5 = @"{
// Code size 14 (0xe)
.maxstack 1
.locals init (S? V_0)
IL_0000: call ""S? Program.N4()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool S?.HasValue.get""
IL_000d: ret
}";
string expectedIL6 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""S? Program.N4()""
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (29,16): warning CS0464: Comparing with null of type 'int?' always produces 'false'
// return ((int?)null) < N3();
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((int?)null) < N3()").WithArguments("int?"),
// (41,16): warning CS0464: Comparing with null of type 'S?' always produces 'false'
// return ((S?)null) < N4();
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((S?)null) < N4()").WithArguments("S?")
);
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
comp.VerifyIL("Program.M5", expectedIL5);
comp.VerifyIL("Program.M6", expectedIL6);
}
[Fact]
public void TestNullableComparisonOpsOneNonNullOneUnknown()
{
// When we have a lifted comparison where we know that one side
// is definitely not null, but know nothing about the other, then
// we make a slight modification to the code generation. For example,
// suppose X() and Y() return int?. For "return X() < Y();" we would generate:
// int? x = X();
// int? y = Y();
// return x.GetValueOrDefault() < y.GetValueOrDefault() ? x.HasValue & y.HasValue : false;
//
// But suppose Z() returns int. For X() < Z(), rather than converting Z() to int? and doing the
// same codegen as before, we simplify the codegen to:
//
// int? x = X();
// int z = Z();
// return x.GetValueOrDefault() < z ? x.HasValue : false;
//
// We apply this same pattern to all lifted comparison operators.
string source = @"
struct S // User-defined relational ops
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return true; }
public static bool operator <(S x, S y) { return true; }
public static bool operator >(S x, S y) { return true; }
public static bool operator <=(S x, S y) { return true; }
public static bool operator >=(S x, S y) { return true; }
public override bool Equals(object x) { return true; }
public override int GetHashCode() { return 0; }
}
class Program
{
static int? N1() { return 1; }
static short? N2() { return 1; }
static decimal? N3() { return 1; }
static S? N4() { return new S(); }
static int V1() { return 1; }
static short V2() { return 1; }
static decimal V3() { return 1; }
static S V4() { return new S(); }
static bool M1()
{
return N1() == new short?(V2());
}
static bool M2()
{
return N1() < new decimal?(V3());
}
static bool M3()
{
return new S?(V4()) == N4();
}
static bool M4()
{
return new S?(V4()) != N4();
}
static bool M5()
{
return new S?(V4()) < N4();
}
static void Main() { }
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 31 (0x1f)
.maxstack 2
.locals init (int? V_0,
int V_1)
IL_0000: call ""int? Program.N1()""
IL_0005: stloc.0
IL_0006: call ""short Program.V2()""
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call ""int int?.GetValueOrDefault()""
IL_0013: ldloc.1
IL_0014: ceq
IL_0016: ldloca.s V_0
IL_0018: call ""bool int?.HasValue.get""
IL_001d: and
IL_001e: ret
}";
// TODO: We do a worse job than the native compiler here. Find out why.
string expectedIL2 = @"{
// Code size 72 (0x48)
.maxstack 2
.locals init (decimal? V_0,
decimal V_1,
int? V_2,
decimal? V_3)
IL_0000: call ""int? Program.N1()""
IL_0005: stloc.2
IL_0006: ldloca.s V_2
IL_0008: call ""bool int?.HasValue.get""
IL_000d: brtrue.s IL_001a
IL_000f: ldloca.s V_3
IL_0011: initobj ""decimal?""
IL_0017: ldloc.3
IL_0018: br.s IL_002b
IL_001a: ldloca.s V_2
IL_001c: call ""int int?.GetValueOrDefault()""
IL_0021: call ""decimal decimal.op_Implicit(int)""
IL_0026: newobj ""decimal?..ctor(decimal)""
IL_002b: stloc.0
IL_002c: call ""decimal Program.V3()""
IL_0031: stloc.1
IL_0032: ldloca.s V_0
IL_0034: call ""decimal decimal?.GetValueOrDefault()""
IL_0039: ldloc.1
IL_003a: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_003f: ldloca.s V_0
IL_0041: call ""bool decimal?.HasValue.get""
IL_0046: and
IL_0047: ret
}";
string expectedIL3 = @"{
// Code size 37 (0x25)
.maxstack 2
.locals init (S V_0,
S? V_1)
IL_0000: call ""S Program.V4()""
IL_0005: stloc.0
IL_0006: call ""S? Program.N4()""
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool S?.HasValue.get""
IL_0013: brtrue.s IL_0017
IL_0015: ldc.i4.0
IL_0016: ret
IL_0017: ldloc.0
IL_0018: ldloca.s V_1
IL_001a: call ""S S?.GetValueOrDefault()""
IL_001f: call ""bool S.op_Equality(S, S)""
IL_0024: ret
}";
string expectedIL4 = @"{
// Code size 37 (0x25)
.maxstack 2
.locals init (S V_0,
S? V_1)
IL_0000: call ""S Program.V4()""
IL_0005: stloc.0
IL_0006: call ""S? Program.N4()""
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool S?.HasValue.get""
IL_0013: brtrue.s IL_0017
IL_0015: ldc.i4.1
IL_0016: ret
IL_0017: ldloc.0
IL_0018: ldloca.s V_1
IL_001a: call ""S S?.GetValueOrDefault()""
IL_001f: call ""bool S.op_Inequality(S, S)""
IL_0024: ret
}";
string expectedIL5 = @"{
// Code size 37 (0x25)
.maxstack 2
.locals init (S V_0,
S? V_1)
IL_0000: call ""S Program.V4()""
IL_0005: stloc.0
IL_0006: call ""S? Program.N4()""
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool S?.HasValue.get""
IL_0013: brtrue.s IL_0017
IL_0015: ldc.i4.0
IL_0016: ret
IL_0017: ldloc.0
IL_0018: ldloca.s V_1
IL_001a: call ""S S?.GetValueOrDefault()""
IL_001f: call ""bool S.op_LessThan(S, S)""
IL_0024: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
comp.VerifyIL("Program.M5", expectedIL5);
}
[Fact]
public void TestLiftedConversionOnTopOfLifted()
{
// Here's an optimization that the dev10 compiler does not do except in some special cases.
// If we have a lifted conversion "on top" of another lifted operation, then the lifted
// conversion can be "distributed" to both branches of the underlying lifted operation.
//
// For example, suppose we have
//
// return (double?)(N1() + N2());
//
// Where N1 and N2 return int?. The dev10 compiler does this in two steps: first it
// computes the int? result of the addition, and then it converts that int? to double?
// with a lifted conversion. Basically, it generates:
//
// int? t1 = N1();
// int? t2 = N2();
// int? t3 = t1.HasValue && t2.HasValue ? new int?(t1.Value + t2.Value) : new int?();
// double? t4 = t3.HasValue ? new double?((double)t3.Value)) : new double?();
//
// But t3 is completely unnecessary here. We observe that the lifted conversion:
//
// (double?) (t1.HasValue && t2.HasValue ? new int?(t1.Value + t2.Value) : new int?())
//
// Is the same as distributing the conversion to the consequence and alternative:
//
// (t1.HasValue && t2.HasValue ? (double?)( new int?(t1.Value + t2.Value) ): (double?) ( new int?() ) )
//
// And now we can optimize the consequence and alternative down to
//
// (t1.HasValue && t2.HasValue ? new double?((double)(t1.Value + t2.Value) ): new double?() )
//
// And the int? t3 disappears entirely.
//
// This optimization has the nice property that it composes well with itself.
string source = @"
struct S
{
public static S operator -(S s) { return s; }
public static implicit operator int(S s) { return 1; }
}
class Program
{
static int? N1() { return 1; }
static int? N2() { return 1; }
static S? N3() { return null; }
// Start with a nice simple case; we have a lifted numeric conversion on top of a
// lifted addition.
static long? M1()
{
return N1() + N2();
}
// This should also work with lifted user-defined conversions, and work on top
// of a lifted unary operator.
static int? M2()
{
return -N3();
}
static void Main() { }
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 61 (0x3d)
.maxstack 2
.locals init (int? V_0,
int? V_1,
long? V_2)
IL_0000: call ""int? Program.N1()""
IL_0005: stloc.0
IL_0006: call ""int? Program.N2()""
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call ""bool int?.HasValue.get""
IL_0013: ldloca.s V_1
IL_0015: call ""bool int?.HasValue.get""
IL_001a: and
IL_001b: brtrue.s IL_0027
IL_001d: ldloca.s V_2
IL_001f: initobj ""long?""
IL_0025: ldloc.2
IL_0026: ret
IL_0027: ldloca.s V_0
IL_0029: call ""int int?.GetValueOrDefault()""
IL_002e: ldloca.s V_1
IL_0030: call ""int int?.GetValueOrDefault()""
IL_0035: add
IL_0036: conv.i8
IL_0037: newobj ""long?..ctor(long)""
IL_003c: ret
}";
string expectedIL2 = @"{
// Code size 48 (0x30)
.maxstack 1
.locals init (S? V_0,
int? V_1)
IL_0000: call ""S? Program.N3()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool S?.HasValue.get""
IL_000d: brtrue.s IL_0019
IL_000f: ldloca.s V_1
IL_0011: initobj ""int?""
IL_0017: ldloc.1
IL_0018: ret
IL_0019: ldloca.s V_0
IL_001b: call ""S S?.GetValueOrDefault()""
IL_0020: call ""S S.op_UnaryNegation(S)""
IL_0025: call ""int S.op_Implicit(S)""
IL_002a: newobj ""int?..ctor(int)""
IL_002f: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
}
[Fact]
public void TestNullableBoolBinOpsBothAlwaysNull()
{
// x & y and x | y are null if both operands are null.
string source = @"
class Program
{
static bool? M1()
{
return new bool?() | new bool?();
}
static bool? M2()
{
return (bool?)null & default(bool?);
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 10 (0xa)
.maxstack 1
.locals init (bool? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""bool?""
IL_0008: ldloc.0
IL_0009: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL);
comp.VerifyIL("Program.M2", expectedIL);
}
[Fact]
public void TestNullableBoolBinOpsBothNotNull()
{
// x & y and x | y can be reduced to their non-lifted forms
// if both operands are known to be non-null.
//
// Roslyn does a slightly better job than the native compiler here.
// The native compiler effectively generates code as though you'd written:
//
// bool temp1 = N();
// bool? temp2 = new bool?(N() & N());
// return temp1 ? new bool?(true) : temp2;
//
// Whereas Roslyn simply generates code as though you'd written:
//
// return new bool?(N() | N() & N())
string source = @"
class Program
{
static bool N() { return true; }
static bool? M1()
{
return new bool?(N()) | new bool?(N()) & new bool?(N());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 23 (0x17)
.maxstack 3
IL_0000: call ""bool Program.N()""
IL_0005: call ""bool Program.N()""
IL_000a: call ""bool Program.N()""
IL_000f: and
IL_0010: or
IL_0011: newobj ""bool?..ctor(bool)""
IL_0016: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL);
}
[Fact]
public void TestNullableBoolBinOpsOneNull()
{
// codegen for x & y and x | y can be simplified if one operand is known to be null,
// and simplified even further if the other operand is known to be non-null.
string source = @"
class Program
{
static bool? N() { return false; }
static bool B() { return false; }
static bool? M1()
{
// Generated as temp = N(), temp.GetValueOrDefault() ? null : temp
return N() & new bool?();
}
static bool? M2()
{
// Generated as temp = N(), temp.GetValueOrDefault() ? null : temp
return default(bool?) & N();
}
static bool? M3()
{
// Generated as temp = N(), temp.GetValueOrDefault() ? temp : null
return N() | new bool?();
}
static bool? M4()
{
// Generated as temp = N(), temp.GetValueOrDefault() ? temp : null
return default(bool?) | N();
}
static bool? M5()
{
// Generated as B() ? null : new bool?(false)
return new bool?(B()) & new bool?();
}
static bool? M6()
{
// Generated as B() ? null : new bool?(false)
return default(bool?) & new bool?(B());
}
static bool? M7()
{
// Generated as B() ? new bool?(true) : null
return new bool?(B()) | new bool?();
}
static bool? M8()
{
// Generated as B() ? new bool?(true) : null
return default(bool?) | new bool?(B());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 27 (0x1b)
.maxstack 1
.locals init (bool? V_0,
bool? V_1)
IL_0000: call ""bool? Program.N()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool bool?.GetValueOrDefault()""
IL_000d: brtrue.s IL_0011
IL_000f: ldloc.0
IL_0010: ret
IL_0011: ldloca.s V_1
IL_0013: initobj ""bool?""
IL_0019: ldloc.1
IL_001a: ret
}";
string expectedIL2 = expectedIL1;
string expectedIL3 = @"{
// Code size 27 (0x1b)
.maxstack 1
.locals init (bool? V_0,
bool? V_1)
IL_0000: call ""bool? Program.N()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool bool?.GetValueOrDefault()""
IL_000d: brtrue.s IL_0019
IL_000f: ldloca.s V_1
IL_0011: initobj ""bool?""
IL_0017: ldloc.1
IL_0018: ret
IL_0019: ldloc.0
IL_001a: ret
}";
string expectedIL4 = expectedIL3;
string expectedIL5 = @"{
// Code size 24 (0x18)
.maxstack 1
.locals init (bool? V_0)
IL_0000: call ""bool Program.B()""
IL_0005: brtrue.s IL_000e
IL_0007: ldc.i4.0
IL_0008: newobj ""bool?..ctor(bool)""
IL_000d: ret
IL_000e: ldloca.s V_0
IL_0010: initobj ""bool?""
IL_0016: ldloc.0
IL_0017: ret
}";
string expectedIL6 = expectedIL5;
string expectedIL7 = @"{
// Code size 24 (0x18)
.maxstack 1
.locals init (bool? V_0)
IL_0000: call ""bool Program.B()""
IL_0005: brtrue.s IL_0011
IL_0007: ldloca.s V_0
IL_0009: initobj ""bool?""
IL_000f: ldloc.0
IL_0010: ret
IL_0011: ldc.i4.1
IL_0012: newobj ""bool?..ctor(bool)""
IL_0017: ret
}
";
string expectedIL8 = expectedIL7;
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
comp.VerifyIL("Program.M5", expectedIL5);
comp.VerifyIL("Program.M6", expectedIL6);
comp.VerifyIL("Program.M7", expectedIL7);
comp.VerifyIL("Program.M8", expectedIL8);
}
[Fact]
public void TestNullableBoolBinOpsOneNonNull()
{
// Codegen for x & y and x | y can be simplified if one operand is known to be non null.
// Note that we have already considered the case where one operand is null and the
// other is non null, in the test case above.
string source = @"
class Program
{
static bool? N() { return false; }
static bool B() { return false; }
static bool? M1()
{
return new bool?(B()) & N();
}
static bool? M2()
{
return N() & new bool?(B());
}
static bool? M3()
{
return new bool?(B()) | N();
}
static bool? M4()
{
return N() | new bool?(B());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 22 (0x16)
.maxstack 2
.locals init (bool? V_0)
IL_0000: call ""bool Program.B()""
IL_0005: call ""bool? Program.N()""
IL_000a: stloc.0
IL_000b: brtrue.s IL_0014
IL_000d: ldc.i4.0
IL_000e: newobj ""bool?..ctor(bool)""
IL_0013: ret
IL_0014: ldloc.0
IL_0015: ret
}";
string expectedIL2 = @"{
// Code size 22 (0x16)
.maxstack 1
.locals init (bool? V_0)
IL_0000: call ""bool? Program.N()""
IL_0005: stloc.0
IL_0006: call ""bool Program.B()""
IL_000b: brtrue.s IL_0014
IL_000d: ldc.i4.0
IL_000e: newobj ""bool?..ctor(bool)""
IL_0013: ret
IL_0014: ldloc.0
IL_0015: ret
}";
string expectedIL3 = @"{
// Code size 22 (0x16)
.maxstack 2
.locals init (bool? V_0)
IL_0000: call ""bool Program.B()""
IL_0005: call ""bool? Program.N()""
IL_000a: stloc.0
IL_000b: brtrue.s IL_000f
IL_000d: ldloc.0
IL_000e: ret
IL_000f: ldc.i4.1
IL_0010: newobj ""bool?..ctor(bool)""
IL_0015: ret
}";
string expectedIL4 = @"{
// Code size 22 (0x16)
.maxstack 1
.locals init (bool? V_0)
IL_0000: call ""bool? Program.N()""
IL_0005: stloc.0
IL_0006: call ""bool Program.B()""
IL_000b: brtrue.s IL_000f
IL_000d: ldloc.0
IL_000e: ret
IL_000f: ldc.i4.1
IL_0010: newobj ""bool?..ctor(bool)""
IL_0015: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
}
[Fact]
public void TestNullableBinOpsBothAlwaysNull()
{
// x op y is null if both ops are null for the binary operators
// * / % + - << >> and for non-bool & ^ |
string source = @"
class Program
{
static long? M1()
{
return new int?() + new long?();
}
static decimal? M2()
{
return (short?)null * default(decimal?);
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 10 (0xa)
.maxstack 1
.locals init (long? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""long?""
IL_0008: ldloc.0
IL_0009: ret
}";
string expectedIL2 = @"{
// Code size 10 (0xa)
.maxstack 1
.locals init (decimal? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""decimal?""
IL_0008: ldloc.0
IL_0009: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (6,16): warning CS0458: The result of the expression is always 'null' of type 'long?'
// return new int?() + new long?();
Diagnostic(ErrorCode.WRN_AlwaysNull, "new int?() + new long?()").WithArguments("long?"),
// (10,16): warning CS0458: The result of the expression is always 'null' of type 'decimal?'
// return (short?)null * default(decimal?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "(short?)null * default(decimal?)").WithArguments("decimal?"));
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
}
[Fact]
public void TestNullableBinOpsBothNonNull()
{
// Lifted x op y is generated as non-lifted if both operands are known to be non-null
// for operators * / % + - << >> and for non-bool & ^ |
//
// Roslyn does a far better job of this optimization than the native compiler.
string source = @"
class Program
{
static int N() { return 1; }
static int? M1()
{
return
new int?(N()) *
new int?(N()) /
new int?(N()) %
new int?(N()) +
new int?(N()) -
new int?(N()) <<
new int?(N()) >>
new int?(N()) &
new int?(N()) ^
new int?(N()) |
new int?(N());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 77 (0x4d)
.maxstack 3
IL_0000: call ""int Program.N()""
IL_0005: call ""int Program.N()""
IL_000a: mul
IL_000b: call ""int Program.N()""
IL_0010: div
IL_0011: call ""int Program.N()""
IL_0016: rem
IL_0017: call ""int Program.N()""
IL_001c: add
IL_001d: call ""int Program.N()""
IL_0022: sub
IL_0023: call ""int Program.N()""
IL_0028: ldc.i4.s 31
IL_002a: and
IL_002b: shl
IL_002c: call ""int Program.N()""
IL_0031: ldc.i4.s 31
IL_0033: and
IL_0034: shr
IL_0035: call ""int Program.N()""
IL_003a: and
IL_003b: call ""int Program.N()""
IL_0040: xor
IL_0041: call ""int Program.N()""
IL_0046: or
IL_0047: newobj ""int?..ctor(int)""
IL_004c: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL);
}
[Fact]
public void TestNullableBinOpsOneNull()
{
// If we have null + N() or null + new int?(B())
// then we simply generate M() as a side effect and result in null.
string source = @"
class Program
{
static int? N() { return 1; }
static int B() { return 1; }
static int? M1()
{
return new int?() + N();
}
static int? M2()
{
return new int?(B()) * default(int?);
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 16 (0x10)
.maxstack 1
.locals init (int? V_0)
IL_0000: call ""int? Program.N()""
IL_0005: pop
IL_0006: ldloca.s V_0
IL_0008: initobj ""int?""
IL_000e: ldloc.0
IL_000f: ret
}";
string expectedIL2 = @"{
// Code size 16 (0x10)
.maxstack 1
.locals init (int? V_0)
IL_0000: call ""int Program.B()""
IL_0005: pop
IL_0006: ldloca.s V_0
IL_0008: initobj ""int?""
IL_000e: ldloc.0
IL_000f: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (9,16): warning CS0458: The result of the expression is always 'null' of type 'int?'
// return new int?() + N();
Diagnostic(ErrorCode.WRN_AlwaysNull, "new int?() + N()").WithArguments("int?"),
// (13,16): warning CS0458: The result of the expression is always 'null' of type 'int?'
// return new int?(B()) * default(int?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "new int?(B()) * default(int?)").WithArguments("int?"));
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
}
[Fact]
public void TestNullableBinOpsOneNonNull()
{
// If one side of the nullable binop is non-null then we skip calling HasValue and GetValueOrDefault
// on that side.
string source = @"
class Program
{
static int B() { return 1; }
static int? N() { return 1; }
static int? M1()
{
return new int?(B()) + N();
}
static int? M2()
{
return new int?(1) + N();
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 46 (0x2e)
.maxstack 2
.locals init (int V_0,
int? V_1,
int? V_2)
IL_0000: call ""int Program.B()""
IL_0005: stloc.0
IL_0006: call ""int? Program.N()""
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool int?.HasValue.get""
IL_0013: brtrue.s IL_001f
IL_0015: ldloca.s V_2
IL_0017: initobj ""int?""
IL_001d: ldloc.2
IL_001e: ret
IL_001f: ldloc.0
IL_0020: ldloca.s V_1
IL_0022: call ""int int?.GetValueOrDefault()""
IL_0027: add
IL_0028: newobj ""int?..ctor(int)""
IL_002d: ret
}";
// TODO: Roslyn does a slightly worse job here than the native compiler does.
// TODO: The native compiler knows that the constant need not be stored in a temporary.
// TODO: We will clean this up in a later checkin.
// TODO: When we do so, add tests for ++ -- +=, etc.
string expectedIL2 = @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (int? V_0,
int? V_1)
IL_0000: call ""int? Program.N()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool int?.HasValue.get""
IL_000d: brtrue.s IL_0019
IL_000f: ldloca.s V_1
IL_0011: initobj ""int?""
IL_0017: ldloc.1
IL_0018: ret
IL_0019: ldc.i4.1
IL_001a: ldloca.s V_0
IL_001c: call ""int int?.GetValueOrDefault()""
IL_0021: add
IL_0022: newobj ""int?..ctor(int)""
IL_0027: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
}
[Fact]
public void TestNullableBinOpsOneZero()
{
// If one side of the nullable binop is non-null then we skip calling HasValue and GetValueOrDefault
// on that side.
string source = @"
class Program
{
static void Main()
{
int? N = 42;
System.Console.WriteLine(0 + N);
System.Console.WriteLine(N + 0);
System.Console.WriteLine(0 - N);
System.Console.WriteLine(N - 0);
System.Console.WriteLine(0 * N);
System.Console.WriteLine(N * 0);
System.Console.WriteLine(1 * N);
System.Console.WriteLine(N * 1);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"
42
42
-42
42
0
0
42
42")
.VerifyIL("Program.Main",
@"
{
// Code size 349 (0x15d)
.maxstack 3
.locals init (int? V_0,
int? V_1)
IL_0000: ldc.i4.s 42
IL_0002: newobj ""int?..ctor(int)""
IL_0007: dup
IL_0008: stloc.0
IL_0009: ldloca.s V_0
IL_000b: call ""bool int?.HasValue.get""
IL_0010: brtrue.s IL_001d
IL_0012: ldloca.s V_1
IL_0014: initobj ""int?""
IL_001a: ldloc.1
IL_001b: br.s IL_0029
IL_001d: ldloca.s V_0
IL_001f: call ""int int?.GetValueOrDefault()""
IL_0024: newobj ""int?..ctor(int)""
IL_0029: box ""int?""
IL_002e: call ""void System.Console.WriteLine(object)""
IL_0033: dup
IL_0034: stloc.0
IL_0035: ldloca.s V_0
IL_0037: call ""bool int?.HasValue.get""
IL_003c: brtrue.s IL_0049
IL_003e: ldloca.s V_1
IL_0040: initobj ""int?""
IL_0046: ldloc.1
IL_0047: br.s IL_0055
IL_0049: ldloca.s V_0
IL_004b: call ""int int?.GetValueOrDefault()""
IL_0050: newobj ""int?..ctor(int)""
IL_0055: box ""int?""
IL_005a: call ""void System.Console.WriteLine(object)""
IL_005f: dup
IL_0060: stloc.0
IL_0061: ldloca.s V_0
IL_0063: call ""bool int?.HasValue.get""
IL_0068: brtrue.s IL_0075
IL_006a: ldloca.s V_1
IL_006c: initobj ""int?""
IL_0072: ldloc.1
IL_0073: br.s IL_0083
IL_0075: ldc.i4.0
IL_0076: ldloca.s V_0
IL_0078: call ""int int?.GetValueOrDefault()""
IL_007d: sub
IL_007e: newobj ""int?..ctor(int)""
IL_0083: box ""int?""
IL_0088: call ""void System.Console.WriteLine(object)""
IL_008d: dup
IL_008e: stloc.0
IL_008f: ldloca.s V_0
IL_0091: call ""bool int?.HasValue.get""
IL_0096: brtrue.s IL_00a3
IL_0098: ldloca.s V_1
IL_009a: initobj ""int?""
IL_00a0: ldloc.1
IL_00a1: br.s IL_00af
IL_00a3: ldloca.s V_0
IL_00a5: call ""int int?.GetValueOrDefault()""
IL_00aa: newobj ""int?..ctor(int)""
IL_00af: box ""int?""
IL_00b4: call ""void System.Console.WriteLine(object)""
IL_00b9: dup
IL_00ba: stloc.0
IL_00bb: ldloca.s V_0
IL_00bd: call ""bool int?.HasValue.get""
IL_00c2: brtrue.s IL_00cf
IL_00c4: ldloca.s V_1
IL_00c6: initobj ""int?""
IL_00cc: ldloc.1
IL_00cd: br.s IL_00d5
IL_00cf: ldc.i4.0
IL_00d0: newobj ""int?..ctor(int)""
IL_00d5: box ""int?""
IL_00da: call ""void System.Console.WriteLine(object)""
IL_00df: dup
IL_00e0: stloc.0
IL_00e1: ldloca.s V_0
IL_00e3: call ""bool int?.HasValue.get""
IL_00e8: brtrue.s IL_00f5
IL_00ea: ldloca.s V_1
IL_00ec: initobj ""int?""
IL_00f2: ldloc.1
IL_00f3: br.s IL_00fb
IL_00f5: ldc.i4.0
IL_00f6: newobj ""int?..ctor(int)""
IL_00fb: box ""int?""
IL_0100: call ""void System.Console.WriteLine(object)""
IL_0105: dup
IL_0106: stloc.0
IL_0107: ldloca.s V_0
IL_0109: call ""bool int?.HasValue.get""
IL_010e: brtrue.s IL_011b
IL_0110: ldloca.s V_1
IL_0112: initobj ""int?""
IL_0118: ldloc.1
IL_0119: br.s IL_0127
IL_011b: ldloca.s V_0
IL_011d: call ""int int?.GetValueOrDefault()""
IL_0122: newobj ""int?..ctor(int)""
IL_0127: box ""int?""
IL_012c: call ""void System.Console.WriteLine(object)""
IL_0131: stloc.0
IL_0132: ldloca.s V_0
IL_0134: call ""bool int?.HasValue.get""
IL_0139: brtrue.s IL_0146
IL_013b: ldloca.s V_1
IL_013d: initobj ""int?""
IL_0143: ldloc.1
IL_0144: br.s IL_0152
IL_0146: ldloca.s V_0
IL_0148: call ""int int?.GetValueOrDefault()""
IL_014d: newobj ""int?..ctor(int)""
IL_0152: box ""int?""
IL_0157: call ""void System.Console.WriteLine(object)""
IL_015c: ret
}");
}
[Fact]
public void TestNullableBinOpsOneZero1()
{
// If one side of the nullable binop is non-null then we skip calling HasValue and GetValueOrDefault
// on that side.
string source = @"
class Program
{
static void Main()
{
System.Console.WriteLine(0 + (int?)42);
System.Console.WriteLine((int?)42 + 0);
System.Console.WriteLine(0 - (int?)42);
System.Console.WriteLine((int?)42 - 0);
System.Console.WriteLine(0 * (int?)42);
System.Console.WriteLine((int?)42 * 0);
System.Console.WriteLine(1 * (int?)42);
System.Console.WriteLine((int?)42 * 1);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"
42
42
-42
42
0
0
42
42")
.VerifyIL("Program.Main",
@"
{
// Code size 97 (0x61)
.maxstack 2
IL_0000: ldc.i4.s 42
IL_0002: box ""int""
IL_0007: call ""void System.Console.WriteLine(object)""
IL_000c: ldc.i4.s 42
IL_000e: box ""int""
IL_0013: call ""void System.Console.WriteLine(object)""
IL_0018: ldc.i4.0
IL_0019: ldc.i4.s 42
IL_001b: sub
IL_001c: box ""int""
IL_0021: call ""void System.Console.WriteLine(object)""
IL_0026: ldc.i4.s 42
IL_0028: box ""int""
IL_002d: call ""void System.Console.WriteLine(object)""
IL_0032: ldc.i4.0
IL_0033: box ""int""
IL_0038: call ""void System.Console.WriteLine(object)""
IL_003d: ldc.i4.0
IL_003e: box ""int""
IL_0043: call ""void System.Console.WriteLine(object)""
IL_0048: ldc.i4.s 42
IL_004a: box ""int""
IL_004f: call ""void System.Console.WriteLine(object)""
IL_0054: ldc.i4.s 42
IL_0056: box ""int""
IL_005b: call ""void System.Console.WriteLine(object)""
IL_0060: ret
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public partial class CodeGenOptimizedNullableOperatorTests : CSharpTestBase
{
[Fact]
public void TestNullableBoxingConversionsAlwaysNull()
{
// The native compiler does not optimize this case; Roslyn does. We know
// that the result of boxing default(int?) to object is the same as casting
// literal null to object, so we do not need to allocate space on the stack
// for the nullable int, initialize it, and then box that to a null ref.
string[] sources = {
@"class Program
{
static void Main()
{
System.Console.WriteLine((object)default(int?));
}
}
",
@"class Program
{
static void Main()
{
System.Console.WriteLine((object)(new int?()));
}
}
",
@"class Program
{
static void Main()
{
System.Console.WriteLine((object)(int?)null);
}
}
"};
string expectedOutput = "";
string expectedIL = @"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldnull
IL_0001: call ""void System.Console.WriteLine(object)""
IL_0006: ret
}";
foreach (string source in sources)
{
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", expectedIL);
}
}
[Fact]
public void TestNullableBoxingConversionNeverNull()
{
// The native compiler does not optimize this case; Roslyn does. We know
// that the result of boxing default(int?) to object is the same as casting
// literal null to object, so we do not need to allocate space on the stack
// for the nullable int, initialize it, and then box that to a null ref.
string[] sources = {
@"class Program
{
static void Main()
{
System.Console.WriteLine((object)new int?(123));
}
}
",
@"class Program
{
static void Main()
{
System.Console.WriteLine((object)(int?)123);
}
}
"};
string expectedOutput = "123";
string expectedIL = @"{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldc.i4.s 123
IL_0002: box ""int""
IL_0007: call ""void System.Console.WriteLine(object)""
IL_000c: ret
}";
foreach (string source in sources)
{
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", expectedIL);
}
}
[Fact]
public void TestNullableConversionAlwaysNull()
{
// A built-in nullable conversion whose argument is known to always be null
// can simply be optimized away to be the null result.
string source = @"
class Program
{
static long? M()
{
return new int?();
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 10 (0xa)
.maxstack 1
.locals init (long? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""long?""
IL_0008: ldloc.0
IL_0009: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestNullableConversionNeverNull()
{
// A built-in nullable conversion whose argument is known to be non-null
// can be generated by converting the value to the underlying target type,
// and then converting that to nullable, without generating the nullable source
// or checking to see if it has a value.
string source = @"
class Program
{
static long? M(int x)
{
return new int?(x);
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: conv.i8
IL_0002: newobj ""long?..ctor(long)""
IL_0007: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestLiftedUserDefinedConversionAlwaysNull()
{
// A user-defined nullable conversion whose argument is known to always be null
// can simply be optimized away to be the null result.
string source = @"
struct S
{
public static implicit operator S(int x) { return new S(); }
}
class Program
{
static S? M()
{
return new int?();
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 10 (0xa)
.maxstack 1
.locals init (S? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S?""
IL_0008: ldloc.0
IL_0009: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestLiftedUserDefinedConversionNeverNull()
{
// A user-defined nullable conversion whose argument is known to never be null
// can have the nullable ctor, temporary store and value test optimized away.
string source = @"
struct S
{
public static implicit operator S(int x) { return new S(); }
public static implicit operator string(S s) { return s.ToString(); }
}
class Program
{
static S? M1(int x)
{
return new int?(x);
}
static S M2(int x)
{
return (S)(new int?(x));
}
static string M3(int x)
{
// The non-null conversion optimizer should chain well. That is,
// we first optimize (string)(S?)(new int?(x)) to (string)(new S?((S)x)), and then
// to (string)(S)x.
return (string)(S?)(new int?(x));
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""S S.op_Implicit(int)""
IL_0006: newobj ""S?..ctor(S)""
IL_000b: ret
}";
string expectedIL2 = @"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""S S.op_Implicit(int)""
IL_0006: ret
}";
string expectedIL3 = @"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""S S.op_Implicit(int)""
IL_0006: call ""string S.op_Implicit(S)""
IL_000b: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
}
[Fact]
public void TestNullableUnaryOpsAlwaysNull()
{
// A unary operator whose argument is known to always be null
// can simply be optimized away to be the null result.
string source = @"
class Program
{
static int? M()
{
return ~(new int?());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 10 (0xa)
.maxstack 1
.locals init (int? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""int?""
IL_0008: ldloc.0
IL_0009: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (6,16): warning CS0458: The result of the expression is always 'null' of type 'int?'
// return ~(new int?());
Diagnostic(ErrorCode.WRN_AlwaysNull, "~(new int?())").WithArguments("int?"));
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestNullableUnaryOpsAlwaysNullChained()
{
// A unary operator whose argument is known to always be null
// can simply be optimized away to be the null result. These
// optimizations should "chain" naturally. Here we combine
// a built-in conversion, two unary operations, and a boxing.
// The net result should simply be a null reference.
//
// The native compiler does not handle these "chained" optimizations,
// interestingly enough; the native compiler will optimize away only the
// innermost one; it is then not treated as "always null" and is checked
// for nullity unnecessarily.
//
// Fortunately, the warning logic does not do a deep analysis; it only
// reports a single warning.
string source = @"
class Program
{
static object M()
{
return ~-(new short?());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (6,17): warning CS0458: The result of the expression is always 'null' of type 'int?'
// return ~-(new short?());
Diagnostic(ErrorCode.WRN_AlwaysNull, "-(new short?())").WithArguments("int?"));
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestNullableUnaryOpsNeverNull()
{
// A unary operator whose argument is known to never be null
// can be optimized to avoid the null check.
string source = @"
class Program
{
static int N() { return 123; }
static int? M()
{
// This can be optimized to new int?(~N())
return ~(new int?(N()));
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: call ""int Program.N()""
IL_0005: not
IL_0006: newobj ""int?..ctor(int)""
IL_000b: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestNullableUnaryOpsNeverNullChained()
{
// A unary operator whose argument is known to never be null
// can simply be optimized away to be the null result. These
// optimizations should "chain" naturally. Here we combine
// two unary operations and a boxing. As you can see, we eliminate
// all the null checks and the "new S?" ctor.
string source = @"
struct S
{
public static S operator +(S s) { return s; }
public static S operator -(S s) { return s; }
public static S operator ~(S s) { return s; }
}
class Program
{
static object M(S s)
{
return ~-(new S?(s));
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""S S.op_UnaryNegation(S)""
IL_0006: call ""S S.op_OnesComplement(S)""
IL_000b: box ""S""
IL_0010: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestLiftedUnaryOpOnTopOfLifted()
{
// Here's an optimization that the dev10 compiler does not do. If we have a
// lifted unary operator "on top" of another lifted operation, then the unary
// operation can be "distributed" to both branches of the underlying lifted operation.
//
// For example, suppose we have
//
// return -(N1() + N2());
//
// Where N1() and N2() return int?. The dev10 compiler does this in two steps: first it
// computes the int? result of the addition, and then it does a fully lifted negation:
//
// int? t1 = N1();
// int? t2 = N2();
// int? t3 = t1.HasValue && t2.HasValue ? new int?(t1.Value + t2.Value) : new int?();
// return t3.HasValue ? new int?(-t3.Value)) : new int?();
//
// But t3 is completely unnecessary here. We could realize this as:
//
// return -(t1.HasValue && t2.HasValue ? new int?(t1.Value + t2.Value) : new int?())
//
// which is the same as distributing the conversion to the consequence and alternative:
//
// return (t1.HasValue && t2.HasValue ? - new int?(t1.Value + t2.Value) ): - ( new int?() ) )
//
// and now we can optimize the consequence and alternative down to
//
// return (t1.HasValue && t2.HasValue ? new int?(-(t1.Value + t2.Value) ): new int?() )
//
// And the int? t3 disappears entirely.
//
// This optimization has the nice property that it composes well with itself, as we'll see.
string source = @"
struct S
{
public static S operator -(S s) { return s; }
public static S operator ~(S s) { return s; }
public static S operator +(S s1, S s2) { return s1; }
}
class Program
{
static int? N1() { return 1; }
static int? N2() { return 2; }
static S? N3() { return null; }
static S? N4() { return null; }
static int? M1()
{
return -(N1() + N2());
}
static S? M2()
{
return -~(N3() + N4());
}
static void Main() { }
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 61 (0x3d)
.maxstack 2
.locals init (int? V_0,
int? V_1,
int? V_2)
IL_0000: call ""int? Program.N1()""
IL_0005: stloc.0
IL_0006: call ""int? Program.N2()""
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call ""bool int?.HasValue.get""
IL_0013: ldloca.s V_1
IL_0015: call ""bool int?.HasValue.get""
IL_001a: and
IL_001b: brtrue.s IL_0027
IL_001d: ldloca.s V_2
IL_001f: initobj ""int?""
IL_0025: ldloc.2
IL_0026: ret
IL_0027: ldloca.s V_0
IL_0029: call ""int int?.GetValueOrDefault()""
IL_002e: ldloca.s V_1
IL_0030: call ""int int?.GetValueOrDefault()""
IL_0035: add
IL_0036: neg
IL_0037: newobj ""int?..ctor(int)""
IL_003c: ret
}
";
string expectedIL2 = @"{
// Code size 74 (0x4a)
.maxstack 2
.locals init (S? V_0,
S? V_1,
S? V_2)
IL_0000: call ""S? Program.N3()""
IL_0005: stloc.0
IL_0006: call ""S? Program.N4()""
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call ""bool S?.HasValue.get""
IL_0013: ldloca.s V_1
IL_0015: call ""bool S?.HasValue.get""
IL_001a: and
IL_001b: brtrue.s IL_0027
IL_001d: ldloca.s V_2
IL_001f: initobj ""S?""
IL_0025: ldloc.2
IL_0026: ret
IL_0027: ldloca.s V_0
IL_0029: call ""S S?.GetValueOrDefault()""
IL_002e: ldloca.s V_1
IL_0030: call ""S S?.GetValueOrDefault()""
IL_0035: call ""S S.op_Addition(S, S)""
IL_003a: call ""S S.op_OnesComplement(S)""
IL_003f: call ""S S.op_UnaryNegation(S)""
IL_0044: newobj ""S?..ctor(S)""
IL_0049: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
}
[Fact]
public void TestLiftedBinaryOpWithConstantOnTopOfLifted()
{
// If we have a lifted binary operation "on top" of a lifted operation,
// and the right side of the outer operation is a constant, then we
// can eliminate several temporaries.
//
// For example, suppose we have
//
// return N1() * N2() + 1;
//
// Where N1() and N2() return int?. We could do this the obvious way:
//
// int? n1 = N1();
// int? n2 = N2();
// int? r = n1.HasValue && n2.HasValue ? new int?(n1.Value * n2.Value) : new int?();
// int v = 1;
// return r.HasValue ? new int?(r.Value + v)) : new int?();
//
// But r and v are both unnecessary. We could instead realize this as:
//
// int? n1 = N1();
// int? n2 = N2();
// return n1.HasValue && n2.HasValue ? new int?(n1.Value * n2.Value + 1) : new int?();
//
// We want to do this optimization in particular because it makes codegen for i++
// and i+=1 better.
//
// The dev10 compiler does this optimization *only* on i++ and not on expressions
// like N1() * N2() + 1 or sh+=1;
string source = @"
class Program
{
static int? N1() { return 1; }
static int? N2() { return 2; }
static short? sh;
static int? M1()
{
return N1() * N2() + 1;
}
static short? M2()
{
return sh++;
}
static short? M3()
{
return ++sh;
}
static short? M4()
{
return sh += 1;
}
static void Main() { }
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 62 (0x3e)
.maxstack 2
.locals init (int? V_0,
int? V_1,
int? V_2)
IL_0000: call ""int? Program.N1()""
IL_0005: stloc.0
IL_0006: call ""int? Program.N2()""
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call ""bool int?.HasValue.get""
IL_0013: ldloca.s V_1
IL_0015: call ""bool int?.HasValue.get""
IL_001a: and
IL_001b: brtrue.s IL_0027
IL_001d: ldloca.s V_2
IL_001f: initobj ""int?""
IL_0025: ldloc.2
IL_0026: ret
IL_0027: ldloca.s V_0
IL_0029: call ""int int?.GetValueOrDefault()""
IL_002e: ldloca.s V_1
IL_0030: call ""int int?.GetValueOrDefault()""
IL_0035: mul
IL_0036: ldc.i4.1
IL_0037: add
IL_0038: newobj ""int?..ctor(int)""
IL_003d: ret
}";
string expectedIL2 = @"{
// Code size 48 (0x30)
.maxstack 3
.locals init (short? V_0,
short? V_1)
IL_0000: ldsfld ""short? Program.sh""
IL_0005: dup
IL_0006: stloc.0
IL_0007: ldloca.s V_0
IL_0009: call ""bool short?.HasValue.get""
IL_000e: brtrue.s IL_001b
IL_0010: ldloca.s V_1
IL_0012: initobj ""short?""
IL_0018: ldloc.1
IL_0019: br.s IL_002a
IL_001b: ldloca.s V_0
IL_001d: call ""short short?.GetValueOrDefault()""
IL_0022: ldc.i4.1
IL_0023: add
IL_0024: conv.i2
IL_0025: newobj ""short?..ctor(short)""
IL_002a: stsfld ""short? Program.sh""
IL_002f: ret
}";
string expectedIL3 = @"{
// Code size 48 (0x30)
.maxstack 2
.locals init (short? V_0,
short? V_1)
IL_0000: ldsfld ""short? Program.sh""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool short?.HasValue.get""
IL_000d: brtrue.s IL_001a
IL_000f: ldloca.s V_1
IL_0011: initobj ""short?""
IL_0017: ldloc.1
IL_0018: br.s IL_0029
IL_001a: ldloca.s V_0
IL_001c: call ""short short?.GetValueOrDefault()""
IL_0021: ldc.i4.1
IL_0022: add
IL_0023: conv.i2
IL_0024: newobj ""short?..ctor(short)""
IL_0029: dup
IL_002a: stsfld ""short? Program.sh""
IL_002f: ret
}";
string expectedIL4 = @"{
// Code size 48 (0x30)
.maxstack 2
.locals init (short? V_0,
short? V_1)
IL_0000: ldsfld ""short? Program.sh""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool short?.HasValue.get""
IL_000d: brtrue.s IL_001a
IL_000f: ldloca.s V_1
IL_0011: initobj ""short?""
IL_0017: ldloc.1
IL_0018: br.s IL_0029
IL_001a: ldloca.s V_0
IL_001c: call ""short short?.GetValueOrDefault()""
IL_0021: ldc.i4.1
IL_0022: add
IL_0023: conv.i2
IL_0024: newobj ""short?..ctor(short)""
IL_0029: dup
IL_002a: stsfld ""short? Program.sh""
IL_002f: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
}
[Fact]
public void TestNullableComparisonOpsBothAlwaysNull()
{
// An ==, !=, <, >, <= or >= operation where both operands
// are null is always true for equality, and always false otherwise.
// Note that the native compiler has a bug; it does not produce the warning
// "comparing null with S? always produces false" -- it incorrectly warns
// that it produces a null of type bool? ! Roslyn does not reproduce this bug.
string source = @"
struct S // User-defined relational ops
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return true; }
public static bool operator <(S x, S y) { return true; }
public static bool operator >(S x, S y) { return true; }
public static bool operator <=(S x, S y) { return true; }
public static bool operator >=(S x, S y) { return true; }
public override bool Equals(object x) { return true; }
public override int GetHashCode() { return 0; }
}
struct T // no user-defined relational ops
{
}
class Program
{
static bool M1()
{
return new int?() == new short?();
}
static bool M2()
{
return default(double?) != new short?();
}
static bool M3()
{
return ((int?)null) < new decimal?();
}
static bool M4()
{
return new S?() == new S?();
}
static bool M5()
{
return default(S?) != new S?();
}
static bool M6()
{
return ((S?)null) < new S?();
}
static bool M7() // Special case for equality with null literal and no overloaded operators.
{
return default(T?) == null;
}
static bool M8()
{
return null != new T?();
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedILTrue = @"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: ret
}";
string expectedILFalse = @"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (25,16): warning CS0464: Comparing with null of type 'decimal?' always produces 'false'
// return ((int?)null) < new decimal?();
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((int?)null) < new decimal?()").WithArguments("decimal?"),
// (37,16): warning CS0464: Comparing with null of type 'S?' always produces 'false'
// return ((S?)null) < new S?();
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((S?)null) < new S?()").WithArguments("S?"));
comp.VerifyIL("Program.M1", expectedILTrue);
comp.VerifyIL("Program.M2", expectedILFalse);
comp.VerifyIL("Program.M3", expectedILFalse);
comp.VerifyIL("Program.M4", expectedILTrue);
comp.VerifyIL("Program.M5", expectedILFalse);
comp.VerifyIL("Program.M6", expectedILFalse);
comp.VerifyIL("Program.M7", expectedILTrue);
comp.VerifyIL("Program.M8", expectedILFalse);
}
[Fact]
public void TestNullableComparisonNonNullWithLiteralNull()
{
// We can optimize this away to simply evaluating N() for its side effects
// and returning false.
string source = @"
struct S {}
class Program
{
static S N() { System.Console.WriteLine(123); return new S(); }
static bool M()
{
return new S?(N()) == null;
}
static void Main() {M();}
}
";
string expectedOutput = "123";
string expectedIL = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""S Program.N()""
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyIL("Program.M", expectedIL);
}
[Fact]
public void TestNullableComparisonOpsBothNeverNull()
{
// An ==, !=, <, >, <= or >= operation where both operands
// are not null simply drops the lifting logic entirely.
string source = @"
struct S // User-defined relational ops
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return true; }
public static bool operator <(S x, S y) { return true; }
public static bool operator >(S x, S y) { return true; }
public static bool operator <=(S x, S y) { return true; }
public static bool operator >=(S x, S y) { return true; }
public override bool Equals(object x) { return true; }
public override int GetHashCode() { return 0; }
}
class Program
{
static int N1() { return 123; }
static short N2() { return 123; }
static double N3() { return 123; }
static decimal N4() { return 123; }
static S N5() { return new S(); }
static bool M1()
{
// Notice that there are two optimizations here and in the next few cases.
// First we optimize the conversion from short? to int? so that the right
// hand side is new int?((int)N2()). Second, we optimize the comparison to
// N1() == (int)N2(), eliminating all the lifting.
return new int?(N1()) == new short?(N2());
}
static bool M2()
{
return new double?(N3()) != new short?(N2());
}
static bool M3()
{
return new int?(N1()) < new decimal?(N4());
}
static bool M4()
{
return new S?(N5()) == new S?(N5());
}
static bool M5()
{
return new S?(N5()) != new S?(N5());
}
static bool M6()
{
return new S?(N5()) < new S?(N5());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 13 (0xd)
.maxstack 2
IL_0000: call ""int Program.N1()""
IL_0005: call ""short Program.N2()""
IL_000a: ceq
IL_000c: ret
}";
string expectedIL2 = @"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: call ""double Program.N3()""
IL_0005: call ""short Program.N2()""
IL_000a: conv.r8
IL_000b: ceq
IL_000d: ldc.i4.0
IL_000e: ceq
IL_0010: ret
}";
string expectedIL3 = @"{
// Code size 21 (0x15)
.maxstack 2
IL_0000: call ""int Program.N1()""
IL_0005: call ""decimal decimal.op_Implicit(int)""
IL_000a: call ""decimal Program.N4()""
IL_000f: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_0014: ret
}
";
string expectedIL4 = @"{
// Code size 16 (0x10)
.maxstack 2
IL_0000: call ""S Program.N5()""
IL_0005: call ""S Program.N5()""
IL_000a: call ""bool S.op_Equality(S, S)""
IL_000f: ret
}";
string expectedIL5 = @"{
// Code size 16 (0x10)
.maxstack 2
IL_0000: call ""S Program.N5()""
IL_0005: call ""S Program.N5()""
IL_000a: call ""bool S.op_Inequality(S, S)""
IL_000f: ret
}";
string expectedIL6 = @"{
// Code size 16 (0x10)
.maxstack 2
IL_0000: call ""S Program.N5()""
IL_0005: call ""S Program.N5()""
IL_000a: call ""bool S.op_LessThan(S, S)""
IL_000f: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
comp.VerifyIL("Program.M5", expectedIL5);
comp.VerifyIL("Program.M6", expectedIL6);
}
[Fact, WorkItem(663, "https://github.com/dotnet/roslyn/issues/663")]
public void TestNullableComparisonOpsOneNullOneNonNull()
{
// An ==, !=, <, >, <= or >= operation where one operand is null and the
// other is non-null is always false except for inequality, which is true.
// We can skip the lifting and just generate the side effect.
// Note that Roslyn produces considerably more warnings here than the
// native compiler; the native compiler only produces warnings for
// "((int?)null) < new decimal?(N3())" and "((S?)null) < new S?(N4())".
// For compatibility Roslyn reports the same diagnostics by default,
// but in "strict" mode (which will be part of the "warning waves" once
// we do that) Roslyn will report warnings for
// new S() == null and new S() != null.
string source = @"
struct S // User-defined relational ops
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return true; }
public static bool operator <(S x, S y) { return true; }
public static bool operator >(S x, S y) { return true; }
public static bool operator <=(S x, S y) { return true; }
public static bool operator >=(S x, S y) { return true; }
public override bool Equals(object x) { return true; }
public override int GetHashCode() { return 0; }
}
class Program
{
static int N1() { return 1; }
static short N2() { return 1; }
static decimal N3() { return 1; }
static S N4() { return new S(); }
static bool M1()
{
return new int?(N1()) == new short?();
}
static bool M2()
{
return default(double?) != new short?(N2());
}
static bool M3()
{
return ((int?)null) < new decimal?(N3());
}
static bool M4()
{
return new S?() == new S?(N4());
}
static bool M5()
{
return default(S?) != new S?(N4());
}
static bool M6()
{
return ((S?)null) < new S?(N4());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""int Program.N1()""
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
}";
string expectedIL2 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""short Program.N2()""
IL_0005: pop
IL_0006: ldc.i4.1
IL_0007: ret
}";
string expectedIL3 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""decimal Program.N3()""
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
}";
string expectedIL4 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""S Program.N4()""
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
}";
string expectedIL5 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""S Program.N4()""
IL_0005: pop
IL_0006: ldc.i4.1
IL_0007: ret
}";
string expectedIL6 = expectedIL4;
CompileAndVerify(source, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe.WithWarningLevel(4)).VerifyDiagnostics(
// (21,16): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'short?'
// return new int?(N1()) == new short?();
Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "new int?(N1()) == new short?()").WithArguments("false", "int", "short?").WithLocation(21, 16),
// (25,16): warning CS0472: The result of the expression is always 'true' since a value of type 'double' is never equal to 'null' of type 'double?'
// return default(double?) != new short?(N2());
Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "default(double?) != new short?(N2())").WithArguments("true", "double", "double?").WithLocation(25, 16),
// (29,16): warning CS0464: Comparing with null of type 'int?' always produces 'false'
// return ((int?)null) < new decimal?(N3());
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((int?)null) < new decimal?(N3())").WithArguments("int?").WithLocation(29, 16),
// (41,16): warning CS0464: Comparing with null of type 'S?' always produces 'false'
// return ((S?)null) < new S?(N4());
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((S?)null) < new S?(N4())").WithArguments("S?").WithLocation(41, 16)
);
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (21,16): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'short?'
// return new int?(N1()) == new short?();
Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "new int?(N1()) == new short?()").WithArguments("false", "int", "short?").WithLocation(21, 16),
// (25,16): warning CS0472: The result of the expression is always 'true' since a value of type 'double' is never equal to 'null' of type 'double?'
// return default(double?) != new short?(N2());
Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "default(double?) != new short?(N2())").WithArguments("true", "double", "double?").WithLocation(25, 16),
// (29,16): warning CS0464: Comparing with null of type 'int?' always produces 'false'
// return ((int?)null) < new decimal?(N3());
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((int?)null) < new decimal?(N3())").WithArguments("int?").WithLocation(29, 16),
// (33,16): warning CS8073: The result of the expression is always 'false' since a value of type 'S' is never equal to 'null' of type 'S?'
// return new S?() == new S?(N4());
Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "new S?() == new S?(N4())").WithArguments("false", "S", "S?").WithLocation(33, 16),
// (37,16): warning CS8073: The result of the expression is always 'true' since a value of type 'S' is never equal to 'null' of type 'S?'
// return default(S?) != new S?(N4());
Diagnostic(ErrorCode.WRN_NubExprIsConstBool2, "default(S?) != new S?(N4())").WithArguments("true", "S", "S?").WithLocation(37, 16),
// (41,16): warning CS0464: Comparing with null of type 'S?' always produces 'false'
// return ((S?)null) < new S?(N4());
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((S?)null) < new S?(N4())").WithArguments("S?").WithLocation(41, 16)
);
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
comp.VerifyIL("Program.M5", expectedIL5);
comp.VerifyIL("Program.M6", expectedIL6);
}
[Fact]
public void TestNullableComparisonOpsOneNullOneUnknown()
{
// An <, >, <= or >= operation where one operand is null and the
// other is unknown is always false; we can skip the lifting and
// generate the side effect.
//
// An == or != operation where one operand is null and the other is
// unknown turns into a call to HasValue.
//
// As mentioned above, the native compiler gets one of the warnings wrong;
// Roslyn gets it right.
string source = @"
struct S // User-defined relational ops
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return true; }
public static bool operator <(S x, S y) { return true; }
public static bool operator >(S x, S y) { return true; }
public static bool operator <=(S x, S y) { return true; }
public static bool operator >=(S x, S y) { return true; }
public override bool Equals(object x) { return true; }
public override int GetHashCode() { return 0; }
}
class Program
{
static int? N1() { return 1; }
static short? N2() { return 1; }
static decimal? N3() { return 1; }
static S? N4() { return new S(); }
static bool M1()
{
return N1() == new short?();
}
static bool M2()
{
return default(double?) != N2();
}
static bool M3()
{
return ((int?)null) < N3();
}
static bool M4()
{
return new S?() == N4();
}
static bool M5()
{
return default(S?) != N4();
}
static bool M6()
{
return ((S?)null) < N4();
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 17 (0x11)
.maxstack 2
.locals init (int? V_0)
IL_0000: call ""int? Program.N1()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool int?.HasValue.get""
IL_000d: ldc.i4.0
IL_000e: ceq
IL_0010: ret
}";
// TODO: Roslyn and the native compiler both produce this sub-optimal code for
// TODO: "default(double?) != N2()". We are essentially generating:
// TODO:
// TODO: short? temp1 = N2();
// TODO: double? temp2 = temp1.HasValue ? new double?((double)temp1.GetValueOrDefault()) : new double?();
// TODO: return temp2.HasValue;
// TODO:
// TODO: We could be instead simply generating
// TODO:
// TODO: return N2().HasValue();
string expectedIL2 = @"{
// Code size 48 (0x30)
.maxstack 1
.locals init (short? V_0,
double? V_1)
IL_0000: call ""short? Program.N2()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool short?.HasValue.get""
IL_000d: brtrue.s IL_001a
IL_000f: ldloca.s V_1
IL_0011: initobj ""double?""
IL_0017: ldloc.1
IL_0018: br.s IL_0027
IL_001a: ldloca.s V_0
IL_001c: call ""short short?.GetValueOrDefault()""
IL_0021: conv.r8
IL_0022: newobj ""double?..ctor(double)""
IL_0027: stloc.1
IL_0028: ldloca.s V_1
IL_002a: call ""bool double?.HasValue.get""
IL_002f: ret
}";
string expectedIL3 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""decimal? Program.N3()""
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
}";
string expectedIL4 = @"{
// Code size 17 (0x11)
.maxstack 2
.locals init (S? V_0)
IL_0000: call ""S? Program.N4()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool S?.HasValue.get""
IL_000d: ldc.i4.0
IL_000e: ceq
IL_0010: ret
}";
string expectedIL5 = @"{
// Code size 14 (0xe)
.maxstack 1
.locals init (S? V_0)
IL_0000: call ""S? Program.N4()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool S?.HasValue.get""
IL_000d: ret
}";
string expectedIL6 = @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: call ""S? Program.N4()""
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (29,16): warning CS0464: Comparing with null of type 'int?' always produces 'false'
// return ((int?)null) < N3();
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((int?)null) < N3()").WithArguments("int?"),
// (41,16): warning CS0464: Comparing with null of type 'S?' always produces 'false'
// return ((S?)null) < N4();
Diagnostic(ErrorCode.WRN_CmpAlwaysFalse, "((S?)null) < N4()").WithArguments("S?")
);
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
comp.VerifyIL("Program.M5", expectedIL5);
comp.VerifyIL("Program.M6", expectedIL6);
}
[Fact]
public void TestNullableComparisonOpsOneNonNullOneUnknown()
{
// When we have a lifted comparison where we know that one side
// is definitely not null, but know nothing about the other, then
// we make a slight modification to the code generation. For example,
// suppose X() and Y() return int?. For "return X() < Y();" we would generate:
// int? x = X();
// int? y = Y();
// return x.GetValueOrDefault() < y.GetValueOrDefault() ? x.HasValue & y.HasValue : false;
//
// But suppose Z() returns int. For X() < Z(), rather than converting Z() to int? and doing the
// same codegen as before, we simplify the codegen to:
//
// int? x = X();
// int z = Z();
// return x.GetValueOrDefault() < z ? x.HasValue : false;
//
// We apply this same pattern to all lifted comparison operators.
string source = @"
struct S // User-defined relational ops
{
public static bool operator ==(S x, S y) { return true; }
public static bool operator !=(S x, S y) { return true; }
public static bool operator <(S x, S y) { return true; }
public static bool operator >(S x, S y) { return true; }
public static bool operator <=(S x, S y) { return true; }
public static bool operator >=(S x, S y) { return true; }
public override bool Equals(object x) { return true; }
public override int GetHashCode() { return 0; }
}
class Program
{
static int? N1() { return 1; }
static short? N2() { return 1; }
static decimal? N3() { return 1; }
static S? N4() { return new S(); }
static int V1() { return 1; }
static short V2() { return 1; }
static decimal V3() { return 1; }
static S V4() { return new S(); }
static bool M1()
{
return N1() == new short?(V2());
}
static bool M2()
{
return N1() < new decimal?(V3());
}
static bool M3()
{
return new S?(V4()) == N4();
}
static bool M4()
{
return new S?(V4()) != N4();
}
static bool M5()
{
return new S?(V4()) < N4();
}
static void Main() { }
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 31 (0x1f)
.maxstack 2
.locals init (int? V_0,
int V_1)
IL_0000: call ""int? Program.N1()""
IL_0005: stloc.0
IL_0006: call ""short Program.V2()""
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call ""int int?.GetValueOrDefault()""
IL_0013: ldloc.1
IL_0014: ceq
IL_0016: ldloca.s V_0
IL_0018: call ""bool int?.HasValue.get""
IL_001d: and
IL_001e: ret
}";
// TODO: We do a worse job than the native compiler here. Find out why.
string expectedIL2 = @"{
// Code size 72 (0x48)
.maxstack 2
.locals init (decimal? V_0,
decimal V_1,
int? V_2,
decimal? V_3)
IL_0000: call ""int? Program.N1()""
IL_0005: stloc.2
IL_0006: ldloca.s V_2
IL_0008: call ""bool int?.HasValue.get""
IL_000d: brtrue.s IL_001a
IL_000f: ldloca.s V_3
IL_0011: initobj ""decimal?""
IL_0017: ldloc.3
IL_0018: br.s IL_002b
IL_001a: ldloca.s V_2
IL_001c: call ""int int?.GetValueOrDefault()""
IL_0021: call ""decimal decimal.op_Implicit(int)""
IL_0026: newobj ""decimal?..ctor(decimal)""
IL_002b: stloc.0
IL_002c: call ""decimal Program.V3()""
IL_0031: stloc.1
IL_0032: ldloca.s V_0
IL_0034: call ""decimal decimal?.GetValueOrDefault()""
IL_0039: ldloc.1
IL_003a: call ""bool decimal.op_LessThan(decimal, decimal)""
IL_003f: ldloca.s V_0
IL_0041: call ""bool decimal?.HasValue.get""
IL_0046: and
IL_0047: ret
}";
string expectedIL3 = @"{
// Code size 37 (0x25)
.maxstack 2
.locals init (S V_0,
S? V_1)
IL_0000: call ""S Program.V4()""
IL_0005: stloc.0
IL_0006: call ""S? Program.N4()""
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool S?.HasValue.get""
IL_0013: brtrue.s IL_0017
IL_0015: ldc.i4.0
IL_0016: ret
IL_0017: ldloc.0
IL_0018: ldloca.s V_1
IL_001a: call ""S S?.GetValueOrDefault()""
IL_001f: call ""bool S.op_Equality(S, S)""
IL_0024: ret
}";
string expectedIL4 = @"{
// Code size 37 (0x25)
.maxstack 2
.locals init (S V_0,
S? V_1)
IL_0000: call ""S Program.V4()""
IL_0005: stloc.0
IL_0006: call ""S? Program.N4()""
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool S?.HasValue.get""
IL_0013: brtrue.s IL_0017
IL_0015: ldc.i4.1
IL_0016: ret
IL_0017: ldloc.0
IL_0018: ldloca.s V_1
IL_001a: call ""S S?.GetValueOrDefault()""
IL_001f: call ""bool S.op_Inequality(S, S)""
IL_0024: ret
}";
string expectedIL5 = @"{
// Code size 37 (0x25)
.maxstack 2
.locals init (S V_0,
S? V_1)
IL_0000: call ""S Program.V4()""
IL_0005: stloc.0
IL_0006: call ""S? Program.N4()""
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool S?.HasValue.get""
IL_0013: brtrue.s IL_0017
IL_0015: ldc.i4.0
IL_0016: ret
IL_0017: ldloc.0
IL_0018: ldloca.s V_1
IL_001a: call ""S S?.GetValueOrDefault()""
IL_001f: call ""bool S.op_LessThan(S, S)""
IL_0024: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
comp.VerifyIL("Program.M5", expectedIL5);
}
[Fact]
public void TestLiftedConversionOnTopOfLifted()
{
// Here's an optimization that the dev10 compiler does not do except in some special cases.
// If we have a lifted conversion "on top" of another lifted operation, then the lifted
// conversion can be "distributed" to both branches of the underlying lifted operation.
//
// For example, suppose we have
//
// return (double?)(N1() + N2());
//
// Where N1 and N2 return int?. The dev10 compiler does this in two steps: first it
// computes the int? result of the addition, and then it converts that int? to double?
// with a lifted conversion. Basically, it generates:
//
// int? t1 = N1();
// int? t2 = N2();
// int? t3 = t1.HasValue && t2.HasValue ? new int?(t1.Value + t2.Value) : new int?();
// double? t4 = t3.HasValue ? new double?((double)t3.Value)) : new double?();
//
// But t3 is completely unnecessary here. We observe that the lifted conversion:
//
// (double?) (t1.HasValue && t2.HasValue ? new int?(t1.Value + t2.Value) : new int?())
//
// Is the same as distributing the conversion to the consequence and alternative:
//
// (t1.HasValue && t2.HasValue ? (double?)( new int?(t1.Value + t2.Value) ): (double?) ( new int?() ) )
//
// And now we can optimize the consequence and alternative down to
//
// (t1.HasValue && t2.HasValue ? new double?((double)(t1.Value + t2.Value) ): new double?() )
//
// And the int? t3 disappears entirely.
//
// This optimization has the nice property that it composes well with itself.
string source = @"
struct S
{
public static S operator -(S s) { return s; }
public static implicit operator int(S s) { return 1; }
}
class Program
{
static int? N1() { return 1; }
static int? N2() { return 1; }
static S? N3() { return null; }
// Start with a nice simple case; we have a lifted numeric conversion on top of a
// lifted addition.
static long? M1()
{
return N1() + N2();
}
// This should also work with lifted user-defined conversions, and work on top
// of a lifted unary operator.
static int? M2()
{
return -N3();
}
static void Main() { }
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 61 (0x3d)
.maxstack 2
.locals init (int? V_0,
int? V_1,
long? V_2)
IL_0000: call ""int? Program.N1()""
IL_0005: stloc.0
IL_0006: call ""int? Program.N2()""
IL_000b: stloc.1
IL_000c: ldloca.s V_0
IL_000e: call ""bool int?.HasValue.get""
IL_0013: ldloca.s V_1
IL_0015: call ""bool int?.HasValue.get""
IL_001a: and
IL_001b: brtrue.s IL_0027
IL_001d: ldloca.s V_2
IL_001f: initobj ""long?""
IL_0025: ldloc.2
IL_0026: ret
IL_0027: ldloca.s V_0
IL_0029: call ""int int?.GetValueOrDefault()""
IL_002e: ldloca.s V_1
IL_0030: call ""int int?.GetValueOrDefault()""
IL_0035: add
IL_0036: conv.i8
IL_0037: newobj ""long?..ctor(long)""
IL_003c: ret
}";
string expectedIL2 = @"{
// Code size 48 (0x30)
.maxstack 1
.locals init (S? V_0,
int? V_1)
IL_0000: call ""S? Program.N3()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool S?.HasValue.get""
IL_000d: brtrue.s IL_0019
IL_000f: ldloca.s V_1
IL_0011: initobj ""int?""
IL_0017: ldloc.1
IL_0018: ret
IL_0019: ldloca.s V_0
IL_001b: call ""S S?.GetValueOrDefault()""
IL_0020: call ""S S.op_UnaryNegation(S)""
IL_0025: call ""int S.op_Implicit(S)""
IL_002a: newobj ""int?..ctor(int)""
IL_002f: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
}
[Fact]
public void TestNullableBoolBinOpsBothAlwaysNull()
{
// x & y and x | y are null if both operands are null.
string source = @"
class Program
{
static bool? M1()
{
return new bool?() | new bool?();
}
static bool? M2()
{
return (bool?)null & default(bool?);
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 10 (0xa)
.maxstack 1
.locals init (bool? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""bool?""
IL_0008: ldloc.0
IL_0009: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL);
comp.VerifyIL("Program.M2", expectedIL);
}
[Fact]
public void TestNullableBoolBinOpsBothNotNull()
{
// x & y and x | y can be reduced to their non-lifted forms
// if both operands are known to be non-null.
//
// Roslyn does a slightly better job than the native compiler here.
// The native compiler effectively generates code as though you'd written:
//
// bool temp1 = N();
// bool? temp2 = new bool?(N() & N());
// return temp1 ? new bool?(true) : temp2;
//
// Whereas Roslyn simply generates code as though you'd written:
//
// return new bool?(N() | N() & N())
string source = @"
class Program
{
static bool N() { return true; }
static bool? M1()
{
return new bool?(N()) | new bool?(N()) & new bool?(N());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 23 (0x17)
.maxstack 3
IL_0000: call ""bool Program.N()""
IL_0005: call ""bool Program.N()""
IL_000a: call ""bool Program.N()""
IL_000f: and
IL_0010: or
IL_0011: newobj ""bool?..ctor(bool)""
IL_0016: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL);
}
[Fact]
public void TestNullableBoolBinOpsOneNull()
{
// codegen for x & y and x | y can be simplified if one operand is known to be null,
// and simplified even further if the other operand is known to be non-null.
string source = @"
class Program
{
static bool? N() { return false; }
static bool B() { return false; }
static bool? M1()
{
// Generated as temp = N(), temp.GetValueOrDefault() ? null : temp
return N() & new bool?();
}
static bool? M2()
{
// Generated as temp = N(), temp.GetValueOrDefault() ? null : temp
return default(bool?) & N();
}
static bool? M3()
{
// Generated as temp = N(), temp.GetValueOrDefault() ? temp : null
return N() | new bool?();
}
static bool? M4()
{
// Generated as temp = N(), temp.GetValueOrDefault() ? temp : null
return default(bool?) | N();
}
static bool? M5()
{
// Generated as B() ? null : new bool?(false)
return new bool?(B()) & new bool?();
}
static bool? M6()
{
// Generated as B() ? null : new bool?(false)
return default(bool?) & new bool?(B());
}
static bool? M7()
{
// Generated as B() ? new bool?(true) : null
return new bool?(B()) | new bool?();
}
static bool? M8()
{
// Generated as B() ? new bool?(true) : null
return default(bool?) | new bool?(B());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 27 (0x1b)
.maxstack 1
.locals init (bool? V_0,
bool? V_1)
IL_0000: call ""bool? Program.N()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool bool?.GetValueOrDefault()""
IL_000d: brtrue.s IL_0011
IL_000f: ldloc.0
IL_0010: ret
IL_0011: ldloca.s V_1
IL_0013: initobj ""bool?""
IL_0019: ldloc.1
IL_001a: ret
}";
string expectedIL2 = expectedIL1;
string expectedIL3 = @"{
// Code size 27 (0x1b)
.maxstack 1
.locals init (bool? V_0,
bool? V_1)
IL_0000: call ""bool? Program.N()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool bool?.GetValueOrDefault()""
IL_000d: brtrue.s IL_0019
IL_000f: ldloca.s V_1
IL_0011: initobj ""bool?""
IL_0017: ldloc.1
IL_0018: ret
IL_0019: ldloc.0
IL_001a: ret
}";
string expectedIL4 = expectedIL3;
string expectedIL5 = @"{
// Code size 24 (0x18)
.maxstack 1
.locals init (bool? V_0)
IL_0000: call ""bool Program.B()""
IL_0005: brtrue.s IL_000e
IL_0007: ldc.i4.0
IL_0008: newobj ""bool?..ctor(bool)""
IL_000d: ret
IL_000e: ldloca.s V_0
IL_0010: initobj ""bool?""
IL_0016: ldloc.0
IL_0017: ret
}";
string expectedIL6 = expectedIL5;
string expectedIL7 = @"{
// Code size 24 (0x18)
.maxstack 1
.locals init (bool? V_0)
IL_0000: call ""bool Program.B()""
IL_0005: brtrue.s IL_0011
IL_0007: ldloca.s V_0
IL_0009: initobj ""bool?""
IL_000f: ldloc.0
IL_0010: ret
IL_0011: ldc.i4.1
IL_0012: newobj ""bool?..ctor(bool)""
IL_0017: ret
}
";
string expectedIL8 = expectedIL7;
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
comp.VerifyIL("Program.M5", expectedIL5);
comp.VerifyIL("Program.M6", expectedIL6);
comp.VerifyIL("Program.M7", expectedIL7);
comp.VerifyIL("Program.M8", expectedIL8);
}
[Fact]
public void TestNullableBoolBinOpsOneNonNull()
{
// Codegen for x & y and x | y can be simplified if one operand is known to be non null.
// Note that we have already considered the case where one operand is null and the
// other is non null, in the test case above.
string source = @"
class Program
{
static bool? N() { return false; }
static bool B() { return false; }
static bool? M1()
{
return new bool?(B()) & N();
}
static bool? M2()
{
return N() & new bool?(B());
}
static bool? M3()
{
return new bool?(B()) | N();
}
static bool? M4()
{
return N() | new bool?(B());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 22 (0x16)
.maxstack 2
.locals init (bool? V_0)
IL_0000: call ""bool Program.B()""
IL_0005: call ""bool? Program.N()""
IL_000a: stloc.0
IL_000b: brtrue.s IL_0014
IL_000d: ldc.i4.0
IL_000e: newobj ""bool?..ctor(bool)""
IL_0013: ret
IL_0014: ldloc.0
IL_0015: ret
}";
string expectedIL2 = @"{
// Code size 22 (0x16)
.maxstack 1
.locals init (bool? V_0)
IL_0000: call ""bool? Program.N()""
IL_0005: stloc.0
IL_0006: call ""bool Program.B()""
IL_000b: brtrue.s IL_0014
IL_000d: ldc.i4.0
IL_000e: newobj ""bool?..ctor(bool)""
IL_0013: ret
IL_0014: ldloc.0
IL_0015: ret
}";
string expectedIL3 = @"{
// Code size 22 (0x16)
.maxstack 2
.locals init (bool? V_0)
IL_0000: call ""bool Program.B()""
IL_0005: call ""bool? Program.N()""
IL_000a: stloc.0
IL_000b: brtrue.s IL_000f
IL_000d: ldloc.0
IL_000e: ret
IL_000f: ldc.i4.1
IL_0010: newobj ""bool?..ctor(bool)""
IL_0015: ret
}";
string expectedIL4 = @"{
// Code size 22 (0x16)
.maxstack 1
.locals init (bool? V_0)
IL_0000: call ""bool? Program.N()""
IL_0005: stloc.0
IL_0006: call ""bool Program.B()""
IL_000b: brtrue.s IL_000f
IL_000d: ldloc.0
IL_000e: ret
IL_000f: ldc.i4.1
IL_0010: newobj ""bool?..ctor(bool)""
IL_0015: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
comp.VerifyIL("Program.M3", expectedIL3);
comp.VerifyIL("Program.M4", expectedIL4);
}
[Fact]
public void TestNullableBinOpsBothAlwaysNull()
{
// x op y is null if both ops are null for the binary operators
// * / % + - << >> and for non-bool & ^ |
string source = @"
class Program
{
static long? M1()
{
return new int?() + new long?();
}
static decimal? M2()
{
return (short?)null * default(decimal?);
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 10 (0xa)
.maxstack 1
.locals init (long? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""long?""
IL_0008: ldloc.0
IL_0009: ret
}";
string expectedIL2 = @"{
// Code size 10 (0xa)
.maxstack 1
.locals init (decimal? V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""decimal?""
IL_0008: ldloc.0
IL_0009: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (6,16): warning CS0458: The result of the expression is always 'null' of type 'long?'
// return new int?() + new long?();
Diagnostic(ErrorCode.WRN_AlwaysNull, "new int?() + new long?()").WithArguments("long?"),
// (10,16): warning CS0458: The result of the expression is always 'null' of type 'decimal?'
// return (short?)null * default(decimal?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "(short?)null * default(decimal?)").WithArguments("decimal?"));
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
}
[Fact]
public void TestNullableBinOpsBothNonNull()
{
// Lifted x op y is generated as non-lifted if both operands are known to be non-null
// for operators * / % + - << >> and for non-bool & ^ |
//
// Roslyn does a far better job of this optimization than the native compiler.
string source = @"
class Program
{
static int N() { return 1; }
static int? M1()
{
return
new int?(N()) *
new int?(N()) /
new int?(N()) %
new int?(N()) +
new int?(N()) -
new int?(N()) <<
new int?(N()) >>
new int?(N()) &
new int?(N()) ^
new int?(N()) |
new int?(N());
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL = @"{
// Code size 77 (0x4d)
.maxstack 3
IL_0000: call ""int Program.N()""
IL_0005: call ""int Program.N()""
IL_000a: mul
IL_000b: call ""int Program.N()""
IL_0010: div
IL_0011: call ""int Program.N()""
IL_0016: rem
IL_0017: call ""int Program.N()""
IL_001c: add
IL_001d: call ""int Program.N()""
IL_0022: sub
IL_0023: call ""int Program.N()""
IL_0028: ldc.i4.s 31
IL_002a: and
IL_002b: shl
IL_002c: call ""int Program.N()""
IL_0031: ldc.i4.s 31
IL_0033: and
IL_0034: shr
IL_0035: call ""int Program.N()""
IL_003a: and
IL_003b: call ""int Program.N()""
IL_0040: xor
IL_0041: call ""int Program.N()""
IL_0046: or
IL_0047: newobj ""int?..ctor(int)""
IL_004c: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL);
}
[Fact]
public void TestNullableBinOpsOneNull()
{
// If we have null + N() or null + new int?(B())
// then we simply generate M() as a side effect and result in null.
string source = @"
class Program
{
static int? N() { return 1; }
static int B() { return 1; }
static int? M1()
{
return new int?() + N();
}
static int? M2()
{
return new int?(B()) * default(int?);
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 16 (0x10)
.maxstack 1
.locals init (int? V_0)
IL_0000: call ""int? Program.N()""
IL_0005: pop
IL_0006: ldloca.s V_0
IL_0008: initobj ""int?""
IL_000e: ldloc.0
IL_000f: ret
}";
string expectedIL2 = @"{
// Code size 16 (0x10)
.maxstack 1
.locals init (int? V_0)
IL_0000: call ""int Program.B()""
IL_0005: pop
IL_0006: ldloca.s V_0
IL_0008: initobj ""int?""
IL_000e: ldloc.0
IL_000f: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics(
// (9,16): warning CS0458: The result of the expression is always 'null' of type 'int?'
// return new int?() + N();
Diagnostic(ErrorCode.WRN_AlwaysNull, "new int?() + N()").WithArguments("int?"),
// (13,16): warning CS0458: The result of the expression is always 'null' of type 'int?'
// return new int?(B()) * default(int?);
Diagnostic(ErrorCode.WRN_AlwaysNull, "new int?(B()) * default(int?)").WithArguments("int?"));
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
}
[Fact]
public void TestNullableBinOpsOneNonNull()
{
// If one side of the nullable binop is non-null then we skip calling HasValue and GetValueOrDefault
// on that side.
string source = @"
class Program
{
static int B() { return 1; }
static int? N() { return 1; }
static int? M1()
{
return new int?(B()) + N();
}
static int? M2()
{
return new int?(1) + N();
}
static void Main() {}
}
";
string expectedOutput = "";
string expectedIL1 = @"{
// Code size 46 (0x2e)
.maxstack 2
.locals init (int V_0,
int? V_1,
int? V_2)
IL_0000: call ""int Program.B()""
IL_0005: stloc.0
IL_0006: call ""int? Program.N()""
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool int?.HasValue.get""
IL_0013: brtrue.s IL_001f
IL_0015: ldloca.s V_2
IL_0017: initobj ""int?""
IL_001d: ldloc.2
IL_001e: ret
IL_001f: ldloc.0
IL_0020: ldloca.s V_1
IL_0022: call ""int int?.GetValueOrDefault()""
IL_0027: add
IL_0028: newobj ""int?..ctor(int)""
IL_002d: ret
}";
// TODO: Roslyn does a slightly worse job here than the native compiler does.
// TODO: The native compiler knows that the constant need not be stored in a temporary.
// TODO: We will clean this up in a later checkin.
// TODO: When we do so, add tests for ++ -- +=, etc.
string expectedIL2 = @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (int? V_0,
int? V_1)
IL_0000: call ""int? Program.N()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: call ""bool int?.HasValue.get""
IL_000d: brtrue.s IL_0019
IL_000f: ldloca.s V_1
IL_0011: initobj ""int?""
IL_0017: ldloc.1
IL_0018: ret
IL_0019: ldc.i4.1
IL_001a: ldloca.s V_0
IL_001c: call ""int int?.GetValueOrDefault()""
IL_0021: add
IL_0022: newobj ""int?..ctor(int)""
IL_0027: ret
}";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.M1", expectedIL1);
comp.VerifyIL("Program.M2", expectedIL2);
}
[Fact]
public void TestNullableBinOpsOneZero()
{
// If one side of the nullable binop is non-null then we skip calling HasValue and GetValueOrDefault
// on that side.
string source = @"
class Program
{
static void Main()
{
int? N = 42;
System.Console.WriteLine(0 + N);
System.Console.WriteLine(N + 0);
System.Console.WriteLine(0 - N);
System.Console.WriteLine(N - 0);
System.Console.WriteLine(0 * N);
System.Console.WriteLine(N * 0);
System.Console.WriteLine(1 * N);
System.Console.WriteLine(N * 1);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"
42
42
-42
42
0
0
42
42")
.VerifyIL("Program.Main",
@"
{
// Code size 349 (0x15d)
.maxstack 3
.locals init (int? V_0,
int? V_1)
IL_0000: ldc.i4.s 42
IL_0002: newobj ""int?..ctor(int)""
IL_0007: dup
IL_0008: stloc.0
IL_0009: ldloca.s V_0
IL_000b: call ""bool int?.HasValue.get""
IL_0010: brtrue.s IL_001d
IL_0012: ldloca.s V_1
IL_0014: initobj ""int?""
IL_001a: ldloc.1
IL_001b: br.s IL_0029
IL_001d: ldloca.s V_0
IL_001f: call ""int int?.GetValueOrDefault()""
IL_0024: newobj ""int?..ctor(int)""
IL_0029: box ""int?""
IL_002e: call ""void System.Console.WriteLine(object)""
IL_0033: dup
IL_0034: stloc.0
IL_0035: ldloca.s V_0
IL_0037: call ""bool int?.HasValue.get""
IL_003c: brtrue.s IL_0049
IL_003e: ldloca.s V_1
IL_0040: initobj ""int?""
IL_0046: ldloc.1
IL_0047: br.s IL_0055
IL_0049: ldloca.s V_0
IL_004b: call ""int int?.GetValueOrDefault()""
IL_0050: newobj ""int?..ctor(int)""
IL_0055: box ""int?""
IL_005a: call ""void System.Console.WriteLine(object)""
IL_005f: dup
IL_0060: stloc.0
IL_0061: ldloca.s V_0
IL_0063: call ""bool int?.HasValue.get""
IL_0068: brtrue.s IL_0075
IL_006a: ldloca.s V_1
IL_006c: initobj ""int?""
IL_0072: ldloc.1
IL_0073: br.s IL_0083
IL_0075: ldc.i4.0
IL_0076: ldloca.s V_0
IL_0078: call ""int int?.GetValueOrDefault()""
IL_007d: sub
IL_007e: newobj ""int?..ctor(int)""
IL_0083: box ""int?""
IL_0088: call ""void System.Console.WriteLine(object)""
IL_008d: dup
IL_008e: stloc.0
IL_008f: ldloca.s V_0
IL_0091: call ""bool int?.HasValue.get""
IL_0096: brtrue.s IL_00a3
IL_0098: ldloca.s V_1
IL_009a: initobj ""int?""
IL_00a0: ldloc.1
IL_00a1: br.s IL_00af
IL_00a3: ldloca.s V_0
IL_00a5: call ""int int?.GetValueOrDefault()""
IL_00aa: newobj ""int?..ctor(int)""
IL_00af: box ""int?""
IL_00b4: call ""void System.Console.WriteLine(object)""
IL_00b9: dup
IL_00ba: stloc.0
IL_00bb: ldloca.s V_0
IL_00bd: call ""bool int?.HasValue.get""
IL_00c2: brtrue.s IL_00cf
IL_00c4: ldloca.s V_1
IL_00c6: initobj ""int?""
IL_00cc: ldloc.1
IL_00cd: br.s IL_00d5
IL_00cf: ldc.i4.0
IL_00d0: newobj ""int?..ctor(int)""
IL_00d5: box ""int?""
IL_00da: call ""void System.Console.WriteLine(object)""
IL_00df: dup
IL_00e0: stloc.0
IL_00e1: ldloca.s V_0
IL_00e3: call ""bool int?.HasValue.get""
IL_00e8: brtrue.s IL_00f5
IL_00ea: ldloca.s V_1
IL_00ec: initobj ""int?""
IL_00f2: ldloc.1
IL_00f3: br.s IL_00fb
IL_00f5: ldc.i4.0
IL_00f6: newobj ""int?..ctor(int)""
IL_00fb: box ""int?""
IL_0100: call ""void System.Console.WriteLine(object)""
IL_0105: dup
IL_0106: stloc.0
IL_0107: ldloca.s V_0
IL_0109: call ""bool int?.HasValue.get""
IL_010e: brtrue.s IL_011b
IL_0110: ldloca.s V_1
IL_0112: initobj ""int?""
IL_0118: ldloc.1
IL_0119: br.s IL_0127
IL_011b: ldloca.s V_0
IL_011d: call ""int int?.GetValueOrDefault()""
IL_0122: newobj ""int?..ctor(int)""
IL_0127: box ""int?""
IL_012c: call ""void System.Console.WriteLine(object)""
IL_0131: stloc.0
IL_0132: ldloca.s V_0
IL_0134: call ""bool int?.HasValue.get""
IL_0139: brtrue.s IL_0146
IL_013b: ldloca.s V_1
IL_013d: initobj ""int?""
IL_0143: ldloc.1
IL_0144: br.s IL_0152
IL_0146: ldloca.s V_0
IL_0148: call ""int int?.GetValueOrDefault()""
IL_014d: newobj ""int?..ctor(int)""
IL_0152: box ""int?""
IL_0157: call ""void System.Console.WriteLine(object)""
IL_015c: ret
}");
}
[Fact]
public void TestNullableBinOpsOneZero1()
{
// If one side of the nullable binop is non-null then we skip calling HasValue and GetValueOrDefault
// on that side.
string source = @"
class Program
{
static void Main()
{
System.Console.WriteLine(0 + (int?)42);
System.Console.WriteLine((int?)42 + 0);
System.Console.WriteLine(0 - (int?)42);
System.Console.WriteLine((int?)42 - 0);
System.Console.WriteLine(0 * (int?)42);
System.Console.WriteLine((int?)42 * 0);
System.Console.WriteLine(1 * (int?)42);
System.Console.WriteLine((int?)42 * 1);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"
42
42
-42
42
0
0
42
42")
.VerifyIL("Program.Main",
@"
{
// Code size 97 (0x61)
.maxstack 2
IL_0000: ldc.i4.s 42
IL_0002: box ""int""
IL_0007: call ""void System.Console.WriteLine(object)""
IL_000c: ldc.i4.s 42
IL_000e: box ""int""
IL_0013: call ""void System.Console.WriteLine(object)""
IL_0018: ldc.i4.0
IL_0019: ldc.i4.s 42
IL_001b: sub
IL_001c: box ""int""
IL_0021: call ""void System.Console.WriteLine(object)""
IL_0026: ldc.i4.s 42
IL_0028: box ""int""
IL_002d: call ""void System.Console.WriteLine(object)""
IL_0032: ldc.i4.0
IL_0033: box ""int""
IL_0038: call ""void System.Console.WriteLine(object)""
IL_003d: ldc.i4.0
IL_003e: box ""int""
IL_0043: call ""void System.Console.WriteLine(object)""
IL_0048: ldc.i4.s 42
IL_004a: box ""int""
IL_004f: call ""void System.Console.WriteLine(object)""
IL_0054: ldc.i4.s 42
IL_0056: box ""int""
IL_005b: call ""void System.Console.WriteLine(object)""
IL_0060: ret
}");
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/QuickInfo/QuickInfoProviderNames.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.QuickInfo
{
/// <summary>
/// Some of the known <see cref="QuickInfoProvider"/> names in use.
/// Names are used for ordering providers with the <see cref="ExtensionOrderAttribute"/>.
/// </summary>
internal static class QuickInfoProviderNames
{
public const string Semantic = nameof(Semantic);
public const string Syntactic = nameof(Syntactic);
public const string DiagnosticAnalyzer = nameof(DiagnosticAnalyzer);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.QuickInfo
{
/// <summary>
/// Some of the known <see cref="QuickInfoProvider"/> names in use.
/// Names are used for ordering providers with the <see cref="ExtensionOrderAttribute"/>.
/// </summary>
internal static class QuickInfoProviderNames
{
public const string Semantic = nameof(Semantic);
public const string Syntactic = nameof(Syntactic);
public const string DiagnosticAnalyzer = nameof(DiagnosticAnalyzer);
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/MSBuildTest/FileSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class FileSet : IEnumerable<(string fileName, object content)>
{
private readonly IImmutableDictionary<string, object> _fileMap;
private FileSet(IImmutableDictionary<string, object> fileMap)
{
_fileMap = fileMap ?? ImmutableDictionary<string, object>.Empty;
}
public FileSet(params (string fileName, object content)[] files)
{
var builder = ImmutableDictionary.CreateBuilder<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var (fileName, fileContent) in files)
{
builder.Add(fileName, fileContent);
}
_fileMap = builder.ToImmutable();
}
public IEnumerator<(string fileName, object content)> GetEnumerator()
{
foreach (var (fileName, content) in _fileMap)
yield return (fileName, content);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public FileSet WithFile(string fileName, object content)
{
var newFileMap = _fileMap.SetItem(fileName, content);
return new FileSet(newFileMap);
}
public FileSet ReplaceFileElement(string fileName, string elementName, string elementValue)
{
if (_fileMap.TryGetValue(fileName, out var content))
{
if (content is string textContent)
{
var elementStartTag = "<" + elementName;
var elementEndTag = "</" + elementName;
var startTagStart = textContent.IndexOf(elementStartTag, StringComparison.Ordinal);
if (startTagStart >= -1)
{
var startTagEnd = textContent.IndexOf('>', startTagStart + 1);
if (startTagEnd >= startTagStart)
{
var endTagStart = textContent.IndexOf(elementEndTag, startTagEnd + 1, StringComparison.Ordinal);
if (endTagStart >= startTagEnd)
{
var newContent = textContent.Substring(0, startTagEnd + 1) + elementValue + textContent.Substring(endTagStart);
return this.WithFile(fileName, newContent);
}
}
}
}
}
return this;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class FileSet : IEnumerable<(string fileName, object content)>
{
private readonly IImmutableDictionary<string, object> _fileMap;
private FileSet(IImmutableDictionary<string, object> fileMap)
{
_fileMap = fileMap ?? ImmutableDictionary<string, object>.Empty;
}
public FileSet(params (string fileName, object content)[] files)
{
var builder = ImmutableDictionary.CreateBuilder<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var (fileName, fileContent) in files)
{
builder.Add(fileName, fileContent);
}
_fileMap = builder.ToImmutable();
}
public IEnumerator<(string fileName, object content)> GetEnumerator()
{
foreach (var (fileName, content) in _fileMap)
yield return (fileName, content);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public FileSet WithFile(string fileName, object content)
{
var newFileMap = _fileMap.SetItem(fileName, content);
return new FileSet(newFileMap);
}
public FileSet ReplaceFileElement(string fileName, string elementName, string elementValue)
{
if (_fileMap.TryGetValue(fileName, out var content))
{
if (content is string textContent)
{
var elementStartTag = "<" + elementName;
var elementEndTag = "</" + elementName;
var startTagStart = textContent.IndexOf(elementStartTag, StringComparison.Ordinal);
if (startTagStart >= -1)
{
var startTagEnd = textContent.IndexOf('>', startTagStart + 1);
if (startTagEnd >= startTagStart)
{
var endTagStart = textContent.IndexOf(elementEndTag, startTagEnd + 1, StringComparison.Ordinal);
if (endTagStart >= startTagEnd)
{
var newContent = textContent.Substring(0, startTagEnd + 1) + elementValue + textContent.Substring(endTagStart);
return this.WithFile(fileName, newContent);
}
}
}
}
}
return this;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/TestUtilities/EditAndContinue/RudeEditDiagnosticDescription.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal struct RudeEditDiagnosticDescription : IEquatable<RudeEditDiagnosticDescription>
{
private readonly RudeEditKind _rudeEditKind;
private readonly string _firstLine;
private readonly string _squiggle;
private readonly string[] _arguments;
internal RudeEditDiagnosticDescription(RudeEditKind rudeEditKind, string squiggle, string[] arguments, string firstLine)
{
_rudeEditKind = rudeEditKind;
_squiggle = squiggle;
_firstLine = firstLine;
_arguments = arguments ?? Array.Empty<string>();
}
public string FirstLine => _firstLine;
public RudeEditDiagnosticDescription WithFirstLine(string value)
=> new RudeEditDiagnosticDescription(_rudeEditKind, _squiggle, _arguments, value.Trim());
public bool Equals(RudeEditDiagnosticDescription other)
{
return _rudeEditKind == other._rudeEditKind
&& _squiggle == other._squiggle
&& (_firstLine == other._firstLine || _firstLine == null || other._firstLine == null)
&& _arguments.SequenceEqual(other._arguments, object.Equals);
}
public override bool Equals(object obj)
=> obj is RudeEditDiagnosticDescription && Equals((RudeEditDiagnosticDescription)obj);
public override int GetHashCode()
{
return
Hash.Combine(_squiggle,
Hash.CombineValues(_arguments, (int)_rudeEditKind));
}
public override string ToString()
{
var arguments = string.Join(", ", new[] { (_squiggle != null) ? "\"" + _squiggle.Replace("\r\n", "\\r\\n") + "\"" : "null" }.Concat(_arguments.Select(a => "\"" + a + "\"")));
var withLine = (_firstLine != null) ? $".WithFirstLine(\"{_firstLine}\")" : null;
return $"Diagnostic(RudeEditKind.{_rudeEditKind}, {arguments}){withLine}";
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal struct RudeEditDiagnosticDescription : IEquatable<RudeEditDiagnosticDescription>
{
private readonly RudeEditKind _rudeEditKind;
private readonly string _firstLine;
private readonly string _squiggle;
private readonly string[] _arguments;
internal RudeEditDiagnosticDescription(RudeEditKind rudeEditKind, string squiggle, string[] arguments, string firstLine)
{
_rudeEditKind = rudeEditKind;
_squiggle = squiggle;
_firstLine = firstLine;
_arguments = arguments ?? Array.Empty<string>();
}
public string FirstLine => _firstLine;
public RudeEditDiagnosticDescription WithFirstLine(string value)
=> new RudeEditDiagnosticDescription(_rudeEditKind, _squiggle, _arguments, value.Trim());
public bool Equals(RudeEditDiagnosticDescription other)
{
return _rudeEditKind == other._rudeEditKind
&& _squiggle == other._squiggle
&& (_firstLine == other._firstLine || _firstLine == null || other._firstLine == null)
&& _arguments.SequenceEqual(other._arguments, object.Equals);
}
public override bool Equals(object obj)
=> obj is RudeEditDiagnosticDescription && Equals((RudeEditDiagnosticDescription)obj);
public override int GetHashCode()
{
return
Hash.Combine(_squiggle,
Hash.CombineValues(_arguments, (int)_rudeEditKind));
}
public override string ToString()
{
var arguments = string.Join(", ", new[] { (_squiggle != null) ? "\"" + _squiggle.Replace("\r\n", "\\r\\n") + "\"" : "null" }.Concat(_arguments.Select(a => "\"" + a + "\"")));
var withLine = (_firstLine != null) ? $".WithFirstLine(\"{_firstLine}\")" : null;
return $"Diagnostic(RudeEditKind.{_rudeEditKind}, {arguments}){withLine}";
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/TestUtilities/EditAndContinue/SemanticEditDescription.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
public sealed class SemanticEditDescription
{
public readonly SemanticEditKind Kind;
public readonly Func<Compilation, ISymbol> SymbolProvider;
public readonly Func<Compilation, ITypeSymbol>? PartialType;
/// <summary>
/// If specified the node mappings will be validated against the actual syntax map function.
/// </summary>
public readonly IEnumerable<KeyValuePair<TextSpan, TextSpan>>? SyntaxMap;
public readonly bool HasSyntaxMap;
public SemanticEditDescription(
SemanticEditKind kind,
Func<Compilation, ISymbol> symbolProvider,
Func<Compilation, ITypeSymbol>? partialType,
IEnumerable<KeyValuePair<TextSpan, TextSpan>>? syntaxMap,
bool hasSyntaxMap)
{
Kind = kind;
SymbolProvider = symbolProvider;
SyntaxMap = syntaxMap;
PartialType = partialType;
HasSyntaxMap = hasSyntaxMap;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
public sealed class SemanticEditDescription
{
public readonly SemanticEditKind Kind;
public readonly Func<Compilation, ISymbol> SymbolProvider;
public readonly Func<Compilation, ITypeSymbol>? PartialType;
/// <summary>
/// If specified the node mappings will be validated against the actual syntax map function.
/// </summary>
public readonly IEnumerable<KeyValuePair<TextSpan, TextSpan>>? SyntaxMap;
public readonly bool HasSyntaxMap;
public SemanticEditDescription(
SemanticEditKind kind,
Func<Compilation, ISymbol> symbolProvider,
Func<Compilation, ITypeSymbol>? partialType,
IEnumerable<KeyValuePair<TextSpan, TextSpan>>? syntaxMap,
bool hasSyntaxMap)
{
Kind = kind;
SymbolProvider = symbolProvider;
SyntaxMap = syntaxMap;
PartialType = partialType;
HasSyntaxMap = hasSyntaxMap;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Portable/Binder/WithTypeParametersBinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal abstract class WithTypeParametersBinder : Binder
{
internal WithTypeParametersBinder(Binder next)
: base(next)
{
}
// TODO: Change this to a data structure that won't allocate enumerators
protected abstract MultiDictionary<string, TypeParameterSymbol> TypeParameterMap { get; }
// This is only overridden by WithMethodTypeParametersBinder.
protected virtual LookupOptions LookupMask
{
get
{
return LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember;
}
}
protected bool CanConsiderTypeParameters(LookupOptions options)
{
return (options & (LookupMask | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0;
}
internal override void LookupSymbolsInSingleBinder(
LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(result.IsClear);
if ((options & LookupMask) != 0)
{
return;
}
foreach (var typeParameter in TypeParameterMap[name])
{
result.MergeEqual(originalBinder.CheckViability(typeParameter, arity, options, null, diagnose, ref useSiteInfo));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal abstract class WithTypeParametersBinder : Binder
{
internal WithTypeParametersBinder(Binder next)
: base(next)
{
}
// TODO: Change this to a data structure that won't allocate enumerators
protected abstract MultiDictionary<string, TypeParameterSymbol> TypeParameterMap { get; }
// This is only overridden by WithMethodTypeParametersBinder.
protected virtual LookupOptions LookupMask
{
get
{
return LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember;
}
}
protected bool CanConsiderTypeParameters(LookupOptions options)
{
return (options & (LookupMask | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0;
}
internal override void LookupSymbolsInSingleBinder(
LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Debug.Assert(result.IsClear);
if ((options & LookupMask) != 0)
{
return;
}
foreach (var typeParameter in TypeParameterMap[name])
{
result.MergeEqual(originalBinder.CheckViability(typeParameter, arity, options, null, diagnose, ref useSiteInfo));
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/CSharp/Impl/EditorConfigSettings/BinaryOperatorSpacingOptionsViewModelFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings
{
[Export(typeof(IEnumSettingViewModelFactory)), Shared]
internal class BinaryOperatorSpacingOptionsViewModelFactory : IEnumSettingViewModelFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public BinaryOperatorSpacingOptionsViewModelFactory()
{
}
public IEnumSettingViewModel CreateViewModel(WhitespaceSetting setting)
{
return new BinaryOperatorSpacingOptionsViewModel(setting);
}
public bool IsSupported(OptionKey2 key)
=> key.Option.Type == typeof(BinaryOperatorSpacingOptions);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings
{
[Export(typeof(IEnumSettingViewModelFactory)), Shared]
internal class BinaryOperatorSpacingOptionsViewModelFactory : IEnumSettingViewModelFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public BinaryOperatorSpacingOptionsViewModelFactory()
{
}
public IEnumSettingViewModel CreateViewModel(WhitespaceSetting setting)
{
return new BinaryOperatorSpacingOptionsViewModel(setting);
}
public bool IsSupported(OptionKey2 key)
=> key.Option.Type == typeof(BinaryOperatorSpacingOptions);
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/Shared/Naming/FallbackNamingRules.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.NamingStyles;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.Shared.Naming
{
internal static class FallbackNamingRules
{
/// <summary>
/// Standard symbol names if the user doesn't have any existing naming rules.
/// </summary>
public static readonly ImmutableArray<NamingRule> Default = ImmutableArray.Create(
// Symbols that should be camel cased.
new NamingRule(
new SymbolSpecification(
Guid.NewGuid(),
nameof(Capitalization.CamelCase),
ImmutableArray.Create(
new SymbolKindOrTypeKind(SymbolKind.Field),
new SymbolKindOrTypeKind(SymbolKind.Local),
new SymbolKindOrTypeKind(SymbolKind.Parameter),
new SymbolKindOrTypeKind(SymbolKind.RangeVariable))),
new NamingStyle(Guid.NewGuid(), capitalizationScheme: Capitalization.CamelCase),
enforcementLevel: ReportDiagnostic.Hidden),
// Include an entry for _ prefixed fields (.Net style). That way features that are looking to see if
// there's a potential matching field for a particular name will find these as well.
new NamingRule(
new SymbolSpecification(
Guid.NewGuid(),
"CamelCaseWithUnderscore",
ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Field))),
new NamingStyle(Guid.NewGuid(), prefix: "_", capitalizationScheme: Capitalization.CamelCase),
enforcementLevel: ReportDiagnostic.Hidden),
// Everything else should be pascal cased.
new NamingRule(
CreateDefaultSymbolSpecification(),
new NamingStyle(Guid.NewGuid(), capitalizationScheme: Capitalization.PascalCase),
enforcementLevel: ReportDiagnostic.Hidden));
/// <summary>
/// Standard name rules for name suggestion/completion utilities.
/// </summary>
internal static readonly ImmutableArray<NamingRule> CompletionOfferingRules = ImmutableArray.Create(
CreateCamelCaseFieldsAndParametersRule(),
CreateEndWithAsyncRule(),
CreateGetAsyncRule(),
CreateMethodStartsWithGetRule());
private static NamingRule CreateGetAsyncRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.Ordinary));
var modifiers = ImmutableArray.Create(new ModifierKind(ModifierKindEnum.IsAsync));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "endswithasync", kinds, accessibilityList: default, modifiers),
new NamingStyle(Guid.NewGuid(), prefix: "Get", suffix: "Async"),
ReportDiagnostic.Info);
}
private static NamingRule CreateCamelCaseFieldsAndParametersRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Field), new SymbolKindOrTypeKind(SymbolKind.Parameter), new SymbolKindOrTypeKind(SymbolKind.Local));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "camelcasefields", kinds, accessibilityList: default, modifiers: default),
new NamingStyle(Guid.NewGuid(), capitalizationScheme: Capitalization.CamelCase),
ReportDiagnostic.Info);
}
private static NamingRule CreateEndWithAsyncRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.Ordinary));
var modifiers = ImmutableArray.Create(new ModifierKind(ModifierKindEnum.IsAsync));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "endswithasynct", kinds, accessibilityList: default, modifiers),
new NamingStyle(Guid.NewGuid(), suffix: "Async"),
ReportDiagnostic.Info);
}
private static NamingRule CreateMethodStartsWithGetRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.Ordinary));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "startswithget", kinds, accessibilityList: default, modifiers: default),
new NamingStyle(Guid.NewGuid(), prefix: "Get"),
ReportDiagnostic.Info);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.NamingStyles;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.Shared.Naming
{
internal static class FallbackNamingRules
{
/// <summary>
/// Standard symbol names if the user doesn't have any existing naming rules.
/// </summary>
public static readonly ImmutableArray<NamingRule> Default = ImmutableArray.Create(
// Symbols that should be camel cased.
new NamingRule(
new SymbolSpecification(
Guid.NewGuid(),
nameof(Capitalization.CamelCase),
ImmutableArray.Create(
new SymbolKindOrTypeKind(SymbolKind.Field),
new SymbolKindOrTypeKind(SymbolKind.Local),
new SymbolKindOrTypeKind(SymbolKind.Parameter),
new SymbolKindOrTypeKind(SymbolKind.RangeVariable))),
new NamingStyle(Guid.NewGuid(), capitalizationScheme: Capitalization.CamelCase),
enforcementLevel: ReportDiagnostic.Hidden),
// Include an entry for _ prefixed fields (.Net style). That way features that are looking to see if
// there's a potential matching field for a particular name will find these as well.
new NamingRule(
new SymbolSpecification(
Guid.NewGuid(),
"CamelCaseWithUnderscore",
ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Field))),
new NamingStyle(Guid.NewGuid(), prefix: "_", capitalizationScheme: Capitalization.CamelCase),
enforcementLevel: ReportDiagnostic.Hidden),
// Everything else should be pascal cased.
new NamingRule(
CreateDefaultSymbolSpecification(),
new NamingStyle(Guid.NewGuid(), capitalizationScheme: Capitalization.PascalCase),
enforcementLevel: ReportDiagnostic.Hidden));
/// <summary>
/// Standard name rules for name suggestion/completion utilities.
/// </summary>
internal static readonly ImmutableArray<NamingRule> CompletionOfferingRules = ImmutableArray.Create(
CreateCamelCaseFieldsAndParametersRule(),
CreateEndWithAsyncRule(),
CreateGetAsyncRule(),
CreateMethodStartsWithGetRule());
private static NamingRule CreateGetAsyncRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.Ordinary));
var modifiers = ImmutableArray.Create(new ModifierKind(ModifierKindEnum.IsAsync));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "endswithasync", kinds, accessibilityList: default, modifiers),
new NamingStyle(Guid.NewGuid(), prefix: "Get", suffix: "Async"),
ReportDiagnostic.Info);
}
private static NamingRule CreateCamelCaseFieldsAndParametersRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(SymbolKind.Field), new SymbolKindOrTypeKind(SymbolKind.Parameter), new SymbolKindOrTypeKind(SymbolKind.Local));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "camelcasefields", kinds, accessibilityList: default, modifiers: default),
new NamingStyle(Guid.NewGuid(), capitalizationScheme: Capitalization.CamelCase),
ReportDiagnostic.Info);
}
private static NamingRule CreateEndWithAsyncRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.Ordinary));
var modifiers = ImmutableArray.Create(new ModifierKind(ModifierKindEnum.IsAsync));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "endswithasynct", kinds, accessibilityList: default, modifiers),
new NamingStyle(Guid.NewGuid(), suffix: "Async"),
ReportDiagnostic.Info);
}
private static NamingRule CreateMethodStartsWithGetRule()
{
var kinds = ImmutableArray.Create(new SymbolKindOrTypeKind(MethodKind.Ordinary));
return new NamingRule(
new SymbolSpecification(Guid.NewGuid(), "startswithget", kinds, accessibilityList: default, modifiers: default),
new NamingStyle(Guid.NewGuid(), prefix: "Get"),
ReportDiagnostic.Info);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Server/VBCSCompilerTests/BuildServerConnectionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommandLine;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
public sealed class BuildServerConnectionTests : IDisposable
{
internal TempRoot TempRoot { get; } = new TempRoot();
internal XunitCompilerServerLogger Logger { get; }
public BuildServerConnectionTests(ITestOutputHelper testOutputHelper)
{
Logger = new XunitCompilerServerLogger(testOutputHelper);
}
public void Dispose()
{
TempRoot.Dispose();
}
[Fact]
public async Task OnlyStartOneServer()
{
ServerData? serverData = null;
try
{
var pipeName = ServerUtil.GetPipeName();
var workingDirectory = TempRoot.CreateDirectory().Path;
for (var i = 0; i < 5; i++)
{
var response = await BuildServerConnection.RunServerBuildRequestAsync(
ProtocolUtil.CreateEmptyCSharp(workingDirectory),
pipeName,
timeoutOverride: Timeout.Infinite,
tryCreateServerFunc: (pipeName, logger) =>
{
Assert.Null(serverData);
serverData = ServerData.Create(logger, pipeName);
return true;
},
Logger,
cancellationToken: default);
Assert.True(response is CompletedBuildResponse);
}
}
finally
{
serverData?.Dispose();
}
}
[Fact]
public async Task UseExistingServer()
{
using var serverData = await ServerUtil.CreateServer(Logger);
var ran = false;
var workingDirectory = TempRoot.CreateDirectory().Path;
for (var i = 0; i < 5; i++)
{
var response = await BuildServerConnection.RunServerBuildRequestAsync(
ProtocolUtil.CreateEmptyCSharp(workingDirectory),
serverData.PipeName,
timeoutOverride: Timeout.Infinite,
tryCreateServerFunc: (_, _) =>
{
ran = true;
return false;
},
Logger,
cancellationToken: default);
Assert.True(response is CompletedBuildResponse);
}
Assert.False(ran);
}
/// <summary>
/// Simulate the case where the server process crashes or hangs on startup
/// and make sure the client properly fails
/// </summary>
[Fact]
public async Task SimulateServerCrashingOnStartup()
{
var pipeName = ServerUtil.GetPipeName();
var ran = false;
var response = await BuildServerConnection.RunServerBuildRequestAsync(
ProtocolUtil.CreateEmptyCSharp(TempRoot.CreateDirectory().Path),
pipeName,
timeoutOverride: (int)TimeSpan.FromSeconds(2).TotalMilliseconds,
tryCreateServerFunc: (_, _) =>
{
ran = true;
// Correct this is a lie. The server did not start. But it also does a nice
// job of simulating a hung or crashed server.
return true;
},
Logger,
cancellationToken: default);
Assert.True(response is RejectedBuildResponse);
Assert.True(ran);
}
[Fact]
public async Task FailedServer()
{
var pipeName = ServerUtil.GetPipeName();
var workingDirectory = TempRoot.CreateDirectory().Path;
var count = 0;
for (var i = 0; i < 5; i++)
{
var response = await BuildServerConnection.RunServerBuildRequestAsync(
ProtocolUtil.CreateEmptyCSharp(workingDirectory),
pipeName,
timeoutOverride: Timeout.Infinite,
tryCreateServerFunc: (_, _) =>
{
count++;
return false;
},
Logger,
cancellationToken: default);
Assert.True(response is RejectedBuildResponse);
}
Assert.Equal(5, count);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommandLine;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
public sealed class BuildServerConnectionTests : IDisposable
{
internal TempRoot TempRoot { get; } = new TempRoot();
internal XunitCompilerServerLogger Logger { get; }
public BuildServerConnectionTests(ITestOutputHelper testOutputHelper)
{
Logger = new XunitCompilerServerLogger(testOutputHelper);
}
public void Dispose()
{
TempRoot.Dispose();
}
[Fact]
public async Task OnlyStartOneServer()
{
ServerData? serverData = null;
try
{
var pipeName = ServerUtil.GetPipeName();
var workingDirectory = TempRoot.CreateDirectory().Path;
for (var i = 0; i < 5; i++)
{
var response = await BuildServerConnection.RunServerBuildRequestAsync(
ProtocolUtil.CreateEmptyCSharp(workingDirectory),
pipeName,
timeoutOverride: Timeout.Infinite,
tryCreateServerFunc: (pipeName, logger) =>
{
Assert.Null(serverData);
serverData = ServerData.Create(logger, pipeName);
return true;
},
Logger,
cancellationToken: default);
Assert.True(response is CompletedBuildResponse);
}
}
finally
{
serverData?.Dispose();
}
}
[Fact]
public async Task UseExistingServer()
{
using var serverData = await ServerUtil.CreateServer(Logger);
var ran = false;
var workingDirectory = TempRoot.CreateDirectory().Path;
for (var i = 0; i < 5; i++)
{
var response = await BuildServerConnection.RunServerBuildRequestAsync(
ProtocolUtil.CreateEmptyCSharp(workingDirectory),
serverData.PipeName,
timeoutOverride: Timeout.Infinite,
tryCreateServerFunc: (_, _) =>
{
ran = true;
return false;
},
Logger,
cancellationToken: default);
Assert.True(response is CompletedBuildResponse);
}
Assert.False(ran);
}
/// <summary>
/// Simulate the case where the server process crashes or hangs on startup
/// and make sure the client properly fails
/// </summary>
[Fact]
public async Task SimulateServerCrashingOnStartup()
{
var pipeName = ServerUtil.GetPipeName();
var ran = false;
var response = await BuildServerConnection.RunServerBuildRequestAsync(
ProtocolUtil.CreateEmptyCSharp(TempRoot.CreateDirectory().Path),
pipeName,
timeoutOverride: (int)TimeSpan.FromSeconds(2).TotalMilliseconds,
tryCreateServerFunc: (_, _) =>
{
ran = true;
// Correct this is a lie. The server did not start. But it also does a nice
// job of simulating a hung or crashed server.
return true;
},
Logger,
cancellationToken: default);
Assert.True(response is RejectedBuildResponse);
Assert.True(ran);
}
[Fact]
public async Task FailedServer()
{
var pipeName = ServerUtil.GetPipeName();
var workingDirectory = TempRoot.CreateDirectory().Path;
var count = 0;
for (var i = 0; i < 5; i++)
{
var response = await BuildServerConnection.RunServerBuildRequestAsync(
ProtocolUtil.CreateEmptyCSharp(workingDirectory),
pipeName,
timeoutOverride: Timeout.Infinite,
tryCreateServerFunc: (_, _) =>
{
count++;
return false;
},
Logger,
cancellationToken: default);
Assert.True(response is RejectedBuildResponse);
}
Assert.Equal(5, count);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileMergeResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal sealed class LinkedFileMergeResult
{
public IEnumerable<DocumentId> DocumentIds { get; internal set; }
public SourceText MergedSourceText { get; internal set; }
public IEnumerable<TextSpan> MergeConflictResolutionSpans { get; }
public bool HasMergeConflicts { get { return MergeConflictResolutionSpans.Any(); } }
public LinkedFileMergeResult(IEnumerable<DocumentId> documentIds, SourceText mergedSourceText, IEnumerable<TextSpan> mergeConflictResolutionSpans)
{
DocumentIds = documentIds;
MergedSourceText = mergedSourceText;
MergeConflictResolutionSpans = mergeConflictResolutionSpans;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal sealed class LinkedFileMergeResult
{
public IEnumerable<DocumentId> DocumentIds { get; internal set; }
public SourceText MergedSourceText { get; internal set; }
public IEnumerable<TextSpan> MergeConflictResolutionSpans { get; }
public bool HasMergeConflicts { get { return MergeConflictResolutionSpans.Any(); } }
public LinkedFileMergeResult(IEnumerable<DocumentId> documentIds, SourceText mergedSourceText, IEnumerable<TextSpan> mergeConflictResolutionSpans)
{
DocumentIds = documentIds;
MergedSourceText = mergedSourceText;
MergeConflictResolutionSpans = mergeConflictResolutionSpans;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/Core/Portable/FindSymbols/SearchQuery.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal class SearchQuery : IDisposable
{
/// <summary>The name being searched for. Is null in the case of custom predicate searching.. But
/// can be used for faster index based searching when it is available.</summary>
public readonly string Name;
///<summary>The kind of search this is. Faster index-based searching can be used if the
/// SearchKind is not <see cref="SearchKind.Custom"/>.</summary>
public readonly SearchKind Kind;
///<summary>The predicate to fall back on if faster index searching is not possible.</summary>
private readonly Func<string, bool> _predicate;
private readonly WordSimilarityChecker _wordSimilarityChecker;
private SearchQuery(string name, SearchKind kind)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Kind = kind;
switch (kind)
{
case SearchKind.Exact:
_predicate = s => StringComparer.Ordinal.Equals(name, s);
break;
case SearchKind.ExactIgnoreCase:
_predicate = s => CaseInsensitiveComparison.Comparer.Equals(name, s);
break;
case SearchKind.Fuzzy:
// Create a single WordSimilarityChecker and capture a delegate reference to
// its 'AreSimilar' method. That way we only create the WordSimilarityChecker
// once and it can cache all the information it needs while it does the AreSimilar
// check against all the possible candidates.
_wordSimilarityChecker = WordSimilarityChecker.Allocate(name, substringsAreSimilar: false);
_predicate = _wordSimilarityChecker.AreSimilar;
break;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private SearchQuery(Func<string, bool> predicate)
{
Kind = SearchKind.Custom;
_predicate = predicate ?? throw new ArgumentNullException(nameof(predicate));
}
public void Dispose()
=> _wordSimilarityChecker?.Free();
public static SearchQuery Create(string name, SearchKind kind)
=> new(name, kind);
public static SearchQuery Create(string name, bool ignoreCase)
=> new(name, ignoreCase ? SearchKind.ExactIgnoreCase : SearchKind.Exact);
public static SearchQuery CreateFuzzy(string name)
=> new(name, SearchKind.Fuzzy);
public static SearchQuery CreateCustom(Func<string, bool> predicate)
=> new(predicate);
public Func<string, bool> GetPredicate()
=> _predicate;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal class SearchQuery : IDisposable
{
/// <summary>The name being searched for. Is null in the case of custom predicate searching.. But
/// can be used for faster index based searching when it is available.</summary>
public readonly string Name;
///<summary>The kind of search this is. Faster index-based searching can be used if the
/// SearchKind is not <see cref="SearchKind.Custom"/>.</summary>
public readonly SearchKind Kind;
///<summary>The predicate to fall back on if faster index searching is not possible.</summary>
private readonly Func<string, bool> _predicate;
private readonly WordSimilarityChecker _wordSimilarityChecker;
private SearchQuery(string name, SearchKind kind)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
Kind = kind;
switch (kind)
{
case SearchKind.Exact:
_predicate = s => StringComparer.Ordinal.Equals(name, s);
break;
case SearchKind.ExactIgnoreCase:
_predicate = s => CaseInsensitiveComparison.Comparer.Equals(name, s);
break;
case SearchKind.Fuzzy:
// Create a single WordSimilarityChecker and capture a delegate reference to
// its 'AreSimilar' method. That way we only create the WordSimilarityChecker
// once and it can cache all the information it needs while it does the AreSimilar
// check against all the possible candidates.
_wordSimilarityChecker = WordSimilarityChecker.Allocate(name, substringsAreSimilar: false);
_predicate = _wordSimilarityChecker.AreSimilar;
break;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private SearchQuery(Func<string, bool> predicate)
{
Kind = SearchKind.Custom;
_predicate = predicate ?? throw new ArgumentNullException(nameof(predicate));
}
public void Dispose()
=> _wordSimilarityChecker?.Free();
public static SearchQuery Create(string name, SearchKind kind)
=> new(name, kind);
public static SearchQuery Create(string name, bool ignoreCase)
=> new(name, ignoreCase ? SearchKind.ExactIgnoreCase : SearchKind.Exact);
public static SearchQuery CreateFuzzy(string name)
=> new(name, SearchKind.Fuzzy);
public static SearchQuery CreateCustom(Func<string, bool> predicate)
=> new(predicate);
public Func<string, bool> GetPredicate()
=> _predicate;
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/Core/Def/xlf/VSPackage.zh-Hans.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hans" original="../VSPackage.resx">
<body />
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hans" original="../VSPackage.resx">
<body />
</file>
</xliff> | -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Analyzers/CSharp/Tests/RemoveUnnecessaryParentheses/RemoveUnnecessaryPatternParenthesesTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryParentheses;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessaryParentheses
{
public partial class RemoveUnnecessaryPatternParenthesesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public RemoveUnnecessaryPatternParenthesesTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpRemoveUnnecessaryPatternParenthesesDiagnosticAnalyzer(), new CSharpRemoveUnnecessaryParenthesesCodeFixProvider());
private async Task TestAsync(string initial, string expected, bool offeredWhenRequireForClarityIsEnabled, int index = 0)
{
await TestInRegularAndScriptAsync(initial, expected, options: RemoveAllUnnecessaryParentheses, index: index);
if (offeredWhenRequireForClarityIsEnabled)
{
await TestInRegularAndScriptAsync(initial, expected, options: RequireAllParenthesesForClarity, index: index);
}
else
{
await TestMissingAsync(initial, parameters: new TestParameters(options: RequireAllParenthesesForClarity));
}
}
internal override bool ShouldSkipMessageDescriptionVerification(DiagnosticDescriptor descriptor)
=> descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary) && descriptor.DefaultSeverity == DiagnosticSeverity.Hidden;
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestArithmeticRequiredForClarity2()
{
await TestInRegularAndScript1Async(
@"class C
{
void M(object o)
{
bool x = o is a or $$(b and c);
}
}",
@"class C
{
void M(object o)
{
bool x = o is a or b and c;
}
}", parameters: new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestLogicalRequiredForClarity1()
{
await TestMissingAsync(
@"class C
{
void M(object o)
{
bool x = o is a or $$(b and c);
}
}", new TestParameters(options: RequireOtherBinaryParenthesesForClarity));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame1()
{
await TestAsync(
@"class C
{
void M(object o)
{
bool x = o is a or $$(b or c);
}
}",
@"class C
{
void M(object o)
{
bool x = o is a or b or c;
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame2()
{
await TestAsync(
@"class C
{
void M(object o)
{
bool x = o is $$(a or b) or c;
}
}",
@"class C
{
void M(object o)
{
bool x = o is a or b or c;
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestAlwaysUnnecessaryForIsPattern()
{
await TestAsync(
@"class C
{
void M(object o)
{
bool x = o is $$(a or b);
}
}",
@"class C
{
void M(object o)
{
bool x = o is a or b;
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestAlwaysUnnecessaryForCasePattern()
{
await TestAsync(
@"class C
{
void M(object o)
{
switch (o)
{
case $$(a or b):
return;
}
}
}",
@"class C
{
void M(object o)
{
switch (o)
{
case a or b:
return;
}
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestAlwaysUnnecessaryForSwitchArmPattern()
{
await TestAsync(
@"class C
{
int M(object o)
{
return o switch
{
$$(a or b) => 0,
};
}
}",
@"class C
{
int M(object o)
{
return o switch
{
a or b => 0,
};
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestAlwaysUnnecessaryForSubPattern()
{
await TestAsync(
@"class C
{
void M(object o)
{
bool x = o is { X: $$(a or b) };
}
}",
@"class C
{
void M(object o)
{
bool x = o is { X: a or b };
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestNotAlwaysUnnecessaryForUnaryPattern1()
{
await TestAsync(
@"class C
{
void M(object o)
{
bool x = o is a or $$(not b);
}
}",
@"class C
{
void M(object o)
{
bool x = o is a or not b;
}
}", offeredWhenRequireForClarityIsEnabled: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestNotAlwaysUnnecessaryForUnaryPattern2()
{
await TestAsync(
@"class C
{
void M(object o)
{
bool x = o is $$(not a) or b;
}
}",
@"class C
{
void M(object o)
{
bool x = o is not a or b;
}
}", offeredWhenRequireForClarityIsEnabled: false);
}
[WorkItem(52589, "https://github.com/dotnet/roslyn/issues/52589")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestAlwaysNecessaryForDiscard()
{
await TestDiagnosticMissingAsync(
@"
class C
{
void M(object o)
{
if (o is $$(_))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestUnnecessaryForDiscardInSubpattern()
{
await TestAsync(
@"
class C
{
void M(object o)
{
if (o is string { Length: $$(_) })
{
}
}
}",
@"
class C
{
void M(object o)
{
if (o is string { Length: _ })
{
}
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryParentheses;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessaryParentheses
{
public partial class RemoveUnnecessaryPatternParenthesesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public RemoveUnnecessaryPatternParenthesesTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpRemoveUnnecessaryPatternParenthesesDiagnosticAnalyzer(), new CSharpRemoveUnnecessaryParenthesesCodeFixProvider());
private async Task TestAsync(string initial, string expected, bool offeredWhenRequireForClarityIsEnabled, int index = 0)
{
await TestInRegularAndScriptAsync(initial, expected, options: RemoveAllUnnecessaryParentheses, index: index);
if (offeredWhenRequireForClarityIsEnabled)
{
await TestInRegularAndScriptAsync(initial, expected, options: RequireAllParenthesesForClarity, index: index);
}
else
{
await TestMissingAsync(initial, parameters: new TestParameters(options: RequireAllParenthesesForClarity));
}
}
internal override bool ShouldSkipMessageDescriptionVerification(DiagnosticDescriptor descriptor)
=> descriptor.ImmutableCustomTags().Contains(WellKnownDiagnosticTags.Unnecessary) && descriptor.DefaultSeverity == DiagnosticSeverity.Hidden;
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestArithmeticRequiredForClarity2()
{
await TestInRegularAndScript1Async(
@"class C
{
void M(object o)
{
bool x = o is a or $$(b and c);
}
}",
@"class C
{
void M(object o)
{
bool x = o is a or b and c;
}
}", parameters: new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestLogicalRequiredForClarity1()
{
await TestMissingAsync(
@"class C
{
void M(object o)
{
bool x = o is a or $$(b and c);
}
}", new TestParameters(options: RequireOtherBinaryParenthesesForClarity));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame1()
{
await TestAsync(
@"class C
{
void M(object o)
{
bool x = o is a or $$(b or c);
}
}",
@"class C
{
void M(object o)
{
bool x = o is a or b or c;
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame2()
{
await TestAsync(
@"class C
{
void M(object o)
{
bool x = o is $$(a or b) or c;
}
}",
@"class C
{
void M(object o)
{
bool x = o is a or b or c;
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestAlwaysUnnecessaryForIsPattern()
{
await TestAsync(
@"class C
{
void M(object o)
{
bool x = o is $$(a or b);
}
}",
@"class C
{
void M(object o)
{
bool x = o is a or b;
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestAlwaysUnnecessaryForCasePattern()
{
await TestAsync(
@"class C
{
void M(object o)
{
switch (o)
{
case $$(a or b):
return;
}
}
}",
@"class C
{
void M(object o)
{
switch (o)
{
case a or b:
return;
}
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestAlwaysUnnecessaryForSwitchArmPattern()
{
await TestAsync(
@"class C
{
int M(object o)
{
return o switch
{
$$(a or b) => 0,
};
}
}",
@"class C
{
int M(object o)
{
return o switch
{
a or b => 0,
};
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestAlwaysUnnecessaryForSubPattern()
{
await TestAsync(
@"class C
{
void M(object o)
{
bool x = o is { X: $$(a or b) };
}
}",
@"class C
{
void M(object o)
{
bool x = o is { X: a or b };
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestNotAlwaysUnnecessaryForUnaryPattern1()
{
await TestAsync(
@"class C
{
void M(object o)
{
bool x = o is a or $$(not b);
}
}",
@"class C
{
void M(object o)
{
bool x = o is a or not b;
}
}", offeredWhenRequireForClarityIsEnabled: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestNotAlwaysUnnecessaryForUnaryPattern2()
{
await TestAsync(
@"class C
{
void M(object o)
{
bool x = o is $$(not a) or b;
}
}",
@"class C
{
void M(object o)
{
bool x = o is not a or b;
}
}", offeredWhenRequireForClarityIsEnabled: false);
}
[WorkItem(52589, "https://github.com/dotnet/roslyn/issues/52589")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestAlwaysNecessaryForDiscard()
{
await TestDiagnosticMissingAsync(
@"
class C
{
void M(object o)
{
if (o is $$(_))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)]
public async Task TestUnnecessaryForDiscardInSubpattern()
{
await TestAsync(
@"
class C
{
void M(object o)
{
if (o is string { Length: $$(_) })
{
}
}
}",
@"
class C
{
void M(object o)
{
if (o is string { Length: _ })
{
}
}
}", offeredWhenRequireForClarityIsEnabled: true);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/Core/Def/Implementation/TaskList/CommentTaskTokenSerializerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider;
using ITaskList = Microsoft.VisualStudio.Shell.ITaskList;
using SAsyncServiceProvider = Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider;
using SVsTaskList = Microsoft.VisualStudio.Shell.Interop.SVsTaskList;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList
{
[Export(typeof(IOptionPersisterProvider))]
internal sealed class CommentTaskTokenSerializerProvider : IOptionPersisterProvider
{
private readonly IThreadingContext _threadingContext;
private readonly IAsyncServiceProvider _serviceProvider;
private readonly IGlobalOptionService _optionService;
private CommentTaskTokenSerializer? _lazyPersister;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CommentTaskTokenSerializerProvider(
IThreadingContext threadingContext,
[Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider serviceProvider,
IGlobalOptionService optionService)
{
_threadingContext = threadingContext;
_serviceProvider = serviceProvider;
_optionService = optionService;
}
public async ValueTask<IOptionPersister> GetOrCreatePersisterAsync(CancellationToken cancellationToken)
{
if (_lazyPersister is not null)
{
return _lazyPersister;
}
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
// Not all SVsTaskList implementations implement ITaskList, but when it does we will use it
var taskList = await _serviceProvider.GetServiceAsync(typeof(SVsTaskList)).ConfigureAwait(true) as ITaskList;
_lazyPersister ??= new CommentTaskTokenSerializer(_optionService, taskList);
return _lazyPersister;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using IAsyncServiceProvider = Microsoft.VisualStudio.Shell.IAsyncServiceProvider;
using ITaskList = Microsoft.VisualStudio.Shell.ITaskList;
using SAsyncServiceProvider = Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider;
using SVsTaskList = Microsoft.VisualStudio.Shell.Interop.SVsTaskList;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TaskList
{
[Export(typeof(IOptionPersisterProvider))]
internal sealed class CommentTaskTokenSerializerProvider : IOptionPersisterProvider
{
private readonly IThreadingContext _threadingContext;
private readonly IAsyncServiceProvider _serviceProvider;
private readonly IGlobalOptionService _optionService;
private CommentTaskTokenSerializer? _lazyPersister;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CommentTaskTokenSerializerProvider(
IThreadingContext threadingContext,
[Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider serviceProvider,
IGlobalOptionService optionService)
{
_threadingContext = threadingContext;
_serviceProvider = serviceProvider;
_optionService = optionService;
}
public async ValueTask<IOptionPersister> GetOrCreatePersisterAsync(CancellationToken cancellationToken)
{
if (_lazyPersister is not null)
{
return _lazyPersister;
}
await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
// Not all SVsTaskList implementations implement ITaskList, but when it does we will use it
var taskList = await _serviceProvider.GetServiceAsync(typeof(SVsTaskList)).ConfigureAwait(true) as ITaskList;
_lazyPersister ??= new CommentTaskTokenSerializer(_optionService, taskList);
return _lazyPersister;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeStyle/UnusedValuePreference.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CodeStyle
{
/// <summary>
/// Assignment preference for unused values from expression statements and assignments.
/// </summary>
internal enum UnusedValuePreference
{
// Unused values must be explicitly assigned to a local variable
// that is never read/used.
UnusedLocalVariable = 1,
// Unused values must be explicitly assigned to a discard '_' variable.
DiscardVariable = 2,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CodeStyle
{
/// <summary>
/// Assignment preference for unused values from expression statements and assignments.
/// </summary>
internal enum UnusedValuePreference
{
// Unused values must be explicitly assigned to a local variable
// that is never read/used.
UnusedLocalVariable = 1,
// Unused values must be explicitly assigned to a discard '_' variable.
DiscardVariable = 2,
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Core/Portable/Operations/Loops/ForToLoopOperationInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.Operations
{
internal class ForToLoopOperationUserDefinedInfo
{
public readonly IBinaryOperation Addition;
public readonly IBinaryOperation Subtraction;
public readonly IOperation LessThanOrEqual;
public readonly IOperation GreaterThanOrEqual;
public ForToLoopOperationUserDefinedInfo(IBinaryOperation addition, IBinaryOperation subtraction, IOperation lessThanOrEqual, IOperation greaterThanOrEqual)
{
Addition = addition;
Subtraction = subtraction;
LessThanOrEqual = lessThanOrEqual;
GreaterThanOrEqual = greaterThanOrEqual;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.Operations
{
internal class ForToLoopOperationUserDefinedInfo
{
public readonly IBinaryOperation Addition;
public readonly IBinaryOperation Subtraction;
public readonly IOperation LessThanOrEqual;
public readonly IOperation GreaterThanOrEqual;
public ForToLoopOperationUserDefinedInfo(IBinaryOperation addition, IBinaryOperation subtraction, IOperation lessThanOrEqual, IOperation greaterThanOrEqual)
{
Addition = addition;
Subtraction = subtraction;
LessThanOrEqual = lessThanOrEqual;
GreaterThanOrEqual = greaterThanOrEqual;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Test/Syntax/Syntax/TrackNodeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class TrackNodeTests
{
[Fact]
public void TestGetCurrentNodeAfterTrackNodesReturnsCurrentNode()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(a);
var currentA = trackedExpr.GetCurrentNode(a);
Assert.NotNull(currentA);
Assert.Equal("a", currentA.ToString());
}
[Fact]
public void TestGetCurrentNodesAfterTrackNodesReturnsSingletonSequence()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(a);
var currentAs = trackedExpr.GetCurrentNodes(a);
Assert.NotNull(currentAs);
Assert.Equal(1, currentAs.Count());
Assert.Equal("a", currentAs.ElementAt(0).ToString());
}
[Fact]
public void TestGetCurrentNodeWithoutTrackNodesReturnsNull()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var currentA = expr.GetCurrentNode(a);
Assert.Null(currentA);
}
[Fact]
public void TestGetCurrentNodesWithoutTrackNodesReturnsEmptySequence()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var currentAs = expr.GetCurrentNodes(a);
Assert.NotNull(currentAs);
Assert.Equal(0, currentAs.Count());
}
[Fact]
public void TestGetCurrentNodeAfterEditReturnsCurrentNode()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(originalA);
var currentA = trackedExpr.GetCurrentNode(originalA);
var newA = currentA.WithLeadingTrivia(SyntaxFactory.Comment("/* ayup */"));
var replacedExpr = trackedExpr.ReplaceNode(currentA, newA);
var latestA = replacedExpr.GetCurrentNode(originalA);
Assert.NotNull(latestA);
Assert.NotSame(latestA, newA); // not the same reference
Assert.Equal(newA.ToFullString(), latestA.ToFullString());
}
[Fact]
public void TestGetCurrentNodeAfterEditReturnsSingletonSequence()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(originalA);
var currentA = trackedExpr.GetCurrentNode(originalA);
var newA = currentA.WithLeadingTrivia(SyntaxFactory.Comment("/* ayup */"));
var replacedExpr = trackedExpr.ReplaceNode(currentA, newA);
var latestAs = replacedExpr.GetCurrentNodes(originalA);
Assert.NotNull(latestAs);
Assert.Equal(1, latestAs.Count());
Assert.Equal(newA.ToFullString(), latestAs.ElementAt(0).ToFullString());
}
[WorkItem(1070667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070667")]
[Fact]
public void TestGetCurrentNodeAfterRemovalReturnsNull()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(originalA);
var currentA = trackedExpr.GetCurrentNode(originalA);
var replacedExpr = trackedExpr.ReplaceNode(currentA, SyntaxFactory.IdentifierName("c"));
var latestA = replacedExpr.GetCurrentNode(originalA);
Assert.Null(latestA);
}
[Fact]
public void TestGetCurrentNodesAfterRemovalEmptySequence()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(originalA);
var currentA = trackedExpr.GetCurrentNode(originalA);
var replacedExpr = trackedExpr.ReplaceNode(currentA, SyntaxFactory.IdentifierName("c"));
var latestAs = replacedExpr.GetCurrentNodes(originalA);
Assert.NotNull(latestAs);
Assert.Equal(0, latestAs.Count());
}
[Fact]
public void TestGetCurrentNodeAfterAddingMultipleThrows()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(originalA);
var currentA = trackedExpr.GetCurrentNode(originalA);
// replace all identifiers with same 'a'
var replacedExpr = trackedExpr.ReplaceNodes(trackedExpr.DescendantNodes().OfType<IdentifierNameSyntax>(), (original, changed) => currentA);
Assert.Throws<InvalidOperationException>(() => replacedExpr.GetCurrentNode(originalA));
}
[Fact]
public void TestGetCurrentNodeAfterAddingMultipleReturnsMultiple()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(originalA);
var currentA = trackedExpr.GetCurrentNode(originalA);
// replace all identifiers with same 'a'
var replacedExpr = trackedExpr.ReplaceNodes(trackedExpr.DescendantNodes().OfType<IdentifierNameSyntax>(), (original, changed) => currentA);
var nodes = replacedExpr.GetCurrentNodes(originalA).ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal("a", nodes[0].ToString());
Assert.Equal("a", nodes[1].ToString());
}
[Fact]
public void TestTrackNodesWithMultipleTracksAllNodes()
{
var expr = SyntaxFactory.ParseExpression("a + b + c");
var ids = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList();
var trackedExpr = expr.TrackNodes(ids);
Assert.Equal(3, ids.Count);
foreach (var id in ids)
{
var currentId = trackedExpr.GetCurrentNode(id);
Assert.NotNull(currentId);
Assert.NotSame(id, currentId);
Assert.Equal(id.ToString(), currentId.ToString());
}
}
[Fact]
public void TestTrackNodesWithNoNodesTracksNothing()
{
var expr = SyntaxFactory.ParseExpression("a + b + c");
var ids = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList();
var trackedExpr = expr.TrackNodes();
Assert.Equal(3, ids.Count);
foreach (var id in ids)
{
var currentId = trackedExpr.GetCurrentNode(id);
Assert.Null(currentId);
}
}
[Fact]
public void TestTrackNodeThatIsNotInTheSubtreeThrows()
{
var expr = SyntaxFactory.ParseExpression("a + b");
Assert.Throws<ArgumentException>(() => expr.TrackNodes(SyntaxFactory.IdentifierName("c")));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class TrackNodeTests
{
[Fact]
public void TestGetCurrentNodeAfterTrackNodesReturnsCurrentNode()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(a);
var currentA = trackedExpr.GetCurrentNode(a);
Assert.NotNull(currentA);
Assert.Equal("a", currentA.ToString());
}
[Fact]
public void TestGetCurrentNodesAfterTrackNodesReturnsSingletonSequence()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(a);
var currentAs = trackedExpr.GetCurrentNodes(a);
Assert.NotNull(currentAs);
Assert.Equal(1, currentAs.Count());
Assert.Equal("a", currentAs.ElementAt(0).ToString());
}
[Fact]
public void TestGetCurrentNodeWithoutTrackNodesReturnsNull()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var currentA = expr.GetCurrentNode(a);
Assert.Null(currentA);
}
[Fact]
public void TestGetCurrentNodesWithoutTrackNodesReturnsEmptySequence()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var currentAs = expr.GetCurrentNodes(a);
Assert.NotNull(currentAs);
Assert.Equal(0, currentAs.Count());
}
[Fact]
public void TestGetCurrentNodeAfterEditReturnsCurrentNode()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(originalA);
var currentA = trackedExpr.GetCurrentNode(originalA);
var newA = currentA.WithLeadingTrivia(SyntaxFactory.Comment("/* ayup */"));
var replacedExpr = trackedExpr.ReplaceNode(currentA, newA);
var latestA = replacedExpr.GetCurrentNode(originalA);
Assert.NotNull(latestA);
Assert.NotSame(latestA, newA); // not the same reference
Assert.Equal(newA.ToFullString(), latestA.ToFullString());
}
[Fact]
public void TestGetCurrentNodeAfterEditReturnsSingletonSequence()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(originalA);
var currentA = trackedExpr.GetCurrentNode(originalA);
var newA = currentA.WithLeadingTrivia(SyntaxFactory.Comment("/* ayup */"));
var replacedExpr = trackedExpr.ReplaceNode(currentA, newA);
var latestAs = replacedExpr.GetCurrentNodes(originalA);
Assert.NotNull(latestAs);
Assert.Equal(1, latestAs.Count());
Assert.Equal(newA.ToFullString(), latestAs.ElementAt(0).ToFullString());
}
[WorkItem(1070667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070667")]
[Fact]
public void TestGetCurrentNodeAfterRemovalReturnsNull()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(originalA);
var currentA = trackedExpr.GetCurrentNode(originalA);
var replacedExpr = trackedExpr.ReplaceNode(currentA, SyntaxFactory.IdentifierName("c"));
var latestA = replacedExpr.GetCurrentNode(originalA);
Assert.Null(latestA);
}
[Fact]
public void TestGetCurrentNodesAfterRemovalEmptySequence()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(originalA);
var currentA = trackedExpr.GetCurrentNode(originalA);
var replacedExpr = trackedExpr.ReplaceNode(currentA, SyntaxFactory.IdentifierName("c"));
var latestAs = replacedExpr.GetCurrentNodes(originalA);
Assert.NotNull(latestAs);
Assert.Equal(0, latestAs.Count());
}
[Fact]
public void TestGetCurrentNodeAfterAddingMultipleThrows()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(originalA);
var currentA = trackedExpr.GetCurrentNode(originalA);
// replace all identifiers with same 'a'
var replacedExpr = trackedExpr.ReplaceNodes(trackedExpr.DescendantNodes().OfType<IdentifierNameSyntax>(), (original, changed) => currentA);
Assert.Throws<InvalidOperationException>(() => replacedExpr.GetCurrentNode(originalA));
}
[Fact]
public void TestGetCurrentNodeAfterAddingMultipleReturnsMultiple()
{
var expr = SyntaxFactory.ParseExpression("a + b");
var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a");
var trackedExpr = expr.TrackNodes(originalA);
var currentA = trackedExpr.GetCurrentNode(originalA);
// replace all identifiers with same 'a'
var replacedExpr = trackedExpr.ReplaceNodes(trackedExpr.DescendantNodes().OfType<IdentifierNameSyntax>(), (original, changed) => currentA);
var nodes = replacedExpr.GetCurrentNodes(originalA).ToList();
Assert.Equal(2, nodes.Count);
Assert.Equal("a", nodes[0].ToString());
Assert.Equal("a", nodes[1].ToString());
}
[Fact]
public void TestTrackNodesWithMultipleTracksAllNodes()
{
var expr = SyntaxFactory.ParseExpression("a + b + c");
var ids = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList();
var trackedExpr = expr.TrackNodes(ids);
Assert.Equal(3, ids.Count);
foreach (var id in ids)
{
var currentId = trackedExpr.GetCurrentNode(id);
Assert.NotNull(currentId);
Assert.NotSame(id, currentId);
Assert.Equal(id.ToString(), currentId.ToString());
}
}
[Fact]
public void TestTrackNodesWithNoNodesTracksNothing()
{
var expr = SyntaxFactory.ParseExpression("a + b + c");
var ids = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList();
var trackedExpr = expr.TrackNodes();
Assert.Equal(3, ids.Count);
foreach (var id in ids)
{
var currentId = trackedExpr.GetCurrentNode(id);
Assert.Null(currentId);
}
}
[Fact]
public void TestTrackNodeThatIsNotInTheSubtreeThrows()
{
var expr = SyntaxFactory.ParseExpression("a + b");
Assert.Throws<ArgumentException>(() => expr.TrackNodes(SyntaxFactory.IdentifierName("c")));
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/MakeMethodAsynchronous/AbstractMakeMethodAsynchronousCodeFixProvider.KnownTypes.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.MakeMethodAsynchronous
{
internal abstract partial class AbstractMakeMethodAsynchronousCodeFixProvider
{
internal readonly struct KnownTypes
{
public readonly INamedTypeSymbol _taskType;
public readonly INamedTypeSymbol _taskOfTType;
public readonly INamedTypeSymbol _valueTaskType;
public readonly INamedTypeSymbol _valueTaskOfTTypeOpt;
public readonly INamedTypeSymbol _iEnumerableOfTType;
public readonly INamedTypeSymbol _iEnumeratorOfTType;
public readonly INamedTypeSymbol _iAsyncEnumerableOfTTypeOpt;
public readonly INamedTypeSymbol _iAsyncEnumeratorOfTTypeOpt;
internal KnownTypes(Compilation compilation)
{
_taskType = compilation.TaskType();
_taskOfTType = compilation.TaskOfTType();
_valueTaskType = compilation.ValueTaskType();
_valueTaskOfTTypeOpt = compilation.ValueTaskOfTType();
_iEnumerableOfTType = compilation.IEnumerableOfTType();
_iEnumeratorOfTType = compilation.IEnumeratorOfTType();
_iAsyncEnumerableOfTTypeOpt = compilation.IAsyncEnumerableOfTType();
_iAsyncEnumeratorOfTTypeOpt = compilation.IAsyncEnumeratorOfTType();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.MakeMethodAsynchronous
{
internal abstract partial class AbstractMakeMethodAsynchronousCodeFixProvider
{
internal readonly struct KnownTypes
{
public readonly INamedTypeSymbol _taskType;
public readonly INamedTypeSymbol _taskOfTType;
public readonly INamedTypeSymbol _valueTaskType;
public readonly INamedTypeSymbol _valueTaskOfTTypeOpt;
public readonly INamedTypeSymbol _iEnumerableOfTType;
public readonly INamedTypeSymbol _iEnumeratorOfTType;
public readonly INamedTypeSymbol _iAsyncEnumerableOfTTypeOpt;
public readonly INamedTypeSymbol _iAsyncEnumeratorOfTTypeOpt;
internal KnownTypes(Compilation compilation)
{
_taskType = compilation.TaskType();
_taskOfTType = compilation.TaskOfTType();
_valueTaskType = compilation.ValueTaskType();
_valueTaskOfTTypeOpt = compilation.ValueTaskOfTType();
_iEnumerableOfTType = compilation.IEnumerableOfTType();
_iEnumeratorOfTType = compilation.IEnumeratorOfTType();
_iAsyncEnumerableOfTTypeOpt = compilation.IAsyncEnumerableOfTType();
_iAsyncEnumeratorOfTTypeOpt = compilation.IAsyncEnumeratorOfTType();
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedMethod.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.Emit.NoPia
{
internal abstract partial class EmbeddedTypesManager<
TPEModuleBuilder,
TModuleCompilationState,
TEmbeddedTypesManager,
TSyntaxNode,
TAttributeData,
TSymbol,
TAssemblySymbol,
TNamedTypeSymbol,
TFieldSymbol,
TMethodSymbol,
TEventSymbol,
TPropertySymbol,
TParameterSymbol,
TTypeParameterSymbol,
TEmbeddedType,
TEmbeddedField,
TEmbeddedMethod,
TEmbeddedEvent,
TEmbeddedProperty,
TEmbeddedParameter,
TEmbeddedTypeParameter>
{
internal abstract class CommonEmbeddedMethod : CommonEmbeddedMember<TMethodSymbol>, Cci.IMethodDefinition
{
public readonly TEmbeddedType ContainingType;
private readonly ImmutableArray<TEmbeddedTypeParameter> _typeParameters;
private readonly ImmutableArray<TEmbeddedParameter> _parameters;
protected CommonEmbeddedMethod(TEmbeddedType containingType, TMethodSymbol underlyingMethod) :
base(underlyingMethod)
{
this.ContainingType = containingType;
_typeParameters = GetTypeParameters();
_parameters = GetParameters();
}
protected abstract ImmutableArray<TEmbeddedTypeParameter> GetTypeParameters();
protected abstract ImmutableArray<TEmbeddedParameter> GetParameters();
protected abstract bool IsAbstract { get; }
protected abstract bool IsAccessCheckedOnOverride { get; }
protected abstract bool IsConstructor { get; }
protected abstract bool IsExternal { get; }
protected abstract bool IsHiddenBySignature { get; }
protected abstract bool IsNewSlot { get; }
protected abstract Cci.IPlatformInvokeInformation PlatformInvokeData { get; }
protected abstract bool IsRuntimeSpecial { get; }
protected abstract bool IsSpecialName { get; }
protected abstract bool IsSealed { get; }
protected abstract bool IsStatic { get; }
protected abstract bool IsVirtual { get; }
protected abstract System.Reflection.MethodImplAttributes GetImplementationAttributes(EmitContext context);
protected abstract bool ReturnValueIsMarshalledExplicitly { get; }
protected abstract Cci.IMarshallingInformation ReturnValueMarshallingInformation { get; }
protected abstract ImmutableArray<byte> ReturnValueMarshallingDescriptor { get; }
protected abstract Cci.TypeMemberVisibility Visibility { get; }
protected abstract string Name { get; }
protected abstract bool AcceptsExtraArguments { get; }
protected abstract Cci.ISignature UnderlyingMethodSignature { get; }
protected abstract Cci.INamespace ContainingNamespace { get; }
public TMethodSymbol UnderlyingMethod => this.UnderlyingSymbol;
protected sealed override TAttributeData PortAttributeIfNeedTo(TAttributeData attrData, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
// Note, when porting attributes, we are not using constructors from original symbol.
// The constructors might be missing (for example, in metadata case) and doing lookup
// will ensure that we report appropriate errors.
if (TypeManager.IsTargetAttribute(UnderlyingMethod, attrData, AttributeDescription.LCIDConversionAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
return TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_LCIDConversionAttribute__ctor, attrData, syntaxNodeOpt, diagnostics);
}
}
return null;
}
Cci.IMethodBody Cci.IMethodDefinition.GetBody(EmitContext context)
{
if (Cci.Extensions.HasBody(this))
{
// This is an error condition, which we already reported.
// To prevent metadata emitter/visitor from crashing, let's
// return an empty body.
return new EmptyBody(this);
}
return null;
}
private sealed class EmptyBody : Cci.IMethodBody
{
private readonly CommonEmbeddedMethod _method;
public EmptyBody(CommonEmbeddedMethod method)
{
_method = method;
}
ImmutableArray<Cci.ExceptionHandlerRegion> Cci.IMethodBody.ExceptionRegions =>
ImmutableArray<Cci.ExceptionHandlerRegion>.Empty;
bool Cci.IMethodBody.HasStackalloc => false;
bool Cci.IMethodBody.AreLocalsZeroed => false;
ImmutableArray<Cci.ILocalDefinition> Cci.IMethodBody.LocalVariables =>
ImmutableArray<Cci.ILocalDefinition>.Empty;
Cci.IMethodDefinition Cci.IMethodBody.MethodDefinition => _method;
ushort Cci.IMethodBody.MaxStack => 0;
ImmutableArray<byte> Cci.IMethodBody.IL => ImmutableArray<byte>.Empty;
ImmutableArray<Cci.SequencePoint> Cci.IMethodBody.SequencePoints => ImmutableArray<Cci.SequencePoint>.Empty;
bool Cci.IMethodBody.HasDynamicLocalVariables => false;
StateMachineMoveNextBodyDebugInfo Cci.IMethodBody.MoveNextBodyInfo => null;
DynamicAnalysisMethodBodyData Cci.IMethodBody.DynamicAnalysisData => null;
ImmutableArray<Cci.LocalScope> Cci.IMethodBody.LocalScopes =>
ImmutableArray<Cci.LocalScope>.Empty;
Cci.IImportScope Cci.IMethodBody.ImportScope => null;
ImmutableArray<StateMachineHoistedLocalScope> Cci.IMethodBody.StateMachineHoistedLocalScopes =>
default(ImmutableArray<StateMachineHoistedLocalScope>);
string Cci.IMethodBody.StateMachineTypeName => null;
ImmutableArray<EncHoistedLocalInfo> Cci.IMethodBody.StateMachineHoistedLocalSlots =>
default(ImmutableArray<EncHoistedLocalInfo>);
ImmutableArray<Cci.ITypeReference> Cci.IMethodBody.StateMachineAwaiterSlots =>
default(ImmutableArray<Cci.ITypeReference>);
ImmutableArray<ClosureDebugInfo> Cci.IMethodBody.ClosureDebugInfo =>
default(ImmutableArray<ClosureDebugInfo>);
ImmutableArray<LambdaDebugInfo> Cci.IMethodBody.LambdaDebugInfo =>
default(ImmutableArray<LambdaDebugInfo>);
public DebugId MethodId => default(DebugId);
}
IEnumerable<Cci.IGenericMethodParameter> Cci.IMethodDefinition.GenericParameters => _typeParameters;
bool Cci.IMethodDefinition.HasDeclarativeSecurity => false;
bool Cci.IMethodDefinition.IsAbstract => IsAbstract;
bool Cci.IMethodDefinition.IsAccessCheckedOnOverride => IsAccessCheckedOnOverride;
bool Cci.IMethodDefinition.IsConstructor => IsConstructor;
bool Cci.IMethodDefinition.IsExternal => IsExternal;
bool Cci.IMethodDefinition.IsHiddenBySignature => IsHiddenBySignature;
bool Cci.IMethodDefinition.IsNewSlot => IsNewSlot;
bool Cci.IMethodDefinition.IsPlatformInvoke => PlatformInvokeData != null;
Cci.IPlatformInvokeInformation Cci.IMethodDefinition.PlatformInvokeData => PlatformInvokeData;
bool Cci.IMethodDefinition.IsRuntimeSpecial => IsRuntimeSpecial;
bool Cci.IMethodDefinition.IsSpecialName => IsSpecialName;
bool Cci.IMethodDefinition.IsSealed => IsSealed;
bool Cci.IMethodDefinition.IsStatic => IsStatic;
bool Cci.IMethodDefinition.IsVirtual => IsVirtual;
System.Reflection.MethodImplAttributes Cci.IMethodDefinition.GetImplementationAttributes(EmitContext context)
{
return GetImplementationAttributes(context);
}
ImmutableArray<Cci.IParameterDefinition> Cci.IMethodDefinition.Parameters
{
get
{
return StaticCast<Cci.IParameterDefinition>.From(_parameters);
}
}
bool Cci.IMethodDefinition.RequiresSecurityObject => false;
IEnumerable<Cci.ICustomAttribute> Cci.IMethodDefinition.GetReturnValueAttributes(EmitContext context)
{
// TODO:
return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>();
}
bool Cci.IMethodDefinition.ReturnValueIsMarshalledExplicitly => ReturnValueIsMarshalledExplicitly;
Cci.IMarshallingInformation Cci.IMethodDefinition.ReturnValueMarshallingInformation => ReturnValueMarshallingInformation;
ImmutableArray<byte> Cci.IMethodDefinition.ReturnValueMarshallingDescriptor => ReturnValueMarshallingDescriptor;
IEnumerable<Cci.SecurityAttribute> Cci.IMethodDefinition.SecurityAttributes =>
SpecializedCollections.EmptyEnumerable<Cci.SecurityAttribute>();
Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition => ContainingType;
Cci.INamespace Cci.IMethodDefinition.ContainingNamespace => ContainingNamespace;
Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility => Visibility;
Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context)
{
return ContainingType;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit(this);
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return this;
}
string Cci.INamedEntity.Name => Name;
bool Cci.IMethodReference.AcceptsExtraArguments => AcceptsExtraArguments;
ushort Cci.IMethodReference.GenericParameterCount => (ushort)_typeParameters.Length;
bool Cci.IMethodReference.IsGeneric => _typeParameters.Length > 0;
Cci.IMethodDefinition Cci.IMethodReference.GetResolvedMethod(EmitContext context)
{
return this;
}
ImmutableArray<Cci.IParameterTypeInformation> Cci.IMethodReference.ExtraParameters
{
get
{
// This is a definition, no information about extra parameters
return ImmutableArray<Cci.IParameterTypeInformation>.Empty;
}
}
Cci.IGenericMethodInstanceReference Cci.IMethodReference.AsGenericMethodInstanceReference => null;
Cci.ISpecializedMethodReference Cci.IMethodReference.AsSpecializedMethodReference => null;
Cci.CallingConvention Cci.ISignature.CallingConvention => UnderlyingMethodSignature.CallingConvention;
ushort Cci.ISignature.ParameterCount => (ushort)_parameters.Length;
ImmutableArray<Cci.IParameterTypeInformation> Cci.ISignature.GetParameters(EmitContext context)
{
return StaticCast<Cci.IParameterTypeInformation>.From(_parameters);
}
ImmutableArray<Cci.ICustomModifier> Cci.ISignature.RefCustomModifiers =>
UnderlyingMethodSignature.RefCustomModifiers;
ImmutableArray<Cci.ICustomModifier> Cci.ISignature.ReturnValueCustomModifiers =>
UnderlyingMethodSignature.ReturnValueCustomModifiers;
bool Cci.ISignature.ReturnValueIsByRef => UnderlyingMethodSignature.ReturnValueIsByRef;
Cci.ITypeReference Cci.ISignature.GetType(EmitContext context)
{
return UnderlyingMethodSignature.GetType(context);
}
/// <remarks>
/// This is only used for testing.
/// </remarks>
public override string ToString()
{
return UnderlyingMethod.GetInternalSymbol().GetISymbol().ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.Emit.NoPia
{
internal abstract partial class EmbeddedTypesManager<
TPEModuleBuilder,
TModuleCompilationState,
TEmbeddedTypesManager,
TSyntaxNode,
TAttributeData,
TSymbol,
TAssemblySymbol,
TNamedTypeSymbol,
TFieldSymbol,
TMethodSymbol,
TEventSymbol,
TPropertySymbol,
TParameterSymbol,
TTypeParameterSymbol,
TEmbeddedType,
TEmbeddedField,
TEmbeddedMethod,
TEmbeddedEvent,
TEmbeddedProperty,
TEmbeddedParameter,
TEmbeddedTypeParameter>
{
internal abstract class CommonEmbeddedMethod : CommonEmbeddedMember<TMethodSymbol>, Cci.IMethodDefinition
{
public readonly TEmbeddedType ContainingType;
private readonly ImmutableArray<TEmbeddedTypeParameter> _typeParameters;
private readonly ImmutableArray<TEmbeddedParameter> _parameters;
protected CommonEmbeddedMethod(TEmbeddedType containingType, TMethodSymbol underlyingMethod) :
base(underlyingMethod)
{
this.ContainingType = containingType;
_typeParameters = GetTypeParameters();
_parameters = GetParameters();
}
protected abstract ImmutableArray<TEmbeddedTypeParameter> GetTypeParameters();
protected abstract ImmutableArray<TEmbeddedParameter> GetParameters();
protected abstract bool IsAbstract { get; }
protected abstract bool IsAccessCheckedOnOverride { get; }
protected abstract bool IsConstructor { get; }
protected abstract bool IsExternal { get; }
protected abstract bool IsHiddenBySignature { get; }
protected abstract bool IsNewSlot { get; }
protected abstract Cci.IPlatformInvokeInformation PlatformInvokeData { get; }
protected abstract bool IsRuntimeSpecial { get; }
protected abstract bool IsSpecialName { get; }
protected abstract bool IsSealed { get; }
protected abstract bool IsStatic { get; }
protected abstract bool IsVirtual { get; }
protected abstract System.Reflection.MethodImplAttributes GetImplementationAttributes(EmitContext context);
protected abstract bool ReturnValueIsMarshalledExplicitly { get; }
protected abstract Cci.IMarshallingInformation ReturnValueMarshallingInformation { get; }
protected abstract ImmutableArray<byte> ReturnValueMarshallingDescriptor { get; }
protected abstract Cci.TypeMemberVisibility Visibility { get; }
protected abstract string Name { get; }
protected abstract bool AcceptsExtraArguments { get; }
protected abstract Cci.ISignature UnderlyingMethodSignature { get; }
protected abstract Cci.INamespace ContainingNamespace { get; }
public TMethodSymbol UnderlyingMethod => this.UnderlyingSymbol;
protected sealed override TAttributeData PortAttributeIfNeedTo(TAttributeData attrData, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
// Note, when porting attributes, we are not using constructors from original symbol.
// The constructors might be missing (for example, in metadata case) and doing lookup
// will ensure that we report appropriate errors.
if (TypeManager.IsTargetAttribute(UnderlyingMethod, attrData, AttributeDescription.LCIDConversionAttribute))
{
if (attrData.CommonConstructorArguments.Length == 1)
{
return TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_LCIDConversionAttribute__ctor, attrData, syntaxNodeOpt, diagnostics);
}
}
return null;
}
Cci.IMethodBody Cci.IMethodDefinition.GetBody(EmitContext context)
{
if (Cci.Extensions.HasBody(this))
{
// This is an error condition, which we already reported.
// To prevent metadata emitter/visitor from crashing, let's
// return an empty body.
return new EmptyBody(this);
}
return null;
}
private sealed class EmptyBody : Cci.IMethodBody
{
private readonly CommonEmbeddedMethod _method;
public EmptyBody(CommonEmbeddedMethod method)
{
_method = method;
}
ImmutableArray<Cci.ExceptionHandlerRegion> Cci.IMethodBody.ExceptionRegions =>
ImmutableArray<Cci.ExceptionHandlerRegion>.Empty;
bool Cci.IMethodBody.HasStackalloc => false;
bool Cci.IMethodBody.AreLocalsZeroed => false;
ImmutableArray<Cci.ILocalDefinition> Cci.IMethodBody.LocalVariables =>
ImmutableArray<Cci.ILocalDefinition>.Empty;
Cci.IMethodDefinition Cci.IMethodBody.MethodDefinition => _method;
ushort Cci.IMethodBody.MaxStack => 0;
ImmutableArray<byte> Cci.IMethodBody.IL => ImmutableArray<byte>.Empty;
ImmutableArray<Cci.SequencePoint> Cci.IMethodBody.SequencePoints => ImmutableArray<Cci.SequencePoint>.Empty;
bool Cci.IMethodBody.HasDynamicLocalVariables => false;
StateMachineMoveNextBodyDebugInfo Cci.IMethodBody.MoveNextBodyInfo => null;
DynamicAnalysisMethodBodyData Cci.IMethodBody.DynamicAnalysisData => null;
ImmutableArray<Cci.LocalScope> Cci.IMethodBody.LocalScopes =>
ImmutableArray<Cci.LocalScope>.Empty;
Cci.IImportScope Cci.IMethodBody.ImportScope => null;
ImmutableArray<StateMachineHoistedLocalScope> Cci.IMethodBody.StateMachineHoistedLocalScopes =>
default(ImmutableArray<StateMachineHoistedLocalScope>);
string Cci.IMethodBody.StateMachineTypeName => null;
ImmutableArray<EncHoistedLocalInfo> Cci.IMethodBody.StateMachineHoistedLocalSlots =>
default(ImmutableArray<EncHoistedLocalInfo>);
ImmutableArray<Cci.ITypeReference> Cci.IMethodBody.StateMachineAwaiterSlots =>
default(ImmutableArray<Cci.ITypeReference>);
ImmutableArray<ClosureDebugInfo> Cci.IMethodBody.ClosureDebugInfo =>
default(ImmutableArray<ClosureDebugInfo>);
ImmutableArray<LambdaDebugInfo> Cci.IMethodBody.LambdaDebugInfo =>
default(ImmutableArray<LambdaDebugInfo>);
public DebugId MethodId => default(DebugId);
}
IEnumerable<Cci.IGenericMethodParameter> Cci.IMethodDefinition.GenericParameters => _typeParameters;
bool Cci.IMethodDefinition.HasDeclarativeSecurity => false;
bool Cci.IMethodDefinition.IsAbstract => IsAbstract;
bool Cci.IMethodDefinition.IsAccessCheckedOnOverride => IsAccessCheckedOnOverride;
bool Cci.IMethodDefinition.IsConstructor => IsConstructor;
bool Cci.IMethodDefinition.IsExternal => IsExternal;
bool Cci.IMethodDefinition.IsHiddenBySignature => IsHiddenBySignature;
bool Cci.IMethodDefinition.IsNewSlot => IsNewSlot;
bool Cci.IMethodDefinition.IsPlatformInvoke => PlatformInvokeData != null;
Cci.IPlatformInvokeInformation Cci.IMethodDefinition.PlatformInvokeData => PlatformInvokeData;
bool Cci.IMethodDefinition.IsRuntimeSpecial => IsRuntimeSpecial;
bool Cci.IMethodDefinition.IsSpecialName => IsSpecialName;
bool Cci.IMethodDefinition.IsSealed => IsSealed;
bool Cci.IMethodDefinition.IsStatic => IsStatic;
bool Cci.IMethodDefinition.IsVirtual => IsVirtual;
System.Reflection.MethodImplAttributes Cci.IMethodDefinition.GetImplementationAttributes(EmitContext context)
{
return GetImplementationAttributes(context);
}
ImmutableArray<Cci.IParameterDefinition> Cci.IMethodDefinition.Parameters
{
get
{
return StaticCast<Cci.IParameterDefinition>.From(_parameters);
}
}
bool Cci.IMethodDefinition.RequiresSecurityObject => false;
IEnumerable<Cci.ICustomAttribute> Cci.IMethodDefinition.GetReturnValueAttributes(EmitContext context)
{
// TODO:
return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>();
}
bool Cci.IMethodDefinition.ReturnValueIsMarshalledExplicitly => ReturnValueIsMarshalledExplicitly;
Cci.IMarshallingInformation Cci.IMethodDefinition.ReturnValueMarshallingInformation => ReturnValueMarshallingInformation;
ImmutableArray<byte> Cci.IMethodDefinition.ReturnValueMarshallingDescriptor => ReturnValueMarshallingDescriptor;
IEnumerable<Cci.SecurityAttribute> Cci.IMethodDefinition.SecurityAttributes =>
SpecializedCollections.EmptyEnumerable<Cci.SecurityAttribute>();
Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition => ContainingType;
Cci.INamespace Cci.IMethodDefinition.ContainingNamespace => ContainingNamespace;
Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility => Visibility;
Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context)
{
return ContainingType;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit(this);
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return this;
}
string Cci.INamedEntity.Name => Name;
bool Cci.IMethodReference.AcceptsExtraArguments => AcceptsExtraArguments;
ushort Cci.IMethodReference.GenericParameterCount => (ushort)_typeParameters.Length;
bool Cci.IMethodReference.IsGeneric => _typeParameters.Length > 0;
Cci.IMethodDefinition Cci.IMethodReference.GetResolvedMethod(EmitContext context)
{
return this;
}
ImmutableArray<Cci.IParameterTypeInformation> Cci.IMethodReference.ExtraParameters
{
get
{
// This is a definition, no information about extra parameters
return ImmutableArray<Cci.IParameterTypeInformation>.Empty;
}
}
Cci.IGenericMethodInstanceReference Cci.IMethodReference.AsGenericMethodInstanceReference => null;
Cci.ISpecializedMethodReference Cci.IMethodReference.AsSpecializedMethodReference => null;
Cci.CallingConvention Cci.ISignature.CallingConvention => UnderlyingMethodSignature.CallingConvention;
ushort Cci.ISignature.ParameterCount => (ushort)_parameters.Length;
ImmutableArray<Cci.IParameterTypeInformation> Cci.ISignature.GetParameters(EmitContext context)
{
return StaticCast<Cci.IParameterTypeInformation>.From(_parameters);
}
ImmutableArray<Cci.ICustomModifier> Cci.ISignature.RefCustomModifiers =>
UnderlyingMethodSignature.RefCustomModifiers;
ImmutableArray<Cci.ICustomModifier> Cci.ISignature.ReturnValueCustomModifiers =>
UnderlyingMethodSignature.ReturnValueCustomModifiers;
bool Cci.ISignature.ReturnValueIsByRef => UnderlyingMethodSignature.ReturnValueIsByRef;
Cci.ITypeReference Cci.ISignature.GetType(EmitContext context)
{
return UnderlyingMethodSignature.GetType(context);
}
/// <remarks>
/// This is only used for testing.
/// </remarks>
public override string ToString()
{
return UnderlyingMethod.GetInternalSymbol().GetISymbol().ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat);
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/VisualBasic/Portable/xlf/VBResources.zh-Hant.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../VBResources.resx">
<body>
<trans-unit id="ERR_AssignmentInitOnly">
<source>Init-only property '{0}' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor.</source>
<target state="translated">只有物件成員初始設定式,或在執行個體建構函式中的 'Me'、'MyClass' 或 'MyBase',才可指派僅限初始化的屬性 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadSwitchValue">
<source>Command-line syntax error: '{0}' is not a valid value for the '{1}' option. The value must be of the form '{2}'.</source>
<target state="translated">命令列語法錯誤: '{0}' 對 '{1}' 選項而言不是有效的值。此值的格式必須是 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CommentsAfterLineContinuationNotAvailable1">
<source>Please use language version {0} or greater to use comments after line continuation character.</source>
<target state="translated">若要在行接續字元後使用註解,請使用 {0} 或更高的語言版本。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultInterfaceImplementationInNoPIAType">
<source>Type '{0}' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false.</source>
<target state="translated">因為類型 '{0}' 有非抽象成員,所以無法內嵌。請考慮將 [內嵌 Interop 類型] 屬性設為 false。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleAnalyzerConfigsInSameDir">
<source>Multiple analyzer config files cannot be in the same directory ('{0}').</source>
<target state="translated">多個分析器組態檔無法處於相同目錄 ('{0}') 中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverridingInitOnlyProperty">
<source>'{0}' cannot override init-only '{1}'.</source>
<target state="translated">'{0}' 無法覆寫僅限初始化的 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyDoesntImplementInitOnly">
<source>Init-only '{0}' cannot be implemented.</source>
<target state="translated">無法實作僅限初始化的 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReAbstractionInNoPIAType">
<source>Type '{0}' cannot be embedded because it has a re-abstraction of a member from base interface. Consider setting the 'Embed Interop Types' property to false.</source>
<target state="translated">因為類型 '{0}' 有重新抽象成員 (來自基底介面),所以無法內嵌。請考慮將 [內嵌 Interop 類型] 屬性設為 false。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation">
<source>Target runtime doesn't support default interface implementation.</source>
<target state="translated">目標執行階段不支援預設介面實作。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember">
<source>Target runtime doesn't support 'Protected', 'Protected Friend', or 'Private Protected' accessibility for a member of an interface.</source>
<target state="translated">目標執行階段不支援對介面成員的 'Protected'、'Protected Friend' 或 'Private Protected' 存取範圍。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedEventNeedsHandlerInTheSameType">
<source>Events of shared WithEvents variables cannot be handled by methods in a different type.</source>
<target state="translated">無法使用其他類型的方法,處理共用 WithEvents 變數的事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnmanagedCallersOnlyNotSupported">
<source>'UnmanagedCallersOnly' attribute is not supported.</source>
<target state="translated">不支援 'UnmanagedCallersOnly' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CallerArgumentExpression">
<source>caller argument expression</source>
<target state="new">caller argument expression</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CommentsAfterLineContinuation">
<source>comments after line continuation</source>
<target state="translated">行接續符號後註解</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_InitOnlySettersUsage">
<source>assigning to or passing 'ByRef' properties with init-only setters</source>
<target state="translated">使用僅限初始化的 setter,指派或傳遞 'ByRef' 屬性</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_UnconstrainedTypeParameterInConditional">
<source>unconstrained type parameters in binary conditional expressions</source>
<target state="translated">二進位條件運算式中的非限制式型別參數</target>
<note />
</trans-unit>
<trans-unit id="IDS_VBCHelp">
<source> Visual Basic Compiler Options
- OUTPUT FILE -
-out:<file> Specifies the output file name.
-target:exe Create a console application (default).
(Short form: -t)
-target:winexe Create a Windows application.
-target:library Create a library assembly.
-target:module Create a module that can be added to an
assembly.
-target:appcontainerexe Create a Windows application that runs in
AppContainer.
-target:winmdobj Create a Windows Metadata intermediate file
-doc[+|-] Generates XML documentation file.
-doc:<file> Generates XML documentation file to <file>.
-refout:<file> Reference assembly output to generate
- INPUT FILES -
-addmodule:<file_list> Reference metadata from the specified modules
-link:<file_list> Embed metadata from the specified interop
assembly. (Short form: -l)
-recurse:<wildcard> Include all files in the current directory
and subdirectories according to the
wildcard specifications.
-reference:<file_list> Reference metadata from the specified
assembly. (Short form: -r)
-analyzer:<file_list> Run the analyzers from this assembly
(Short form: -a)
-additionalfile:<file list> Additional files that don't directly affect code
generation but may be used by analyzers for producing
errors or warnings.
- RESOURCES -
-linkresource:<resinfo> Links the specified file as an external
assembly resource.
resinfo:<file>[,<name>[,public|private]]
(Short form: -linkres)
-nowin32manifest The default manifest should not be embedded
in the manifest section of the output PE.
-resource:<resinfo> Adds the specified file as an embedded
assembly resource.
resinfo:<file>[,<name>[,public|private]]
(Short form: -res)
-win32icon:<file> Specifies a Win32 icon file (.ico) for the
default Win32 resources.
-win32manifest:<file> The provided file is embedded in the manifest
section of the output PE.
-win32resource:<file> Specifies a Win32 resource file (.res).
- CODE GENERATION -
-optimize[+|-] Enable optimizations.
-removeintchecks[+|-] Remove integer checks. Default off.
-debug[+|-] Emit debugging information.
-debug:full Emit full debugging information (default).
-debug:pdbonly Emit full debugging information.
-debug:portable Emit cross-platform debugging information.
-debug:embedded Emit cross-platform debugging information into
the target .dll or .exe.
-deterministic Produce a deterministic assembly
(including module version GUID and timestamp)
-refonly Produce a reference assembly in place of the main output
-instrument:TestCoverage Produce an assembly instrumented to collect
coverage information
-sourcelink:<file> Source link info to embed into PDB.
- ERRORS AND WARNINGS -
-nowarn Disable all warnings.
-nowarn:<number_list> Disable a list of individual warnings.
-warnaserror[+|-] Treat all warnings as errors.
-warnaserror[+|-]:<number_list> Treat a list of warnings as errors.
-ruleset:<file> Specify a ruleset file that disables specific
diagnostics.
-errorlog:<file>[,version=<sarif_version>]
Specify a file to log all compiler and analyzer
diagnostics in SARIF format.
sarif_version:{1|2|2.1} Default is 1. 2 and 2.1
both mean SARIF version 2.1.0.
-reportanalyzer Report additional analyzer information, such as
execution time.
-skipanalyzers[+|-] Skip execution of diagnostic analyzers.
- LANGUAGE -
-define:<symbol_list> Declare global conditional compilation
symbol(s). symbol_list:name=value,...
(Short form: -d)
-imports:<import_list> Declare global Imports for namespaces in
referenced metadata files.
import_list:namespace,...
-langversion:? Display the allowed values for language version
-langversion:<string> Specify language version such as
`default` (latest major version), or
`latest` (latest version, including minor versions),
or specific versions like `14` or `15.3`
-optionexplicit[+|-] Require explicit declaration of variables.
-optioninfer[+|-] Allow type inference of variables.
-rootnamespace:<string> Specifies the root Namespace for all type
declarations.
-optionstrict[+|-] Enforce strict language semantics.
-optionstrict:custom Warn when strict language semantics are not
respected.
-optioncompare:binary Specifies binary-style string comparisons.
This is the default.
-optioncompare:text Specifies text-style string comparisons.
- MISCELLANEOUS -
-help Display this usage message. (Short form: -?)
-noconfig Do not auto-include VBC.RSP file.
-nologo Do not display compiler copyright banner.
-quiet Quiet output mode.
-verbose Display verbose messages.
-parallel[+|-] Concurrent build.
-version Display the compiler version number and exit.
- ADVANCED -
-baseaddress:<number> The base address for a library or module
(hex).
-checksumalgorithm:<alg> Specify algorithm for calculating source file
checksum stored in PDB. Supported values are:
SHA1 or SHA256 (default).
-codepage:<number> Specifies the codepage to use when opening
source files.
-delaysign[+|-] Delay-sign the assembly using only the public
portion of the strong name key.
-publicsign[+|-] Public-sign the assembly using only the public
portion of the strong name key.
-errorreport:<string> Specifies how to handle internal compiler
errors; must be prompt, send, none, or queue
(default).
-filealign:<number> Specify the alignment used for output file
sections.
-highentropyva[+|-] Enable high-entropy ASLR.
-keycontainer:<string> Specifies a strong name key container.
-keyfile:<file> Specifies a strong name key file.
-libpath:<path_list> List of directories to search for metadata
references. (Semi-colon delimited.)
-main:<class> Specifies the Class or Module that contains
Sub Main. It can also be a Class that
inherits from System.Windows.Forms.Form.
(Short form: -m)
-moduleassemblyname:<string> Name of the assembly which this module will
be a part of.
-netcf Target the .NET Compact Framework.
-nostdlib Do not reference standard libraries
(system.dll and VBC.RSP file).
-pathmap:<K1>=<V1>,<K2>=<V2>,...
Specify a mapping for source path names output by
the compiler.
-platform:<string> Limit which platforms this code can run on;
must be x86, x64, Itanium, arm, arm64
AnyCPU32BitPreferred or anycpu (default).
-preferreduilang Specify the preferred output language name.
-nosdkpath Disable searching the default SDK path for standard library assemblies.
-sdkpath:<path> Location of the .NET Framework SDK directory
(mscorlib.dll).
-subsystemversion:<version> Specify subsystem version of the output PE.
version:<number>[.<number>]
-utf8output[+|-] Emit compiler output in UTF8 character
encoding.
@<file> Insert command-line settings from a text file
-vbruntime[+|-|*] Compile with/without the default Visual Basic
runtime.
-vbruntime:<file> Compile with the alternate Visual Basic
runtime in <file>.
</source>
<target state="translated"> Visual Basic 編譯器選項
- 輸出檔案 -
-out:<file> 指定輸出檔名稱。
-target:exe 建立主控台應用程式 (預設)。
(簡短形式: -t)
-target:winexe 建立 Windows 應用程式。
-target:library 建立程式庫組件。
-target:module 建立可以新增至組件的
模組。
-target:appcontainerexe 建立可在 AppContainer 中執行的
Windows 應用程式。
-target:winmdobj 建立 Windows Metadata 中繼檔案
-doc[+|-] 產生 XML 文件檔。
-doc:<file> 產生 XML 文件檔至 <file>。
-refout:<file> 要產生的參考組件輸出
- 輸入檔 -
-addmodule:<file_list> 從指定的模組來參考中繼資料
-link:<file_list> 從指定的 Interop 組件內嵌
中繼資料。(簡短形式: -l)
-recurse:<wildcard> 根據萬用字元規格
來加入目前目錄和子目錄中的
所有檔案。
-reference:<file_list> 從指定的組件參考
中繼資料。(簡短形式: -r)
-analyzer:<file_list> 從此組件執行分析器
(簡短形式: -a)
-additionalfile:<file list> 不直接影響程式碼產生,
但分析器可能用於產生錯誤或警告的
其他檔案。
- 資源 -
-linkresource:<resinfo> 連結指定的檔案作為外部
組件資源。
resinfo:<file>[,<name>[,public|private]]
(簡短形式: -linkres)
-nowin32manifest 預設資訊清單不應內嵌於
輸出 PE 的資訊清單區段中。
-resource:<resinfo> 將指定的檔案新增為內嵌的
組件資源。
resinfo:<file>[,<name>[,public|private]]
(簡短形式: -res)
-win32icon:<file> 指定某一個 Win32 圖示檔 (.ico) 給
預設的 Win32 資源。
-win32manifest:<file> 提供的檔案內嵌於輸出 PE 的
資訊清單區段中。
-win32resource:<file> 指定 Win32 資源檔 (.res)。
- 程式碼產生 -
-optimize[+|-] 啟用最佳化。
-removeintchecks[+|-] 不檢查整數。預設為關閉。
-debug[+|-] 發出偵錯資訊。
-debug:full 發出完整偵錯資訊 (預設)。
-debug:pdbonly 發出完整偵錯資訊。
-debug:portable 發出跨平台的偵錯資訊。
-debug:embedded 對目標 .dll 或 .exe 發出
跨平台偵錯資訊。
-deterministic 產生確定性組件
(含模組版本 GUID 與時間戳記)
-refonly 產生取代主要輸出的參考組件
-instrument:TestCoverage 產生經檢測的組件,以收集
涵蓋範圍資訊
-sourcelink:<file> 要內嵌至 PDB 的來源連結資訊。
- 錯誤與警告 -
-nowarn 停用所有警告。
-nowarn:<number_list> 停用個別警告清單。
-warnaserror[+|-] 將所有警告視為錯誤。
-warnaserror[+|-]:<number_list> 將警告清單視為錯誤。
-ruleset:<file> 指定規則集檔案,以停用特定的
診斷。
-errorlog:<file>[,version=<sarif_version>]
指定檔案,以 SARIF 的格式記錄所有編譯器
與分析器診斷。
sarif_version:{1|2|2.1} 預設為 1、2 與 2.1
兩者皆表示 SARIF 2.1.0 版。
-reportanalyzer 回報其他分析器資訊,例如
執行時間。
-skipanalyzers[+|-] 略過診斷分析器的執行。
- 語言 -
-define:<symbol_list> 宣告全域條件式編譯的
符號。symbol_list:name=value,...
(簡短形式: -d)
-imports:<import_list> 在參考的中繼資料檔案中宣告命名空間的
全域匯入。
import_list:namespace,...
-langversion:? 顯示允許的語言版本值
-langversion:<string> 指定語言版本,例如
`default` (最新的主要版本) 或
`latest` (最新版本,包括次要版本)
或特定的版本,例如 `14` 或 `15.3`
-optionexplicit[+|-] 變數必須明確宣告。
-optioninfer[+|-] 允許變數的類型推斷。
-rootnamespace:<string> 指定所有類型宣告的
根命名空間。
-optionstrict[+|-] 強制採用嚴格的語意。
-optionstrict:custom 未遵守嚴格的語意時
發出警告。
-optioncompare:binary 採用二進位樣式來比較字串。
這是預設值。
-optioncompare:text 採用文字樣式來比較字串。
- 其他 -
-help 顯示此使用方式訊息。(簡短形式: -?)
-noconfig 不要自動納入 VBC.RSP 檔。
-nologo 不要顯示編譯器著作權橫幅。
-quiet 無對話輸出模式。
-verbose 顯示詳細訊息。
-parallel[+|-] 並行組建。
-version 顯示編譯器版本編號然後結束。
- 進階 -
-baseaddress:<number> 程式庫或模組的基底位置
(十六進位)。
-checksumalgorithm:<alg> 指定演算法,以計算儲存於 PDB 的
來源檔案總和檢查碼。支援的值有:
SHA1 或 SHA256 (預設)。
-codepage:<number> 指定開啟原始程式檔時所要使用的
字碼頁。
-delaysign[+|-] 僅使用強式名稱金鑰的公開
部分延遲簽署組件。
-publicsign[+|-] 僅使用強式名稱金鑰的公開
部分公開簽署組件。
-errorreport:<string> 指定如何處理內部編譯器
錯誤;必須是 prompt、send、none 或 queue
(預設)。
-filealign:<number> 指定用於輸出檔案區段的對齊
方式。
-highentropyva[+|-] 啟用高熵 ASLR。
-keycontainer:<string> 指定強式名稱金鑰容器。
-keyfile:<file> 指定強式名稱金鑰檔。
-libpath:<path_list> 搜尋中繼資料參考的
目錄清單 (以分號分隔)。
-main:<class> 指定包含 Sub Main 的
Class 或 Module。也可以是繼承自
System.Windows.Forms.Form 的 Class。
(簡短形式: -m)
-moduleassemblyname:<string> 這個模組將成為其一部分的
組件名稱。
-netcf 以 .NET Compact Framework 為目標。
-nostdlib 不要參考標準程式庫
(system.dll 與 VBC.RSP 檔)。
-pathmap:<K1>=<V1>,<K2>=<V2>,...
指定由編譯器輸出的來源路徑名稱對應
對應。
-platform:<string> 限制這個程式碼可以在哪些平台執行;
必須是 x86、x64、Itanium、arm、arm64
AnyCPU32BitPreferred 或 anycpu (預設)。
-preferreduilang 指定慣用的輸出語言名稱。
-nosdkpath 禁止搜尋預設 SDK 路徑的標準程式庫組件。
-sdkpath:<path> .NET Framework SDK 目錄
(mscorlib.dll) 的位置。
-subsystemversion:<version> 指定輸出 PE 的子系統版本。
版本:<number>[.<number>]
-utf8output[+|-] 以 UTF8 字元編碼發出編譯器
輸出。
@<file> 從文字檔插入命令列設定
-vbruntime[+|-|*] 使用 (或不使用) 預設 Visual Basic
執行階段編譯。
-vbruntime:<file> 使用 <file> 中的其他 Visual Basic
執行階段編譯。
</target>
<note />
</trans-unit>
<trans-unit id="ThereAreNoFunctionPointerTypesInVB">
<source>There are no function pointer types in VB.</source>
<target state="translated">VB 中沒有函式指標類型。</target>
<note />
</trans-unit>
<trans-unit id="ThereAreNoNativeIntegerTypesInVB">
<source>There are no native integer types in VB.</source>
<target state="translated">VB 中沒有任何原生整數類型。</target>
<note />
</trans-unit>
<trans-unit id="Trees0">
<source>trees({0})</source>
<target state="translated">trees({0})</target>
<note />
</trans-unit>
<trans-unit id="TreesMustHaveRootNode">
<source>trees({0}) must have root node with SyntaxKind.CompilationUnit.</source>
<target state="translated">trees({0}) 必須要有具備 SyntaxKind.CompilationUnit 的根節點。</target>
<note />
</trans-unit>
<trans-unit id="CannotAddCompilerSpecialTree">
<source>Cannot add compiler special tree</source>
<target state="translated">無法加入編譯器特殊樹狀結構</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTreeAlreadyPresent">
<source>Syntax tree already present</source>
<target state="translated">語法樹狀結構已存在</target>
<note />
</trans-unit>
<trans-unit id="SubmissionCanHaveAtMostOneSyntaxTree">
<source>Submission can have at most one syntax tree.</source>
<target state="translated">提交最多可以有一個語法樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="CannotRemoveCompilerSpecialTree">
<source>Cannot remove compiler special tree</source>
<target state="translated">無法移除編譯器特殊樹狀結構</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTreeNotFoundToRemove">
<source>SyntaxTree '{0}' not found to remove</source>
<target state="translated">找不到要移除的語法樹狀結構 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="TreeMustHaveARootNodeWithCompilationUnit">
<source>Tree must have a root node with SyntaxKind.CompilationUnit</source>
<target state="translated">樹狀結構必須要有具備 SyntaxKind.CompilationUnit 的根節點</target>
<note />
</trans-unit>
<trans-unit id="CompilationVisualBasic">
<source>Compilation (Visual Basic): </source>
<target state="translated">編譯 (Visual Basic): </target>
<note />
</trans-unit>
<trans-unit id="NodeIsNotWithinSyntaxTree">
<source>Node is not within syntax tree</source>
<target state="translated">Node 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="CantReferenceCompilationFromTypes">
<source>Can't reference compilation of type '{0}' from {1} compilation.</source>
<target state="translated">無法從 {1} 編譯來參考類型為 '{0}' 的編譯</target>
<note />
</trans-unit>
<trans-unit id="PositionOfTypeParameterTooLarge">
<source>position of type parameter too large</source>
<target state="translated">類型參數的位置太大</target>
<note />
</trans-unit>
<trans-unit id="AssociatedTypeDoesNotHaveTypeParameters">
<source>Associated type does not have type parameters</source>
<target state="translated">相關聯的類型沒有類型參數</target>
<note />
</trans-unit>
<trans-unit id="IDS_FunctionReturnType">
<source>function return type</source>
<target state="translated">函式傳回類型</target>
<note />
</trans-unit>
<trans-unit id="TypeArgumentCannotBeNothing">
<source>Type argument cannot be Nothing</source>
<target state="translated">類型引數不可為 Nothing</target>
<note />
</trans-unit>
<trans-unit id="WRN_AnalyzerReferencesFramework">
<source>The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported.</source>
<target state="translated">包含類型 '{1}' 的組件 '{0}' 參考了 .NET Framework,此情形不受支援。</target>
<note>{1} is the type that was loaded, {0} is the containing assembly.</note>
</trans-unit>
<trans-unit id="WRN_AnalyzerReferencesFramework_Title">
<source>The loaded assembly references .NET Framework, which is not supported.</source>
<target state="translated">載入的組件參考了 .NET Framework,此情形不受支援。</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName">
<source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName_Title">
<source>The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential">
<source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential_Title">
<source>The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.</target>
<note />
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringGeneration">
<source>Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source>
<target state="translated">產生器 '{0}' 無法產生來源。其不會提供給輸出,並可能導致編譯錯誤。例外狀況的類型為 '{1}',訊息為 '{2}'</target>
<note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringGeneration_Description">
<source>Generator threw the following exception:
'{0}'.</source>
<target state="translated">產生器擲回了下列例外狀況:
'{0}'。</target>
<note>{0} is the string representation of the exception that was thrown.</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringGeneration_Title">
<source>Generator failed to generate source.</source>
<target state="translated">產生器無法產生來源。</target>
<note />
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringInitialization">
<source>Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source>
<target state="translated">產生器 '{0}' 無法初始化。其不會提供給輸出,並可能導致編譯錯誤。例外狀況的類型為 '{1}',訊息為 '{2}'</target>
<note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringInitialization_Description">
<source>Generator threw the following exception:
'{0}'.</source>
<target state="translated">產生器擲回了下列例外狀況:
'{0}'。</target>
<note>{0} is the string representation of the exception that was thrown.</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringInitialization_Title">
<source>Generator failed to initialize.</source>
<target state="translated">產生器無法初始化。</target>
<note />
</trans-unit>
<trans-unit id="WrongNumberOfTypeArguments">
<source>Wrong number of type arguments</source>
<target state="translated">類型引數的數目錯誤</target>
<note />
</trans-unit>
<trans-unit id="ERR_FileNotFound">
<source>file '{0}' could not be found</source>
<target state="translated">找不到檔案 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoResponseFile">
<source>unable to open response file '{0}'</source>
<target state="translated">無法開啟回應檔 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentRequired">
<source>option '{0}' requires '{1}'</source>
<target state="translated">選項 '{0}' 需要 '{1}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_SwitchNeedsBool">
<source>option '{0}' can be followed only by '+' or '-'</source>
<target state="translated">選項 '{0}' 之後只可接著 '+' 或 '-'</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSwitchValue">
<source>the value '{1}' is invalid for option '{0}'</source>
<target state="translated">值 '{1}' 對選項 '{0}' 無效</target>
<note />
</trans-unit>
<trans-unit id="ERR_MutuallyExclusiveOptions">
<source>Compilation options '{0}' and '{1}' can't both be specified at the same time.</source>
<target state="translated">不得同時指定編輯選項 '{0}' 與 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadUILang">
<source>The language name '{0}' is invalid.</source>
<target state="translated">語言名稱 '{0}' 無效。</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadUILang_Title">
<source>The language name for /preferreduilang is invalid</source>
<target state="translated">/preferreduilang 的語言名稱無效</target>
<note />
</trans-unit>
<trans-unit id="ERR_VBCoreNetModuleConflict">
<source>The options /vbruntime* and /target:module cannot be combined.</source>
<target state="translated">無法結合選項 /vbruntime* 和 /target:module。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidFormatForGuidForOption">
<source>Command-line syntax error: Invalid Guid format '{0}' for option '{1}'</source>
<target state="translated">命令列語法錯誤: 選項 '{1}' 的 Guid 格式 '{0}' 無效</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingGuidForOption">
<source>Command-line syntax error: Missing Guid for option '{1}'</source>
<target state="translated">命令列語法錯誤: 遺漏選項 '{1}' 的 Guid</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadChecksumAlgorithm">
<source>Algorithm '{0}' is not supported</source>
<target state="translated">不支援演算法 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadSwitch">
<source>unrecognized option '{0}'; ignored</source>
<target state="translated">無法辨認的選項 '{0}'; 已經忽略</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadSwitch_Title">
<source>Unrecognized command-line option</source>
<target state="translated">無法辨認的命令列選項</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSources">
<source>no input sources specified</source>
<target state="translated">未指定輸入來源</target>
<note />
</trans-unit>
<trans-unit id="WRN_FileAlreadyIncluded">
<source>source file '{0}' specified multiple times</source>
<target state="translated">已經多次指定原始程式檔 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="WRN_FileAlreadyIncluded_Title">
<source>Source file specified multiple times</source>
<target state="translated">已指定多次原始程式檔</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOpenFileWrite">
<source>can't open '{0}' for writing: {1}</source>
<target state="translated">無法開啟 '{0}' 進行寫入: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadCodepage">
<source>code page '{0}' is invalid or not installed</source>
<target state="translated">字碼頁 '{0}' 無效或尚未安裝</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryFile">
<source>the file '{0}' is not a text file</source>
<target state="translated">檔案 '{0}' 不是文字檔</target>
<note />
</trans-unit>
<trans-unit id="ERR_LibNotFound">
<source>could not find library '{0}'</source>
<target state="translated">找不到程式庫 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetadataReferencesNotSupported">
<source>Metadata references not supported.</source>
<target state="translated">不支援中繼資料參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IconFileAndWin32ResFile">
<source>cannot specify both /win32icon and /win32resource</source>
<target state="translated">無法同時指定 /win32icon 和 /win32resource</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoConfigInResponseFile">
<source>ignoring /noconfig option because it was specified in a response file</source>
<target state="translated">忽略 /noconfig 選項,因為在回應檔中已指定</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoConfigInResponseFile_Title">
<source>Ignoring /noconfig option because it was specified in a response file</source>
<target state="translated">因為在回應檔中已指定 /noconfig 選項,所以將會忽略該選項</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidWarningId">
<source>warning number '{0}' for the option '{1}' is either not configurable or not valid</source>
<target state="translated">選項 '{1}' 的警告編號 '{0}' 無法設定或其無效</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidWarningId_Title">
<source>Warning number is either not configurable or not valid</source>
<target state="translated">警告編號可能無法設定或是無效</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSourcesOut">
<source>cannot infer an output file name from resource only input files; provide the '/out' option</source>
<target state="translated">無法從只有輸入檔的資源推斷輸出檔名,請提供 '/out' 選項</target>
<note />
</trans-unit>
<trans-unit id="ERR_NeedModule">
<source>the /moduleassemblyname option may only be specified when building a target of type 'module'</source>
<target state="translated">/moduleassemblyname 選項只能在建置 'module' 類型的目標時指定</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyName">
<source>'{0}' is not a valid value for /moduleassemblyname</source>
<target state="translated">'{0}' 不是 /moduleassemblyname 的有效值</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictingManifestSwitches">
<source>Error embedding Win32 manifest: Option /win32manifest conflicts with /nowin32manifest.</source>
<target state="translated">內嵌 Win32 資訊清單時發生錯誤: 選項 /win32manifest 與 /nowin32manifest 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IgnoreModuleManifest">
<source>Option /win32manifest ignored. It can be specified only when the target is an assembly.</source>
<target state="translated">已忽略選項 /win32manifest。只能在目標為組件時指定此選項。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IgnoreModuleManifest_Title">
<source>Option /win32manifest ignored</source>
<target state="translated">已忽略 /win32manifest 選項</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidInNamespace">
<source>Statement is not valid in a namespace.</source>
<target state="translated">命名空間中的陳述式無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UndefinedType1">
<source>Type '{0}' is not defined.</source>
<target state="translated">類型 '{0}' 未定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingNext">
<source>'Next' expected.</source>
<target state="translated">'必須是 'Next'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalCharConstant">
<source>Character constant must contain exactly one character.</source>
<target state="translated">字元常數必須剛好包含一個字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedAssemblyEvent3">
<source>Reference required to assembly '{0}' containing the definition for event '{1}'. Add one to your project.</source>
<target state="translated">組件 '{0}' (包含事件 '{1}' 的定義) 需要參考。請在您的專案中加入一個參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedModuleEvent3">
<source>Reference required to module '{0}' containing the definition for event '{1}'. Add one to your project.</source>
<target state="translated">模組 '{0}' (包含事件 '{1}' 的定義) 需要參考。請在您的專案中加入一個參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbExpectedEndIf">
<source>'#If' block must end with a matching '#End If'.</source>
<target state="translated">'#If' 區塊之後必須搭配相對應的 '#End If'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbNoMatchingIf">
<source>'#ElseIf', '#Else', or '#End If' must be preceded by a matching '#If'.</source>
<target state="translated">'#ElseIf'、'#Else' 或 '#End If' 之前必須搭配相對應的 '#If'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbBadElseif">
<source>'#ElseIf' must be preceded by a matching '#If' or '#ElseIf'.</source>
<target state="translated">'#ElseIf' 之前必須搭配相對應的 '#If' 或 '#ElseIf'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromRestrictedType1">
<source>Inheriting from '{0}' is not valid.</source>
<target state="translated">從 '{0}' 繼承無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvOutsideProc">
<source>Labels are not valid outside methods.</source>
<target state="translated">方法外的標籤無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateCantImplement">
<source>Delegates cannot implement interface methods.</source>
<target state="translated">委派 (Delegate) 無法實作介面方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateCantHandleEvents">
<source>Delegates cannot handle events.</source>
<target state="translated">委派 (Delegate) 無法處理事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsOperatorRequiresReferenceTypes1">
<source>'Is' operator does not accept operands of type '{0}'. Operands must be reference or nullable types.</source>
<target state="translated">'Is' 運算子不接受類型 '{0}' 的運算元。運算元必須是參考或可為 Null 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOfRequiresReferenceType1">
<source>'TypeOf ... Is' requires its left operand to have a reference type, but this operand has the value type '{0}'.</source>
<target state="translated">'TypeOf ... Is' 的左運算元必須是參考類型,但此運算元是實值類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyHasSet">
<source>Properties declared 'ReadOnly' cannot have a 'Set'.</source>
<target state="translated">宣告為 'ReadOnly' 的屬性無法擁有 'Set'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_WriteOnlyHasGet">
<source>Properties declared 'WriteOnly' cannot have a 'Get'.</source>
<target state="translated">宣告為 'WriteOnly' 的屬性無法擁有 'Get'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideProc">
<source>Statement is not valid inside a method.</source>
<target state="translated">方法內的陳述式無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideBlock">
<source>Statement is not valid inside '{0}' block.</source>
<target state="translated">'{0}' 區塊內的陳述式無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnexpectedExpressionStatement">
<source>Expression statement is only allowed at the end of an interactive submission.</source>
<target state="translated">只有在互動提交結束時,才可出現運算式陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndProp">
<source>Property missing 'End Property'.</source>
<target state="translated">屬性遺漏了 'End Property'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndSubExpected">
<source>'End Sub' expected.</source>
<target state="translated">'必須有 'End Sub'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndFunctionExpected">
<source>'End Function' expected.</source>
<target state="translated">'必須有 'End Function'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbElseNoMatchingIf">
<source>'#Else' must be preceded by a matching '#If' or '#ElseIf'.</source>
<target state="translated">'#Else' 之前必須搭配相對應的 '#If' 或 '#ElseIf'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantRaiseBaseEvent">
<source>Derived classes cannot raise base class events.</source>
<target state="translated">衍生的類別無法引發基底類別事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryWithoutCatchOrFinally">
<source>Try must have at least one 'Catch' or a 'Finally'.</source>
<target state="translated">Try 至少必須有一個 'Catch' 或 'Finally'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventsCantBeFunctions">
<source>Events cannot have a return type.</source>
<target state="translated">事件不可以有傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndBrack">
<source>Bracketed identifier is missing closing ']'.</source>
<target state="translated">有括號的識別項遺漏右括號 ']'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_Syntax">
<source>Syntax error.</source>
<target state="translated">語法錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_Overflow">
<source>Overflow.</source>
<target state="translated">溢位。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalChar">
<source>Character is not valid.</source>
<target state="translated">字元無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StdInOptionProvidedButConsoleInputIsNotRedirected">
<source>stdin argument '-' is specified, but input has not been redirected from the standard input stream.</source>
<target state="translated">已指定 stdin 引數 '-',但尚未從標準輸入資料流重新導向輸入。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsObjectOperand1">
<source>Option Strict On prohibits operands of type Object for operator '{0}'.</source>
<target state="translated">Option Strict 為 On 時,禁止為運算子 '{0}' 使用 Object 類型的運算元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopControlMustNotBeProperty">
<source>Loop control variable cannot be a property or a late-bound indexed array.</source>
<target state="translated">迴圈控制變數不可以是屬性或晚期繫結索引陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodBodyNotAtLineStart">
<source>First statement of a method body cannot be on the same line as the method declaration.</source>
<target state="translated">方法主體的第一個陳述式不可以和方法宣告在同一行上。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MaximumNumberOfErrors">
<source>Maximum number of errors has been exceeded.</source>
<target state="translated">已超過錯誤上限數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfKeywordNotInInstanceMethod1">
<source>'{0}' is valid only within an instance method.</source>
<target state="translated">'{0}' 只在執行個體方法中有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfKeywordFromStructure1">
<source>'{0}' is not valid within a structure.</source>
<target state="translated">'{0}' 在結構中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeConstructor1">
<source>Attribute constructor has a parameter of type '{0}', which is not an integral, floating-point or Enum type or one of Object, Char, String, Boolean, System.Type or 1-dimensional array of these types.</source>
<target state="translated">屬性建構函式的參數類型為 '{0}',其非整數、浮點或列舉類型,也不是 Object、Char、String、Boolean、System.Type 或這些類型的一維陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayWithOptArgs">
<source>Method cannot have both a ParamArray and Optional parameters.</source>
<target state="translated">方法不可以同時有 ParamArray 和 Optional 引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedArray1">
<source>'{0}' statement requires an array.</source>
<target state="translated">'{0}' 陳述式需要陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayNotArray">
<source>ParamArray parameter must be an array.</source>
<target state="translated">ParamArray 參數必須為陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayRank">
<source>ParamArray parameter must be a one-dimensional array.</source>
<target state="translated">ParamArray 參數必須是一維陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayRankLimit">
<source>Array exceeds the limit of 32 dimensions.</source>
<target state="translated">陣列超過 32 個維度的限制。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AsNewArray">
<source>Arrays cannot be declared with 'New'.</source>
<target state="translated">不可使用 'New' 宣告陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyArgs1">
<source>Too many arguments to '{0}'.</source>
<target state="translated">'{0}' 的引數太多。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedCase">
<source>Statements and labels are not valid between 'Select Case' and first 'Case'.</source>
<target state="translated">在 'Select Case' 與第一個 'Case' 間,不可以使用陳述式和標籤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredConstExpr">
<source>Constant expression is required.</source>
<target state="translated">必須是常數運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredConstConversion2">
<source>Conversion from '{0}' to '{1}' cannot occur in a constant expression.</source>
<target state="translated">常數運算式中不可進行從 '{0}' 到 '{1}' 的轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMe">
<source>'Me' cannot be the target of an assignment.</source>
<target state="translated">'Me' 不可以是指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyAssignment">
<source>'ReadOnly' variable cannot be the target of an assignment.</source>
<target state="translated">'ReadOnly' 變數不可以是指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitSubOfFunc">
<source>'Exit Sub' is not valid in a Function or Property.</source>
<target state="translated">'Function 或 Property 中的 'Exit Sub' 無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitPropNot">
<source>'Exit Property' is not valid in a Function or Sub.</source>
<target state="translated">'Function 或 Sub 中的 'Exit Property' 無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitFuncOfSub">
<source>'Exit Function' is not valid in a Sub or Property.</source>
<target state="translated">'Sub 或 Property 中的 'Exit Function' 無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LValueRequired">
<source>Expression is a value and therefore cannot be the target of an assignment.</source>
<target state="translated">運算式是一個數值,不可以是指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForIndexInUse1">
<source>For loop control variable '{0}' already in use by an enclosing For loop.</source>
<target state="translated">For 迴圈控制變數 '{0}' 已由封閉式 For 迴圈所使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NextForMismatch1">
<source>Next control variable does not match For loop control variable '{0}'.</source>
<target state="translated">Next 控制變數與 For 迴圈控制變數 '{0}' 不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CaseElseNoSelect">
<source>'Case Else' can only appear inside a 'Select Case' statement.</source>
<target state="translated">'Case Else' 只可出現在 'Select Case' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CaseNoSelect">
<source>'Case' can only appear inside a 'Select Case' statement.</source>
<target state="translated">'Case' 只可出現在 'Select Case' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantAssignToConst">
<source>Constant cannot be the target of an assignment.</source>
<target state="translated">常數不可以當做指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedSubscript">
<source>Named arguments are not valid as array subscripts.</source>
<target state="translated">具名引數不可以當做陣列註標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndIf">
<source>'If' must end with a matching 'End If'.</source>
<target state="translated">'If' 之後必須搭配相對應的 'End If'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndWhile">
<source>'While' must end with a matching 'End While'.</source>
<target state="translated">'While' 之後必須搭配相對應的 'End While'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLoop">
<source>'Do' must end with a matching 'Loop'.</source>
<target state="translated">'Do' 之後必須搭配相對應的 'Loop'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedNext">
<source>'For' must end with a matching 'Next'.</source>
<target state="translated">'For' 之後必須搭配相對應的 'Next'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndWith">
<source>'With' must end with a matching 'End With'.</source>
<target state="translated">'With' 之後必須搭配相對應的 'End With'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ElseNoMatchingIf">
<source>'Else' must be preceded by a matching 'If' or 'ElseIf'.</source>
<target state="translated">'Else' 之前必須搭配相對應的 'If' 或 'ElseIf'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndIfNoMatchingIf">
<source>'End If' must be preceded by a matching 'If'.</source>
<target state="translated">'End If' 之前必須搭配相對應的 'If'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndSelectNoSelect">
<source>'End Select' must be preceded by a matching 'Select Case'.</source>
<target state="translated">'End Select' 之前必須搭配相對應的 'Select Case'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitDoNotWithinDo">
<source>'Exit Do' can only appear inside a 'Do' statement.</source>
<target state="translated">'Exit Do' 只可以在 'Do' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndWhileNoWhile">
<source>'End While' must be preceded by a matching 'While'.</source>
<target state="translated">'End While' 之前必須搭配相對應的 'While'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopNoMatchingDo">
<source>'Loop' must be preceded by a matching 'Do'.</source>
<target state="translated">'Loop' 之前必須搭配相對應的 'Do'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NextNoMatchingFor">
<source>'Next' must be preceded by a matching 'For'.</source>
<target state="translated">'Next' 之前必須搭配相對應的 'For'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndWithWithoutWith">
<source>'End With' must be preceded by a matching 'With'.</source>
<target state="translated">'End With' 之前必須搭配相對應的 'With'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultiplyDefined1">
<source>Label '{0}' is already defined in the current method.</source>
<target state="translated">標籤 '{0}' 已定義在目前的方法中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndSelect">
<source>'Select Case' must end with a matching 'End Select'.</source>
<target state="translated">'Select Case' 的結尾必須是相對應的 'End Select'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitForNotWithinFor">
<source>'Exit For' can only appear inside a 'For' statement.</source>
<target state="translated">'Exit For' 只可以在 'For' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitWhileNotWithinWhile">
<source>'Exit While' can only appear inside a 'While' statement.</source>
<target state="translated">'Exit While' 只可以在 'While' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyProperty1">
<source>'ReadOnly' property '{0}' cannot be the target of an assignment.</source>
<target state="translated">'ReadOnly' 屬性 '{0}' 不可為指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitSelectNotWithinSelect">
<source>'Exit Select' can only appear inside a 'Select' statement.</source>
<target state="translated">'Exit Select' 只可以在 'Select' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BranchOutOfFinally">
<source>Branching out of a 'Finally' is not valid.</source>
<target state="translated">Finally' 的分支無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QualNotObjectRecord1">
<source>'!' requires its left operand to have a type parameter, class or interface type, but this operand has the type '{0}'.</source>
<target state="translated">'!' 左側的運算元必須是類型參數、類別或介面類型,但此運算元是 '{0}' 類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooFewIndices">
<source>Number of indices is less than the number of dimensions of the indexed array.</source>
<target state="translated">索引數目少於索引陣列維度的數目。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyIndices">
<source>Number of indices exceeds the number of dimensions of the indexed array.</source>
<target state="translated">索引數目超過索引陣列維度的數目。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EnumNotExpression1">
<source>'{0}' is an Enum type and cannot be used as an expression.</source>
<target state="translated">'{0}' 是列舉類型,無法用做為運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeNotExpression1">
<source>'{0}' is a type and cannot be used as an expression.</source>
<target state="translated">'{0}' 為類型,無法用做為運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassNotExpression1">
<source>'{0}' is a class type and cannot be used as an expression.</source>
<target state="translated">'{0}' 是類別類型,無法用做為運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructureNotExpression1">
<source>'{0}' is a structure type and cannot be used as an expression.</source>
<target state="translated">'{0}' 是結構類型,無法用做為運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceNotExpression1">
<source>'{0}' is an interface type and cannot be used as an expression.</source>
<target state="translated">'{0}' 是介面類型,無法用做為運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamespaceNotExpression1">
<source>'{0}' is a namespace and cannot be used as an expression.</source>
<target state="translated">'{0}' 是命名空間,無法用做為運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadNamespaceName1">
<source>'{0}' is not a valid name and cannot be used as the root namespace name.</source>
<target state="translated">'{0}' 不是有效的名稱,且無法用做為根命名空間名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlPrefixNotExpression">
<source>'{0}' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object.</source>
<target state="translated">'{0}' 為 XML 前置詞,不可用做為運算式。請使用 GetXmlNamespace 運算子建立命名空間物件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleExtends">
<source>'Inherits' can appear only once within a 'Class' statement and can only specify one class.</source>
<target state="translated">'Inherits' 只可以在 'Class' 陳述式中出現一次,並且只能指定一個類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropMustHaveGetSet">
<source>Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.</source>
<target state="translated">沒有 'ReadOnly' 或 'WriteOnly' 規範的屬性必須提供 'Get' 和 'Set'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_WriteOnlyHasNoWrite">
<source>'WriteOnly' property must provide a 'Set'.</source>
<target state="translated">'WriteOnly' 屬性必須提供 'Set'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyHasNoGet">
<source>'ReadOnly' property must provide a 'Get'.</source>
<target state="translated">'ReadOnly' 屬性必須提供 'Get'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttribute1">
<source>Attribute '{0}' is not valid: Incorrect argument value.</source>
<target state="translated">屬性 '{0}' 無效: 引數值不正確。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LabelNotDefined1">
<source>Label '{0}' is not defined.</source>
<target state="translated">標籤 '{0}' 未定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ErrorCreatingWin32ResourceFile">
<source>Error creating Win32 resources: {0}</source>
<target state="translated">建立 Win32 資源時發生錯誤: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnableToCreateTempFile">
<source>Cannot create temporary file: {0}</source>
<target state="translated">無法建立暫存檔: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNewCall2">
<source>First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' does not have an accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">此 'Sub New' 的第一個陳述式,必須呼叫 'MyBase.New' 或 'MyClass.New',因為 '{1}' 的基底類別 '{0}' 沒有不使用引數即可呼叫的可存取 'Sub New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnimplementedMember3">
<source>{0} '{1}' must implement '{2}' for interface '{3}'.</source>
<target state="translated">{0} '{1}' 必須為介面 '{3}' 實作 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadWithRef">
<source>Leading '.' or '!' can only appear inside a 'With' statement.</source>
<target state="translated">前置的 '.' 或 '!' 只可以在 'With' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAccessCategoryUsed">
<source>Only one of 'Public', 'Private', 'Protected', 'Friend', 'Protected Friend', or 'Private Protected' can be specified.</source>
<target state="translated">只可指定 'Public'、'Private'、'Protected'、'Friend'、'Protected Friend' 或 'Private Protected' 其中之一。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateModifierCategoryUsed">
<source>Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.</source>
<target state="translated">只可以指定 'NotOverridable'、'MustOverride' 或 'Overridable' 其中之一。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateSpecifier">
<source>Specifier is duplicated.</source>
<target state="translated">重複規範。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeConflict6">
<source>{0} '{1}' and {2} '{3}' conflict in {4} '{5}'.</source>
<target state="translated">{0} '{1}' 和 {2} '{3}' 在 {4} '{5}' 中互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedTypeKeyword">
<source>Keyword does not name a type.</source>
<target state="translated">關鍵字無法為類型命名。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtraSpecifiers">
<source>Specifiers valid only at the beginning of a declaration.</source>
<target state="translated">規範只在宣告的開頭有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedType">
<source>Type expected.</source>
<target state="translated">應有類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidUseOfKeyword">
<source>Keyword is not valid as an identifier.</source>
<target state="translated">以關鍵字做為識別項無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndEnum">
<source>'End Enum' must be preceded by a matching 'Enum'.</source>
<target state="translated">'End Enum' 之前必須搭配相對應的 'Enum'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndEnum">
<source>'Enum' must end with a matching 'End Enum'.</source>
<target state="translated">'Enum' 之後必須搭配相對應的 'End Enum'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDeclaration">
<source>Declaration expected.</source>
<target state="translated">應有宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayMustBeLast">
<source>End of parameter list expected. Cannot define parameters after a paramarray parameter.</source>
<target state="translated">必須是參數清單的結尾。無法在 paramarray 參數之後定義參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SpecifiersInvalidOnInheritsImplOpt">
<source>Specifiers and attributes are not valid on this statement.</source>
<target state="translated">在此陳述式上的規範和屬性無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSpecifier">
<source>Expected one of 'Dim', 'Const', 'Public', 'Private', 'Protected', 'Friend', 'Shadows', 'ReadOnly' or 'Shared'.</source>
<target state="translated">必須是 'Dim'、'Const'、'Public'、'Private'、'Protected'、'Friend'、'Shadows'、'ReadOnly' 或 'Shared' 其中之一。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedComma">
<source>Comma expected.</source>
<target state="translated">必須有逗號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAs">
<source>'As' expected.</source>
<target state="translated">'必須有 'As'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedRparen">
<source>')' expected.</source>
<target state="translated">'必須有 ')'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLparen">
<source>'(' expected.</source>
<target state="translated">'必須有 '('。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidNewInType">
<source>'New' is not valid in this context.</source>
<target state="translated">'New' 在此內容中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedExpression">
<source>Expression expected.</source>
<target state="translated">應有運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedOptional">
<source>'Optional' expected.</source>
<target state="translated">'必須有 'Optional'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIdentifier">
<source>Identifier expected.</source>
<target state="translated">應有識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIntLiteral">
<source>Integer constant expected.</source>
<target state="translated">必須有整數常數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEOS">
<source>End of statement expected.</source>
<target state="translated">必須有陳述式結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedForOptionStmt">
<source>'Option' must be followed by 'Compare', 'Explicit', 'Infer', or 'Strict'.</source>
<target state="translated">'Option' 必須在 'Compare'、'Explicit'、'Infer' 或 'Strict' 之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionCompare">
<source>'Option Compare' must be followed by 'Text' or 'Binary'.</source>
<target state="translated">'Option Compare' 必須在 'Text' 或 'Binary' 之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedOptionCompare">
<source>'Compare' expected.</source>
<target state="translated">'必須有 'Compare'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowImplicitObject">
<source>Option Strict On requires all variable declarations to have an 'As' clause.</source>
<target state="translated">Option Strict 為 On 時,對於所有變數宣告,都要求要有 'As' 子句。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsImplicitProc">
<source>Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.</source>
<target state="translated">Option Strict 為 On 時,對所有函式、屬性及運算子宣告,都要求要有 'As' 子句。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsImplicitArgs">
<source>Option Strict On requires that all method parameters have an 'As' clause.</source>
<target state="translated">Option Strict 為 On 時,對所有方法參數,都要求要有 'As' 子句。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidParameterSyntax">
<source>Comma or ')' expected.</source>
<target state="translated">必須是逗號或 ')'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSubFunction">
<source>'Sub' or 'Function' expected.</source>
<target state="translated">'必須有 'Sub' 或 'Function'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedStringLiteral">
<source>String constant expected.</source>
<target state="translated">必須有字串常數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingLibInDeclare">
<source>'Lib' expected.</source>
<target state="translated">'必須有 'Lib'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateNoInvoke1">
<source>Delegate class '{0}' has no Invoke method, so an expression of this type cannot be the target of a method call.</source>
<target state="translated">委派類別 '{0}' 沒有 Invoke 方法,因此這個類型的運算式不可成為方法呼叫的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingIsInTypeOf">
<source>'Is' expected.</source>
<target state="translated">'必須是 'Is'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateOption1">
<source>'Option {0}' statement can only appear once per file.</source>
<target state="translated">'每個檔案只能出現一次 'Option {0}' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantInherit">
<source>'Inherits' not valid in Modules.</source>
<target state="translated">'Inherits' 在模組中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantImplement">
<source>'Implements' not valid in Modules.</source>
<target state="translated">'Implements' 在模組中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadImplementsType">
<source>Implemented type must be an interface.</source>
<target state="translated">實作類型必須是介面。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadConstFlags1">
<source>'{0}' is not valid on a constant declaration.</source>
<target state="translated">'{0}' 在常數宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadWithEventsFlags1">
<source>'{0}' is not valid on a WithEvents declaration.</source>
<target state="translated">'{0}' 在 WithEvents 宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDimFlags1">
<source>'{0}' is not valid on a member variable declaration.</source>
<target state="translated">'{0}' 在成員變數宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateParamName1">
<source>Parameter already declared with name '{0}'.</source>
<target state="translated">參數已使用名稱 '{0}' 進行宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopDoubleCondition">
<source>'Loop' cannot have a condition if matching 'Do' has one.</source>
<target state="translated">'如果對稱的 'Do' 有條件,'Loop' 就不可有條件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedRelational">
<source>Relational operator expected.</source>
<target state="translated">必須有關係運算子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedExitKind">
<source>'Exit' must be followed by 'Sub', 'Function', 'Property', 'Do', 'For', 'While', 'Select', or 'Try'.</source>
<target state="translated">'Exit' 必須在 'Sub'、'Function'、'Property'、'Do'、'For'、'While'、'Select' 或 'Try' 之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedNamedArgumentInAttributeList">
<source>Named argument expected.</source>
<target state="translated">必須是具名引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgumentSpecificationBeforeFixedArgumentInLateboundInvocation">
<source>Named argument specifications must appear after all fixed arguments have been specified in a late bound invocation.</source>
<target state="translated">必須在所有固定引數皆已在晚期繫結引動過程中指定之後,具名引數規格才可出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedNamedArgument">
<source>Named argument expected. Please use language version {0} or greater to use non-trailing named arguments.</source>
<target state="translated">必須是具名引數。請使用語言版本 {0} 或更高版本,以使用非後置的具名引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadMethodFlags1">
<source>'{0}' is not valid on a method declaration.</source>
<target state="translated">'{0}' 在方法宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadEventFlags1">
<source>'{0}' is not valid on an event declaration.</source>
<target state="translated">'{0}' 在事件宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDeclareFlags1">
<source>'{0}' is not valid on a Declare.</source>
<target state="translated">'{0}' 在 Declare 中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadLocalConstFlags1">
<source>'{0}' is not valid on a local constant declaration.</source>
<target state="translated">'{0}' 在區域常數宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadLocalDimFlags1">
<source>'{0}' is not valid on a local variable declaration.</source>
<target state="translated">'{0}' 在區域變數宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedConditionalDirective">
<source>'If', 'ElseIf', 'Else', 'Const', 'Region', 'ExternalSource', 'ExternalChecksum', 'Enable', 'Disable', 'End' or 'R' expected.</source>
<target state="translated">'必須是 'If'、'ElseIf'、'Else'、'Const'、'Region'、'ExternalSource'、'ExternalChecksum'、'Enable'、'Disable'、'End' 或 'R'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEQ">
<source>'=' expected.</source>
<target state="translated">'必須有 '='。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorNotFound1">
<source>Type '{0}' has no constructors.</source>
<target state="translated">類型 '{0}' 沒有建構函式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndInterface">
<source>'End Interface' must be preceded by a matching 'Interface'.</source>
<target state="translated">'End Interface' 之前必須搭配相對應的 'Interface'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndInterface">
<source>'Interface' must end with a matching 'End Interface'.</source>
<target state="translated">'Interface' 之後必須搭配相對應的 'End Interface'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFrom2">
<source>
'{0}' inherits from '{1}'.</source>
<target state="translated">
'{0}' 繼承自 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNestedIn2">
<source>
'{0}' is nested in '{1}'.</source>
<target state="translated">
'{0}' 巢狀於 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceCycle1">
<source>Class '{0}' cannot inherit from itself: {1}</source>
<target state="translated">類別 '{0}' 無法繼承其本身: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromNonClass">
<source>Classes can inherit only from other classes.</source>
<target state="translated">類別只能繼承自其他類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultiplyDefinedType3">
<source>'{0}' is already declared as '{1}' in this {2}.</source>
<target state="translated">'{0}' 在此 {2} 中已宣告為 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadOverrideAccess2">
<source>'{0}' cannot override '{1}' because they have different access levels.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為它們的存取層級不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOverrideNotOverridable2">
<source>'{0}' cannot override '{1}' because it is declared 'NotOverridable'.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其宣告為 'NotOverridable'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateProcDef1">
<source>'{0}' has multiple definitions with identical signatures.</source>
<target state="translated">'{0}' 有多個具相同簽章的定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateProcDefWithDifferentTupleNames2">
<source>'{0}' has multiple definitions with identical signatures with different tuple element names, including '{1}'.</source>
<target state="translated">'{0}' 具有多個定義,且這些定義的簽章相同,但卻有不同的 Tuple 項目名稱,包括 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceMethodFlags1">
<source>'{0}' is not valid on an interface method declaration.</source>
<target state="translated">'{0}' 在介面方法宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamNotFound2">
<source>'{0}' is not a parameter of '{1}'.</source>
<target state="translated">'{0}' 不是 '{1}' 的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfacePropertyFlags1">
<source>'{0}' is not valid on an interface property declaration.</source>
<target state="translated">'{0}' 在介面屬性宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgUsedTwice2">
<source>Parameter '{0}' of '{1}' already has a matching argument.</source>
<target state="translated">'{1}' 的參數 '{0}' 已有相符的引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceCantUseEventSpecifier1">
<source>'{0}' is not valid on an interface event declaration.</source>
<target state="translated">'{0}' 在介面事件宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypecharNoMatch2">
<source>Type character '{0}' does not match declared data type '{1}'.</source>
<target state="translated">類型字元 '{0}' 不符合宣告的資料類型 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSubOrFunction">
<source>'Sub' or 'Function' expected after 'Delegate'.</source>
<target state="translated">'Delegate' 之後必須有 'Sub' 或 'Function'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadEmptyEnum1">
<source>Enum '{0}' must contain at least one member.</source>
<target state="translated">列舉 '{0}' 至少必須包含一個成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidConstructorCall">
<source>Constructor call is valid only as the first statement in an instance constructor.</source>
<target state="translated">只在當做執行個體建構函式中第一個陳述式時,建構函式呼叫才有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOverrideConstructor">
<source>'Sub New' cannot be declared 'Overrides'.</source>
<target state="translated">'無法將 'Sub New' 宣告為 'Overrides'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorCannotBeDeclaredPartial">
<source>'Sub New' cannot be declared 'Partial'.</source>
<target state="translated">'Sub New' 不可宣告為 'Partial'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleEmitFailure">
<source>Failed to emit module '{0}': {1}</source>
<target state="translated">無法發出模組 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncUpdateFailedMissingAttribute">
<source>Cannot update '{0}'; attribute '{1}' is missing.</source>
<target state="translated">無法更新 '{0}'; 缺少屬性 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideNotNeeded3">
<source>{0} '{1}' cannot be declared 'Overrides' because it does not override a {0} in a base class.</source>
<target state="translated">{0} '{1}' 不可宣告為 'Overrides',因為其在基底類別中不會覆寫 {0}。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDot">
<source>'.' expected.</source>
<target state="translated">'必須有 '.'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateLocals1">
<source>Local variable '{0}' is already declared in the current block.</source>
<target state="translated">目前區塊中已宣告過區域變數 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsProc">
<source>Statement cannot appear within a method body. End of method assumed.</source>
<target state="translated">陳述式不可以在方法主體中出現。已假設是方法結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalSameAsFunc">
<source>Local variable cannot have the same name as the function containing it.</source>
<target state="translated">區域變數不可以和包含它的函式具有相同名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RecordEmbeds2">
<source>
'{0}' contains '{1}' (variable '{2}').</source>
<target state="translated">
'{0}' 包含 '{1}' (變數 '{2}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RecordCycle2">
<source>Structure '{0}' cannot contain an instance of itself: {1}</source>
<target state="translated">結構 '{0}' 不可包含本身的執行個體: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceCycle1">
<source>Interface '{0}' cannot inherit from itself: {1}</source>
<target state="translated">介面 '{0}' 無法繼承其本身: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubNewCycle2">
<source>
'{0}' calls '{1}'.</source>
<target state="translated">
'{0}' 呼叫 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubNewCycle1">
<source>Constructor '{0}' cannot call itself: {1}</source>
<target state="translated">建構函式 '{0}' 不可呼叫其本身: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromCantInherit3">
<source>'{0}' cannot inherit from {2} '{1}' because '{1}' is declared 'NotInheritable'.</source>
<target state="translated">'{0}' 無法從 {2} '{1}' 繼承,因為 '{1}' 已宣告為 'NotInheritable'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithOptional2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by optional parameters.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為它們的差異只在於選擇性參數不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithReturnType2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by return types.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為它們的差異只在於傳回類型不同而已。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharWithType1">
<source>Type character '{0}' cannot be used in a declaration with an explicit type.</source>
<target state="translated">類型字元 '{0}' 不可用在明確類型的宣告中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharOnSub">
<source>Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.</source>
<target state="translated">由於 'Sub' 不會傳回值,類型字元不可以在 'Sub' 宣告中使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithDefault2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by the default values of optional parameters.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為它們的差異只在於選擇性參數的預設值不同而已。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingSubscript">
<source>Array subscript expression missing.</source>
<target state="translated">遺漏陣列註標運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithDefault2">
<source>'{0}' cannot override '{1}' because they differ by the default values of optional parameters.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其選擇性參數的預設值不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithOptional2">
<source>'{0}' cannot override '{1}' because they differ by optional parameters.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其選擇性參數不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FieldOfValueFieldOfMarshalByRef3">
<source>Cannot refer to '{0}' because it is a member of the value-typed field '{1}' of class '{2}' which has 'System.MarshalByRefObject' as a base class.</source>
<target state="translated">無法參考 '{0}',因為其為類別 '{2}' 之實值類型欄位 '{1}' 的成員,其基底類別為 'System.MarshalByRefObject'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeMismatch2">
<source>Value of type '{0}' cannot be converted to '{1}'.</source>
<target state="translated">類型 '{0}' 的值無法轉換成 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CaseAfterCaseElse">
<source>'Case' cannot follow a 'Case Else' in the same 'Select' statement.</source>
<target state="translated">'在相同的 'Select' 陳述式中,'Case' 不可接在 'Case Else' 之後。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvertArrayMismatch4">
<source>Value of type '{0}' cannot be converted to '{1}' because '{2}' is not derived from '{3}'.</source>
<target state="translated">類型 '{0}' 的值無法轉換成 '{1}',因為 '{2}' 並非衍生自 '{3}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvertObjectArrayMismatch3">
<source>Value of type '{0}' cannot be converted to '{1}' because '{2}' is not a reference type.</source>
<target state="translated">類型 '{0}' 的值無法轉換成 '{1}',因為 '{2}' 不是參考類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForLoopType1">
<source>'For' loop control variable cannot be of type '{0}' because the type does not support the required operators.</source>
<target state="translated">'For' 迴圈控制變數不可為類型 '{0}',因為此類型不支援所需的運算子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithByref2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為它們的差異只在於宣告為 'ByRef' 或 'ByVal' 的參數不同而已。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromNonInterface">
<source>Interface can inherit only from another interface.</source>
<target state="translated">介面只可以繼承自另一個介面。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceOrderOnInherits">
<source>'Inherits' statements must precede all declarations in an interface.</source>
<target state="translated">'Inherits' 陳述式必須位於介面中的所有宣告之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateDefaultProps1">
<source>'Default' can be applied to only one property name in a {0}.</source>
<target state="translated">'Default' 只可以套用至 {0} 中的一個屬性名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultMissingFromProperty2">
<source>'{0}' and '{1}' cannot overload each other because only one is declared 'Default'.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為只有一個宣告為 'Default'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverridingPropertyKind2">
<source>'{0}' cannot override '{1}' because they differ by 'ReadOnly' or 'WriteOnly'.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其出現 'ReadOnly' 或 'WriteOnly' 的差異。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewInInterface">
<source>'Sub New' cannot be declared in an interface.</source>
<target state="translated">'無法在介面中宣告 'Sub New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnNew1">
<source>'Sub New' cannot be declared '{0}'.</source>
<target state="translated">'Sub New' 不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadingPropertyKind2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為它們的差異只在於 'ReadOnly' 或 'WriteOnly' 不同而已。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoDefaultNotExtend1">
<source>Class '{0}' cannot be indexed because it has no default property.</source>
<target state="translated">無法對類別 '{0}' 編製索引,因為其無預設屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithArrayVsParamArray2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ParamArray'.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為它們的差異只在於宣告為 'ParamArray' 的參數不同而已。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInstanceMemberAccess">
<source>Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.</source>
<target state="translated">沒有類別的明確執行個體,因此無法從共用方法或共用成員初始設定式中參考至類別的執行個體成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedRbrace">
<source>'}' expected.</source>
<target state="translated">'必須有 '}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleAsType1">
<source>Module '{0}' cannot be used as a type.</source>
<target state="translated">模組 '{0}' 不能用做為類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewIfNullOnNonClass">
<source>'New' cannot be used on an interface.</source>
<target state="translated">'New' 無法在介面上使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchAfterFinally">
<source>'Catch' cannot appear after 'Finally' within a 'Try' statement.</source>
<target state="translated">'在 'Try' 陳述式中,'Catch' 不可以出現在 'Finally' 之後。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchNoMatchingTry">
<source>'Catch' cannot appear outside a 'Try' statement.</source>
<target state="translated">'Catch' 不可以出現在 'Try' 陳述式之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FinallyAfterFinally">
<source>'Finally' can only appear once in a 'Try' statement.</source>
<target state="translated">'Finally' 只能在 'Try' 陳述式中出現一次。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FinallyNoMatchingTry">
<source>'Finally' cannot appear outside a 'Try' statement.</source>
<target state="translated">'Finally' 不可以出現在 'Try' 陳述式之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndTryNoTry">
<source>'End Try' must be preceded by a matching 'Try'.</source>
<target state="translated">'End Try' 之前必須搭配相對應的 'Try'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndTry">
<source>'Try' must end with a matching 'End Try'.</source>
<target state="translated">'Try' 之後必須搭配相對應的 'End Try'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDelegateFlags1">
<source>'{0}' is not valid on a Delegate declaration.</source>
<target state="translated">'{0}' 在 Delegate 宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoConstructorOnBase2">
<source>Class '{0}' must declare a 'Sub New' because its base class '{1}' does not have an accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">類別 '{0}' 必須宣告 'Sub New',因為其基底類別 '{1}' 沒有不用引數即可呼叫之可存取的 'Sub New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InaccessibleSymbol2">
<source>'{0}' is not accessible in this context because it is '{1}'.</source>
<target state="translated">'無法在此內容中存取 '{0}',因為它是 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InaccessibleMember3">
<source>'{0}.{1}' is not accessible in this context because it is '{2}'.</source>
<target state="translated">'無法在此內容中存取 '{0}.{1}',因為其為 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchNotException1">
<source>'Catch' cannot catch type '{0}' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.</source>
<target state="translated">'Catch' 無法攔截類型 '{0}',因為其非 'System.Exception' 或繼承自 'System.Exception' 的類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitTryNotWithinTry">
<source>'Exit Try' can only appear inside a 'Try' statement.</source>
<target state="translated">'Exit Try' 只能在 'Try' 陳述式內出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadRecordFlags1">
<source>'{0}' is not valid on a Structure declaration.</source>
<target state="translated">'{0}' 在 Structure 宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadEnumFlags1">
<source>'{0}' is not valid on an Enum declaration.</source>
<target state="translated">'{0}' 在列舉宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceFlags1">
<source>'{0}' is not valid on an Interface declaration.</source>
<target state="translated">'{0}' 在 Interface 宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithByref2">
<source>'{0}' cannot override '{1}' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為它們的差異只在於參數標記為 'ByRef' 或 'ByVal' 而已。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyBaseAbstractCall1">
<source>'MyBase' cannot be used with method '{0}' because it is declared 'MustOverride'.</source>
<target state="translated">'無法以方法 '{0}' 使用 'MyBase',因為其已宣告為 'MustOverride'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IdentNotMemberOfInterface4">
<source>'{0}' cannot implement '{1}' because there is no matching {2} on interface '{3}'.</source>
<target state="translated">'{0}' 無法實作 '{1}',因為在介面 '{3}' 上沒有相符的 {2}。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementingInterfaceWithDifferentTupleNames5">
<source>'{0}' cannot implement {1} '{2}' on interface '{3}' because the tuple element names in '{4}' do not match those in '{5}'.</source>
<target state="translated">'因為 '{4}' 中的 Tuple 項目名稱與 '{5}' 中的 Tuple 項目名稱不相符,導致 '{0}' 無法在介面 '{3}' 上實作 {1} '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_WithEventsRequiresClass">
<source>'WithEvents' variables must have an 'As' clause.</source>
<target state="translated">'WithEvents' 變數必須要有 'As' 子句。</target>
<note />
</trans-unit>
<trans-unit id="ERR_WithEventsAsStruct">
<source>'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.</source>
<target state="translated">'WithEvents' 變數類型只能設定為具有類別條件約束的類別、介面或類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvertArrayRankMismatch2">
<source>Value of type '{0}' cannot be converted to '{1}' because the array types have different numbers of dimensions.</source>
<target state="translated">類型 '{0}' 的值無法轉換成 '{1}',因為陣列類型的維度數目不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RedimRankMismatch">
<source>'ReDim' cannot change the number of dimensions of an array.</source>
<target state="translated">'ReDim' 無法變更陣列的維度數目。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StartupCodeNotFound1">
<source>'Sub Main' was not found in '{0}'.</source>
<target state="translated">'在 '{0}' 中找不到 'Sub Main'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstAsNonConstant">
<source>Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.</source>
<target state="translated">常數必須是內建或列舉類型,而不是類別、結構、類型參數或陣列類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndSub">
<source>'End Sub' must be preceded by a matching 'Sub'.</source>
<target state="translated">'End Sub' 之前必須搭配相對應的 'Sub'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndFunction">
<source>'End Function' must be preceded by a matching 'Function'.</source>
<target state="translated">'End Function' 之前必須搭配相對應的 'Function'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndProperty">
<source>'End Property' must be preceded by a matching 'Property'.</source>
<target state="translated">'End Property' 之前必須搭配相對應的 'Property'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseMethodSpecifier1">
<source>Methods in a Module cannot be declared '{0}'.</source>
<target state="translated">Module 中的方法不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseEventSpecifier1">
<source>Events in a Module cannot be declared '{0}'.</source>
<target state="translated">Module 中的事件不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructCantUseVarSpecifier1">
<source>Members in a Structure cannot be declared '{0}'.</source>
<target state="translated">結構中的成員不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOverrideDueToReturn2">
<source>'{0}' cannot override '{1}' because they differ by their return types.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為它們的傳回類型不同。</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidOverrideDueToTupleNames2">
<source>'{0}' cannot override '{1}' because they differ by their tuple element names.</source>
<target state="translated">'因為 '{0}' 的 Tuple 項目名稱各不相同,所以無法覆寫 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidOverrideDueToTupleNames2_Title">
<source>Member cannot override because it differs by its tuple element names.</source>
<target state="translated">因為成員的 Tuple 項目名稱各不相同,所以無法覆寫。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstantWithNoValue">
<source>Constants must have a value.</source>
<target state="translated">必須有常數值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpressionOverflow1">
<source>Constant expression not representable in type '{0}'.</source>
<target state="translated">在類型 '{0}' 中無法呈現常數運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicatePropertyGet">
<source>'Get' is already declared.</source>
<target state="translated">'Get' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicatePropertySet">
<source>'Set' is already declared.</source>
<target state="translated">'Set' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotDeclared1">
<source>'{0}' is not declared. It may be inaccessible due to its protection level.</source>
<target state="translated">'{0}' 未宣告。由於其保護層級,可能無法對其進行存取。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryOperands3">
<source>Operator '{0}' is not defined for types '{1}' and '{2}'.</source>
<target state="translated">未對類型 '{1}' 和 '{2}' 定義運算子 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedProcedure">
<source>Expression is not a method.</source>
<target state="translated">運算式不是方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedArgument2">
<source>Argument not specified for parameter '{0}' of '{1}'.</source>
<target state="translated">未對 '{1}' 的參數 '{0}' 指定引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotMember2">
<source>'{0}' is not a member of '{1}'.</source>
<target state="translated">'{0}' 不是 '{1}' 的成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndClassNoClass">
<source>'End Class' must be preceded by a matching 'Class'.</source>
<target state="translated">'End Class' 之前必須搭配相對應的 'Class'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadClassFlags1">
<source>Classes cannot be declared '{0}'.</source>
<target state="translated">類別不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImportsMustBeFirst">
<source>'Imports' statements must precede any declarations.</source>
<target state="translated">'Imports' 陳述式必須在任何宣告之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NonNamespaceOrClassOnImport2">
<source>'{1}' for the Imports '{0}' does not refer to a Namespace, Class, Structure, Enum or Module.</source>
<target state="translated">'Imports '{0}' 的 '{1}' 並未參考 Namespace、Class、Structure、Enum 或 Module。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypecharNotallowed">
<source>Type declaration characters are not valid in this context.</source>
<target state="translated">類型宣告字元在此內容中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObjectReferenceNotSupplied">
<source>Reference to a non-shared member requires an object reference.</source>
<target state="translated">參考非共用成員需要物件參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyClassNotInClass">
<source>'MyClass' cannot be used outside of a class.</source>
<target state="translated">'MyClass' 無法在類別外使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IndexedNotArrayOrProc">
<source>Expression is not an array or a method, and cannot have an argument list.</source>
<target state="translated">運算式不是陣列或方法,所以不可以有引數清單。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventSourceIsArray">
<source>'WithEvents' variables cannot be typed as arrays.</source>
<target state="translated">'WithEvents' 變數的類型不可以是陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedConstructorWithParams">
<source>Shared 'Sub New' cannot have any parameters.</source>
<target state="translated">共用的 'Sub New' 不可以有任何參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedConstructorIllegalSpec1">
<source>Shared 'Sub New' cannot be declared '{0}'.</source>
<target state="translated">共用的 'Sub New' 不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndClass">
<source>'Class' statement must end with a matching 'End Class'.</source>
<target state="translated">'Class' 陳述式之後必須搭配相對應的 'End Class'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnaryOperand2">
<source>Operator '{0}' is not defined for type '{1}'.</source>
<target state="translated">未對類型 '{1}' 定義運算子 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsWithDefault1">
<source>'Default' cannot be combined with '{0}'.</source>
<target state="translated">'Default' 無法和 '{0}' 相結合。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VoidValue">
<source>Expression does not produce a value.</source>
<target state="translated">運算式沒有產生值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorFunction">
<source>Constructor must be declared as a Sub, not as a Function.</source>
<target state="translated">建構函式必須宣告為 Sub,而不是 Function。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidLiteralExponent">
<source>Exponent is not valid.</source>
<target state="translated">指數無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewCannotHandleEvents">
<source>'Sub New' cannot handle events.</source>
<target state="translated">'Sub New' 無法處理事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CircularEvaluation1">
<source>Constant '{0}' cannot depend on its own value.</source>
<target state="translated">常數 '{0}' 無法相依其本身的值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnSharedMeth1">
<source>'Shared' cannot be combined with '{0}' on a method declaration.</source>
<target state="translated">'Shared' 無法在方法宣告上和 '{0}' 相結合。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnSharedProperty1">
<source>'Shared' cannot be combined with '{0}' on a property declaration.</source>
<target state="translated">'Shared' 無法在屬性宣告上與 '{0}' 相結合。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnStdModuleProperty1">
<source>Properties in a Module cannot be declared '{0}'.</source>
<target state="translated">模組中的屬性不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedOnProcThatImpl">
<source>Methods or events that implement interface members cannot be declared 'Shared'.</source>
<target state="translated">實作介面成員的方法或事件不可以宣告為 'Shared'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoWithEventsVarOnHandlesList">
<source>Handles clause requires a WithEvents variable defined in the containing type or one of its base types.</source>
<target state="translated">Handles 子句需要 WithEvents 變數,該變數定義於包含類型或它的一種基底類型中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceAccessMismatch5">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} to {3} '{4}'.</source>
<target state="translated">'{0}' 無法繼承自 {1} '{2}',因為它會將基底 {1} 的存取展開至 {3} '{4}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NarrowingConversionDisallowed2">
<source>Option Strict On disallows implicit conversions from '{0}' to '{1}'.</source>
<target state="translated">Option Strict 為 On 時,不可進行 '{0}' 至 '{1}' 的隱含轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoArgumentCountOverloadCandidates1">
<source>Overload resolution failed because no accessible '{0}' accepts this number of arguments.</source>
<target state="translated">因為沒有可存取的 '{0}' 接受此引數數目,所以多載解析失敗。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoViableOverloadCandidates1">
<source>Overload resolution failed because no '{0}' is accessible.</source>
<target state="translated">因為沒有任何可存取的 '{0}',所以多載解析失敗。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoCallableOverloadCandidates2">
<source>Overload resolution failed because no accessible '{0}' can be called with these arguments:{1}</source>
<target state="translated">因為沒有可利用這些引數呼叫之可存取的 '{0}',所以多載解析失敗: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadOverloadCandidates2">
<source>Overload resolution failed because no accessible '{0}' can be called:{1}</source>
<target state="translated">多載解析失敗,因為無法呼叫可存取的 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonNarrowingOverloadCandidates2">
<source>Overload resolution failed because no accessible '{0}' can be called without a narrowing conversion:{1}</source>
<target state="translated">因為沒有不需要縮減轉換即可呼叫之可存取的 '{0}',所以多載解析失敗: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentNarrowing3">
<source>Argument matching parameter '{0}' narrows from '{1}' to '{2}'.</source>
<target state="translated">與參數 '{0}' 對應的引數,從 '{1}' 縮減 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoMostSpecificOverload2">
<source>Overload resolution failed because no accessible '{0}' is most specific for these arguments:{1}</source>
<target state="translated">因為沒有可存取的 '{0}' 對這些引數而言是最適合的,所以多載解析失敗: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_NotMostSpecificOverload">
<source>Not most specific.</source>
<target state="translated">並非最適合。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadCandidate2">
<source>
'{0}': {1}</source>
<target state="translated">
'{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoGetProperty1">
<source>Property '{0}' is 'WriteOnly'.</source>
<target state="translated">屬性 '{0}' 是 'WriteOnly'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSetProperty1">
<source>Property '{0}' is 'ReadOnly'.</source>
<target state="translated">屬性 '{0}' 是 'ReadOnly'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamTypingInconsistency">
<source>All parameters must be explicitly typed if any of them are explicitly typed.</source>
<target state="translated">如果明確輸入任何一個參數,則必須明確輸入所有參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamNameFunctionNameCollision">
<source>Parameter cannot have the same name as its defining function.</source>
<target state="translated">函式名稱不可同時做為參數名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DateToDoubleConversion">
<source>Conversion from 'Date' to 'Double' requires calling the 'Date.ToOADate' method.</source>
<target state="translated">要將 'Date' 轉換成 'Double' 需要呼叫 'Date.ToOADate' 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DoubleToDateConversion">
<source>Conversion from 'Double' to 'Date' requires calling the 'Date.FromOADate' method.</source>
<target state="translated">要將 'Double' 轉換成 'Date' 需要呼叫 'Date.FromOADate' 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ZeroDivide">
<source>Division by zero occurred while evaluating this expression.</source>
<target state="translated">評估此運算式時發生除數為零的情形。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryAndOnErrorDoNotMix">
<source>Method cannot contain both a 'Try' statement and an 'On Error' or 'Resume' statement.</source>
<target state="translated">方法不可以同時包含 'Try' 陳述式以及 'On Error' 或 'Resume' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyAccessIgnored">
<source>Property access must assign to the property or use its value.</source>
<target state="translated">屬性的存取必須是指定值給屬性或使用屬性值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceNoDefault1">
<source>'{0}' cannot be indexed because it has no default property.</source>
<target state="translated">'無法對 '{0}' 編製索引,因為其無預設屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyAttribute1">
<source>Attribute '{0}' cannot be applied to an assembly.</source>
<target state="translated">無法將屬性 '{0}' 套用至組件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidModuleAttribute1">
<source>Attribute '{0}' cannot be applied to a module.</source>
<target state="translated">無法將屬性 '{0}' 套用至模組。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInUnnamedNamespace1">
<source>'{0}' is ambiguous.</source>
<target state="translated">'{0}' 模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultMemberNotProperty1">
<source>Default member of '{0}' is not a property.</source>
<target state="translated">'{0}' 的預設成員並非屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInNamespace2">
<source>'{0}' is ambiguous in the namespace '{1}'.</source>
<target state="translated">'{0}' 在命名空間 '{1}' 中模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInImports2">
<source>'{0}' is ambiguous, imported from the namespaces or types '{1}'.</source>
<target state="translated">'從命名空間或類型 '{1}' 匯入的 '{0}' 模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInModules2">
<source>'{0}' is ambiguous between declarations in Modules '{1}'.</source>
<target state="translated">'{0}' 在模組 '{1}' 中的宣告之間模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInNamespaces2">
<source>'{0}' is ambiguous between declarations in namespaces '{1}'.</source>
<target state="translated">'{0}' 在命名空間 '{1}' 中的宣告之間模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitializerTooFewDimensions">
<source>Array initializer has too few dimensions.</source>
<target state="translated">陣列初始設定式的維度太少。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitializerTooManyDimensions">
<source>Array initializer has too many dimensions.</source>
<target state="translated">陣列初始設定式的維度太多。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerTooFewElements1">
<source>Array initializer is missing {0} elements.</source>
<target state="translated">陣列初始設定式遺漏 {0} 個元素。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerTooManyElements1">
<source>Array initializer has {0} too many elements.</source>
<target state="translated">陣列初始設定式有 {0} 太多元素。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewOnAbstractClass">
<source>'New' cannot be used on a class that is declared 'MustInherit'.</source>
<target state="translated">'New' 不可以使用在宣告為 'MustInherit' 的類別上。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateNamedImportAlias1">
<source>Alias '{0}' is already declared.</source>
<target state="translated">別名 '{0}' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicatePrefix">
<source>XML namespace prefix '{0}' is already declared.</source>
<target state="translated">XML 命名空間前置詞 '{0}' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsLateBinding">
<source>Option Strict On disallows late binding.</source>
<target state="translated">Option Strict 為 On 時,不可使用晚期繫結。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfOperandNotMethod">
<source>'AddressOf' operand must be the name of a method (without parentheses).</source>
<target state="translated">'AddressOf' 運算元必須是方法名稱 (沒有括號)。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndExternalSource">
<source>'#End ExternalSource' must be preceded by a matching '#ExternalSource'.</source>
<target state="translated">'#End ExternalSource' 之前必須搭配相對應的 '#ExternalSource'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndExternalSource">
<source>'#ExternalSource' statement must end with a matching '#End ExternalSource'.</source>
<target state="translated">'#ExternalSource' 之後必須搭配相對應的 '#End ExternalSource'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedExternalSource">
<source>'#ExternalSource' directives cannot be nested.</source>
<target state="translated">'#ExternalSource' 指示詞不可以是巢狀。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfNotDelegate1">
<source>'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.</source>
<target state="translated">'因為 '{0}' 不是委派類型,所以 'AddressOf' 運算式無法轉換成 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SyncLockRequiresReferenceType1">
<source>'SyncLock' operand cannot be of type '{0}' because '{0}' is not a reference type.</source>
<target state="translated">'SyncLock' 運算元不可是類型 '{0}',因為 '{0}' 不是參考類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodAlreadyImplemented2">
<source>'{0}.{1}' cannot be implemented more than once.</source>
<target state="translated">'{0}.{1}' 只能實作一次。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateInInherits1">
<source>'{0}' cannot be inherited more than once.</source>
<target state="translated">'{0}' 不能繼承一次以上。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamArrayArgument">
<source>Named argument cannot match a ParamArray parameter.</source>
<target state="translated">具名引數無法符合 ParamArray 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedParamArrayArgument">
<source>Omitted argument cannot match a ParamArray parameter.</source>
<target state="translated">省略的引數無法符合 ParamArray 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayArgumentMismatch">
<source>Argument cannot match a ParamArray parameter.</source>
<target state="translated">引數無法符合 ParamArray 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventNotFound1">
<source>Event '{0}' cannot be found.</source>
<target state="translated">找不到事件 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseVariableSpecifier1">
<source>Variables in Modules cannot be declared '{0}'.</source>
<target state="translated">Module 中的變數不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedEventNeedsSharedHandler">
<source>Events of shared WithEvents variables cannot be handled by non-shared methods.</source>
<target state="translated">共用 WithEvents 變數的事件不能由非共用的方法處理。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedMinus">
<source>'-' expected.</source>
<target state="translated">'必須有 '-'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceMemberSyntax">
<source>Interface members must be methods, properties, events, or type definitions.</source>
<target state="translated">介面成員必須是方法、屬性、事件或類型定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideInterface">
<source>Statement cannot appear within an interface body.</source>
<target state="translated">陳述式不能出現在介面主體內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsInterface">
<source>Statement cannot appear within an interface body. End of interface assumed.</source>
<target state="translated">陳述式不可以在介面主體中出現。已假設是介面結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsInNotInheritableClass1">
<source>'NotInheritable' classes cannot have members declared '{0}'.</source>
<target state="translated">'NotInheritable' 類別不可有宣告為 '{0}' 的成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseOnlyClassesMustBeExplicit2">
<source>Class '{0}' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): {1}.</source>
<target state="translated">類別 '{0}' 必須宣告為 'MustInherit',或是覆寫下列繼承的 'MustOverride' 成員: {1}。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustInheritEventNotOverridden">
<source>'{0}' is a MustOverride event in the base class '{1}'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class '{2}' MustInherit.</source>
<target state="translated">'{0}' 是基底類別 '{1}' 中的 MustOverride 事件。Visual Basic 不支援事件覆寫。您必須提供基底類別中的事件實作,或將類別 '{2}' 設為 MustInherit。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NegativeArraySize">
<source>Array dimensions cannot have a negative size.</source>
<target state="translated">陣列維度大小不可以是負數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyClassAbstractCall1">
<source>'MustOverride' method '{0}' cannot be called with 'MyClass'.</source>
<target state="translated">'無法以 'MyClass' 呼叫 'MustOverride' 方法 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndDisallowedInDllProjects">
<source>'End' statement cannot be used in class library projects.</source>
<target state="translated">'不可以在類別庫專案中使用 'End' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BlockLocalShadowing1">
<source>Variable '{0}' hides a variable in an enclosing block.</source>
<target state="translated">變數 '{0}' 在封閉區塊中隱藏了變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleNotAtNamespace">
<source>'Module' statements can occur only at file or namespace level.</source>
<target state="translated">'Module' 陳述式只可以發生在檔案或命名空間層級。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamespaceNotAtNamespace">
<source>'Namespace' statements can occur only at file or namespace level.</source>
<target state="translated">'Namespace' 陳述式只可以發生在檔案或命名空間層級。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEnum">
<source>Statement cannot appear within an Enum body.</source>
<target state="translated">陳述式不可出現在列舉主體中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsEnum">
<source>Statement cannot appear within an Enum body. End of Enum assumed.</source>
<target state="translated">陳述式不可以在列舉主體中出現。已假設是列舉結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionStrict">
<source>'Option Strict' can be followed only by 'On' or 'Off'.</source>
<target state="translated">'Option Strict' 之後只能是 'On' 或 'Off'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndStructureNoStructure">
<source>'End Structure' must be preceded by a matching 'Structure'.</source>
<target state="translated">'End Structure' 之前必須搭配相對應的 'Structure'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndModuleNoModule">
<source>'End Module' must be preceded by a matching 'Module'.</source>
<target state="translated">'End Module' 之前必須搭配相對應的 'Module'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndNamespaceNoNamespace">
<source>'End Namespace' must be preceded by a matching 'Namespace'.</source>
<target state="translated">'End Namespace' 之前必須搭配相對應的 'Namespace'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndStructure">
<source>'Structure' statement must end with a matching 'End Structure'.</source>
<target state="translated">'Structure' 陳述式之後必須搭配相對應的 'End Structure'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndModule">
<source>'Module' statement must end with a matching 'End Module'.</source>
<target state="translated">'Module' 陳述式之後必須搭配相對應的 'End Module'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndNamespace">
<source>'Namespace' statement must end with a matching 'End Namespace'.</source>
<target state="translated">'Namespace' 陳述式之後必須搭配相對應的 'End Namespace'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionStmtWrongOrder">
<source>'Option' statements must precede any declarations or 'Imports' statements.</source>
<target state="translated">'Option' 陳述式必須在所有的宣告或 'Imports' 陳述式之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructCantInherit">
<source>Structures cannot have 'Inherits' statements.</source>
<target state="translated">結構不可出現 'Inherits' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewInStruct">
<source>Structures cannot declare a non-shared 'Sub New' with no parameters.</source>
<target state="translated">結構無法宣告非共用且無參數的 'Sub New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndGet">
<source>'End Get' must be preceded by a matching 'Get'.</source>
<target state="translated">'End Get' 之前必須搭配相對應的 'Get'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndGet">
<source>'Get' statement must end with a matching 'End Get'.</source>
<target state="translated">'Get' 陳述式之後必須搭配相對應的 'End Get'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndSet">
<source>'End Set' must be preceded by a matching 'Set'.</source>
<target state="translated">'End Set' 之前必須搭配相對應的 'Set'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndSet">
<source>'Set' statement must end with a matching 'End Set'.</source>
<target state="translated">'Set' 陳述式之後必須搭配相對應的 'End Set'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsProperty">
<source>Statement cannot appear within a property body. End of property assumed.</source>
<target state="translated">陳述式不可以在屬性主體中出現。已假設是屬性結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateWriteabilityCategoryUsed">
<source>'ReadOnly' and 'WriteOnly' cannot be combined.</source>
<target state="translated">'無法結合 'ReadOnly' 和 'WriteOnly'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedGreater">
<source>'>' expected.</source>
<target state="translated">'必須有 '>'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeStmtWrongOrder">
<source>Assembly or Module attribute statements must precede any declarations in a file.</source>
<target state="translated">組件或模組屬性陳述式必須在檔案中任何宣告之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoExplicitArraySizes">
<source>Array bounds cannot appear in type specifiers.</source>
<target state="translated">陣列界限的宣告不可以出現在類型規範中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyFlags1">
<source>Properties cannot be declared '{0}'.</source>
<target state="translated">屬性不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionExplicit">
<source>'Option Explicit' can be followed only by 'On' or 'Off'.</source>
<target state="translated">'Option Explicit' 之後只能是 'On' 或 'Off'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleParameterSpecifiers">
<source>'ByVal' and 'ByRef' cannot be combined.</source>
<target state="translated">'無法結合 'ByVal' 和 'ByRef'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleOptionalParameterSpecifiers">
<source>'Optional' and 'ParamArray' cannot be combined.</source>
<target state="translated">'無法結合 'Optional' 和 'ParamArray'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedProperty1">
<source>Property '{0}' is of an unsupported type.</source>
<target state="translated">屬性 '{0}' 是不支援的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionalParameterUsage1">
<source>Attribute '{0}' cannot be applied to a method with optional parameters.</source>
<target state="translated">無法將屬性 '{0}' 套用至具有選擇性參數的方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReturnFromNonFunction">
<source>'Return' statement in a Sub or a Set cannot return a value.</source>
<target state="translated">'在 Sub 或 Set 中的 'Return' 陳述式無法傳回值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnterminatedStringLiteral">
<source>String constants must end with a double quote.</source>
<target state="translated">字串常數必須以雙引號結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedType1">
<source>'{0}' is an unsupported type.</source>
<target state="translated">'{0}' 是不支援的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEnumBase">
<source>Enums must be declared as an integral type.</source>
<target state="translated">列舉必須宣告為整數類資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ByRefIllegal1">
<source>{0} parameters cannot be declared 'ByRef'.</source>
<target state="translated">{0} 參數不可宣告為 'ByRef'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedAssembly3">
<source>Reference required to assembly '{0}' containing the type '{1}'. Add one to your project.</source>
<target state="translated">組件 '{0}' (包含類型 '{1}') 需要參考。請在您的專案中加入一個參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedModule3">
<source>Reference required to module '{0}' containing the type '{1}'. Add one to your project.</source>
<target state="translated">模組 '{0}' (包含類型 '{1}') 需要參考。請在您的專案中加入一個參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReturnWithoutValue">
<source>'Return' statement in a Function, Get, or Operator must return a value.</source>
<target state="translated">'在 Function、Get 或 Operator 中的 'Return' 陳述式必須傳回值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedField1">
<source>Field '{0}' is of an unsupported type.</source>
<target state="translated">欄位 '{0}' 是不支援的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedMethod1">
<source>'{0}' has a return type that is not supported or parameter types that are not supported.</source>
<target state="translated">'{0}' 含有不支援的傳回類型或多個不支援的參數類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonIndexProperty1">
<source>Property '{0}' with no parameters cannot be found.</source>
<target state="translated">找不到不含有參數的屬性 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributePropertyType1">
<source>Property or field '{0}' does not have a valid attribute type.</source>
<target state="translated">屬性或欄位 '{0}' 不具備有效的屬性類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalsCannotHaveAttributes">
<source>Attributes cannot be applied to local variables.</source>
<target state="translated">屬性不可以套用至區域變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyOrFieldNotDefined1">
<source>Field or property '{0}' is not found.</source>
<target state="translated">找不到欄位或屬性 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeUsage2">
<source>Attribute '{0}' cannot be applied to '{1}' because the attribute is not valid on this declaration type.</source>
<target state="translated">無法將屬性 '{0}' 套用至 '{1}',因為該屬性在此宣告類型上無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeUsageOnAccessor">
<source>Attribute '{0}' cannot be applied to '{1}' of '{2}' because the attribute is not valid on this declaration type.</source>
<target state="translated">無法將屬性 '{0}' 套用至 '{2}' 的 '{1}',因為該屬性在此宣告類型上無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedTypeInInheritsClause2">
<source>Class '{0}' cannot reference its nested type '{1}' in Inherits clause.</source>
<target state="translated">類別 '{0}' 無法參考其在 Inherits 子句中的巢狀類型 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInItsInheritsClause1">
<source>Class '{0}' cannot reference itself in Inherits clause.</source>
<target state="translated">類別 '{0}' 無法在 Inherits 子句中參考自己本身。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseTypeReferences2">
<source>
Base type of '{0}' needs '{1}' to be resolved.</source>
<target state="translated">
'{0}' 的基底類型需要解析 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalBaseTypeReferences3">
<source>Inherits clause of {0} '{1}' causes cyclic dependency: {2}</source>
<target state="translated">{0} '{1}' 的 Inherits 子句造成了循環依存性: {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMultipleAttributeUsage1">
<source>Attribute '{0}' cannot be applied multiple times.</source>
<target state="translated">屬性 '{0}' 不可多次套用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMultipleAttributeUsageInNetModule2">
<source>Attribute '{0}' in '{1}' cannot be applied multiple times.</source>
<target state="translated">'{1}' 中的屬性 '{0}' 不可多次套用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantThrowNonException">
<source>'Throw' operand must derive from 'System.Exception'.</source>
<target state="translated">'Throw' 運算元必須衍生自 'System.Exception'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustBeInCatchToRethrow">
<source>'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.</source>
<target state="translated">'Throw' 陳述式不可以在 'Catch' 陳述式外或 'Finally' 陳述式內省略運算元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayMustBeByVal">
<source>ParamArray parameters must be declared 'ByVal'.</source>
<target state="translated">ParamArray 參數必須宣告為 'ByVal'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoleteSymbol2">
<source>'{0}' is obsolete: '{1}'.</source>
<target state="translated">'{0}' 已經過時: '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RedimNoSizes">
<source>'ReDim' statements require a parenthesized list of the new bounds of each dimension of the array.</source>
<target state="translated">'ReDim' 陳述式需要每個陣列維度新界限的小括號內清單。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitWithMultipleDeclarators">
<source>Explicit initialization is not permitted with multiple variables declared with a single type specifier.</source>
<target state="translated">以單一類型規範來宣告多個變數時不允許明確初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitWithExplicitArraySizes">
<source>Explicit initialization is not permitted for arrays declared with explicit bounds.</source>
<target state="translated">以明確的界限來宣告陣列時不允許明確初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndSyncLockNoSyncLock">
<source>'End SyncLock' must be preceded by a matching 'SyncLock'.</source>
<target state="translated">'End SyncLock' 之前必須搭配相對應的 'SyncLock'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndSyncLock">
<source>'SyncLock' statement must end with a matching 'End SyncLock'.</source>
<target state="translated">'SyncLock' 之後必須搭配相對應的 'End SyncLock'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotEvent2">
<source>'{0}' is not an event of '{1}'.</source>
<target state="translated">'{0}' 不是 '{1}' 的事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddOrRemoveHandlerEvent">
<source>'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.</source>
<target state="translated">'AddHandler' 或 'RemoveHandler' 陳述式事件運算元必須是點限定運算式 (Dot-qualified Expression) 或是簡單名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedEnd">
<source>'End' statement not valid.</source>
<target state="translated">'End' 陳述式無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitForNonArray2">
<source>Array initializers are valid only for arrays, but the type of '{0}' is '{1}'.</source>
<target state="translated">陣列初始設定式只對陣列有效,但 '{0}' 的類型是 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndRegionNoRegion">
<source>'#End Region' must be preceded by a matching '#Region'.</source>
<target state="translated">'#End Region' 之前必須搭配相對應的 '#Region'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndRegion">
<source>'#Region' statement must end with a matching '#End Region'.</source>
<target state="translated">'#Region' 之後必須搭配相對應的 '#End Region'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsStmtWrongOrder">
<source>'Inherits' statement must precede all declarations in a class.</source>
<target state="translated">'Inherits' 陳述式必須在類別中所有宣告之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousAcrossInterfaces3">
<source>'{0}' is ambiguous across the inherited interfaces '{1}' and '{2}'.</source>
<target state="translated">'跨繼承介面 '{1}' 和 '{2}' 的 '{0}' 模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultPropertyAmbiguousAcrossInterfaces4">
<source>Default property access is ambiguous between the inherited interface members '{0}' of interface '{1}' and '{2}' of interface '{3}'.</source>
<target state="translated">在介面 '{1}' 的繼承介面成員 '{0}' 以及介面 '{3}' 的 '{2}' 之間,預設屬性存取模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceEventCantUse1">
<source>Events in interfaces cannot be declared '{0}'.</source>
<target state="translated">介面中的事件不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExecutableAsDeclaration">
<source>Statement cannot appear outside of a method body.</source>
<target state="translated">陳述式不可出現在方法主體之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructureNoDefault1">
<source>Structure '{0}' cannot be indexed because it has no default property.</source>
<target state="translated">無法對結構 '{0}' 編製索引,因為其無預設屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustShadow2">
<source>{0} '{1}' must be declared 'Shadows' because another member with this name is declared 'Shadows'.</source>
<target state="translated">{0} '{1}' 必須宣告為 'Shadows',因為使用此名稱的另一個成員已宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithOptionalTypes2">
<source>'{0}' cannot override '{1}' because they differ by the types of optional parameters.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其選擇性參數類型不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndOfExpression">
<source>End of expression expected.</source>
<target state="translated">必須是運算式結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructsCannotHandleEvents">
<source>Methods declared in structures cannot have 'Handles' clauses.</source>
<target state="translated">結構中宣告的方法不能有 'Handles' 子句。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverridesImpliesOverridable">
<source>Methods declared 'Overrides' cannot be declared 'Overridable' because they are implicitly overridable.</source>
<target state="translated">宣告為 'Overrides' 的方法無法宣告為 'Overridable',因為它們可以被隱含地覆寫。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalNamedSameAsParam1">
<source>'{0}' is already declared as a parameter of this method.</source>
<target state="translated">'{0}' 已經宣告為此方法的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalNamedSameAsParamInLambda1">
<source>Variable '{0}' is already declared as a parameter of this or an enclosing lambda expression.</source>
<target state="translated">變數 '{0}' 已宣告為此運算式或封閉式 Lambda 運算式的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseTypeSpecifier1">
<source>Type in a Module cannot be declared '{0}'.</source>
<target state="translated">Module 中的類型不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InValidSubMainsFound1">
<source>No accessible 'Main' method with an appropriate signature was found in '{0}'.</source>
<target state="translated">在 '{0}' 中找不到具有適當簽章的可存取 'Main' 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MoreThanOneValidMainWasFound2">
<source>'Sub Main' is declared more than once in '{0}': {1}</source>
<target state="translated">'在 '{0}' 中已重複宣告 'Sub Main': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotConvertValue2">
<source>Value '{0}' cannot be converted to '{1}'.</source>
<target state="translated">值 '{0}' 無法轉換成 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnErrorInSyncLock">
<source>'On Error' statements are not valid within 'SyncLock' statements.</source>
<target state="translated">'SyncLock' 陳述式中的 'On Error' 陳述式無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NarrowingConversionCollection2">
<source>Option Strict On disallows implicit conversions from '{0}' to '{1}'; the Visual Basic 6.0 collection type is not compatible with the .NET Framework collection type.</source>
<target state="translated">Option Strict 為 On 時,不可進行 '{0}' 至 '{1}' 的隱含轉換。Visual Basic 6.0 集合類型與 .NET Framework 集合類型不相容。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoTryHandler">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.</source>
<target state="translated">'GoTo {0}' 無效,因為 '{0}' 位於不包含此陳述式的 'Try'、'Catch' 或 'Finally' 陳述式內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoSyncLock">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'SyncLock' statement that does not contain this statement.</source>
<target state="translated">'GoTo {0}' 無效,因為 '{0}' 位於不包含此陳述式的 'SyncLock' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoWith">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'With' statement that does not contain this statement.</source>
<target state="translated">'GoTo {0}' 無效,因為 '{0}' 位於不包含此陳述式的 'With' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoFor">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'For' or 'For Each' statement that does not contain this statement.</source>
<target state="translated">'GoTo {0}' 無效,因為 '{0}' 位於不包含此陳述式的 'For' 或 'For Each' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicConstructor">
<source>Attribute cannot be used because it does not have a Public constructor.</source>
<target state="translated">無法使用屬性,因為它沒有 Public 建構函式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultEventNotFound1">
<source>Event '{0}' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.</source>
<target state="translated">DefaultEvent' 屬性所指定的 '{0}' 事件,對此類別而言並非可公開存取的事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidNonSerializedUsage">
<source>'NonSerialized' attribute will not have any effect on this member because its containing class is not exposed as 'Serializable'.</source>
<target state="translated">'NonSerialized' 屬性對這個成員將沒有任何作用,因為它的包含類別並未公開為 'Serializable'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedContinueKind">
<source>'Continue' must be followed by 'Do', 'For' or 'While'.</source>
<target state="translated">'Continue' 必須在 'Do'、'For' 或 'While' 之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ContinueDoNotWithinDo">
<source>'Continue Do' can only appear inside a 'Do' statement.</source>
<target state="translated">'Continue Do' 只可以在 'Do' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ContinueForNotWithinFor">
<source>'Continue For' can only appear inside a 'For' statement.</source>
<target state="translated">'Continue For' 只可以在 'For' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ContinueWhileNotWithinWhile">
<source>'Continue While' can only appear inside a 'While' statement.</source>
<target state="translated">'Continue While' 只可以在 'While' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateParameterSpecifier">
<source>Parameter specifier is duplicated.</source>
<target state="translated">參數規範重複。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseDLLDeclareSpecifier1">
<source>'Declare' statements in a Module cannot be declared '{0}'.</source>
<target state="translated">'Module 中的 'Declare' 陳述式不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructCantUseDLLDeclareSpecifier1">
<source>'Declare' statements in a structure cannot be declared '{0}'.</source>
<target state="translated">'結構中的 'Declare' 陳述式不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryCastOfValueType1">
<source>'TryCast' operand must be reference type, but '{0}' is a value type.</source>
<target state="translated">'TryCast' 運算元必須要是參考類型,但 '{0}' 是實值類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryCastOfUnconstrainedTypeParam1">
<source>'TryCast' operands must be class-constrained type parameter, but '{0}' has no class constraint.</source>
<target state="translated">'TryCast' 運算元必須是具備類別條件約束的類型參數,但 '{0}' 沒有類別條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousDelegateBinding2">
<source>No accessible '{0}' is most specific: {1}</source>
<target state="translated">沒有最適用的 '{0}' 可供存取: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedStructMemberCannotSpecifyNew">
<source>Non-shared members in a Structure cannot be declared 'New'.</source>
<target state="translated">Structure 中的非共用成員不可以宣告為 'New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericSubMainsFound1">
<source>None of the accessible 'Main' methods with the appropriate signatures found in '{0}' can be the startup method since they are all either generic or nested in generic types.</source>
<target state="translated">在 '{0}' 中所找到具有適當簽章之可存取的 'Main' 方法,沒有任何一個可做為啟動方法,因為所有這些方法都可能是泛型類型或是泛型類型中的巢狀類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GeneralProjectImportsError3">
<source>Error in project-level import '{0}' at '{1}' : {2}</source>
<target state="translated">專案層級的匯入 '{0}' 在 '{1}' 發生錯誤: {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidTypeForAliasesImport2">
<source>'{1}' for the Imports alias to '{0}' does not refer to a Namespace, Class, Structure, Interface, Enum or Module.</source>
<target state="translated">'Imports 別名為 '{0}' 的 '{1}',並未參考 Namespace、Class、Structure、Interface、Enum 或 Module。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedConstant2">
<source>Field '{0}.{1}' has an invalid constant value.</source>
<target state="translated">欄位 '{0}.{1}' 的常數值無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteArgumentsNeedParens">
<source>Method arguments must be enclosed in parentheses.</source>
<target state="translated">方法引數必須放在括號之中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteLineNumbersAreLabels">
<source>Labels that are numbers must be followed by colons.</source>
<target state="translated">內容為數字的標籤之後必須跟隨冒號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteStructureNotType">
<source>'Type' statements are no longer supported; use 'Structure' statements instead.</source>
<target state="translated">'不再支援 'Type' 陳述式。請使用 'Structure' 陳述式代替。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteObjectNotVariant">
<source>'Variant' is no longer a supported type; use the 'Object' type instead.</source>
<target state="translated">'不再支援 'Variant' 類型。請使用 'Object' 類型代替。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteLetSetNotNeeded">
<source>'Let' and 'Set' assignment statements are no longer supported.</source>
<target state="translated">'不再支援 'Let' 和 'Set' 指派陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoletePropertyGetLetSet">
<source>Property Get/Let/Set are no longer supported; use the new Property declaration syntax.</source>
<target state="translated">不再支援 Property Get/Let/Set; 請使用新的 Property 宣告語法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteWhileWend">
<source>'Wend' statements are no longer supported; use 'End While' statements instead.</source>
<target state="translated">'不再支援 'Wend' 陳述式; 請使用 'End While' 陳述式代替。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteRedimAs">
<source>'ReDim' statements can no longer be used to declare array variables.</source>
<target state="translated">'無法再使用 'ReDim' 陳述式來宣告陣列變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteOptionalWithoutValue">
<source>Optional parameters must specify a default value.</source>
<target state="translated">選擇性參數必須指定預設值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteGosub">
<source>'GoSub' statements are no longer supported.</source>
<target state="translated">'不再支援 'GoSub' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteOnGotoGosub">
<source>'On GoTo' and 'On GoSub' statements are no longer supported.</source>
<target state="translated">'不再支援 'On GoTo' 和 'On GoSub' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteEndIf">
<source>'EndIf' statements are no longer supported; use 'End If' instead.</source>
<target state="translated">'不再支援 'EndIf' 陳述式; 請使用 'End If' 代替。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteExponent">
<source>'D' can no longer be used to indicate an exponent, use 'E' instead.</source>
<target state="translated">'不再使用 'D' 來表示指數,請使用 'E' 代替。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteAsAny">
<source>'As Any' is not supported in 'Declare' statements.</source>
<target state="translated">'Declare' 陳述式中不支援 'As Any'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteGetStatement">
<source>'Get' statements are no longer supported. File I/O functionality is available in the 'Microsoft.VisualBasic' namespace.</source>
<target state="translated">'不再支援 'Get' 陳述式。檔案 I/O 的功能可以在 'Microsoft.VisualBasic' 命名空間中使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithArrayVsParamArray2">
<source>'{0}' cannot override '{1}' because they differ by parameters declared 'ParamArray'.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其宣告為 'ParamArray' 的參數不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CircularBaseDependencies4">
<source>This inheritance causes circular dependencies between {0} '{1}' and its nested or base type '{2}'.</source>
<target state="translated">此繼承會導致 {0} '{1}' 與其巢狀或基底類型 '{2}' 之間發生循環相依。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedBase2">
<source>{0} '{1}' cannot inherit from a type nested within it.</source>
<target state="translated">{0} '{1}' 無法繼承自其內部的巢狀類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatchOutsideAssembly4">
<source>'{0}' cannot expose type '{1}' outside the project through {2} '{3}'.</source>
<target state="translated">'{0}' 無法經由 {2} '{3}',在專案外公開類型 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceAccessMismatchOutside3">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} outside the assembly.</source>
<target state="translated">'{0}' 無法繼承自 {1} '{2}',因為其會在組件外展開基底 {1} 的存取。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoletePropertyAccessor3">
<source>'{0}' accessor of '{1}' is obsolete: '{2}'.</source>
<target state="translated">'{1}' 的 '{0}' 存取子已經過時: '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoletePropertyAccessor2">
<source>'{0}' accessor of '{1}' is obsolete.</source>
<target state="translated">'{1}' 的 '{0}' 存取子已經過時。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatchImplementedEvent6">
<source>'{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing to {2} '{3}' through {4} '{5}'.</source>
<target state="translated">'{0}' 無法將其實作之事件的基礎委派類型 '{1}',經由 {4} '{5}' 公開至 {2} '{3}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatchImplementedEvent4">
<source>'{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing outside the project through {2} '{3}'.</source>
<target state="translated">'{0}' 無法將其實作之事件的基礎委派類型 '{1}',經由 {2} '{3}' 公開於專案之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceCycleInImportedType1">
<source>Type '{0}' is not supported because it either directly or indirectly inherits from itself.</source>
<target state="translated">因為類型 '{0}' 直接或間接繼承其本身,所以不受支援。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonObsoleteConstructorOnBase3">
<source>Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete.</source>
<target state="translated">類別 '{0}' 必須宣告 'Sub New',因為基底類別 '{2}' 中的 '{1}' 已標記為過時。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonObsoleteConstructorOnBase4">
<source>Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'.</source>
<target state="translated">類別 '{0}' 必須宣告 'Sub New',因為基底類別 '{2}' 中的 '{1}' 已標記為過時: '{3}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNonObsoleteNewCall3">
<source>First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete.</source>
<target state="translated">此 'Sub New' 的第一個陳述式,必須是對 'MyBase.New' 或 'MyClass.New' 的明確呼叫,因為 '{2}' 的基底類別 '{1}' 中之 '{0}' 已標記為過時。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNonObsoleteNewCall4">
<source>First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'.</source>
<target state="translated">此 'Sub New' 的第一個陳述式,必須是對 'MyBase.New' 或 'MyClass.New' 的明確呼叫,因為 '{2}' 的基底類別 '{1}' 中之 '{0}' 已標記為過時: '{3}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsTypeArgAccessMismatch7">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' to {4} '{5}'.</source>
<target state="translated">'{0}' 無法繼承自 {1} '{2}',因為它會將類型 '{3}' 的存取展開至 {4} '{5}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsTypeArgAccessMismatchOutside5">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' outside the assembly.</source>
<target state="translated">'{0}' 無法繼承自 {1} '{2}',因為它會在組件外展開類型 '{3}' 的存取。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeAccessMismatch3">
<source>Specified access '{0}' for '{1}' does not match the access '{2}' specified on one of its other partial types.</source>
<target state="translated">對於某個其他部分類型所指定的存取 '{2}' 而言,為 '{1}' 所指定的存取 '{0}' 不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeBadMustInherit1">
<source>'MustInherit' cannot be specified for partial type '{0}' because it cannot be combined with 'NotInheritable' specified for one of its other partial types.</source>
<target state="translated">'不可為部分類型 '{0}' 指定 'MustInherit',因為其無法與針對某個其他部分類型所指定的 'NotInheritable' 相結合。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustOverOnNotInheritPartClsMem1">
<source>'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition.</source>
<target state="translated">'因為成員所屬的部分類型,在另一個部分定義中已宣告為 'NotInheritable',所以無法對該成員指定 'MustOverride',</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseMismatchForPartialClass3">
<source>Base class '{0}' specified for class '{1}' cannot be different from the base class '{2}' of one of its other partial types.</source>
<target state="translated">為類別 '{1}' 指定的基底類別 '{0}',不可與其任一其他部分類型的基底類別 '{2}' 不相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeTypeParamNameMismatch3">
<source>Type parameter name '{0}' does not match the name '{1}' of the corresponding type parameter defined on one of the other partial types of '{2}'.</source>
<target state="translated">對於 '{2}' 的某個其他部分類型所定義之對應類型參數的 '{1}' 名稱而言,類型參數名稱 '{0}' 不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeConstraintMismatch1">
<source>Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of '{0}'.</source>
<target state="translated">對於 '{0}' 的某個其他部分類型所定義之相對應類型參數的條件約束而言,此類型參數的條件約束不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LateBoundOverloadInterfaceCall1">
<source>Late bound overload resolution cannot be applied to '{0}' because the accessing instance is an interface type.</source>
<target state="translated">因為進行存取的執行個體為介面類型,所以晚期繫結多載解析無法套用至 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredAttributeConstConversion2">
<source>Conversion from '{0}' to '{1}' cannot occur in a constant expression used as an argument to an attribute.</source>
<target state="translated">用做為屬性的引數之常數運算式中,不可進行從 '{0}' 到 '{1}' 的轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousOverrides3">
<source>Member '{0}' that matches this signature cannot be overridden because the class '{1}' contains multiple members with this same name and signature: {2}</source>
<target state="translated">無法覆寫與此簽章相符的成員 '{0}',因為類別 '{1}' 包含多位具有此相同名稱與簽章的成員: {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverriddenCandidate1">
<source>
'{0}'</source>
<target state="translated">
'{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousImplements3">
<source>Member '{0}.{1}' that matches this signature cannot be implemented because the interface '{2}' contains multiple members with this same name and signature:
'{3}'
'{4}'</source>
<target state="translated">無法實作與此簽章相符的成員 '{0}.{1}',因為介面 '{2}' 包含多位具有此相同名稱與簽章的成員:
'{3}'
'{4}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfNotCreatableDelegate1">
<source>'AddressOf' expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.</source>
<target state="translated">'因為類型 '{0}' 宣告為 'MustInherit' 但卻無法建立,所以 'AddressOf' 運算式無法轉換成 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassGenericMethod">
<source>Generic methods cannot be exposed to COM.</source>
<target state="translated">泛型方法不可以公開至 COM。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SyntaxInCastOp">
<source>Syntax error in cast operator; two arguments separated by comma are required.</source>
<target state="translated">轉型運算子中的語法錯誤; 兩個引數之間必須以逗號分隔。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitializerForNonConstDim">
<source>Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'.</source>
<target state="translated">無法指定非常數維度的陣列初始設定式; 請使用空的初始設定式 '{}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingFailure3">
<source>No accessible method '{0}' has a signature compatible with delegate '{1}':{2}</source>
<target state="translated">沒有任何可存取的方法 '{0}' 具備與委派 '{1}' 相容的簽章: {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructLayoutAttributeNotAllowed">
<source>Attribute 'StructLayout' cannot be applied to a generic type.</source>
<target state="translated">屬性 'StructLayout' 不能套用到泛型類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IterationVariableShadowLocal1">
<source>Range variable '{0}' hides a variable in an enclosing block or a range variable previously defined in the query expression.</source>
<target state="translated">範圍變數 '{0}' 可隱藏封閉區塊中的變數,或查詢運算式中預先定義的範圍變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionInfer">
<source>'Option Infer' can be followed only by 'On' or 'Off'.</source>
<target state="translated">'Option Infer' 之後只能是 'On' 或 'Off'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CircularInference1">
<source>Type of '{0}' cannot be inferred from an expression containing '{0}'.</source>
<target state="translated">無法從包含 '{0}' 的運算式推斷 '{0}' 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InAccessibleOverridingMethod5">
<source>'{0}' in class '{1}' cannot override '{2}' in class '{3}' because an intermediate class '{4}' overrides '{2}' in class '{3}' but is not accessible.</source>
<target state="translated">'類別 '{1}' 中的 '{0}' 無法覆寫類別 '{3}' 中的 '{2}',因為中繼類別 '{4}' 會覆寫類別 '{3}' 中的 '{2}',但無法存取。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSuitableWidestType1">
<source>Type of '{0}' cannot be inferred because the loop bounds and the step clause do not convert to the same type.</source>
<target state="translated">因為迴圈繫結和 step 子句不會轉換成相同類型,所以無法推斷 '{0}' 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousWidestType3">
<source>Type of '{0}' is ambiguous because the loop bounds and the step clause do not convert to the same type.</source>
<target state="translated">類型 '{0}' 模稜兩可,因為迴圈繫結和 step 子句不會轉換成相同的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAssignmentOperatorInInit">
<source>'=' expected (object initializer).</source>
<target state="translated">'必須是 '=' (物件初始設定式)。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedQualifiedNameInInit">
<source>Name of field or property being initialized in an object initializer must start with '.'.</source>
<target state="translated">在物件初始設定式中初始化的欄位或屬性,其名稱開頭必須是 '.'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLbrace">
<source>'{' expected.</source>
<target state="translated">'必須是 '{'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedTypeOrWith">
<source>Type or 'With' expected.</source>
<target state="translated">必須是類型或 'With'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAggrMemberInit1">
<source>Multiple initializations of '{0}'. Fields and properties can be initialized only once in an object initializer expression.</source>
<target state="translated">'{0}' 的多個初始設定。欄位和屬性只能在一個物件初始設定式運算式中初始化一次。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NonFieldPropertyAggrMemberInit1">
<source>Member '{0}' cannot be initialized in an object initializer expression because it is not a field or property.</source>
<target state="translated">成員 '{0}' 因為不是欄位或屬性,所以無法在物件初始設定式運算式中進行初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedMemberAggrMemberInit1">
<source>Member '{0}' cannot be initialized in an object initializer expression because it is shared.</source>
<target state="translated">因為成員 '{0}' 為共用成員,所以無法在物件初始設定式運算式中進行初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParameterizedPropertyInAggrInit1">
<source>Property '{0}' cannot be initialized in an object initializer expression because it requires arguments.</source>
<target state="translated">因為屬性 '{0}' 需要有引數,所以無法在物件初始設定式運算式中進行初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoZeroCountArgumentInitCandidates1">
<source>Property '{0}' cannot be initialized in an object initializer expression because all accessible overloads require arguments.</source>
<target state="translated">因為所有可存取的多載都需要有引數,所以屬性 '{0}' 無法在物件初始設定式運算式中進行初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AggrInitInvalidForObject">
<source>Object initializer syntax cannot be used to initialize an instance of 'System.Object'.</source>
<target state="translated">物件初始設定式語法無法用來初始化 'System.Object' 的執行個體。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerExpected">
<source>Initializer expected.</source>
<target state="translated">必須是初始設定式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LineContWithCommentOrNoPrecSpace">
<source>The line continuation character '_' must be preceded by at least one white space and it must be followed by a comment or the '_' must be the last character on the line.</source>
<target state="translated">行接續字元 '_' 前面必須至少有一個空白字元,後面必須接著註解,否則 '_' 必須是該行的最後一個字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadModuleFile1">
<source>Unable to load module file '{0}': {1}</source>
<target state="translated">無法載入模組檔 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadRefLib1">
<source>Unable to load referenced library '{0}': {1}</source>
<target state="translated">無法載入參考的程式庫 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventHandlerSignatureIncompatible2">
<source>Method '{0}' cannot handle event '{1}' because they do not have a compatible signature.</source>
<target state="translated">方法 '{0}' 因為沒有相容的簽章,所以無法處理事件 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConditionalCompilationConstantNotValid">
<source>Conditional compilation constant '{1}' is not valid: {0}</source>
<target state="translated">條件式編譯常數 '{1}' 無效: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwice1">
<source>Interface '{0}' can be implemented only once by this type.</source>
<target state="translated">介面 '{0}' 只可由此類型實作一次。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames2">
<source>Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}'.</source>
<target state="translated">此類型只可在介面 '{0}' 上實作一次,但卻已有不同的 Tuple 項目名稱 ('{1}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames3">
<source>Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}' (via '{2}').</source>
<target state="translated">此類型只可在介面 '{0}' 上實作一次,但卻已有不同的 Tuple 項目名稱 ('{1}',經由 '{2}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNamesReverse3">
<source>Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}'.</source>
<target state="translated">此類型只可在介面 '{0}' 上實作一次 (經由 '{1}'),但卻已有不同的 Tuple 項目名稱 ('{2}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames4">
<source>Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}' (via '{3}').</source>
<target state="translated">此類型只可在介面 '{0}' 上實作一次 (經由 '{1}'),但卻已有不同的 Tuple 項目名稱 ('{2}',經由 '{3}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames2">
<source>Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}'.</source>
<target state="translated">此介面只可繼承介面 '{0}' 一次,但卻已有不同的 Tuple 項目名稱 ('{1}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames3">
<source>Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}' (via '{2}').</source>
<target state="translated">此介面只可繼承介面 '{0}' 一次,但卻已有不同的 Tuple 項目名稱 ('{1}',經由 '{2}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNamesReverse3">
<source>Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}'.</source>
<target state="translated">此介面只可繼承介面 '{0}' 一次 (經由 '{1}'),但卻已有不同的 Tuple 項目名稱 ('{2}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames4">
<source>Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}' (via '{3}').</source>
<target state="translated">此介面只可繼承介面 '{0}' 一次 (經由 '{1}'),但卻已有不同的 Tuple 項目名稱 ('{2}',經由 '{3}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceNotImplemented1">
<source>Interface '{0}' is not implemented by this class.</source>
<target state="translated">介面 '{0}' 尚未由此類別實作。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousImplementsMember3">
<source>'{0}' exists in multiple base interfaces. Use the name of the interface that declares '{0}' in the 'Implements' clause instead of the name of the derived interface.</source>
<target state="translated">'{0}' 存在於多個基底介面中。請使用 'Implements' 子句中宣告 '{0}' 的介面名稱,來取代衍生介面的名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsOnNew">
<source>'Sub New' cannot implement interface members.</source>
<target state="translated">'Sub New' 無法實作介面成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitInStruct">
<source>Arrays declared as structure members cannot be declared with an initial size.</source>
<target state="translated">宣告為結構成員的陣列無法以初始大小宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventTypeNotDelegate">
<source>Events declared with an 'As' clause must have a delegate type.</source>
<target state="translated">使用 'As' 子句宣告的事件必須有委派類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ProtectedTypeOutsideClass">
<source>Protected types can only be declared inside of a class.</source>
<target state="translated">只可以在類別內宣告 Protected 類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultPropertyWithNoParams">
<source>Properties with no required parameters cannot be declared 'Default'.</source>
<target state="translated">沒有必要參數的屬性不可以宣告為 'Default'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerInStruct">
<source>Initializers on structure members are valid only for 'Shared' members and constants.</source>
<target state="translated">結構成員上的初始設定式只有對 'Shared' 成員和常數有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateImport1">
<source>Namespace or type '{0}' has already been imported.</source>
<target state="translated">命名空間或類型 '{0}' 已經匯入。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadModuleFlags1">
<source>Modules cannot be declared '{0}'.</source>
<target state="translated">模組不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsStmtWrongOrder">
<source>'Implements' statements must follow any 'Inherits' statement and precede all declarations in a class.</source>
<target state="translated">'Implements' 陳述式必須位在所有 'Inherits' 陳述式之後,並且必須在類別中的所有宣告之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynthMemberClashesWithSynth7">
<source>{0} '{1}' implicitly defines '{2}', which conflicts with a member implicitly declared for {3} '{4}' in {5} '{6}'.</source>
<target state="translated">{0} '{1}' 隱含定義 '{2}',其與 {5} '{6}' 中為 {3} '{4}' 所隱含宣告的成員互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynthMemberClashesWithMember5">
<source>{0} '{1}' implicitly defines '{2}', which conflicts with a member of the same name in {3} '{4}'.</source>
<target state="translated">{0} '{1}' 隱含定義 '{2}',其與 {3} '{4}' 中相同名稱的成員互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MemberClashesWithSynth6">
<source>{0} '{1}' conflicts with a member implicitly declared for {2} '{3}' in {4} '{5}'.</source>
<target state="translated">{0} '{1}' 與 {4} '{5}' 中為 {2} '{3}' 所隱含宣告的成員互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeClashesWithVbCoreType4">
<source>{0} '{1}' conflicts with a Visual Basic Runtime {2} '{3}'.</source>
<target state="translated">{0} '{1}' 與 Visual Basic 執行階段 {2} '{3}' 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeMissingAction">
<source>First argument to a security attribute must be a valid SecurityAction.</source>
<target state="translated">安全屬性的第一個引數,必須是有效的 SecurityAction。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidAction">
<source>Security attribute '{0}' has an invalid SecurityAction value '{1}'.</source>
<target state="translated">安全屬性 '{0}' 的 SecurityAction 值 '{1}' 無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidActionAssembly">
<source>SecurityAction value '{0}' is invalid for security attributes applied to an assembly.</source>
<target state="translated">SecurityAction 值 '{0}' 對套用至組件的安全屬性無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidActionTypeOrMethod">
<source>SecurityAction value '{0}' is invalid for security attributes applied to a type or a method.</source>
<target state="translated">SecurityAction 值 '{0}' 對套用至類型或方法的安全屬性無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PrincipalPermissionInvalidAction">
<source>SecurityAction value '{0}' is invalid for PrincipalPermission attribute.</source>
<target state="translated">SecurityAction 值 '{0}' 對 PrincipalPermission 屬性無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PermissionSetAttributeInvalidFile">
<source>Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute.</source>
<target state="translated">無法解析指定給 PermissionSet 屬性之具名引數 '{1}' 的檔案路徑 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PermissionSetAttributeFileReadError">
<source>Error reading file '{0}' specified for the named argument '{1}' for PermissionSet attribute: '{2}'.</source>
<target state="translated">讀取指定給 PermissionSet 屬性之具名引數 '{1}' 的檔案 '{0}' 時發生錯誤: '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SetHasOnlyOneParam">
<source>'Set' method cannot have more than one parameter.</source>
<target state="translated">'Set' 方法不可以有多個參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SetValueNotPropertyType">
<source>'Set' parameter must have the same type as the containing property.</source>
<target state="translated">'Set' 參數必須和包含的屬性具有相同的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SetHasToBeByVal1">
<source>'Set' parameter cannot be declared '{0}'.</source>
<target state="translated">'Set' 參數不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructureCantUseProtected">
<source>Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.</source>
<target state="translated">在結構中的方法不可宣告為 'Protected'、'Protected Friend' 或 'Private Protected'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceDelegateSpecifier1">
<source>Delegate in an interface cannot be declared '{0}'.</source>
<target state="translated">介面中的委派不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceEnumSpecifier1">
<source>Enum in an interface cannot be declared '{0}'.</source>
<target state="translated">介面中的列舉不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceClassSpecifier1">
<source>Class in an interface cannot be declared '{0}'.</source>
<target state="translated">介面中的類別不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceStructSpecifier1">
<source>Structure in an interface cannot be declared '{0}'.</source>
<target state="translated">介面中的結構不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceInterfaceSpecifier1">
<source>Interface in an interface cannot be declared '{0}'.</source>
<target state="translated">介面中的介面不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoleteSymbolNoMessage1">
<source>'{0}' is obsolete.</source>
<target state="translated">'{0}' 已經過時。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetaDataIsNotAssembly">
<source>'{0}' is a module and cannot be referenced as an assembly.</source>
<target state="translated">'{0}' 是一個模組,且無法當做組件來參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetaDataIsNotModule">
<source>'{0}' is an assembly and cannot be referenced as a module.</source>
<target state="translated">'{0}' 是一個組件,且無法當做模組來參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReferenceComparison3">
<source>Operator '{0}' is not defined for types '{1}' and '{2}'. Use 'Is' operator to compare two reference types.</source>
<target state="translated">未定義類型 '{1}' 和 '{2}' 的運算子 '{0}'。請使用 'Is' 運算子比較兩個參考類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchVariableNotLocal1">
<source>'{0}' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.</source>
<target state="translated">'{0}' 不是區域變數或參數,所以不能用做為 'Catch' 變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleMemberCantImplement">
<source>Members in a Module cannot implement interface members.</source>
<target state="translated">模組中的成員不可以實作介面成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventDelegatesCantBeFunctions">
<source>Events cannot be declared with a delegate type that has a return type.</source>
<target state="translated">事件不可以宣告為具有傳回類型的委派類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidDate">
<source>Date constant is not valid.</source>
<target state="translated">日期常數無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOverride4">
<source>'{0}' cannot override '{1}' because it is not declared 'Overridable'.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其未宣告為 'Overridable'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyArraysOnBoth">
<source>Array modifiers cannot be specified on both a variable and its type.</source>
<target state="translated">無法同時在變數及其類型上指定陣列修飾元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NotOverridableRequiresOverrides">
<source>'NotOverridable' cannot be specified for methods that do not override another method.</source>
<target state="translated">'NotOverridable' 無法指定給不覆寫其他方法的方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PrivateTypeOutsideType">
<source>Types declared 'Private' must be inside another type.</source>
<target state="translated">宣告為 'Private' 的類型必須在另一個類型內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeRefResolutionError3">
<source>Import of type '{0}' from assembly or module '{1}' failed.</source>
<target state="translated">從組件或模組 '{1}' 匯入類型 '{0}' 失敗。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ValueTupleTypeRefResolutionError1">
<source>Predefined type '{0}' is not defined or imported.</source>
<target state="translated">預先定義的類型 '{0}' 未經定義或匯入。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayWrongType">
<source>ParamArray parameters must have an array type.</source>
<target state="translated">ParamArray 參數必須有陣列類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CoClassMissing2">
<source>Implementing class '{0}' for interface '{1}' cannot be found.</source>
<target state="translated">找不到介面 '{1}' 的實作類別 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidCoClass1">
<source>Type '{0}' cannot be used as an implementing class.</source>
<target state="translated">類型 '{0}' 無法用做為實作類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMeReference">
<source>Reference to object under construction is not valid when calling another constructor.</source>
<target state="translated">呼叫其他建構函式時,參考建構中的物件是無效的。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidImplicitMeReference">
<source>Implicit reference to object under construction is not valid when calling another constructor.</source>
<target state="translated">呼叫其他建構函式時,隱含參考建構中的物件是無效的。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RuntimeMemberNotFound2">
<source>Member '{0}' cannot be found in class '{1}'. This condition is usually the result of a mismatched 'Microsoft.VisualBasic.dll'.</source>
<target state="translated">在類別 '{1}' 中找不到成員 '{0}'。這種情況通常是 'Microsoft.VisualBasic.dll' 不相符的結果。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags">
<source>Property accessors cannot be declared '{0}'.</source>
<target state="translated">屬性存取子不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlagsRestrict">
<source>Access modifier '{0}' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.</source>
<target state="translated">存取修飾詞 '{0}' 無效。'Get' 和 'Set' 的存取修飾詞,應較屬性存取層級有更多限制。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyOneAccessorForGetSet">
<source>Access modifier can only be applied to either 'Get' or 'Set', but not both.</source>
<target state="translated">存取修飾詞只能套用至 'Get' 或 'Set',但不能同時套用至兩者。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAccessibleSet">
<source>'Set' accessor of property '{0}' is not accessible.</source>
<target state="translated">'無法存取屬性 '{0}' 的 'Set' 存取子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAccessibleGet">
<source>'Get' accessor of property '{0}' is not accessible.</source>
<target state="translated">'無法存取屬性 '{0}' 的 'Get' 存取子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_WriteOnlyNoAccessorFlag">
<source>'WriteOnly' properties cannot have an access modifier on 'Set'.</source>
<target state="translated">'WriteOnly' 屬性在 'Set' 上不能有存取修飾詞。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyNoAccessorFlag">
<source>'ReadOnly' properties cannot have an access modifier on 'Get'.</source>
<target state="translated">'ReadOnly' 屬性在 'Get' 上不能有存取修飾詞。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags1">
<source>Property accessors cannot be declared '{0}' in a 'NotOverridable' property.</source>
<target state="translated">屬性存取子在 'NotOverridable' 屬性中不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags2">
<source>Property accessors cannot be declared '{0}' in a 'Default' property.</source>
<target state="translated">屬性存取子在 'Default' 屬性中不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags3">
<source>Property cannot be declared '{0}' because it contains a 'Private' accessor.</source>
<target state="translated">屬性不可宣告為 '{0}',因為它包含 'Private' 存取子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InAccessibleCoClass3">
<source>Implementing class '{0}' for interface '{1}' is not accessible in this context because it is '{2}'.</source>
<target state="translated">無法在此內容中存取介面 '{1}' 的實作類別 '{0}',因為其為 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingValuesForArraysInApplAttrs">
<source>Arrays used as attribute arguments are required to explicitly specify values for all elements.</source>
<target state="translated">明確指定所有元素的值時,用做為屬性引數的陣列為必要項目。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitEventMemberNotInvalid">
<source>'Exit AddHandler', 'Exit RemoveHandler' and 'Exit RaiseEvent' are not valid. Use 'Return' to exit from event members.</source>
<target state="translated">'Exit AddHandler'、'Exit RemoveHandler' 和 'Exit RaiseEvent' 無效。請使用 'Return' 結束事件成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsEvent">
<source>Statement cannot appear within an event body. End of event assumed.</source>
<target state="translated">陳述式不能出現在事件主體內。假設是事件結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndEvent">
<source>'Custom Event' must end with a matching 'End Event'.</source>
<target state="translated">'Custom Event' 結尾必須是對應的 'End Event'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndAddHandler">
<source>'AddHandler' declaration must end with a matching 'End AddHandler'.</source>
<target state="translated">'AddHandler' 宣告之後必須搭配相對應的 'End AddHandler'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndRemoveHandler">
<source>'RemoveHandler' declaration must end with a matching 'End RemoveHandler'.</source>
<target state="translated">'RemoveHandler' 宣告之後必須搭配相對應的 'End RemoveHandler'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndRaiseEvent">
<source>'RaiseEvent' declaration must end with a matching 'End RaiseEvent'.</source>
<target state="translated">'RaiseEvent' 宣告之後必須搭配相對應的 'End RaiseEvent'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CustomEventInvInInterface">
<source>'Custom' modifier is not valid on events declared in interfaces.</source>
<target state="translated">'Custom' 修飾元在以介面宣告的事件中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CustomEventRequiresAs">
<source>'Custom' modifier is not valid on events declared without explicit delegate types.</source>
<target state="translated">'Custom' 修飾元在沒有以明確委派類型宣告的事件中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndEvent">
<source>'End Event' must be preceded by a matching 'Custom Event'.</source>
<target state="translated">'End Event' 之前必須搭配相對應的 'Custom Event'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndAddHandler">
<source>'End AddHandler' must be preceded by a matching 'AddHandler' declaration.</source>
<target state="translated">'End AddHandler' 之前必須搭配相對應的 'AddHandler' 宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndRemoveHandler">
<source>'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration.</source>
<target state="translated">'End RemoveHandler' 之前必須搭配相對應的 'RemoveHandler' 宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndRaiseEvent">
<source>'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration.</source>
<target state="translated">'End RaiseEvent' 之前必須搭配相對應的 'RaiseEvent' 宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAddHandlerDef">
<source>'AddHandler' is already declared.</source>
<target state="translated">'AddHandler' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateRemoveHandlerDef">
<source>'RemoveHandler' is already declared.</source>
<target state="translated">'RemoveHandler' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateRaiseEventDef">
<source>'RaiseEvent' is already declared.</source>
<target state="translated">'RaiseEvent' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingAddHandlerDef1">
<source>'AddHandler' definition missing for event '{0}'.</source>
<target state="translated">'事件 '{0}' 遺漏 'AddHandler' 定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingRemoveHandlerDef1">
<source>'RemoveHandler' definition missing for event '{0}'.</source>
<target state="translated">'事件 '{0}' 遺漏 'RemoveHandler' 定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingRaiseEventDef1">
<source>'RaiseEvent' definition missing for event '{0}'.</source>
<target state="translated">'事件 '{0}' 遺漏 'RaiseEvent' 定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventAddRemoveHasOnlyOneParam">
<source>'AddHandler' and 'RemoveHandler' methods must have exactly one parameter.</source>
<target state="translated">'AddHandler' 和 'RemoveHandler' 方法必須剛好有一個參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventAddRemoveByrefParamIllegal">
<source>'AddHandler' and 'RemoveHandler' method parameters cannot be declared 'ByRef'.</source>
<target state="translated">'AddHandler' 和 'RemoveHandler' 方法參數不可以宣告為 'ByRef'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SpecifiersInvOnEventMethod">
<source>Specifiers are not valid on 'AddHandler', 'RemoveHandler' and 'RaiseEvent' methods.</source>
<target state="translated">AddHandler'、'RemoveHandler' 和 'RaiseEvent' 方法上的規範無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddRemoveParamNotEventType">
<source>'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event.</source>
<target state="translated">'AddHandler' 和 'RemoveHandler' 方法參數必須與包含事件擁有相同的委派類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RaiseEventShapeMismatch1">
<source>'RaiseEvent' method must have the same signature as the containing event's delegate type '{0}'.</source>
<target state="translated">'RaiseEvent' 方法必須與包含的事件委派類型 '{0}',擁有相同的簽章。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventMethodOptionalParamIllegal1">
<source>'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared '{0}'.</source>
<target state="translated">'AddHandler'、'RemoveHandler' 和 'RaiseEvent' 方法參數不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantReferToMyGroupInsideGroupType1">
<source>'{0}' cannot refer to itself through its default instance; use 'Me' instead.</source>
<target state="translated">'{0}' 不可透過其預設執行個體參考本身; 請改用 'Me'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidUseOfCustomModifier">
<source>'Custom' modifier can only be used immediately before an 'Event' declaration.</source>
<target state="translated">'Custom' 修飾元只能緊接地用於 'Event' 宣告的前面。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionStrictCustom">
<source>Option Strict Custom can only be used as an option to the command-line compiler (vbc.exe).</source>
<target state="translated">Option Strict Custom 只能當做命令列編譯器 (vbc.exe) 選項使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteInvalidOnEventMember">
<source>'{0}' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event.</source>
<target state="translated">'{0}' 無法套用至 'AddHandler'、'RemoveHandler' 或 'RaiseEvent' 定義。必要時,請將屬性直接套用至事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingIncompatible2">
<source>Method '{0}' does not have a signature compatible with delegate '{1}'.</source>
<target state="translated">方法 '{0}' 沒有與委派 '{1}' 相容的簽章。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlName">
<source>XML name expected.</source>
<target state="translated">必須是 XML 名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UndefinedXmlPrefix">
<source>XML namespace prefix '{0}' is not defined.</source>
<target state="translated">XML 命名空間前置詞 '{0}' 未定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateXmlAttribute">
<source>Duplicate XML attribute '{0}'.</source>
<target state="translated">重複的 XML 屬性 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MismatchedXmlEndTag">
<source>End tag </{0}{1}{2}> expected.</source>
<target state="translated">必須是結束標記 </{0}{1}{2}>。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingXmlEndTag">
<source>Element is missing an end tag.</source>
<target state="translated">項目中遺漏結束標記。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReservedXmlPrefix">
<source>XML namespace prefix '{0}' is reserved for use by XML and the namespace URI cannot be changed.</source>
<target state="translated">XML 命名空間前置詞 '{0}' 已保留供 XML 使用,且不可變更命名空間 URI。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingVersionInXmlDecl">
<source>Required attribute 'version' missing from XML declaration.</source>
<target state="translated">XML 宣告遺漏必要的屬性 'version'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalAttributeInXmlDecl">
<source>XML declaration does not allow attribute '{0}{1}{2}'.</source>
<target state="translated">XML 宣告不可使用屬性 '{0}{1}{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QuotedEmbeddedExpression">
<source>Embedded expression cannot appear inside a quoted attribute value. Try removing quotes.</source>
<target state="translated">有引號的屬性值中不能出現內嵌運算式。請移除引號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VersionMustBeFirstInXmlDecl">
<source>XML attribute 'version' must be the first attribute in XML declaration.</source>
<target state="translated">XML 屬性 'version' 必須是 XML 宣告中的第一個屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeOrder">
<source>XML attribute '{0}' must appear before XML attribute '{1}'.</source>
<target state="translated">XML 屬性 '{0}' 必須出現在 XML 屬性 '{1}' 之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndEmbedded">
<source>Expected closing '%>' for embedded expression.</source>
<target state="translated">內嵌運算式必須以 '%>' 結尾</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndPI">
<source>Expected closing '?>' for XML processor instruction.</source>
<target state="translated">XML 處理器指示必須以 '?>' 結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndComment">
<source>Expected closing '-->' for XML comment.</source>
<target state="translated">XML 註解必須以 '-->' 結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndCData">
<source>Expected closing ']]>' for XML CDATA section.</source>
<target state="translated">XML CDATA 區段必須以 ']]>' 結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSQuote">
<source>Expected matching closing single quote for XML attribute value.</source>
<target state="translated">XML 屬性值的結束單引號必須相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedQuote">
<source>Expected matching closing double quote for XML attribute value.</source>
<target state="translated">必須是對應的 XML 屬性值右雙引號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLT">
<source>Expected beginning '<' for an XML tag.</source>
<target state="translated">XML 標記應以 '<' 開頭。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StartAttributeValue">
<source>Expected quoted XML attribute value or embedded expression.</source>
<target state="translated">必須為引號 XML 屬性值或內嵌運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDiv">
<source>Expected '/' for XML end tag.</source>
<target state="translated">XML 結束標記必須是 '/'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoXmlAxesLateBinding">
<source>XML axis properties do not support late binding.</source>
<target state="translated">XML 軸屬性不支援晚期繫結。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlStartNameChar">
<source>Character '{0}' ({1}) is not allowed at the beginning of an XML name.</source>
<target state="translated">XML 名稱的開頭不可使用字元 '{0}' ({1})。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlNameChar">
<source>Character '{0}' ({1}) is not allowed in an XML name.</source>
<target state="translated">XML 名稱中不可使用字元 '{0}' ({1})。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlCommentChar">
<source>Character sequence '--' is not allowed in an XML comment.</source>
<target state="translated">XML 註解中不可有字元順序 '--'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EmbeddedExpression">
<source>An embedded expression cannot be used here.</source>
<target state="translated">內嵌運算式不能用在這裡。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlWhiteSpace">
<source>Missing required white space.</source>
<target state="translated">遺漏必要的空白字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalProcessingInstructionName">
<source>XML processing instruction name '{0}' is not valid.</source>
<target state="translated">XML 處理指示名稱 '{0}' 無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DTDNotSupported">
<source>XML DTDs are not supported.</source>
<target state="translated">不支援 XML DTD。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlWhiteSpace">
<source>White space cannot appear here.</source>
<target state="translated">空白字元不可出現在這裡。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSColon">
<source>Expected closing ';' for XML entity.</source>
<target state="translated">XML 實體必須以 ';' 結尾</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlBeginEmbedded">
<source>Expected '%=' at start of an embedded expression.</source>
<target state="translated">內嵌運算式的開頭必須是 '%='。</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlEntityReference">
<source>XML entity references are not supported.</source>
<target state="translated">不支援 XML 實體參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeValue1">
<source>Attribute value is not valid; expecting '{0}'.</source>
<target state="translated">屬性值無效,必須是 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeValue2">
<source>Attribute value is not valid; expecting '{0}' or '{1}'.</source>
<target state="translated">屬性值無效,必須是 '{0}' 或 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReservedXmlNamespace">
<source>Prefix '{0}' cannot be bound to namespace name reserved for '{1}'.</source>
<target state="translated">前置詞 '{0}' 無法繫結至為 '{1}' 保留的命名空間名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalDefaultNamespace">
<source>Namespace declaration with prefix cannot have an empty value inside an XML literal.</source>
<target state="translated">具有前置字元的命名空間宣告在 XML 常值中不能有空值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QualifiedNameNotAllowed">
<source>':' is not allowed. XML qualified names cannot be used in this context.</source>
<target state="translated">'不允許 ':'。XML 限定名稱不能用在此內容中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlns">
<source>Namespace declaration must start with 'xmlns'.</source>
<target state="translated">命名空間宣告必須要使用 'xmlns' 開頭。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlnsPrefix">
<source>Element names cannot use the 'xmlns' prefix.</source>
<target state="translated">項目名稱不能使用 'xmlns' 前置字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlFeaturesNotAvailable">
<source>XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types.</source>
<target state="translated">無法使用 XML 常值與 XML 軸屬性。請將參考加入 System.Xml、System.Xml.Linq、System.Core,或其他宣告 System.Linq.Enumerable、System.Xml.Linq.XElement、System.Xml.Linq.XName、System.Xml.Linq.XAttribute 和 System.Xml.Linq.XNamespace 類型的組件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnableToReadUacManifest2">
<source>Unable to open Win32 manifest file '{0}' : {1}</source>
<target state="translated">無法開啟 Win32 資訊清單檔 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseValueForXmlExpression3">
<source>Cannot convert '{0}' to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'.</source>
<target state="translated">無法將 '{0}' 轉換成 '{1}'。您可使用 'Value' 屬性來取得 '{2}' 第一個元素之字串值。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseValueForXmlExpression3_Title">
<source>Cannot convert IEnumerable(Of XElement) to String</source>
<target state="translated">無法將 IEnumerable(Of XElement) 轉換成字串</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeMismatchForXml3">
<source>Value of type '{0}' cannot be converted to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'.</source>
<target state="translated">類型 '{0}' 的值無法轉換成 '{1}'。您可以使用 'Value' 屬性,取得 '{2}' 第一個元素的字串值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryOperandsForXml4">
<source>Operator '{0}' is not defined for types '{1}' and '{2}'. You can use the 'Value' property to get the string value of the first element of '{3}'.</source>
<target state="translated">未對類型 '{1}' 和 '{2}' 定義運算子 '{0}'。您可使用 'Value' 屬性取得 '{3}' 第一個元素的字串值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FullWidthAsXmlDelimiter">
<source>Full width characters are not valid as XML delimiters.</source>
<target state="translated">全形字元不能做為 XML 分隔符號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSubsystemVersion">
<source>The value '{0}' is not a valid subsystem version. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise.</source>
<target state="translated">值 '{0}' 不是有效的子系統版本。ARM 或 AppContainerExe 的版本必須是 6.02 (含) 以上,而其他則必須是 4.00 (含) 以上。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidFileAlignment">
<source>Invalid file section alignment '{0}'</source>
<target state="translated">無效的檔案區段記憶體對齊 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOutputName">
<source>Invalid output name: {0}</source>
<target state="translated">無效的輸出名稱: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidDebugInformationFormat">
<source>Invalid debug information format: {0}</source>
<target state="translated">無效的偵錯資訊格式: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_LibAnycpu32bitPreferredConflict">
<source>/platform:anycpu32bitpreferred can only be used with /t:exe, /t:winexe and /t:appcontainerexe.</source>
<target state="translated">/platform:anycpu32bitpreferred 只能搭配 /t:exe、/t:winexe 和 /t:appcontainerexe 一起使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedAccess">
<source>Expression has the type '{0}' which is a restricted type and cannot be used to access members inherited from 'Object' or 'ValueType'.</source>
<target state="translated">運算式的類型為 '{0}',其為受限制的類型且不可用以存取繼承自 'Object' 或 'ValueType' 的成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedConversion1">
<source>Expression of type '{0}' cannot be converted to 'Object' or 'ValueType'.</source>
<target state="translated">類型 '{0}' 的運算式無法轉換成 'Object' 或 'ValueType'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoTypecharInLabel">
<source>Type characters are not allowed in label identifiers.</source>
<target state="translated">標籤識別項中不允許類型字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedType1">
<source>'{0}' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.</source>
<target state="translated">'{0}' 不可為 Null,且不可用做為陣列元素、欄位、匿名類型成員、類型引數、'ByRef' 參數或傳回陳述式的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoTypecharInAlias">
<source>Type characters are not allowed on Imports aliases.</source>
<target state="translated">Imports 別名上不允許類型字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAccessibleConstructorOnBase">
<source>Class '{0}' has no accessible 'Sub New' and cannot be inherited.</source>
<target state="translated">類別 '{0}' 沒有可存取的 'Sub New',且無法被繼承。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadStaticLocalInStruct">
<source>Local variables within methods of structures cannot be declared 'Static'.</source>
<target state="translated">結構方法中的區域變數無法宣告為 'Static'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateLocalStatic1">
<source>Static local variable '{0}' is already declared.</source>
<target state="translated">靜態區域變數 '{0}' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImportAliasConflictsWithType2">
<source>Imports alias '{0}' conflicts with '{1}' declared in the root namespace.</source>
<target state="translated">Imports 別名 '{0}' 和根命名空間中宣告的 '{1}' 衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantShadowAMustOverride1">
<source>'{0}' cannot shadow a method declared 'MustOverride'.</source>
<target state="translated">'{0}' 不可遮蔽宣告為 'MustOverride' 的方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleEventImplMismatch3">
<source>Event '{0}' cannot implement event '{2}.{1}' because its delegate type does not match the delegate type of another event implemented by '{0}'.</source>
<target state="translated">事件 '{0}' 無法實作事件 '{2}.{1}',因為其委派類型與其他以 '{0}' 實作的事件之委派類型不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadSpecifierCombo2">
<source>'{0}' and '{1}' cannot be combined.</source>
<target state="translated">'無法結合 '{0}' 和 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustBeOverloads2">
<source>{0} '{1}' must be declared 'Overloads' because another '{1}' is declared 'Overloads' or 'Overrides'.</source>
<target state="translated">{0} '{1}' 必須宣告為 'Overloads',因為另一個 '{1}' 已宣告為 'Overloads' 或 'Overrides'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustOverridesInClass1">
<source>'{0}' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.</source>
<target state="translated">'{0}' 必須宣告為 'MustInherit',因為其包含宣告為 'MustOverride' 的方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_HandlesSyntaxInClass">
<source>'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.</source>
<target state="translated">'類別中的 'Handles' 必須指定以單一識別項限定的 'WithEvents' 變數、'MyBase'、'MyClass' 或 'Me'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynthMemberShadowsMustOverride5">
<source>'{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'.</source>
<target state="translated">'為 {1} '{2}' 隱含宣告的 '{0}',無法遮蔽基底 {3} '{4}' 中的 'MustOverride' 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotOverrideInAccessibleMember">
<source>'{0}' cannot override '{1}' because it is not accessible in this context.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為在此內容中無法存取它。</target>
<note />
</trans-unit>
<trans-unit id="ERR_HandlesSyntaxInModule">
<source>'Handles' in modules must specify a 'WithEvents' variable qualified with a single identifier.</source>
<target state="translated">'模組中的 'Handles' 必須指定以單一識別項限定的 'WithEvents' 變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNotOpRequiresReferenceTypes1">
<source>'IsNot' requires operands that have reference types, but this operand has the value type '{0}'.</source>
<target state="translated">'IsNot' 需要具有參考類型的運算元,但此運算元為實值類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClashWithReservedEnumMember1">
<source>'{0}' conflicts with the reserved member by this name that is implicitly declared in all enums.</source>
<target state="translated">'{0}' 與使用此名稱的保留成員互相衝突,此名稱已在所有列舉中隱含宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultiplyDefinedEnumMember2">
<source>'{0}' is already declared in this {1}.</source>
<target state="translated">'在此 {1} 中已宣告 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadUseOfVoid">
<source>'System.Void' can only be used in a GetType expression.</source>
<target state="translated">'System.Void' 只能使用於 GetType 運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventImplMismatch5">
<source>Event '{0}' cannot implement event '{1}' on interface '{2}' because their delegate types '{3}' and '{4}' do not match.</source>
<target state="translated">事件 '{0}' 無法在介面 '{2}' 上實作事件 '{1}',因為它們的委派類型 '{3}' 和 '{4}' 不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypeUnavailable3">
<source>Type '{0}' in assembly '{1}' has been forwarded to assembly '{2}'. Either a reference to '{2}' is missing from your project or the type '{0}' is missing from assembly '{2}'.</source>
<target state="translated">組件 '{1}' 中的類型 '{0}',已轉送至組件 '{2}'。專案中遺漏對 '{2}' 的參考,或者組件 '{2}' 中遺漏類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeFwdCycle2">
<source>'{0}' in assembly '{1}' has been forwarded to itself and so is an unsupported type.</source>
<target state="translated">'組件 '{1}' 中的 '{0}' 已轉送至其本身,所以不支援該類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeInCCExpression">
<source>Non-intrinsic type names are not allowed in conditional compilation expressions.</source>
<target state="translated">條件式編譯運算式中不允許非內建的類型名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadCCExpression">
<source>Syntax error in conditional compilation expression.</source>
<target state="translated">條件式編譯運算式中的語法錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VoidArrayDisallowed">
<source>Arrays of type 'System.Void' are not allowed in this expression.</source>
<target state="translated">此運算式中不允許類型 'System.Void' 的陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetadataMembersAmbiguous3">
<source>'{0}' is ambiguous because multiple kinds of members with this name exist in {1} '{2}'.</source>
<target state="translated">'因為在 {1} '{2}' 中有多種具備此名稱的成員,因而 '{0}' 模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOfExprAlwaysFalse2">
<source>Expression of type '{0}' can never be of type '{1}'.</source>
<target state="translated">類型 '{0}' 的運算式不能為類型 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyPrivatePartialMethods1">
<source>Partial methods must be declared 'Private' instead of '{0}'.</source>
<target state="translated">部分方法必須宣告為 'Private',而非 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodsMustBePrivate">
<source>Partial methods must be declared 'Private'.</source>
<target state="translated">部分方法必須宣告為 'Private'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyOnePartialMethodAllowed2">
<source>Method '{0}' cannot be declared 'Partial' because only one method '{1}' can be marked 'Partial'.</source>
<target state="translated">方法 '{0}' 不可宣告為 'Partial',因為只有一個方法 '{1}' 可標記為 'Partial'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyOneImplementingMethodAllowed3">
<source>Method '{0}' cannot implement partial method '{1}' because '{2}' already implements it. Only one method can implement a partial method.</source>
<target state="translated">方法 '{0}' 無法實作部分方法 '{1}',因為 '{2}' 已實作該方法。只有一個方法可實作部分方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodMustBeEmpty">
<source>Partial methods must have empty method bodies.</source>
<target state="translated">部分方法的方法主體必須是空的。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodsMustBeSub1">
<source>'{0}' cannot be declared 'Partial' because partial methods must be Subs.</source>
<target state="translated">'{0}' 不可宣告為 'Partial',因為部分方法必須是 Sub。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodGenericConstraints2">
<source>Method '{0}' does not have the same generic constraints as the partial method '{1}'.</source>
<target state="translated">方法 '{0}' 沒有與部分方法 '{1}' 相同的泛型條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialDeclarationImplements1">
<source>Partial method '{0}' cannot use the 'Implements' keyword.</source>
<target state="translated">部分方法 '{0}' 不可使用 'Implements' 關鍵字。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoPartialMethodInAddressOf1">
<source>'AddressOf' cannot be applied to '{0}' because '{0}' is a partial method without an implementation.</source>
<target state="translated">'AddressOf' 無法套用至 '{0}',因為 '{0}' 是沒有實作的部分方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementationMustBePrivate2">
<source>Method '{0}' must be declared 'Private' in order to implement partial method '{1}'.</source>
<target state="translated">方法 '{0}' 必須宣告為 'Private',才能實作部分方法 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodParamNamesMustMatch3">
<source>Parameter name '{0}' does not match the name of the corresponding parameter, '{1}', defined on the partial method declaration '{2}'.</source>
<target state="translated">參數名稱 '{0}' 與部分方法宣告 '{2}' 中所定義之對應參數 '{1}' 的名稱不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodTypeParamNameMismatch3">
<source>Name of type parameter '{0}' does not match '{1}', the corresponding type parameter defined on the partial method declaration '{2}'.</source>
<target state="translated">類型參數 '{0}' 的名稱,與部分方法宣告 '{2}' 中所定義的對應類型參數 '{1}' 不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeSharedProperty1">
<source>'Shared' attribute property '{0}' cannot be the target of an assignment.</source>
<target state="translated">'Shared' 屬性 (Attribute) 的屬性 (Property) '{0}',不可是指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeReadOnlyProperty1">
<source>'ReadOnly' attribute property '{0}' cannot be the target of an assignment.</source>
<target state="translated">'ReadOnly' 屬性 (Attribute) 的屬性 (Property) '{0}',不可是指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateResourceName1">
<source>Resource name '{0}' cannot be used more than once.</source>
<target state="translated">資源名稱 '{0}' 不可重複使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateResourceFileName1">
<source>Each linked resource and module must have a unique filename. Filename '{0}' is specified more than once in this assembly.</source>
<target state="translated">每個連結的資源與模組,都必須要有不重複的檔名。檔名 '{0}' 在此組件中指定了一次以上。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeMustBeClassNotStruct1">
<source>'{0}' cannot be used as an attribute because it is not a class.</source>
<target state="translated">'無法將 '{0}' 用做為屬性,因為其非類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeMustInheritSysAttr">
<source>'{0}' cannot be used as an attribute because it does not inherit from 'System.Attribute'.</source>
<target state="translated">'無法將 '{0}' 用做為屬性,因為其非繼承自 'System.Attribute'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeCannotBeAbstract">
<source>'{0}' cannot be used as an attribute because it is declared 'MustInherit'.</source>
<target state="translated">'無法將 '{0}' 用做為屬性,因為其宣告為 'MustInherit'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnableToOpenResourceFile1">
<source>Unable to open resource file '{0}': {1}</source>
<target state="translated">無法開啟資源檔 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicProperty1">
<source>Attribute member '{0}' cannot be the target of an assignment because it is not declared 'Public'.</source>
<target state="translated">屬性成員 '{0}' 不可是指派的目標,因為其未宣告為 'Public'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_STAThreadAndMTAThread0">
<source>'System.STAThreadAttribute' and 'System.MTAThreadAttribute' cannot both be applied to the same method.</source>
<target state="translated">'System.STAThreadAttribute' 和 'System.MTAThreadAttribute' 無法同時套用至同一個方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IndirectUnreferencedAssembly4">
<source>Project '{0}' makes an indirect reference to assembly '{1}', which contains '{2}'. Add a file reference to '{3}' to your project.</source>
<target state="translated">專案 '{0}' 會間接參考含有 '{2}' 的組件 '{1}'。請在您的專案中加入 '{3}' 的檔案參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicType1">
<source>Type '{0}' cannot be used in an attribute because it is not declared 'Public'.</source>
<target state="translated">無法在屬性中使用類型 '{0}',因為其未宣告為 'Public'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicContType2">
<source>Type '{0}' cannot be used in an attribute because its container '{1}' is not declared 'Public'.</source>
<target state="translated">無法在屬性中使用類型 '{0}',因為其容器 '{1}' 未宣告為 'Public'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnNonEmptySubOrFunction">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Sub, Function, or Operator with a non-empty body.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至非空白主體的 Sub、Function 或 Operator。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportNotLegalOnDeclare">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Declare.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至 Declare。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportNotLegalOnGetOrSet">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Get or Set.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至 Get 或 Set。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnGenericSubOrFunction">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a method that is generic or contained in a generic type.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至泛型方法,或套用至包含在泛型類型中的方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassOnGeneric">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type.</source>
<target state="translated">'Microsoft.VisualBasic.ComClassAttribute' 無法套用至泛型類別,或套用至包含在泛型類型內的類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnInstanceMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to instance method.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至執行個體方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnInterfaceMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to interface methods.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至介面方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportNotLegalOnEventMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to 'AddHandler', 'RemoveHandler' or 'RaiseEvent' method.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至 'AddHandler'、'RemoveHandler' 或 'RaiseEvent' 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyBadArguments">
<source>Friend assembly reference '{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified.</source>
<target state="translated">Friend 組件參考 '{0}' 無效。InternalsVisibleTo 宣告不可指定版本、文化特性、公開金鑰語彙基元或處理器架構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyStrongNameRequired">
<source>Friend assembly reference '{0}' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations.</source>
<target state="translated">Friend 組件參考 '{0}' 無效。以強式名稱簽署的組件,在其 InternalsVisibleTo 宣告中必須指定公開金鑰。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyNameInvalid">
<source>Friend declaration '{0}' is invalid and cannot be resolved.</source>
<target state="translated">Friend 宣告 '{0}' 無效,無法解析。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyBadAccessOverride2">
<source>Member '{0}' cannot override member '{1}' defined in another assembly/project because the access modifier 'Protected Friend' expands accessibility. Use 'Protected' instead.</source>
<target state="translated">成員 '{0}' 無法覆寫在另一個組件/專案中定義的成員 '{1}',因為存取修飾詞 'Protected Friend' 會展開存取範圍。請改用 'Protected'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfLocalBeforeDeclaration1">
<source>Local variable '{0}' cannot be referred to before it is declared.</source>
<target state="translated">在宣告區域變數 '{0}' 之前,無法參考該區域變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfKeywordFromModule1">
<source>'{0}' is not valid within a Module.</source>
<target state="translated">'{0}' 在 Module 中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BogusWithinLineIf">
<source>Statement cannot end a block outside of a line 'If' statement.</source>
<target state="translated">陳述式不能在 'If' 陳述式行之外結束區塊。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CharToIntegralTypeMismatch1">
<source>'Char' values cannot be converted to '{0}'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit.</source>
<target state="translated">'Char' 的值無法轉換成 '{0}'。請使用 'Microsoft.VisualBasic.AscW' 將字元解譯為 Unicode 值,或使用 'Microsoft.VisualBasic.Val' 將其解譯為數字。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IntegralToCharTypeMismatch1">
<source>'{0}' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit.</source>
<target state="translated">'{0}' 的值無法轉換成 'Char'。請使用 'Microsoft.VisualBasic.ChrW' 將數值解譯為 Unicode 字元,或先將其轉換成 'String',以產生數字。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoDirectDelegateConstruction1">
<source>Delegate '{0}' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.</source>
<target state="translated">委派 '{0}' 必須使用 'AddressOf' 運算式或 Lambda 運算式,做為其建構函式唯一的引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodMustBeFirstStatementOnLine">
<source>Method declaration statements must be the first statement on a logical line.</source>
<target state="translated">方法宣告陳述式必須是邏輯程式敘述行中的第一個陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttrAssignmentNotFieldOrProp1">
<source>'{0}' cannot be named as a parameter in an attribute specifier because it is not a field or property.</source>
<target state="translated">'{0}' 不是欄位或屬性 (Property),所以無法命名為屬性 (Attribute) 規範中的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsObjectComparison1">
<source>Option Strict On disallows operands of type Object for operator '{0}'. Use the 'Is' operator to test for object identity.</source>
<target state="translated">Option Strict 為 On 時,不可為運算子 '{0}' 使用 Object 類型的運算元。請使用 'Is' 運算子來測試物件識別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoConstituentArraySizes">
<source>Bounds can be specified only for the top-level array when initializing an array of arrays.</source>
<target state="translated">在初始化陣列的陣列時,只可以指定最上層陣列的界限。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FileAttributeNotAssemblyOrModule">
<source>'Assembly' or 'Module' expected.</source>
<target state="translated">'必須是 'Assembly' 或 'Module'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FunctionResultCannotBeIndexed1">
<source>'{0}' has no parameters and its return type cannot be indexed.</source>
<target state="translated">'{0}' 沒有參數,且無法對其傳回類型編製索引。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentSyntax">
<source>Comma, ')', or a valid expression continuation expected.</source>
<target state="translated">必須是逗號、')' 或有效的運算式接續符號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedResumeOrGoto">
<source>'Resume' or 'GoTo' expected.</source>
<target state="translated">'必須是 'Resume' 或 'GoTo'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAssignmentOperator">
<source>'=' expected.</source>
<target state="translated">'必須有 '='。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgAlsoOmitted2">
<source>Parameter '{0}' in '{1}' already has a matching omitted argument.</source>
<target state="translated">'{1}' 中的參數 '{0}' 已有相符的省略引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotCallEvent1">
<source>'{0}' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.</source>
<target state="translated">'{0}' 為一事件,不可直接呼叫。請使用 'RaiseEvent' 陳述式引發事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForEachCollectionDesignPattern1">
<source>Expression is of type '{0}', which is not a collection type.</source>
<target state="translated">運算式類型為 '{0}',非集合類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultValueForNonOptionalParam">
<source>Default values cannot be supplied for parameters that are not declared 'Optional'.</source>
<target state="translated">無法提供預設值給未宣告為 'Optional' 的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDotAfterMyBase">
<source>'MyBase' must be followed by '.' and an identifier.</source>
<target state="translated">'在 'MyBase' 之後必須接著 '.' 及一個識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDotAfterMyClass">
<source>'MyClass' must be followed by '.' and an identifier.</source>
<target state="translated">'在 'MyClass' 之後必須接著 '.' 及一個識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictArgumentCopyBackNarrowing3">
<source>Option Strict On disallows narrowing from type '{1}' to type '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument.</source>
<target state="translated">Option Strict 為 On 時,不可將 'ByRef' 參數 '{0}' 的值複製回相對應的引數,而將類型 '{1}' 縮減為類型 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbElseifAfterElse">
<source>'#ElseIf' cannot follow '#Else' as part of a '#If' block.</source>
<target state="translated">'#ElseIf' 不可以跟隨在 '#Else' 之後做為 '#If' 區塊的一部分。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StandaloneAttribute">
<source>Attribute specifier is not a complete statement. Use a line continuation to apply the attribute to the following statement.</source>
<target state="translated">屬性規範不是完整的陳述式。請使用行接續符號將屬性套用至下列陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoUniqueConstructorOnBase2">
<source>Class '{0}' must declare a 'Sub New' because its base class '{1}' has more than one accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">類別 '{0}' 必須宣告 'Sub New',因為其基底類別 '{1}' 有一個以上不用引數即可呼叫的可存取 'Sub New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtraNextVariable">
<source>'Next' statement names more variables than there are matching 'For' statements.</source>
<target state="translated">'Next' 陳述式命名超過符合 'For' 陳述式的變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNewCallTooMany2">
<source>First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' has more than one accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">此 'Sub New' 的第一個陳述式,必須呼叫 'MyBase.New' 或 'MyClass.New',因為 '{1}' 的基底類別 '{0}' 有一個以上不使用引數即可呼叫的可存取 'Sub New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForCtlVarArraySizesSpecified">
<source>Array declared as for loop control variable cannot be declared with an initial size.</source>
<target state="translated">宣告為 for 迴圈控制變數的陣列不能宣告它的初始大小。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnNewOverloads">
<source>The '{0}' keyword is used to overload inherited members; do not use the '{0}' keyword when overloading 'Sub New'.</source>
<target state="translated">'{0}' 關鍵字是用以多載繼承的成員; 當多載 'Sub New' 時,請勿使用 '{0}' 關鍵字。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharOnGenericParam">
<source>Type character cannot be used in a type parameter declaration.</source>
<target state="translated">類型字元無法在類型參數宣告中使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooFewGenericArguments1">
<source>Too few type arguments to '{0}'.</source>
<target state="translated">'{0}' 的類型引數太少。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyGenericArguments1">
<source>Too many type arguments to '{0}'.</source>
<target state="translated">'{0}' 的類型引數太多。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericConstraintNotSatisfied2">
<source>Type argument '{0}' does not inherit from or implement the constraint type '{1}'.</source>
<target state="translated">類型引數 '{0}' 並未繼承或實作條件約束類型 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOrMemberNotGeneric1">
<source>'{0}' has no type parameters and so cannot have type arguments.</source>
<target state="translated">'{0}' 沒有類型參數,因此不可有類型引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewIfNullOnGenericParam">
<source>'New' cannot be used on a type parameter that does not have a 'New' constraint.</source>
<target state="translated">'New' 無法在沒有 'New' 條件約束的類型參數上使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleClassConstraints1">
<source>Type parameter '{0}' can only have one constraint that is a class.</source>
<target state="translated">類型參數 '{0}' 只可有一個為類別的條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstNotClassInterfaceOrTypeParam1">
<source>Type constraint '{0}' must be either a class, interface or type parameter.</source>
<target state="translated">類型條件約束 '{0}' 必須是類別、介面或類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateTypeParamName1">
<source>Type parameter already declared with name '{0}'.</source>
<target state="translated">類型參數已使用名稱 '{0}' 進行宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnboundTypeParam2">
<source>Type parameter '{0}' for '{1}' cannot be inferred.</source>
<target state="translated">無法推斷 '{1}' 的類型參數 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsOperatorGenericParam1">
<source>'Is' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a type parameter with no class constraint.</source>
<target state="translated">'類型 '{0}' 的 'Is' 運算元只能與 'Nothing' 進行比較,因為 '{0}' 是沒有類別條件約束的類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentCopyBackNarrowing3">
<source>Copying the value of 'ByRef' parameter '{0}' back to the matching argument narrows from type '{1}' to type '{2}'.</source>
<target state="translated">將 'ByRef' 參數的值 '{0}' 複製回對稱的引數,會從類型 '{1}' 縮減到 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ShadowingGenericParamWithMember1">
<source>'{0}' has the same name as a type parameter.</source>
<target state="translated">'{0}' 與類型參數擁有相同的名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericParamBase2">
<source>{0} '{1}' cannot inherit from a type parameter.</source>
<target state="translated">{0} '{1}' 無法繼承自類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsGenericParam">
<source>Type parameter not allowed in 'Implements' clause.</source>
<target state="translated">Implements' 子句中不允許類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyNullLowerBound">
<source>Array lower bounds can be only '0'.</source>
<target state="translated">陣列的下限只能是 '0'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassConstraintNotInheritable1">
<source>Type constraint cannot be a 'NotInheritable' class.</source>
<target state="translated">類型條件約束不可以為 'NotInheritable' 類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintIsRestrictedType1">
<source>'{0}' cannot be used as a type constraint.</source>
<target state="translated">'{0}' 不能用做為類型條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericParamsOnInvalidMember">
<source>Type parameters cannot be specified on this declaration.</source>
<target state="translated">不可以在這個宣告上指定類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericArgsOnAttributeSpecifier">
<source>Type arguments are not valid because attributes cannot be generic.</source>
<target state="translated">類型引數無效,因為屬性不可以是泛型的。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttrCannotBeGenerics">
<source>Type parameters, generic types or types contained in generic types cannot be used as attributes.</source>
<target state="translated">類型參數、泛型類型或泛型類型中所包含的類型不能當做屬性使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadStaticLocalInGenericMethod">
<source>Local variables within generic methods cannot be declared 'Static'.</source>
<target state="translated">泛型方法內的區域變數不可以宣告為 'Static'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SyntMemberShadowsGenericParam3">
<source>{0} '{1}' implicitly defines a member '{2}' which has the same name as a type parameter.</source>
<target state="translated">{0} '{1}' 隱含定義成員 '{2}',該成員與類型參數擁有相同的名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintAlreadyExists1">
<source>Constraint type '{0}' already specified for this type parameter.</source>
<target state="translated">已為此類型參數指定條件約束類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfacePossiblyImplTwice2">
<source>Cannot implement interface '{0}' because its implementation could conflict with the implementation of another implemented interface '{1}' for some type arguments.</source>
<target state="translated">無法實作介面 '{0}',因為它的實作可能與某些類型引數的另一個實作介面 '{1}' 之實作互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModulesCannotBeGeneric">
<source>Modules cannot be generic.</source>
<target state="translated">模組不可以是泛型的。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericClassCannotInheritAttr">
<source>Classes that are generic or contained in a generic type cannot inherit from an attribute class.</source>
<target state="translated">泛型類別或包含在泛型類型中的類別不可以繼承自屬性類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DeclaresCantBeInGeneric">
<source>'Declare' statements are not allowed in generic types or types contained in generic types.</source>
<target state="translated">'泛型類型或包含在泛型類型中的類型,不可使用 'Declare' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithConstraintMismatch2">
<source>'{0}' cannot override '{1}' because they differ by type parameter constraints.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其類型參數條件約束不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsWithConstraintMismatch3">
<source>'{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints.</source>
<target state="translated">'{0}' 無法實作 '{1}.{2}',因為它們的類型參數條件約束不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OpenTypeDisallowed">
<source>Type parameters or types constructed with type parameters are not allowed in attribute arguments.</source>
<target state="translated">屬性引數中不允許類型參數或以類型參數建構的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_HandlesInvalidOnGenericMethod">
<source>Generic methods cannot use 'Handles' clause.</source>
<target state="translated">泛型方法不可以使用 'Handles' 子句。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleNewConstraints">
<source>'New' constraint cannot be specified multiple times for the same type parameter.</source>
<target state="translated">'不能針對相同的類型參數多次指定 'New' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustInheritForNewConstraint2">
<source>Type argument '{0}' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter '{1}'.</source>
<target state="translated">類型引數 '{0}' 宣告為 'MustInherit',且不符合類型參數 '{1}' 的 'New' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSuitableNewForNewConstraint2">
<source>Type argument '{0}' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter '{1}'.</source>
<target state="translated">類型引數 '{0}' 必須擁有公用的無參數執行個體建構函式,才能滿足類型參數 '{1}' 的 'New' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadGenericParamForNewConstraint2">
<source>Type parameter '{0}' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter '{1}'.</source>
<target state="translated">類型參數 '{0}' 必須擁有 'New' 條件約束或 'Structure' 條件約束,才能符合類型參數 '{1}' 的 'New' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewArgsDisallowedForTypeParam">
<source>Arguments cannot be passed to a 'New' used on a type parameter.</source>
<target state="translated">引數無法傳遞至類型參數上所使用的 'New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateRawGenericTypeImport1">
<source>Generic type '{0}' cannot be imported more than once.</source>
<target state="translated">不可匯入一次以上的泛型類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoTypeArgumentCountOverloadCand1">
<source>Overload resolution failed because no accessible '{0}' accepts this number of type arguments.</source>
<target state="translated">因為沒有可存取的 '{0}' 接受此數目的類型引數,所以多載解析失敗。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeArgsUnexpected">
<source>Type arguments unexpected.</source>
<target state="translated">未預期的類型引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameSameAsMethodTypeParam1">
<source>'{0}' is already declared as a type parameter of this method.</source>
<target state="translated">'{0}' 已經宣告為此方法的類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamNameFunctionNameCollision">
<source>Type parameter cannot have the same name as its defining function.</source>
<target state="translated">類型參數不可以與其定義函式擁有相同的名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadConstraintSyntax">
<source>Type or 'New' expected.</source>
<target state="translated">必須是類型或 'New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OfExpected">
<source>'Of' required when specifying type arguments for a generic type or method.</source>
<target state="translated">'為泛型類型或方法指定類型引數時需要 'Of'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayOfRawGenericInvalid">
<source>'(' unexpected. Arrays of uninstantiated generic types are not allowed.</source>
<target state="translated">'出現未預期的 '('。不可使用未執行個體化的泛型類型陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForEachAmbiguousIEnumerable1">
<source>'For Each' on type '{0}' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'.</source>
<target state="translated">'類型 '{0}' 上的 'For Each' 模稜兩可,因為該類型實作了多個 'System.Collections.Generic.IEnumerable(Of T)' 具現化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNotOperatorGenericParam1">
<source>'IsNot' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a type parameter with no class constraint.</source>
<target state="translated">'類型 '{0}' 的 'IsNot' 運算元只能與 'Nothing' 進行比較,因為 '{0}' 是沒有類別條件約束的類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamQualifierDisallowed">
<source>Type parameters cannot be used as qualifiers.</source>
<target state="translated">類型參數不能當做限定詞使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamMissingCommaOrRParen">
<source>Comma or ')' expected.</source>
<target state="translated">必須是逗號或 ')'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamMissingAsCommaOrRParen">
<source>'As', comma or ')' expected.</source>
<target state="translated">'必須是 'As'、逗號或 ')'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleReferenceConstraints">
<source>'Class' constraint cannot be specified multiple times for the same type parameter.</source>
<target state="translated">'不能針對相同的類型參數多次指定 'Class' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleValueConstraints">
<source>'Structure' constraint cannot be specified multiple times for the same type parameter.</source>
<target state="translated">'不能針對相同的類型參數多次指定 'Structure' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewAndValueConstraintsCombined">
<source>'New' constraint and 'Structure' constraint cannot be combined.</source>
<target state="translated">'無法合併 'New' 條件約束和 'Structure' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RefAndValueConstraintsCombined">
<source>'Class' constraint and 'Structure' constraint cannot be combined.</source>
<target state="translated">'無法合併 'Class' 條件約束和 'Structure' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeArgForStructConstraint2">
<source>Type argument '{0}' does not satisfy the 'Structure' constraint for type parameter '{1}'.</source>
<target state="translated">類型引數 '{0}' 不符合類型參數 '{1}' 的 'Structure' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeArgForRefConstraint2">
<source>Type argument '{0}' does not satisfy the 'Class' constraint for type parameter '{1}'.</source>
<target state="translated">類型引數 '{0}' 不符合類型參數 '{1}' 的 'Class' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RefAndClassTypeConstrCombined">
<source>'Class' constraint and a specific class type constraint cannot be combined.</source>
<target state="translated">'無法合併 'Class' 條件約束和特定類別的類型條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ValueAndClassTypeConstrCombined">
<source>'Structure' constraint and a specific class type constraint cannot be combined.</source>
<target state="translated">'無法合併 'Structure' 條件約束和特定類別的類型條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintClashIndirectIndirect4">
<source>Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the indirect constraint '{2}' obtained from the type parameter constraint '{3}'.</source>
<target state="translated">從類型參數條件約束 '{1}' 取得的間接條件約束 '{0}',與從類型參數條件約束 '{3}' 取得的間接條件約束 '{2}',互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintClashDirectIndirect3">
<source>Constraint '{0}' conflicts with the indirect constraint '{1}' obtained from the type parameter constraint '{2}'.</source>
<target state="translated">條件約束 '{0}' 與從類型參數條件約束 '{2}' 取得的間接條件約束 '{1}' 互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintClashIndirectDirect3">
<source>Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the constraint '{2}'.</source>
<target state="translated">從類型參數條件約束 '{1}' 取得的間接條件約束 '{0}',與條件約束 '{2}' 互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintCycleLink2">
<source>
'{0}' is constrained to '{1}'.</source>
<target state="translated">
'{0}' 已限制為 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintCycle2">
<source>Type parameter '{0}' cannot be constrained to itself: {1}</source>
<target state="translated">類型參數 '{0}' 不可限制為其本身: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamWithStructConstAsConst">
<source>Type parameter with a 'Structure' constraint cannot be used as a constraint.</source>
<target state="translated">具有 'Structure' 條件約束的類型參數不可以當做條件約束使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableDisallowedForStructConstr1">
<source>'System.Nullable' does not satisfy the 'Structure' constraint for type parameter '{0}'. Only non-nullable 'Structure' types are allowed.</source>
<target state="translated">'System.Nullable' 不符合類型參數 '{0}' 的 'Structure' 條件約束。只可使用不可為 null 的 'Structure' 類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictingDirectConstraints3">
<source>Constraint '{0}' conflicts with the constraint '{1}' already specified for type parameter '{2}'.</source>
<target state="translated">條件約束 '{0}' 與已經指定給類型參數 '{2}' 的條件約束 '{1}' 互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceUnifiesWithInterface2">
<source>Cannot inherit interface '{0}' because it could be identical to interface '{1}' for some type arguments.</source>
<target state="translated">無法繼承介面 '{0}',因為它可能與某些類型引數的介面 '{1}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseUnifiesWithInterfaces3">
<source>Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' for some type arguments.</source>
<target state="translated">無法繼承介面 '{0}',因為它所繼承的介面 '{1}' 可能與某些類型引數之介面 '{2}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceBaseUnifiesWithBase4">
<source>Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the interface '{3}' inherits for some type arguments.</source>
<target state="translated">無法繼承介面 '{0}',因為它所繼承的介面 '{1}' 可能與某些類型引數的介面 '{3}' 所繼承之介面 '{2}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceUnifiesWithBase3">
<source>Cannot inherit interface '{0}' because it could be identical to interface '{1}' from which the interface '{2}' inherits for some type arguments.</source>
<target state="translated">無法繼承介面 '{0}',因為它可能與某些類型引數的介面 '{2}' 所繼承之介面 '{1}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassInheritsBaseUnifiesWithInterfaces3">
<source>Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to implemented interface '{2}' for some type arguments.</source>
<target state="translated">無法實作介面 '{0}',因為它所繼承的介面 '{1}' 可能與某些類型引數之實作介面 '{2}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassInheritsInterfaceBaseUnifiesWithBase4">
<source>Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the implemented interface '{3}' inherits for some type arguments.</source>
<target state="translated">無法實作介面 '{0}',因為它所繼承的介面 '{1}' 可能與某些類型引數的實作介面 '{3}' 所繼承之介面 '{2}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassInheritsInterfaceUnifiesWithBase3">
<source>Cannot implement interface '{0}' because it could be identical to interface '{1}' from which the implemented interface '{2}' inherits for some type arguments.</source>
<target state="translated">無法實作介面 '{0}',因為它可能與某些類型引數的實作介面 '{2}' 所繼承之介面 '{1}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionalsCantBeStructGenericParams">
<source>Generic parameters used as optional parameter types must be class constrained.</source>
<target state="translated">用以做為選擇性參數類型的泛型參數,必須受到類別條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfNullableMethod">
<source>Methods of 'System.Nullable(Of T)' cannot be used as operands of the 'AddressOf' operator.</source>
<target state="translated">System.Nullable(Of T)' 的方法無法做為 'AddressOf' 運算子的運算元</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsOperatorNullable1">
<source>'Is' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a nullable type.</source>
<target state="translated">'類型 '{0}' 的 'Is' 運算元只能與 'Nothing' 進行比較,因為 '{0}' 是可為 Null 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNotOperatorNullable1">
<source>'IsNot' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a nullable type.</source>
<target state="translated">'類型 '{0}' 的 'IsNot' 運算元只能與 'Nothing' 進行比較,因為 '{0}' 是可為 Null 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ShadowingTypeOutsideClass1">
<source>'{0}' cannot be declared 'Shadows' outside of a class, structure, or interface.</source>
<target state="translated">'{0}' 不可在類別、結構或介面外部宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertySetParamCollisionWithValue">
<source>Property parameters cannot have the name 'Value'.</source>
<target state="translated">屬性參數的名稱不可為 'Value'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SxSIndirectRefHigherThanDirectRef3">
<source>The project currently contains references to more than one version of '{0}', a direct reference to version {2} and an indirect reference to version {1}. Change the direct reference to use version {1} (or higher) of {0}.</source>
<target state="translated">專案目前包含一個以上版本之 '{0}' 的參考、版本 {2} 的直接參考,以及版本 {1} 的間接參考。請變更直接參考以使用 {0} 的版本 {1} (或更新版本)。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateReferenceStrong">
<source>Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references.</source>
<target state="translated">已匯入具有相同識別的多個組件: '{0}' 和 '{1}'。請移除其中一個重複的參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateReference2">
<source>Project already has a reference to assembly '{0}'. A second reference to '{1}' cannot be added.</source>
<target state="translated">專案已經有組件 '{0}' 的參考。無法對 '{1}' 加入第二個參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalCallOrIndex">
<source>Illegal call expression or index expression.</source>
<target state="translated">不合法的呼叫運算式或索引運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictDefaultPropertyAttribute">
<source>Conflict between the default property and the 'DefaultMemberAttribute' defined on '{0}'.</source>
<target state="translated">預設屬性與 '{0}' 上定義的 'DefaultMemberAttribute' 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeUuid2">
<source>'{0}' cannot be applied because the format of the GUID '{1}' is not correct.</source>
<target state="translated">'無法套用 '{0}',因為 GUID '{1}' 的格式不正確。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassAndReservedAttribute1">
<source>'Microsoft.VisualBasic.ComClassAttribute' and '{0}' cannot both be applied to the same class.</source>
<target state="translated">'無法將 'Microsoft.VisualBasic.ComClassAttribute' 和 '{0}' 同時套用至相同的類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassRequiresPublicClass2">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because its container '{1}' is not declared 'Public'.</source>
<target state="translated">'Microsoft.VisualBasic.ComClassAttribute' 無法套用至 '{0}',因為其容器 '{1}' 未宣告為 'Public'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassReservedDispIdZero1">
<source>'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property.</source>
<target state="translated">'System.Runtime.InteropServices.DispIdAttribute' 無法套用至 '{0}',因為 'Microsoft.VisualBasic.ComClassAttribute' 為預設屬性保留的值為零。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassReservedDispId1">
<source>'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero.</source>
<target state="translated">'System.Runtime.InteropServices.DispIdAttribute' 無法套用至 '{0}',因為 'Microsoft.VisualBasic.ComClassAttribute' 保留的值小於零。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassDuplicateGuids1">
<source>'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on '{0}' cannot have the same value.</source>
<target state="translated">'位於 '{0}' 的 'Microsoft.VisualBasic.ComClassAttribute' 之 'InterfaceId' 與 'EventsId' 參數,不可有相同的值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassCantBeAbstract0">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is declared 'MustInherit'.</source>
<target state="translated">'Microsoft.VisualBasic.ComClassAttribute' 無法套用至宣告為 'MustInherit' 的類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassRequiresPublicClass1">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because it is not declared 'Public'.</source>
<target state="translated">'Microsoft.VisualBasic.ComClassAttribute' 無法套用至 '{0}',因為其未宣告為 'Public'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnknownOperator">
<source>Operator declaration must be one of: +, -, *, \, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.</source>
<target state="translated">運算子宣告必須為下列其中之一: +、-、*、\、/、^、&、Like、Mod、And、Or、Xor、Not、<<、>>、=、<>、<、<=、>、>=、CType、IsTrue、IsFalse。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateConversionCategoryUsed">
<source>'Widening' and 'Narrowing' cannot be combined.</source>
<target state="translated">'無法合併 'Widening' 和 'Narrowing'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorNotOverloadable">
<source>Operator is not overloadable. Operator declaration must be one of: +, -, *, \, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.</source>
<target state="translated">運算子不可多載。運算子宣告必須為下列其中之一: +、-、*、\、/、^、&、Like、Mod、And、Or、Xor、Not、<<、>>、=、<>、<、<=、>、>=、CType、IsTrue、IsFalse。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidHandles">
<source>'Handles' is not valid on operator declarations.</source>
<target state="translated">'Handles' 在運算子宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidImplements">
<source>'Implements' is not valid on operator declarations.</source>
<target state="translated">'Implements' 在運算子宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndOperatorExpected">
<source>'End Operator' expected.</source>
<target state="translated">'必須是 'End Operator'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndOperatorNotAtLineStart">
<source>'End Operator' must be the first statement on a line.</source>
<target state="translated">'End Operator' 必須是該行的第一個陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndOperator">
<source>'End Operator' must be preceded by a matching 'Operator'.</source>
<target state="translated">'End Operator' 之前必須搭配相對應的 'Operator'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitOperatorNotValid">
<source>'Exit Operator' is not valid. Use 'Return' to exit an operator.</source>
<target state="translated">'Exit Operator' 無效。請使用 'Return' 結束運算子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayIllegal1">
<source>'{0}' parameters cannot be declared 'ParamArray'.</source>
<target state="translated">'{0}' 參數不可宣告為 'ParamArray'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionalIllegal1">
<source>'{0}' parameters cannot be declared 'Optional'.</source>
<target state="translated">'{0}' 參數不可宣告為 'Optional'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorMustBePublic">
<source>Operators must be declared 'Public'.</source>
<target state="translated">運算子必須宣告為 'Public'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorMustBeShared">
<source>Operators must be declared 'Shared'.</source>
<target state="translated">運算子必須宣告為 'Shared'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadOperatorFlags1">
<source>Operators cannot be declared '{0}'.</source>
<target state="translated">運算子不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OneParameterRequired1">
<source>Operator '{0}' must have one parameter.</source>
<target state="translated">運算子 '{0}' 必須要有一個參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TwoParametersRequired1">
<source>Operator '{0}' must have two parameters.</source>
<target state="translated">運算子 '{0}' 必須要有兩個參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OneOrTwoParametersRequired1">
<source>Operator '{0}' must have either one or two parameters.</source>
<target state="translated">運算子 '{0}' 必須要有一個或兩個參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvMustBeWideningOrNarrowing">
<source>Conversion operators must be declared either 'Widening' or 'Narrowing'.</source>
<target state="translated">轉換運算子必須宣告為 'Widening' 或 'Narrowing'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorDeclaredInModule">
<source>Operators cannot be declared in modules.</source>
<target state="translated">不能在模組中宣告運算子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSpecifierOnNonConversion1">
<source>Only conversion operators can be declared '{0}'.</source>
<target state="translated">只有轉換運算子可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnaryParamMustBeContainingType1">
<source>Parameter of this unary operator must be of the containing type '{0}'.</source>
<target state="translated">此一元運算子的參數必須屬於包含類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryParamMustBeContainingType1">
<source>At least one parameter of this binary operator must be of the containing type '{0}'.</source>
<target state="translated">此二元運算子至少必須要有一個參數屬於包含類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvParamMustBeContainingType1">
<source>Either the parameter type or the return type of this conversion operator must be of the containing type '{0}'.</source>
<target state="translated">此轉換運算子的參數類型或傳回類型,必須屬於包含類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorRequiresBoolReturnType1">
<source>Operator '{0}' must have a return type of Boolean.</source>
<target state="translated">運算子 '{0}' 必須要有布林的傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToSameType">
<source>Conversion operators cannot convert from a type to the same type.</source>
<target state="translated">轉換運算子無法從類型轉換為相同的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToInterfaceType">
<source>Conversion operators cannot convert to an interface type.</source>
<target state="translated">轉換運算子無法轉換為介面類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToBaseType">
<source>Conversion operators cannot convert from a type to its base type.</source>
<target state="translated">轉換運算子無法從類型轉換為其基底類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToDerivedType">
<source>Conversion operators cannot convert from a type to its derived type.</source>
<target state="translated">轉換運算子無法從類型轉換為其衍生類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToObject">
<source>Conversion operators cannot convert to Object.</source>
<target state="translated">轉換運算子無法轉換為物件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromInterfaceType">
<source>Conversion operators cannot convert from an interface type.</source>
<target state="translated">轉換運算子無法從介面類型進行轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromBaseType">
<source>Conversion operators cannot convert from a base type.</source>
<target state="translated">轉換運算子無法從基底類型進行轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromDerivedType">
<source>Conversion operators cannot convert from a derived type.</source>
<target state="translated">轉換運算子無法從衍生類型進行轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromObject">
<source>Conversion operators cannot convert from Object.</source>
<target state="translated">轉換運算子無法從物件進行轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MatchingOperatorExpected2">
<source>Matching '{0}' operator is required for '{1}'.</source>
<target state="translated">'{1}' 必須要有對稱的 '{0}' 運算子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnacceptableLogicalOperator3">
<source>Return and parameter types of '{0}' must be '{1}' to be used in a '{2}' expression.</source>
<target state="translated">'{0}' 的傳回類型與參數類型必須是 '{1}',才可用在 '{2}' 運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConditionOperatorRequired3">
<source>Type '{0}' must define operator '{1}' to be used in a '{2}' expression.</source>
<target state="translated">類型 '{0}' 必須定義要用於 '{2}' 運算式中的運算子 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CopyBackTypeMismatch3">
<source>Cannot copy the value of 'ByRef' parameter '{0}' back to the matching argument because type '{1}' cannot be converted to type '{2}'.</source>
<target state="translated">無法將 'ByRef' 參數的值 '{0}' 複製回相對應的引數,因為類型 '{1}' 無法轉換成類型 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForLoopOperatorRequired2">
<source>Type '{0}' must define operator '{1}' to be used in a 'For' statement.</source>
<target state="translated">類型 '{0}' 必須定義要用於 'For' 陳述式中的運算子 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnacceptableForLoopOperator2">
<source>Return and parameter types of '{0}' must be '{1}' to be used in a 'For' statement.</source>
<target state="translated">'{0}' 的傳回類型與參數類型必須是 '{1}',才可用在 'For' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnacceptableForLoopRelOperator2">
<source>Parameter types of '{0}' must be '{1}' to be used in a 'For' statement.</source>
<target state="translated">'{0}' 的參數類型必須是 '{1}',才可用在 'For' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorRequiresIntegerParameter1">
<source>Operator '{0}' must have a second parameter of type 'Integer' or 'Integer?'.</source>
<target state="translated">運算子 '{0}' 的第二個參數類型必須為 'Integer' 或 'Integer?'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyNullableOnBoth">
<source>Nullable modifier cannot be specified on both a variable and its type.</source>
<target state="translated">無法同時在變數及其類型上指定可為 Null 的修飾元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeArgForStructConstraintNull">
<source>Type '{0}' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.</source>
<target state="translated">類型 '{0}' 必須是實值類型或已限制為 'Structure' 的類型引數,才可與 'Nullable' 或可為 Null 的修飾元 '?' 搭配使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyArrayAndNullableOnBoth">
<source>Nullable modifier '?' and array modifiers '(' and ')' cannot be specified on both a variable and its type.</source>
<target state="translated">無法同時在變數及其類型上指定可為 Null 的修飾元 '?' 以及陣列修飾元 '(' 和 ')'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyTypeCharacterOnIIF">
<source>Expressions used with an 'If' expression cannot contain type characters.</source>
<target state="translated">與 'If' 運算式一併使用的運算式,不可包含類型字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFName">
<source>'If' operands cannot be named arguments.</source>
<target state="translated">'If' 運算元不能是具名引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFConversion">
<source>Cannot infer a common type for the second and third operands of the 'If' operator. One must have a widening conversion to the other.</source>
<target state="translated">無法推斷 'If' 運算子的第二個和第三個運算元之一般類型。一個運算元必須要能夠放大轉換成另一個運算元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalCondTypeInIIF">
<source>First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type.</source>
<target state="translated">二進位 'If' 運算式的第一個運算元必須是可為 Null 或是參考類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantCallIIF">
<source>'If' operator cannot be used in a 'Call' statement.</source>
<target state="translated">'If' 運算子無法用於 'Call' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyAsNewAndNullable">
<source>Nullable modifier cannot be specified in variable declarations with 'As New'.</source>
<target state="translated">包含 'As New' 的變數宣告中不能指定可為 Null 的修飾元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFConversion2">
<source>Cannot infer a common type for the first and second operands of the binary 'If' operator. One must have a widening conversion to the other.</source>
<target state="translated">無法推斷二元 'If' 運算子的第一個和第二個運算元之一般類型。一個運算元必須要能夠放大轉換成另一個運算元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadNullTypeInCCExpression">
<source>Nullable types are not allowed in conditional compilation expressions.</source>
<target state="translated">條件式編譯運算式中不可使用可為 Null 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableImplicit">
<source>Nullable modifier cannot be used with a variable whose implicit type is 'Object'.</source>
<target state="translated">可為 Null 的修飾元不能用於隱含類型為 'Object' 的變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingRuntimeHelper">
<source>Requested operation is not available because the runtime library function '{0}' is not defined.</source>
<target state="translated">因為未定義執行階段程式庫函式 '{0}',所以無法進行要求的作業。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDotAfterGlobalNameSpace">
<source>'Global' must be followed by '.' and an identifier.</source>
<target state="translated">'在 'Global' 之後必須接著 '.' 及一個識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoGlobalExpectedIdentifier">
<source>'Global' not allowed in this context; identifier expected.</source>
<target state="translated">'此內容中不允許 'Global'; 必須是識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoGlobalInHandles">
<source>'Global' not allowed in handles; local name expected.</source>
<target state="translated">'控制代碼中不允許 'Global'; 必須是區域名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ElseIfNoMatchingIf">
<source>'ElseIf' must be preceded by a matching 'If' or 'ElseIf'.</source>
<target state="translated">'ElseIf' 之前必須搭配相對應的 'If' 或 'ElseIf'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeConstructor2">
<source>Attribute constructor has a 'ByRef' parameter of type '{0}'; cannot use constructors with byref parameters to apply the attribute.</source>
<target state="translated">屬性建構函式的 'ByRef' 參數類型為 '{0}'; 不可使用具有 byref 參數的建構函式來套用屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndUsingWithoutUsing">
<source>'End Using' must be preceded by a matching 'Using'.</source>
<target state="translated">'End Using' 之前必須搭配相對應的 'Using'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndUsing">
<source>'Using' must end with a matching 'End Using'.</source>
<target state="translated">'Using' 之後必須搭配相對應的 'End Using'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoUsing">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'Using' statement that does not contain this statement.</source>
<target state="translated">'GoTo {0}' 無效,因為 '{0}' 位於不包含此陳述式的 'Using' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UsingRequiresDisposePattern">
<source>'Using' operand of type '{0}' must implement 'System.IDisposable'.</source>
<target state="translated">'類型 '{0}' 的 'Using' 運算元必須實作 'System.IDisposable'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UsingResourceVarNeedsInitializer">
<source>'Using' resource variable must have an explicit initialization.</source>
<target state="translated">'Using' 資源變數必須擁有明確的初始設定。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UsingResourceVarCantBeArray">
<source>'Using' resource variable type can not be array type.</source>
<target state="translated">'Using' 資源變數類型不能是陣列類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnErrorInUsing">
<source>'On Error' statements are not valid within 'Using' statements.</source>
<target state="translated">'On Error' 陳述式在 'Using' 陳述式內無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyNameConflictInMyCollection">
<source>'{0}' has the same name as a member used for type '{1}' exposed in a 'My' group. Rename the type or its enclosing namespace.</source>
<target state="translated">'{0}' 與用在 'My' 群組中所公開之類型 '{1}' 的成員,有相同的名稱。請重新命名類型或其內含的命名空間。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidImplicitVar">
<source>Implicit variable '{0}' is invalid because of '{1}'.</source>
<target state="translated">隱含變數 '{0}' 無效,原因為 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObjectInitializerRequiresFieldName">
<source>Object initializers require a field name to initialize.</source>
<target state="translated">物件初始設定式需要欄位名稱,才可進行初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedFrom">
<source>'From' expected.</source>
<target state="translated">'必須是 'From'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaBindingMismatch1">
<source>Nested function does not have the same signature as delegate '{0}'.</source>
<target state="translated">巢狀函式與委派 '{0}' 沒有相同的簽章。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaBindingMismatch2">
<source>Nested sub does not have a signature that is compatible with delegate '{0}'.</source>
<target state="translated">巢狀 Sub 沒有與委派 '{0}' 相容的簽章。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftByRefParamQuery1">
<source>'ByRef' parameter '{0}' cannot be used in a query expression.</source>
<target state="translated">'ByRef' 參數 '{0}' 不可用在查詢運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpressionTreeNotSupported">
<source>Expression cannot be converted into an expression tree.</source>
<target state="translated">運算式不可轉換成運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftStructureMeQuery">
<source>Instance members and 'Me' cannot be used within query expressions in structures.</source>
<target state="translated">執行個體成員和 'Me' 不能用在結構的查詢運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InferringNonArrayType1">
<source>Variable cannot be initialized with non-array type '{0}'.</source>
<target state="translated">不能以非陣列類型 '{0}' 初始化變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ByRefParamInExpressionTree">
<source>References to 'ByRef' parameters cannot be converted to an expression tree.</source>
<target state="translated">ByRef' 參數的參考不可轉換成運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAnonTypeMemberName1">
<source>Anonymous type member or property '{0}' is already declared.</source>
<target state="translated">匿名類型成員或屬性 '{0}' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAnonymousTypeForExprTree">
<source>Cannot convert anonymous type to an expression tree because a property of the type is used to initialize another property.</source>
<target state="translated">無法將匿名類型轉換成運算式樹狀結構,因為類型的屬性會用以初始化另一個屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftAnonymousType1">
<source>Anonymous type property '{0}' cannot be used in the definition of a lambda expression within the same initialization list.</source>
<target state="translated">匿名類型屬性 '{0}' 不可用在同一個初始設定清單中之 Lambda 運算式的定義內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionOnlyAllowedOnModuleSubOrFunction">
<source>'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations.</source>
<target state="translated">'Extension' 屬性只能套用到 'Module'、'Sub' 或 'Function' 宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodNotInModule">
<source>Extension methods can be defined only in modules.</source>
<target state="translated">擴充方法只能在模組內定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodNoParams">
<source>Extension methods must declare at least one parameter. The first parameter specifies which type to extend.</source>
<target state="translated">擴充方法必須宣告至少一個參數。第一個參數會指定要擴充的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodOptionalFirstArg">
<source>'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.</source>
<target state="translated">'Optional' 不能套用至擴充方法的第一個參數。第一個參數會指定要擴充的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodParamArrayFirstArg">
<source>'ParamArray' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.</source>
<target state="translated">'ParamArray' 不能套用至擴充方法的第一個參數。第一個參數會指定要擴充的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeFieldNameInference">
<source>Anonymous type member name can be inferred only from a simple or qualified name with no arguments.</source>
<target state="translated">只能從不含引數的簡單或限定名稱來推斷匿名類型成員名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotMemberOfAnonymousType2">
<source>'{0}' is not a member of '{1}'; it does not exist in the current context.</source>
<target state="translated">'{0}' 不是 '{1}' 的成員,其不存在於目前的內容中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionAttributeInvalid">
<source>The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods.</source>
<target state="translated">這個由編譯器所發現的 'System.Runtime.CompilerServices.ExtensionAttribute' 自訂版本無效。它的屬性使用方式旗標必須設定成允許組件、類別和方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypePropertyOutOfOrder1">
<source>Anonymous type member property '{0}' cannot be used to infer the type of another member property because the type of '{0}' is not yet established.</source>
<target state="translated">匿名類型成員屬性 '{0}' 無法用以推斷另一個成員屬性的類型,因為尚未建立類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeDisallowsTypeChar">
<source>Type characters cannot be used in anonymous type declarations.</source>
<target state="translated">匿名類型宣告中不能使用類型字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleLiteralDisallowsTypeChar">
<source>Type characters cannot be used in tuple literals.</source>
<target state="translated">元組常值中不得使用類型字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewWithTupleTypeSyntax">
<source>'New' cannot be used with tuple type. Use a tuple literal expression instead.</source>
<target state="translated">'Tuple 類型不得使用 'New'。請改用 Tuple 常值運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PredefinedValueTupleTypeMustBeStruct">
<source>Predefined type '{0}' must be a structure.</source>
<target state="translated">預先定義的類型 '{0}' 必須是結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodUncallable1">
<source>Extension method '{0}' has type constraints that can never be satisfied.</source>
<target state="translated">擴充方法 '{0}' 有一直無法滿足的類型條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodOverloadCandidate3">
<source>
Extension method '{0}' defined in '{1}': {2}</source>
<target state="translated">
定義於 '{1}' 中的擴充方法 '{0}': {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingMismatch">
<source>Method does not have a signature compatible with the delegate.</source>
<target state="translated">方法沒有與委派相容的簽章。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingTypeInferenceFails">
<source>Type arguments could not be inferred from the delegate.</source>
<target state="translated">無法從委派推斷類型引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyArgs">
<source>Too many arguments.</source>
<target state="translated">引數太多。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgAlsoOmitted1">
<source>Parameter '{0}' already has a matching omitted argument.</source>
<target state="translated">參數 '{0}' 已有相符的省略引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgUsedTwice1">
<source>Parameter '{0}' already has a matching argument.</source>
<target state="translated">參數 '{0}' 已有相符的引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamNotFound1">
<source>'{0}' is not a method parameter.</source>
<target state="translated">'{0}' 不是方法參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedArgument1">
<source>Argument not specified for parameter '{0}'.</source>
<target state="translated">參數 '{0}' 未指定引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnboundTypeParam1">
<source>Type parameter '{0}' cannot be inferred.</source>
<target state="translated">無法推斷類型參數 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodOverloadCandidate2">
<source>
Extension method '{0}' defined in '{1}'.</source>
<target state="translated">
定義於 '{1}' 中的擴充方法 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeNeedField">
<source>Anonymous type must contain at least one member.</source>
<target state="translated">匿名類型必須至少有一名成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeNameWithoutPeriod">
<source>Anonymous type member name must be preceded by a period.</source>
<target state="translated">匿名類型成員名稱前面必須有一個句號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeExpectedIdentifier">
<source>Identifier expected, preceded with a period.</source>
<target state="translated">必須是識別項,前面加上句號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyArgs2">
<source>Too many arguments to extension method '{0}' defined in '{1}'.</source>
<target state="translated">在 '{1}' 中定義的擴充方法 '{0}',有太多引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgAlsoOmitted3">
<source>Parameter '{0}' in extension method '{1}' defined in '{2}' already has a matching omitted argument.</source>
<target state="translated">'{2}' 中定義之擴充方法 '{1}' 內的參數 '{0}',已有相符的省略引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgUsedTwice3">
<source>Parameter '{0}' of extension method '{1}' defined in '{2}' already has a matching argument.</source>
<target state="translated">'{2}' 中定義之擴充方法 '{1}' 的參數 '{0}',已有相符的引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamNotFound3">
<source>'{0}' is not a parameter of extension method '{1}' defined in '{2}'.</source>
<target state="translated">'{0}' 不是 '{2}' 中定義之擴充方法 '{1}' 的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedArgument3">
<source>Argument not specified for parameter '{0}' of extension method '{1}' defined in '{2}'.</source>
<target state="translated">未對 '{2}' 中定義的擴充方法 '{1}' 之參數 '{0}' 指定引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnboundTypeParam3">
<source>Type parameter '{0}' for extension method '{1}' defined in '{2}' cannot be inferred.</source>
<target state="translated">無法推斷在 '{2}' 中定義之擴充方法 '{1}' 的類型參數 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooFewGenericArguments2">
<source>Too few type arguments to extension method '{0}' defined in '{1}'.</source>
<target state="translated">在 '{1}' 中定義的擴充方法 '{0}',類型引數太少。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyGenericArguments2">
<source>Too many type arguments to extension method '{0}' defined in '{1}'.</source>
<target state="translated">在 '{1}' 中定義的擴充方法 '{0}',有太多類型引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedInOrEq">
<source>'In' or '=' expected.</source>
<target state="translated">'必須是 'In' 或 '='。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedQueryableSource">
<source>Expression of type '{0}' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.</source>
<target state="translated">類型 '{0}' 的運算式無法查詢。請確定您沒有遺漏組件參考及 (或) LINQ 提供者的命名空間匯入。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryOperatorNotFound">
<source>Definition of method '{0}' is not accessible in this context.</source>
<target state="translated">在此內容中無法存取方法 '{0}' 的定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotUseOnErrorGotoWithClosure">
<source>Method cannot contain both a '{0}' statement and a definition of a variable that is used in a lambda or query expression.</source>
<target state="translated">方法不可同時包含 '{0}' 陳述式以及用於 Lambda 或查詢運算式中的變數定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotGotoNonScopeBlocksWithClosure">
<source>'{0}{1}' is not valid because '{2}' is inside a scope that defines a variable that is used in a lambda or query expression.</source>
<target state="translated">'{0}{1}' 無效,因為 '{2}' 所在的範圍內,定義了用於 Lambda 或查詢運算式中的變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftRestrictedTypeQuery">
<source>Instance of restricted type '{0}' cannot be used in a query expression.</source>
<target state="translated">受限制的類型 '{0}' 之執行個體,不能用在查詢運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryAnonymousTypeFieldNameInference">
<source>Range variable name can be inferred only from a simple or qualified name with no arguments.</source>
<target state="translated">只能從不含引數的簡單或限定名稱來推斷範圍變數名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryDuplicateAnonTypeMemberName1">
<source>Range variable '{0}' is already declared.</source>
<target state="translated">範圍變數 '{0}' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryAnonymousTypeDisallowsTypeChar">
<source>Type characters cannot be used in range variable declarations.</source>
<target state="translated">範圍變數宣告中不能使用類型字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyInClosure">
<source>'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.</source>
<target state="translated">'ReadOnly' 變數不能做為建構函式內 Lambda 運算式中的指派目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExprTreeNoMultiDimArrayCreation">
<source>Multi-dimensional array cannot be converted to an expression tree.</source>
<target state="translated">多維陣列不可轉換成運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExprTreeNoLateBind">
<source>Late binding operations cannot be converted to an expression tree.</source>
<target state="translated">晚期繫結作業無法轉換成運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedBy">
<source>'By' expected.</source>
<target state="translated">'必須是 'By'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryInvalidControlVariableName1">
<source>Range variable name cannot match the name of a member of the 'Object' class.</source>
<target state="translated">範圍變數名稱無法符合 'Object' 類別成員的名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIn">
<source>'In' expected.</source>
<target state="translated">'必須是 'In'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryNameNotDeclared">
<source>Name '{0}' is either not declared or not in the current scope.</source>
<target state="translated">名稱 '{0}' 未宣告或不在目前的範圍內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedFunctionArgumentNarrowing3">
<source>Return type of nested function matching parameter '{0}' narrows from '{1}' to '{2}'.</source>
<target state="translated">與參數 '{0}' 相對應的巢狀函式之傳回類型,從 '{1}' 縮減到 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonTypeFieldXMLNameInference">
<source>Anonymous type member name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.</source>
<target state="translated">無法從非有效 Visual Basic 識別項的 XML 識別項來推斷匿名類型成員名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryAnonTypeFieldXMLNameInference">
<source>Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.</source>
<target state="translated">無法從非有效 Visual Basic 識別項的 XML 識別項來推斷範圍變數名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedInto">
<source>'Into' expected.</source>
<target state="translated">'必須是 'Into'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharOnAggregation">
<source>Aggregate function name cannot be used with a type character.</source>
<target state="translated">彙總函式名稱不能與類型字元一起使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedOn">
<source>'On' expected.</source>
<target state="translated">'必須是 'On'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEquals">
<source>'Equals' expected.</source>
<target state="translated">'必須是 'Equals'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAnd">
<source>'And' expected.</source>
<target state="translated">'必須是 'And'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EqualsTypeMismatch">
<source>'Equals' cannot compare a value of type '{0}' with a value of type '{1}'.</source>
<target state="translated">'Equals' 無法比較類型 '{0}' 的值與類型 '{1}' 的值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EqualsOperandIsBad">
<source>You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) {0} must appear on one side of the 'Equals' operator, and range variable(s) {1} must appear on the other.</source>
<target state="translated">在 'Equals' 運算子的兩端,至少都必須都要參考一個範圍變數。範圍變數 {0} 必須出現在 'Equals' 運算子的一端,而範圍變數 {1} 則必須出現在另一端。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNotDelegate1">
<source>Lambda expression cannot be converted to '{0}' because '{0}' is not a delegate type.</source>
<target state="translated">Lambda 運算式無法轉換成 '{0}',因為 '{0}' 不是委派類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNotCreatableDelegate1">
<source>Lambda expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.</source>
<target state="translated">Lambda 運算式無法轉換成 '{0}',因為類型 '{0}' 宣告為 'MustInherit' 但卻無法建立。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotInferNullableForVariable1">
<source>A nullable type cannot be inferred for variable '{0}'.</source>
<target state="translated">無法為變數 '{0}' 推斷可為 Null 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableTypeInferenceNotSupported">
<source>Nullable type inference is not supported in this context.</source>
<target state="translated">此處不支援可為 Null 的類型推斷。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedJoin">
<source>'Join' expected.</source>
<target state="translated">'必須是 'Join'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableParameterMustSpecifyType">
<source>Nullable parameters must specify a type.</source>
<target state="translated">可為 Null 的參數必須指定類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IterationVariableShadowLocal2">
<source>Range variable '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.</source>
<target state="translated">範圍變數 '{0}' 可隱藏封閉區塊中的變數、預先定義的範圍變數,或查詢運算式中隱含宣告的變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdasCannotHaveAttributes">
<source>Attributes cannot be applied to parameters of lambda expressions.</source>
<target state="translated">屬性無法套用到 Lambda 運算式的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaInSelectCaseExpr">
<source>Lambda expressions are not valid in the first expression of a 'Select Case' statement.</source>
<target state="translated">Lambda 運算式在 'Select Case' 陳述式的第一個運算式中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfInSelectCaseExpr">
<source>'AddressOf' expressions are not valid in the first expression of a 'Select Case' statement.</source>
<target state="translated">'AddressOf' 運算式在 'Select Case' 陳述式的第一個運算式中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableCharNotSupported">
<source>The '?' character cannot be used here.</source>
<target state="translated">?' 字元不能用在這裡。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftStructureMeLambda">
<source>Instance members and 'Me' cannot be used within a lambda expression in structures.</source>
<target state="translated">執行個體成員和 'Me' 不能用在結構的 Lambda 運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftByRefParamLambda1">
<source>'ByRef' parameter '{0}' cannot be used in a lambda expression.</source>
<target state="translated">'ByRef' 參數 '{0}' 不可用在 Lambda 運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftRestrictedTypeLambda">
<source>Instance of restricted type '{0}' cannot be used in a lambda expression.</source>
<target state="translated">受限制的類型 '{0}' 之執行個體,不能用在 Lambda 運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaParamShadowLocal1">
<source>Lambda parameter '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.</source>
<target state="translated">Lambda 參數 '{0}' 隱藏了封閉區塊中的變數、預先定義的範圍變數,或查詢運算式中隱含宣告的變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowImplicitObjectLambda">
<source>Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred.</source>
<target state="translated">Option Strict 為 On 時,要求如果無法推斷每個 Lambda 運算式參數的類型,就必須以 'As' 子句宣告該參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyParamsOnLambdaParamNoType">
<source>Array modifiers cannot be specified on lambda expression parameter name. They must be specified on its type.</source>
<target state="translated">不能在 Lambda 運算式參數名稱上指定陣列修飾元,而必須在其類型上指定。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailure1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">無法從這些引數推斷類型參數的資料類型。明確指定資料類型或許可以改正這項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailure2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">無法從這些引數推斷方法 '{0}' 中類型參數的資料類型。明確指定資料類型或許可更正此項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailure3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">無法從這些引數推斷定義在 '{1}' 中擴充方法 '{0}' 內類型參數的資料類型。明確指定資料類型或許可更正此項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicit1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments.</source>
<target state="translated">無法從這些引數推斷類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicit2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments.</source>
<target state="translated">無法從這些引數推斷方法 '{0}' 中類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicit3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments.</source>
<target state="translated">無法從這些引數推斷定義在 '{1}' 中擴充方法 '{0}' 內類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureAmbiguous1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">無法從這些引數推斷類型參數的資料類型,因為可能的類型不止一種。明確指定資料類型或許可以改正這項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureAmbiguous2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">因為可能的類型不只一種,所以無法從這些引數推斷方法 '{0}' 中類型參數的資料類型。明確指定資料類型或許可更正此項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureAmbiguous3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">因為可能的類型不只一種,所以無法從這些引數推斷定義在 '{1}' 中擴充方法 '{0}' 內類型參數的資料類型。明確指定資料類型或許可更正此項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible.</source>
<target state="translated">無法從這些引數推斷類型參數的資料類型,因為可能會有一個以上的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible.</source>
<target state="translated">因為可能的類型不只一種,所以無法從這些引數推斷方法 '{0}' 中類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible.</source>
<target state="translated">因為可能的類型不只一種,所以無法從這些引數推斷定義在 '{1}' 中擴充方法 '{0}' 內類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoBest1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">無法從這些引數推斷類型參數的資料類型,因為它們不會轉換成相同類型。明確指定資料類型或許可以改正這項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoBest2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">因為引數不會轉換成相同類型,所以無法從這些引數推斷方法 '{0}' 中類型參數的資料類型。明確指定資料類型或許可更正此項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoBest3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">因為引數不會轉換成相同類型,所以無法從這些引數推斷定義在 '{1}' 中擴充方法 '{0}' 內類型參數的資料類型。明確指定資料類型或許可更正此項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type.</source>
<target state="translated">無法從這些引數推斷類型參數的資料類型,因為它們不會轉換成相同類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type.</source>
<target state="translated">因為引數不會轉換成相同類型,所以無法從這些引數推斷方法 '{0}' 中類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type.</source>
<target state="translated">因為引數不會轉換成相同類型,所以無法從這些引數推斷定義在 '{1}' 中擴充方法 '{0}' 內類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingMismatchStrictOff2">
<source>Option Strict On does not allow narrowing in implicit type conversions between method '{0}' and delegate '{1}'.</source>
<target state="translated">Option Strict 為 On 時,不可縮減方法 '{0}' 與委派 '{1}' 之間隱含的類型轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InaccessibleReturnTypeOfMember2">
<source>'{0}' is not accessible in this context because the return type is not accessible.</source>
<target state="translated">'無法在此內容中存取 '{0}',因為無法存取傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIdentifierOrGroup">
<source>'Group' or an identifier expected.</source>
<target state="translated">'必須是 'Group' 或識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnexpectedGroup">
<source>'Group' not allowed in this context; identifier expected.</source>
<target state="translated">'此內容中不允許 'Group'; 必須是識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingMismatchStrictOff3">
<source>Option Strict On does not allow narrowing in implicit type conversions between extension method '{0}' defined in '{2}' and delegate '{1}'.</source>
<target state="translated">Option Strict 為 On 時,不可縮減 '{2}' 中定義的擴充方法 '{0}' 與委派 '{1}' 之間隱含的類型轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingIncompatible3">
<source>Extension Method '{0}' defined in '{2}' does not have a signature compatible with delegate '{1}'.</source>
<target state="translated">'{2}' 中定義的擴充方法 '{0}',沒有與委派 '{1}' 相容的簽章。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentNarrowing2">
<source>Argument matching parameter '{0}' narrows to '{1}'.</source>
<target state="translated">與參數 '{0}' 對應的引數,縮減到 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadCandidate1">
<source>
{0}</source>
<target state="translated">
{0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_AutoPropertyInitializedInStructure">
<source>Auto-implemented Properties contained in Structures cannot have initializers unless they are marked 'Shared'.</source>
<target state="translated">結構中包含的自動實作屬性不能有初始設定式,除非標記為 'Shared'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeDisallowsElements">
<source>XML elements cannot be selected from type '{0}'.</source>
<target state="translated">無法從類型 '{0}' 選取 XML 元素。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeDisallowsAttributes">
<source>XML attributes cannot be selected from type '{0}'.</source>
<target state="translated">無法從類型 '{0}' 選取 XML 屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeDisallowsDescendants">
<source>XML descendant elements cannot be selected from type '{0}'.</source>
<target state="translated">無法從類型 '{0}' 選取 XML 子元素。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOrMemberNotGeneric2">
<source>Extension method '{0}' defined in '{1}' is not generic (or has no free type parameters) and so cannot have type arguments.</source>
<target state="translated">在 '{1}' 中定義的擴充方法 '{0}' 不是泛型 (或沒有不受限的類型參數),因此不可有類型引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodCannotBeLateBound">
<source>Late-bound extension methods are not supported.</source>
<target state="translated">不支援晚期繫結擴充方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceArrayRankMismatch1">
<source>Cannot infer a data type for '{0}' because the array dimensions do not match.</source>
<target state="translated">因為陣列維度不相符,所以無法推斷 '{0}' 的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryStrictDisallowImplicitObject">
<source>Type of the range variable cannot be inferred, and late binding is not allowed with Option Strict on. Use an 'As' clause to specify the type.</source>
<target state="translated">無法推斷範圍變數的類型,Option Strict 為 On 時不可使用晚期繫結。請使用 'As' 子句指定類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotEmbedInterfaceWithGeneric">
<source>Type '{0}' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.</source>
<target state="translated">無法內嵌類型 '{0}',因為它有泛型引數。請考慮停用內嵌 Interop 類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotUseGenericTypeAcrossAssemblyBoundaries">
<source>Type '{0}' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.</source>
<target state="translated">因為類型 '{0}' 有內嵌 Interop 類型的泛型類型引數,所以不可跨組件的界限使用。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbol2">
<source>'{0}' is obsolete: '{1}'.</source>
<target state="translated">'{0}' 已經過時: '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbol2_Title">
<source>Type or member is obsolete</source>
<target state="translated">類型或成員已經過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverloadBase4">
<source>{0} '{1}' shadows an overloadable member declared in the base {2} '{3}'. If you want to overload the base method, this method must be declared 'Overloads'.</source>
<target state="translated">{0} '{1}' 會遮蔽基底 {2} '{3}' 中宣告的可多載成員。若要多載基底方法,必須將此方法宣告為 'Overloads'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverloadBase4_Title">
<source>Member shadows an overloadable member declared in the base type</source>
<target state="translated">成員遮蔽了基底類型中所宣告的可多載成員</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverrideType5">
<source>{0} '{1}' conflicts with {2} '{1}' in the base {3} '{4}' and should be declared 'Shadows'.</source>
<target state="translated">{0} '{1}' 與基底 {3} '{4}' 中的 {2} '{1}' 互相衝突,因此應宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverrideType5_Title">
<source>Member conflicts with member in the base type and should be declared 'Shadows'</source>
<target state="translated">成員與基底類型中的成員互相衝突,因此應該宣告為 'Shadows'</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverride2">
<source>{0} '{1}' shadows an overridable method in the base {2} '{3}'. To override the base method, this method must be declared 'Overrides'.</source>
<target state="translated">{0} '{1}' 會遮蔽基底 {2} '{3}' 中可覆寫的方法。若要覆寫基底方法,必須將此方法宣告為 'Overrides'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverride2_Title">
<source>Member shadows an overridable method in the base type</source>
<target state="translated">成員遮蔽了基底類型中可覆寫的方法</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefaultnessShadowed4">
<source>Default property '{0}' conflicts with the default property '{1}' in the base {2} '{3}'. '{0}' will be the default property. '{0}' should be declared 'Shadows'.</source>
<target state="translated">預設屬性 '{0}' 與基底 {2} '{3}' 中的預設屬性 '{1}' 相互衝突。'{0}' 將成為預設屬性。'{0}' 應該宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefaultnessShadowed4_Title">
<source>Default property conflicts with the default property in the base type</source>
<target state="translated">預設屬性與基底類型中的預設屬性互相衝突</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbolNoMessage1">
<source>'{0}' is obsolete.</source>
<target state="translated">'{0}' 已經過時。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbolNoMessage1_Title">
<source>Type or member is obsolete</source>
<target state="translated">類型或成員已經過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration0">
<source>Possible problem detected while building assembly: {0}</source>
<target state="translated">建置組件時偵測到的可能問題: {0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration0_Title">
<source>Possible problem detected while building assembly</source>
<target state="translated">建置組件時偵測的可能問題</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration1">
<source>Possible problem detected while building assembly '{0}': {1}</source>
<target state="translated">建置組件 '{0}' 時偵測到的可能問題: {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration1_Title">
<source>Possible problem detected while building assembly</source>
<target state="translated">建置組件時偵測的可能問題</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassNoMembers1">
<source>'Microsoft.VisualBasic.ComClassAttribute' is specified for class '{0}' but '{0}' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.</source>
<target state="translated">'為類別 '{0}' 指定了 'Microsoft.VisualBasic.ComClassAttribute',但 '{0}' 沒有可公開至 COM 的公用成員。因此,未產生 COM 介面。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassNoMembers1_Title">
<source>'Microsoft.VisualBasic.ComClassAttribute' is specified for class but class has no public members that can be exposed to COM</source>
<target state="translated">'為類別指定了 'Microsoft.VisualBasic.ComClassAttribute',但類別沒有可對 COM 公開的 Public 成員</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsMember5">
<source>{0} '{1}' implicitly declares '{2}', which conflicts with a member in the base {3} '{4}', and so the {0} should be declared 'Shadows'.</source>
<target state="translated">{0} '{1}' 隱含宣告 '{2}',其與基底 {3} '{4}' 中的成員相衝突,因此 {0} 應宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsMember5_Title">
<source>Property or event implicitly declares type or member that conflicts with a member in the base type</source>
<target state="translated">屬性或事件隱含宣告了與基底類型中的成員互相衝突的類型或成員</target>
<note />
</trans-unit>
<trans-unit id="WRN_MemberShadowsSynthMember6">
<source>{0} '{1}' conflicts with a member implicitly declared for {2} '{3}' in the base {4} '{5}' and should be declared 'Shadows'.</source>
<target state="translated">{0} '{1}' 與基底 {4} '{5}' 中對 {2} '{3}' 隱含宣告的成員互相衝突,所以應宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MemberShadowsSynthMember6_Title">
<source>Member conflicts with a member implicitly declared for property or event in the base type</source>
<target state="translated">成員與針對基底類型中屬性或事件進行隱含宣告的成員互相衝突</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsSynthMember7">
<source>{0} '{1}' implicitly declares '{2}', which conflicts with a member implicitly declared for {3} '{4}' in the base {5} '{6}'. {0} should be declared 'Shadows'.</source>
<target state="translated">{0} '{1}' 隱含宣告 '{2}',其與基底 {5} '{6}' 中為 {3} '{4}' 所隱含宣告的成員相衝突。{0} 應宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsSynthMember7_Title">
<source>Property or event implicitly declares member, which conflicts with a member implicitly declared for property or event in the base type</source>
<target state="translated">屬性或事件所隱含宣告的成員,與基底類型中為屬性或事件隱含宣告的成員互相衝突</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor3">
<source>'{0}' accessor of '{1}' is obsolete: '{2}'.</source>
<target state="translated">'{1}' 的 '{0}' 存取子已經過時: '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor3_Title">
<source>Property accessor is obsolete</source>
<target state="translated">屬性存取子已過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor2">
<source>'{0}' accessor of '{1}' is obsolete.</source>
<target state="translated">'{1}' 的 '{0}' 存取子已經過時。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor2_Title">
<source>Property accessor is obsolete</source>
<target state="translated">屬性存取子已過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_FieldNotCLSCompliant1">
<source>Type of member '{0}' is not CLS-compliant.</source>
<target state="translated">成員 '{0}' 的類型不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_FieldNotCLSCompliant1_Title">
<source>Type of member is not CLS-compliant</source>
<target state="translated">成員的類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_BaseClassNotCLSCompliant2">
<source>'{0}' is not CLS-compliant because it derives from '{1}', which is not CLS-compliant.</source>
<target state="translated">'{0}' 不符合 CLS 規範,因為其衍生自不符合 CLS 規範的 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_BaseClassNotCLSCompliant2_Title">
<source>Type is not CLS-compliant because it derives from base type that is not CLS-compliant</source>
<target state="translated">類型不符合 CLS 規範,因為它是衍生自不符合 CLS 規範的基底類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_ProcTypeNotCLSCompliant1">
<source>Return type of function '{0}' is not CLS-compliant.</source>
<target state="translated">函式 '{0}' 的傳回類型不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ProcTypeNotCLSCompliant1_Title">
<source>Return type of function is not CLS-compliant</source>
<target state="translated">函式的傳回類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_ParamNotCLSCompliant1">
<source>Type of parameter '{0}' is not CLS-compliant.</source>
<target state="translated">參數 '{0}' 的類型不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ParamNotCLSCompliant1_Title">
<source>Type of parameter is not CLS-compliant</source>
<target state="translated">參數的類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_InheritedInterfaceNotCLSCompliant2">
<source>'{0}' is not CLS-compliant because the interface '{1}' it inherits from is not CLS-compliant.</source>
<target state="translated">'{0}' 不符合 CLS 規範,因為其繼承的介面 '{1}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_InheritedInterfaceNotCLSCompliant2_Title">
<source>Type is not CLS-compliant because the interface it inherits from is not CLS-compliant</source>
<target state="translated">類型不符合 CLS 規範,因為它所繼承的介面不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSMemberInNonCLSType3">
<source>{0} '{1}' cannot be marked CLS-compliant because its containing type '{2}' is not CLS-compliant.</source>
<target state="translated">{0} '{1}' 無法標記為符合 CLS 規範,因為其包含類型 '{2}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSMemberInNonCLSType3_Title">
<source>Member cannot be marked CLS-compliant because its containing type is not CLS-compliant</source>
<target state="translated">無法將成員標記為符合 CLS 規範,因為其包含類型並不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_NameNotCLSCompliant1">
<source>Name '{0}' is not CLS-compliant.</source>
<target state="translated">名稱 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NameNotCLSCompliant1_Title">
<source>Name is not CLS-compliant</source>
<target state="translated">名稱不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_EnumUnderlyingTypeNotCLS1">
<source>Underlying type '{0}' of Enum is not CLS-compliant.</source>
<target state="translated">列舉的基礎類型 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_EnumUnderlyingTypeNotCLS1_Title">
<source>Underlying type of Enum is not CLS-compliant</source>
<target state="translated">列舉的基礎類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMemberInCLSInterface1">
<source>Non CLS-compliant '{0}' is not allowed in a CLS-compliant interface.</source>
<target state="translated">符合 CLS 規範的介面中,不可出現不符合 CLS 規範的 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMemberInCLSInterface1_Title">
<source>Non CLS-compliant member is not allowed in a CLS-compliant interface</source>
<target state="translated">符合 CLS 規範的介面中不得有不符合 CLS 規範的成員</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMustOverrideInCLSType1">
<source>Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type '{0}'.</source>
<target state="translated">符合 CLS 規範的類型 '{0}' 中不能有不符合 CLS 規範的 'MustOverride' 成員。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMustOverrideInCLSType1_Title">
<source>Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type</source>
<target state="translated">符合 CLS 規範的類型中不得有不符合 CLS 規範的 'MustOverride' 成員</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayOverloadsNonCLS2">
<source>'{0}' is not CLS-compliant because it overloads '{1}' which differs from it only by array of array parameter types or by the rank of the array parameter types.</source>
<target state="translated">'{0}' 不符合 CLS 規範,因為其多載了 '{1}',兩者的差別只在於陣列參數類型的陣列,或是陣列參數類型的陣序。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayOverloadsNonCLS2_Title">
<source>Method is not CLS-compliant because it overloads method which differs from it only by array of array parameter types or by the rank of the array parameter types</source>
<target state="translated">方法不符合 CLS 規範,因為它所多載的方法與其本身之間只有陣列參數類型的陣列或陣列參數類型的順位方面的差異</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant1">
<source>Root namespace '{0}' is not CLS-compliant.</source>
<target state="translated">根命名空間 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant1_Title">
<source>Root namespace is not CLS-compliant</source>
<target state="translated">根命名空間不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant2">
<source>Name '{0}' in the root namespace '{1}' is not CLS-compliant.</source>
<target state="translated">根命名空間 '{1}' 中的名稱 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant2_Title">
<source>Part of the root namespace is not CLS-compliant</source>
<target state="translated">根命名空間有部分不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_GenericConstraintNotCLSCompliant1">
<source>Generic parameter constraint type '{0}' is not CLS-compliant.</source>
<target state="translated">泛型參數條件約束類型 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_GenericConstraintNotCLSCompliant1_Title">
<source>Generic parameter constraint type is not CLS-compliant</source>
<target state="translated">泛型參數條件約束類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeNotCLSCompliant1">
<source>Type '{0}' is not CLS-compliant.</source>
<target state="translated">類型 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeNotCLSCompliant1_Title">
<source>Type is not CLS-compliant</source>
<target state="translated">類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_OptionalValueNotCLSCompliant1">
<source>Type of optional value for optional parameter '{0}' is not CLS-compliant.</source>
<target state="translated">選擇性參數 '{0}' 的選擇性值類型不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_OptionalValueNotCLSCompliant1_Title">
<source>Type of optional value for optional parameter is not CLS-compliant</source>
<target state="translated">選用參數的選用值類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSAttrInvalidOnGetSet">
<source>System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.</source>
<target state="translated">System.CLSCompliantAttribute 無法套用至屬性 'Get' 或 'Set'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSAttrInvalidOnGetSet_Title">
<source>System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'</source>
<target state="translated">System.CLSCompliantAttribute 無法套用至屬性 'Get' 或 'Set'</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeConflictButMerged6">
<source>{0} '{1}' and partial {2} '{3}' conflict in {4} '{5}', but are being merged because one of them is declared partial.</source>
<target state="translated">{0} '{1}' 和部分 {2} '{3}' 在 {4} '{5}' 中互相衝突,但是因為其中一個宣告為部分,所以已合併。</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeConflictButMerged6_Title">
<source>Type and partial type conflict, but are being merged because one of them is declared partial</source>
<target state="translated">類型與部分類型相衝突,但將予以合併,因為其中一個已宣告為部分</target>
<note />
</trans-unit>
<trans-unit id="WRN_ShadowingGenericParamWithParam1">
<source>Type parameter '{0}' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.</source>
<target state="translated">類型參數 '{0}' 與封入類型的類型參數,擁有相同的名稱。將會遮蔽封入類型的類型參數。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ShadowingGenericParamWithParam1_Title">
<source>Type parameter has the same name as a type parameter of an enclosing type</source>
<target state="translated">類型參數與封入類型的類型參數擁有相同的名稱</target>
<note />
</trans-unit>
<trans-unit id="WRN_CannotFindStandardLibrary1">
<source>Could not find standard library '{0}'.</source>
<target state="translated">找不到標準程式庫 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_CannotFindStandardLibrary1_Title">
<source>Could not find standard library</source>
<target state="translated">找不到標準程式庫</target>
<note />
</trans-unit>
<trans-unit id="WRN_EventDelegateTypeNotCLSCompliant2">
<source>Delegate type '{0}' of event '{1}' is not CLS-compliant.</source>
<target state="translated">事件 '{1}' 的委派類型 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_EventDelegateTypeNotCLSCompliant2_Title">
<source>Delegate type of event is not CLS-compliant</source>
<target state="translated">事件的委派類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_DebuggerHiddenIgnoredOnProperties">
<source>System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate.</source>
<target state="translated">當 System.Diagnostics.DebuggerHiddenAttribute 套用至屬性 (Property) 定義時,它並不會影響 'Get' 或 'Set'。請依適當的情況直接將屬性 (Attribute) 套用至 'Get' 和 'Set' 程序。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DebuggerHiddenIgnoredOnProperties_Title">
<source>System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition</source>
<target state="translated">System.Diagnostics.DebuggerHiddenAttribute 在套用至 Property 定義時,並不會影響 'Get' 或 'Set'</target>
<note />
</trans-unit>
<trans-unit id="WRN_SelectCaseInvalidRange">
<source>Range specified for 'Case' statement is not valid. Make sure that the lower bound is less than or equal to the upper bound.</source>
<target state="translated">Case' 陳述式的指定範圍無效。請確定下限小於或等於上限。</target>
<note />
</trans-unit>
<trans-unit id="WRN_SelectCaseInvalidRange_Title">
<source>Range specified for 'Case' statement is not valid</source>
<target state="translated">Case' 陳述式的指定範圍無效</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSEventMethodInNonCLSType3">
<source>'{0}' method for event '{1}' cannot be marked CLS compliant because its containing type '{2}' is not CLS compliant.</source>
<target state="translated">'事件 '{1}' 的 '{0}' 方法無法標記為符合 CLS 規範,因為其包含類型 '{2}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSEventMethodInNonCLSType3_Title">
<source>AddHandler or RemoveHandler method for event cannot be marked CLS compliant because its containing type is not CLS compliant</source>
<target state="translated">無法將事件的 AddHandler 或 RemoveHandler 方法標記為符合 CLS 規範,因為其包含類型並不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_ExpectedInitComponentCall2">
<source>'{0}' in designer-generated type '{1}' should call InitializeComponent method.</source>
<target state="translated">'設計工具所產生的類型 '{1}' 之 '{0}',應呼叫 InitializeComponent 方法。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ExpectedInitComponentCall2_Title">
<source>Constructor in designer-generated type should call InitializeComponent method</source>
<target state="translated">設計工具產生的類型中的建構函式,應該呼叫 InitializeComponent 方法</target>
<note />
</trans-unit>
<trans-unit id="WRN_NamespaceCaseMismatch3">
<source>Casing of namespace name '{0}' does not match casing of namespace name '{1}' in '{2}'.</source>
<target state="translated">命名空間名稱 '{0}' 的大小寫,與 '{2}' 中命名空間名稱 '{1}' 的大小寫不相符。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NamespaceCaseMismatch3_Title">
<source>Casing of namespace name does not match</source>
<target state="translated">命名空間名稱大小寫不相符</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyNamespaceOrClass1">
<source>Namespace or type specified in the Imports '{0}' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</source>
<target state="translated">Imports '{0}' 中指定的命名空間或類型,不包含任何 Public 成員,或是找不到該命名空間或類型。請確定已定義該命名空間或類型,且至少包含一個 Public 成員。請確定匯入的元素名稱沒有使用任何別名。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyNamespaceOrClass1_Title">
<source>Namespace or type specified in Imports statement doesn't contain any public member or cannot be found</source>
<target state="translated">Imports 陳述式中指定的命名空間或類型,不包含任何 Public 成員,或找不到該命名空間或類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyProjectNamespaceOrClass1">
<source>Namespace or type specified in the project-level Imports '{0}' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</source>
<target state="translated">在專案層級 Imports '{0}' 中指定的命名空間或類型不包含任何 Public 成員,或是找不到該命名空間或類型。請確定已定義命名空間或類型,而且其中包含至少一個 Public 成員。請確定匯入的項目名稱未使用任何別名。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyProjectNamespaceOrClass1_Title">
<source>Namespace or type imported at project level doesn't contain any public member or cannot be found</source>
<target state="translated">在專案層級匯入的命名空間或類型不包含任何 Public 成員,或是找不到該命名空間或類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_IndirectRefToLinkedAssembly2">
<source>A reference was created to embedded interop assembly '{0}' because of an indirect reference to that assembly from assembly '{1}'. Consider changing the 'Embed Interop Types' property on either assembly.</source>
<target state="translated">已建立內嵌 Interop 組件 '{0}' 的參考,因為該組件的間接參考來自組件 '{1}'。請考慮變更其中任一組件上的 [內嵌 Interop 類型] 屬性。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IndirectRefToLinkedAssembly2_Title">
<source>A reference was created to embedded interop assembly because of an indirect reference to that assembly</source>
<target state="translated">已建立內嵌 Interop 組件的參考,因為對該組件已有間接參考</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase3">
<source>Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete.</source>
<target state="translated">類別 '{0}' 應宣告 'Sub New',因為其基底類別 '{2}' 中的 '{1}' 已標記為過時。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase3_Title">
<source>Class should declare a 'Sub New' because the constructor in its base class is marked obsolete</source>
<target state="translated">類別應該宣告 'Sub New',因為其基底類別中的建構函式已標記為過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase4">
<source>Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'.</source>
<target state="translated">類別 '{0}' 應宣告 'Sub New',因為其基底類別 '{2}' 中的 '{1}' 已標記為過時: '{3}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase4_Title">
<source>Class should declare a 'Sub New' because the constructor in its base class is marked obsolete</source>
<target state="translated">類別應該宣告 'Sub New',因為其基底類別中的建構函式已標記為過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall3">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete.</source>
<target state="translated">此 'Sub New' 的第一個陳述式,必須是對 'MyBase.New' 或 'MyClass.New' 的明確呼叫,因為 '{2}' 的基底類別 '{1}' 中之 '{0}' 已標記為過時。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall3_Title">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete</source>
<target state="translated">這個 'Sub New' 的第一個陳述式應明確呼叫 'MyBase.New' 或 'MyClass.New',因為基底類別中的建構函式已標記為過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall4">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'</source>
<target state="translated">此 'Sub New' 的第一個陳述式,必須是對 'MyBase.New' 或 'MyClass.New' 的明確呼叫,因為 '{2}' 的基底類別 '{1}' 中之 '{0}' 已標記為過時: '{3}'</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall4_Title">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete</source>
<target state="translated">這個 'Sub New' 的第一個陳述式應明確呼叫 'MyBase.New' 或 'MyClass.New',因為基底類別中的建構函式已標記為過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinOperator">
<source>Operator without an 'As' clause; type of Object assumed.</source>
<target state="translated">沒有 'As' 子句的運算子; 假設是 Object 的類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinOperator_Title">
<source>Operator without an 'As' clause</source>
<target state="translated">運算子沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConstraintsFailedForInferredArgs2">
<source>Type arguments inferred for method '{0}' result in the following warnings :{1}</source>
<target state="translated">方法 '{0}' 的推斷類型引數,導致下列錯誤 :{1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConstraintsFailedForInferredArgs2_Title">
<source>Type arguments inferred for method result in warnings</source>
<target state="translated">為方法推斷的類型引數引發了警告</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConditionalNotValidOnFunction">
<source>Attribute 'Conditional' is only valid on 'Sub' declarations.</source>
<target state="translated">屬性 'Conditional' 只在 'Sub' 宣告中有效。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConditionalNotValidOnFunction_Title">
<source>Attribute 'Conditional' is only valid on 'Sub' declarations</source>
<target state="translated">屬性 'Conditional' 只在 'Sub' 宣告中有效</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseSwitchInsteadOfAttribute">
<source>Use command-line option '{0}' or appropriate project settings instead of '{1}'.</source>
<target state="translated">使用命令列選項 '{0}' 或適當的專案設定代替 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseSwitchInsteadOfAttribute_Title">
<source>Use command-line option /keyfile, /keycontainer, or /delaysign instead of AssemblyKeyFileAttribute, AssemblyKeyNameAttribute, or AssemblyDelaySignAttribute</source>
<target state="translated">使用命令列選項 /keyfile、/keycontainer 或 /delaysign 而非 AssemblyKeyFileAttribute、AssemblyKeyNameAttribute 或 AssemblyDelaySignAttribute</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveAddHandlerCall">
<source>Statement recursively calls the containing '{0}' for event '{1}'.</source>
<target state="translated">陳述式遞迴呼叫事件 '{1}' 的包含 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveAddHandlerCall_Title">
<source>Statement recursively calls the event's containing AddHandler</source>
<target state="translated">陳述式會遞迴呼叫事件的包含 AddHandler</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionCopyBack">
<source>Implicit conversion from '{1}' to '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument.</source>
<target state="translated">在將 'ByRef' 參數的值 '{0}' 複製回相對應的引數時,將 '{1}' 隱含轉換至 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionCopyBack_Title">
<source>Implicit conversion in copying the value of 'ByRef' parameter back to the matching argument</source>
<target state="translated">將 'ByRef' 參數的值複製回相符引數時的隱含轉換</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustShadowOnMultipleInheritance2">
<source>{0} '{1}' conflicts with other members of the same name across the inheritance hierarchy and so should be declared 'Shadows'.</source>
<target state="translated">{0} '{1}' 與其他跨繼承階層的同名成員互相衝突,所以應宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustShadowOnMultipleInheritance2_Title">
<source>Method conflicts with other members of the same name across the inheritance hierarchy and so should be declared 'Shadows'</source>
<target state="translated">方法與繼承階層中的其他同名成員互相衝突,因此應該宣告為 'Shadows'</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveOperatorCall">
<source>Expression recursively calls the containing Operator '{0}'.</source>
<target state="translated">運算式遞迴呼叫包含運算子 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveOperatorCall_Title">
<source>Expression recursively calls the containing Operator</source>
<target state="translated">運算式會遞迴呼叫包含運算子</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversion2">
<source>Implicit conversion from '{0}' to '{1}'.</source>
<target state="translated">從 '{0}' 隱含轉換至 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversion2_Title">
<source>Implicit conversion</source>
<target state="translated">隱含轉換</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableStructureInUsing">
<source>Local variable '{0}' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block.</source>
<target state="translated">區域變數 '{0}' 是唯讀變數,且其類型為結構。叫用其成員或將 ByRef 傳遞給它,並不會變更其內容,但可能導致非預期的結果。請考慮在 'Using' 區塊外宣告此變數。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableStructureInUsing_Title">
<source>Local variable declared by Using statement is read-only and its type is a structure</source>
<target state="translated">Using 陳述式所宣告的區域變數是唯讀變數,且其類型為一結構</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableGenericStructureInUsing">
<source>Local variable '{0}' is read-only. When its type is a structure, invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block.</source>
<target state="translated">區域變數 '{0}' 是唯讀變數。當其類型為結構時,叫用它的成員或將 ByRef 傳遞給它,並不會變更其內容,但可能導致非預期的結果。請考慮在 'Using' 區塊外宣告此變數。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableGenericStructureInUsing_Title">
<source>Local variable declared by Using statement is read-only and its type may be a structure</source>
<target state="translated">Using 陳述式所宣告的區域變數是唯讀變數,且其類型可能為一結構</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionSubst1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionSubst1_Title">
<source>Implicit conversion</source>
<target state="translated">隱含轉換</target>
<note />
</trans-unit>
<trans-unit id="WRN_LateBindingResolution">
<source>Late bound resolution; runtime errors could occur.</source>
<target state="translated">晚期繫結解析; 可能發生執行階段錯誤。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LateBindingResolution_Title">
<source>Late bound resolution</source>
<target state="translated">晚期繫結解析</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1">
<source>Operands of type Object used for operator '{0}'; use the 'Is' operator to test object identity.</source>
<target state="translated">供運算子 '{0}' 使用之 Object 類型的運算元; 請使用 'Is' 運算子測試物件識別。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1_Title">
<source>Operands of type Object used for operator</source>
<target state="translated">對運算子使用了 Object 類型的運算元</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath2">
<source>Operands of type Object used for operator '{0}'; runtime errors could occur.</source>
<target state="translated">供運算子 '{0}' 使用之 Object 類型的運算元; 可能會發生執行階段錯誤。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath2_Title">
<source>Operands of type Object used for operator</source>
<target state="translated">對運算子使用了 Object 類型的運算元</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedVar1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedVar1_Title">
<source>Variable declaration without an 'As' clause</source>
<target state="translated">變數宣告沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumed1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumed1_Title">
<source>Function without an 'As' clause</source>
<target state="translated">函式沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedProperty1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedProperty1_Title">
<source>Property without an 'As' clause</source>
<target state="translated">屬性沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinVarDecl">
<source>Variable declaration without an 'As' clause; type of Object assumed.</source>
<target state="translated">沒有 'As' 子句的變數宣告; 假設是 Object 的類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinVarDecl_Title">
<source>Variable declaration without an 'As' clause</source>
<target state="translated">變數宣告沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinFunction">
<source>Function without an 'As' clause; return type of Object assumed.</source>
<target state="translated">沒有 'As' 子句的函式; 假設是 Object 的傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinFunction_Title">
<source>Function without an 'As' clause</source>
<target state="translated">函式沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinProperty">
<source>Property without an 'As' clause; type of Object assumed.</source>
<target state="translated">沒有 'As' 子句的屬性; 假設是 Object 的類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinProperty_Title">
<source>Property without an 'As' clause</source>
<target state="translated">屬性沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocal">
<source>Unused local variable: '{0}'.</source>
<target state="translated">未使用的區域變數: '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocal_Title">
<source>Unused local variable</source>
<target state="translated">未使用的區域變數</target>
<note />
</trans-unit>
<trans-unit id="WRN_SharedMemberThroughInstance">
<source>Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.</source>
<target state="translated">透過執行個體存取共用成員、常數成員、列舉成員或巢狀類型。將不會評估合格的運算式。</target>
<note />
</trans-unit>
<trans-unit id="WRN_SharedMemberThroughInstance_Title">
<source>Access of shared member, constant member, enum member or nested type through an instance</source>
<target state="translated">透過執行個體存取共用成員、常數成員、列舉成員或巢狀類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursivePropertyCall">
<source>Expression recursively calls the containing property '{0}'.</source>
<target state="translated">運算式遞迴呼叫包含屬性 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursivePropertyCall_Title">
<source>Expression recursively calls the containing property</source>
<target state="translated">運算式會遞迴呼叫包含屬性</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverlappingCatch">
<source>'Catch' block never reached, because '{0}' inherits from '{1}'.</source>
<target state="translated">'因為 '{0}' 繼承自 '{1}',所以一律不會執行到 'Catch' 區塊。</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverlappingCatch_Title">
<source>'Catch' block never reached; exception type's base type handled above in the same Try statement</source>
<target state="translated">'一律不會執行到 'Catch' 區塊; 例外狀況類型的基底類型已在相同的 Try 陳述式中處理過此項</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRef">
<source>Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime.</source>
<target state="translated">為變數 '{0}' 指派值之前,已藉傳址方式傳遞該數數。可能會在執行階段產生 null 參考例外狀況。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRef_Title">
<source>Variable is passed by reference before it has been assigned a value</source>
<target state="translated">變數在獲派值之前就已藉傳址方式傳遞</target>
<note />
</trans-unit>
<trans-unit id="WRN_DuplicateCatch">
<source>'Catch' block never reached; '{0}' handled above in the same Try statement.</source>
<target state="translated">'{0}' 已在相同的 Try 陳述式中處理過上述項目,所以一律不會進行到 'Catch' 區塊。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DuplicateCatch_Title">
<source>'Catch' block never reached; exception type handled above in the same Try statement</source>
<target state="translated">'一律不會執行到 'Catch' 區塊; 例外狀況類型會在相同 Try 陳述式的上方處理</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1Not">
<source>Operands of type Object used for operator '{0}'; use the 'IsNot' operator to test object identity.</source>
<target state="translated">供運算子 '{0}' 使用之 Object 類型的運算元; 請使用 'IsNot' 運算子測試物件識別。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1Not_Title">
<source>Operands of type Object used for operator <></source>
<target state="translated">對運算子 <> 使用了 Object 類型的運算元</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadChecksumValExtChecksum">
<source>Bad checksum value, non hex digits or odd number of hex digits.</source>
<target state="translated">錯誤的總和檢查碼值、非十六進位數字或奇數的十六進位數字。</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadChecksumValExtChecksum_Title">
<source>Bad checksum value, non hex digits or odd number of hex digits</source>
<target state="translated">錯誤的總和檢查碼值,非十六進位數字或奇數的十六進位數字</target>
<note />
</trans-unit>
<trans-unit id="WRN_MultipleDeclFileExtChecksum">
<source>File name already declared with a different GUID and checksum value.</source>
<target state="translated">已使用不同 GUID 與總和檢查碼宣告的檔名。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MultipleDeclFileExtChecksum_Title">
<source>File name already declared with a different GUID and checksum value</source>
<target state="translated">已使用不同的 GUID 與總和檢查碼值宣告的檔名</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadGUIDFormatExtChecksum">
<source>Bad GUID format.</source>
<target state="translated">GUID 格式錯誤。</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadGUIDFormatExtChecksum_Title">
<source>Bad GUID format</source>
<target state="translated">GUID 格式錯誤</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMathSelectCase">
<source>Operands of type Object used in expressions for 'Select', 'Case' statements; runtime errors could occur.</source>
<target state="translated">Select'、'Case' 陳述式的運算式中所使用的類型 Object 的運算元; 可能發生執行階段錯誤。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMathSelectCase_Title">
<source>Operands of type Object used in expressions for 'Select', 'Case' statements</source>
<target state="translated">Select'、'Case' 陳述式的運算式中使用了 Object 類型的運算元</target>
<note />
</trans-unit>
<trans-unit id="WRN_EqualToLiteralNothing">
<source>This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'.</source>
<target state="translated">這個運算式永遠會評估為 Nothing (由於等號運算子的 null 傳播所造成)。若要檢查此值是否為 null,請考慮使用 'Is Nothing'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_EqualToLiteralNothing_Title">
<source>This expression will always evaluate to Nothing</source>
<target state="translated">這個運算式一律會評估為 Nothing</target>
<note />
</trans-unit>
<trans-unit id="WRN_NotEqualToLiteralNothing">
<source>This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'.</source>
<target state="translated">這個運算式永遠會評估為 Nothing (由於等號運算子的 null 傳播所造成)。若要檢查此值是否並非為 null,請考慮使用 'IsNot Nothing'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NotEqualToLiteralNothing_Title">
<source>This expression will always evaluate to Nothing</source>
<target state="translated">這個運算式一律會評估為 Nothing</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocalConst">
<source>Unused local constant: '{0}'.</source>
<target state="translated">未使用的區域常數: '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocalConst_Title">
<source>Unused local constant</source>
<target state="translated">未使用的區域常數</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassInterfaceShadows5">
<source>'Microsoft.VisualBasic.ComClassAttribute' on class '{0}' implicitly declares {1} '{2}', which conflicts with a member of the same name in {3} '{4}'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base {4}.</source>
<target state="translated">'在類別 '{0}' 上的 'Microsoft.VisualBasic.ComClassAttribute' 隱含宣告的 {1} '{2}',與 {3} '{4}' 中的同名成員互相衝突。若要隱藏基底 {4} 上的名稱,請使用 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassInterfaceShadows5_Title">
<source>'Microsoft.VisualBasic.ComClassAttribute' on class implicitly declares member, which conflicts with a member of the same name</source>
<target state="translated">'類別上的 'Microsoft.VisualBasic.ComClassAttribute' 隱含宣告了與同名成員互相衝突的成員</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassPropertySetObject1">
<source>'{0}' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement.</source>
<target state="translated">'{0}' 無法以屬性 'Let' 公開給 COM。您無法從 Visual Basic 6.0 使用 'Let' 陳述式,將非物件值 (例如數值或字串) 指定給此屬性。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassPropertySetObject1_Title">
<source>Property cannot be exposed to COM as a property 'Let'</source>
<target state="translated">無法以屬性 'Let' 的形式將屬性公開給 COM</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRef">
<source>Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime.</source>
<target state="translated">為變數 '{0}' 指派值之前,已使用該變數。可能會在執行階段產生 null 參考例外狀況。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRef_Title">
<source>Variable is used before it has been assigned a value</source>
<target state="translated">變數在獲派值之前就已使用</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncRef1">
<source>Function '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source>
<target state="translated">函式 '{0}' 並未傳回有關所有程式碼路徑的值。使用該結果時,可能會在執行階段發生 null 參考例外狀況。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncRef1_Title">
<source>Function doesn't return a value on all code paths</source>
<target state="translated">函式在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpRef1">
<source>Operator '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source>
<target state="translated">運算子 '{0}' 並未傳回有關所有程式碼路徑的值。使用該結果時,可能會在執行階段發生 null 參考例外狀況。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpRef1_Title">
<source>Operator doesn't return a value on all code paths</source>
<target state="translated">運算子在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropRef1">
<source>Property '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source>
<target state="translated">屬性 '{0}' 並未傳回有關所有程式碼路徑的值。使用該結果時,可能會在執行階段發生 null 參考例外狀況。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropRef1_Title">
<source>Property doesn't return a value on all code paths</source>
<target state="translated">屬性在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRefStr">
<source>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</source>
<target state="translated">為變數 '{0}' 指派值之前,已藉傳址方式傳遞該變數。可能會在執行階段產生 null 參考例外狀況。請確定結構或所有的參考成員,都在使用前進行過初始化。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRefStr_Title">
<source>Variable is passed by reference before it has been assigned a value</source>
<target state="translated">變數在獲派值之前就已藉傳址方式傳遞</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefStr">
<source>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</source>
<target state="translated">為變數 '{0}' 指派值之前,已使用該變數。可能會在執行階段產生 null 參考例外狀況。請確定結構或所有的參考成員,都在使用前進行過初始化。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefStr_Title">
<source>Variable is used before it has been assigned a value</source>
<target state="translated">變數在獲派值之前就已使用</target>
<note />
</trans-unit>
<trans-unit id="WRN_StaticLocalNoInference">
<source>Static variable declared without an 'As' clause; type of Object assumed.</source>
<target state="translated">沒有 'As' 子句的靜態變數宣告; 假設是 Object 的類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_StaticLocalNoInference_Title">
<source>Static variable declared without an 'As' clause</source>
<target state="translated">宣告的靜態變數沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidAssemblyName">
<source>Assembly reference '{0}' is invalid and cannot be resolved.</source>
<target state="translated">組件參考 '{0}' 無效,無法解析。</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidAssemblyName_Title">
<source>Assembly reference is invalid and cannot be resolved</source>
<target state="translated">組件參考無效,無法進行解析</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadXMLLine">
<source>XML comment block must immediately precede the language element to which it applies. XML comment will be ignored.</source>
<target state="translated">XML 註解區塊必須緊接在所套用的語言元素之前。將會忽略 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadXMLLine_Title">
<source>XML comment block must immediately precede the language element to which it applies</source>
<target state="translated">XML 註解區塊必須緊接在所套用的語言項目之前</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocMoreThanOneCommentBlock">
<source>Only one XML comment block is allowed per language element.</source>
<target state="translated">每個語言項目只允許一個 XML 註解區塊。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocMoreThanOneCommentBlock_Title">
<source>Only one XML comment block is allowed per language element</source>
<target state="translated">每個語言項目只允許一個 XML 註解區塊</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocNotFirstOnLine">
<source>XML comment must be the first statement on a line. XML comment will be ignored.</source>
<target state="translated">XML 註解必須是該行的第一個陳述式。將會忽略 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocNotFirstOnLine_Title">
<source>XML comment must be the first statement on a line</source>
<target state="translated">XML 註解必須是該行的第一個陳述式</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInsideMethod">
<source>XML comment cannot appear within a method or a property. XML comment will be ignored.</source>
<target state="translated">XML 註解不可出現在方法或屬性中。將會忽略 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInsideMethod_Title">
<source>XML comment cannot appear within a method or a property</source>
<target state="translated">XML 註解不得出現在方法或屬性中</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParseError1">
<source>XML documentation parse error: {0} XML comment will be ignored.</source>
<target state="translated">XML 文件剖析錯誤: {0} 將會忽略 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParseError1_Title">
<source>XML documentation parse error</source>
<target state="translated">XML 文件剖析錯誤</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocDuplicateXMLNode1">
<source>XML comment tag '{0}' appears with identical attributes more than once in the same XML comment block.</source>
<target state="translated">在同一個 XML 註解區塊中,XML 註解標記 '{0}' 使用相同的屬性出現多次。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocDuplicateXMLNode1_Title">
<source>XML comment tag appears with identical attributes more than once in the same XML comment block</source>
<target state="translated">在相同的 XML 註解區塊中,XML 註解標記以相同的屬性出現多次</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocIllegalTagOnElement2">
<source>XML comment tag '{0}' is not permitted on a '{1}' language element.</source>
<target state="translated">'{1}' 語言元素上不可使用 XML 註解標記 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocIllegalTagOnElement2_Title">
<source>XML comment tag is not permitted on language element</source>
<target state="translated">語言項目上不得有 XML 註解標記</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadParamTag2">
<source>XML comment parameter '{0}' does not match a parameter on the corresponding '{1}' statement.</source>
<target state="translated">XML 註解參數 '{0}' 與對應的 '{1}' 陳述式上之參數不相符。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadParamTag2_Title">
<source>XML comment parameter does not match a parameter on the corresponding declaration statement</source>
<target state="translated">XML 註解參數與對應的宣告陳述式上的參數不相符</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParamTagWithoutName">
<source>XML comment parameter must have a 'name' attribute.</source>
<target state="translated">XML 註解參數必須要有 'name' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParamTagWithoutName_Title">
<source>XML comment parameter must have a 'name' attribute</source>
<target state="translated">XML 註解參數必須要有 'name' 屬性</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefAttributeNotFound1">
<source>XML comment has a tag with a 'cref' attribute '{0}' that could not be resolved.</source>
<target state="translated">XML 註解的標記具有無法解析的 'cref' 屬性 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefAttributeNotFound1_Title">
<source>XML comment has a tag with a 'cref' attribute that could not be resolved</source>
<target state="translated">XML 註解的標記具有無法解析的 'cref' 屬性</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLMissingFileOrPathAttribute1">
<source>XML comment tag 'include' must have a '{0}' attribute. XML comment will be ignored.</source>
<target state="translated">XML 註解標記 'include' 必須要有 '{0}' 屬性。將會忽略 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLMissingFileOrPathAttribute1_Title">
<source>XML comment tag 'include' must have 'file' and 'path' attributes</source>
<target state="translated">XML 註解標記 'include' 必須要有 'file' 和 'path' 屬性</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLCannotWriteToXMLDocFile2">
<source>Unable to create XML documentation file '{0}': {1}</source>
<target state="translated">無法建立 XML 文件檔 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLCannotWriteToXMLDocFile2_Title">
<source>Unable to create XML documentation file</source>
<target state="translated">無法建立 XML 文件檔</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocWithoutLanguageElement">
<source>XML documentation comments must precede member or type declarations.</source>
<target state="translated">XML 文件註解必須在成員或類型宣告之前。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocWithoutLanguageElement_Title">
<source>XML documentation comments must precede member or type declarations</source>
<target state="translated">XML 文件註解必須在成員或類型宣告之前</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnWriteOnlyProperty">
<source>XML comment tag 'returns' is not permitted on a 'WriteOnly' Property.</source>
<target state="translated">WriteOnly' 屬性上不可使用 XML 註解標記 'returns'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnWriteOnlyProperty_Title">
<source>XML comment tag 'returns' is not permitted on a 'WriteOnly' Property</source>
<target state="translated">WriteOnly' 屬性上不得使用 XML 註解標記 'returns'</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocOnAPartialType">
<source>XML comment cannot be applied more than once on a partial {0}. XML comments for this {0} will be ignored.</source>
<target state="translated">在部分 {0} 上不可套用多次 XML 註解。將會忽略此 {0} 的 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocOnAPartialType_Title">
<source>XML comment cannot be applied more than once on a partial type</source>
<target state="translated">在部分類型上不可套用多次 XML 註解</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnADeclareSub">
<source>XML comment tag 'returns' is not permitted on a 'declare sub' language element.</source>
<target state="translated">declare sub' 語言元素上不可使用 XML 註解標記 'returns'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnADeclareSub_Title">
<source>XML comment tag 'returns' is not permitted on a 'declare sub' language element</source>
<target state="translated">declare sub' 語言項目上不可使用 XML 註解標記 'returns'</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocStartTagWithNoEndTag">
<source>XML documentation parse error: Start tag '{0}' doesn't have a matching end tag. XML comment will be ignored.</source>
<target state="translated">XML 文件剖析錯誤: 起始標記 '{0}' 並沒有對稱的結束標記。將會忽略 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocStartTagWithNoEndTag_Title">
<source>XML documentation parse error: Start tag doesn't have a matching end tag</source>
<target state="translated">XML 文件剖析錯誤: 起始標記並沒有對稱的結束標記</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadGenericParamTag2">
<source>XML comment type parameter '{0}' does not match a type parameter on the corresponding '{1}' statement.</source>
<target state="translated">XML 註解類型參數 '{0}' 與對應的 '{1}' 陳述式上之類型參數不相符。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadGenericParamTag2_Title">
<source>XML comment type parameter does not match a type parameter on the corresponding declaration statement</source>
<target state="translated">XML 註解類型參數與對應的宣告陳述式上的類型參數不相符</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocGenericParamTagWithoutName">
<source>XML comment type parameter must have a 'name' attribute.</source>
<target state="translated">XML 註解類型參數必須要有 'name' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocGenericParamTagWithoutName_Title">
<source>XML comment type parameter must have a 'name' attribute</source>
<target state="translated">XML 註解類型參數必須要有 'name' 屬性</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocExceptionTagWithoutCRef">
<source>XML comment exception must have a 'cref' attribute.</source>
<target state="translated">XML 註解例外狀況必須要有 'cref' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocExceptionTagWithoutCRef_Title">
<source>XML comment exception must have a 'cref' attribute</source>
<target state="translated">XML 註解例外狀況必須要有 'cref' 屬性</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInvalidXMLFragment">
<source>Unable to include XML fragment '{0}' of file '{1}'.</source>
<target state="translated">無法包含檔案 '{1}' 的 XML 片段 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInvalidXMLFragment_Title">
<source>Unable to include XML fragment</source>
<target state="translated">無法包含 XML 片段</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadFormedXML">
<source>Unable to include XML fragment '{1}' of file '{0}'. {2}</source>
<target state="translated">無法包含檔案 '{0}' 的 XML 片段 '{1}'。{2}</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadFormedXML_Title">
<source>Unable to include XML fragment</source>
<target state="translated">無法包含 XML 片段</target>
<note />
</trans-unit>
<trans-unit id="WRN_InterfaceConversion2">
<source>Runtime errors might occur when converting '{0}' to '{1}'.</source>
<target state="translated">從 '{0}' 轉換至 '{1}' 時,可能會發生執行階段錯誤。</target>
<note />
</trans-unit>
<trans-unit id="WRN_InterfaceConversion2_Title">
<source>Runtime errors might occur when converting to or from interface type</source>
<target state="translated">對介面類型進行來回轉換時可能發生執行階段錯誤</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableLambda">
<source>Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.</source>
<target state="translated">在 Lambda 運算式中使用反覆運算變數可能會產生非預期的結果,請改成在迴圈中建立區域變數,並將反覆運算變數的值指派給它。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableLambda_Title">
<source>Using the iteration variable in a lambda expression may have unexpected results</source>
<target state="translated">在 Lambda 運算式中使用反覆運算變數可能會產生非預期的結果</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaPassedToRemoveHandler">
<source>Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event.</source>
<target state="translated">Lambda 運算式將不會從這個事件處理常式中移除。請將 Lambda 運算式指派給變數,然後使用該變數來加入和移除事件。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaPassedToRemoveHandler_Title">
<source>Lambda expression will not be removed from this event handler</source>
<target state="translated">將不會從這個事件處理常式中移除 Lambda 運算式</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableQuery">
<source>Using the iteration variable in a query expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.</source>
<target state="translated">在查詢運算式中使用反覆運算變數可能會產生非預期的結果,請改成在迴圈中建立區域變數,並將反覆運算變數的值指派給它。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableQuery_Title">
<source>Using the iteration variable in a query expression may have unexpected results</source>
<target state="translated">在查詢運算式中使用反覆運算變數可能會產生非預期的結果</target>
<note />
</trans-unit>
<trans-unit id="WRN_RelDelegatePassedToRemoveHandler">
<source>The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event. Assign the 'AddressOf' expression to a variable, and use the variable to add or remove the method as the handler.</source>
<target state="translated">AddressOf' 運算式在此內容中沒有作用,因為 'AddressOf' 的方法引數必須以寬鬆的方式轉換成事件的委派類型。請將 'AddressOf' 運算式指派給變數,然後使用該變數來加入或移除做為處理常式的方法。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RelDelegatePassedToRemoveHandler_Title">
<source>The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event</source>
<target state="translated">AddressOf' 運算式在這個內容中沒有作用,因為 'AddressOf' 的方法引數必須以寬鬆的方式轉換成事件的委派類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_QueryMissingAsClauseinVarDecl">
<source>Range variable is assumed to be of type Object because its type cannot be inferred. Use an 'As' clause to specify a different type.</source>
<target state="translated">因為無法推斷範圍變數的類型,所以會將其假設為 Object 類型。請使用 'As' 子句指定不同的類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_QueryMissingAsClauseinVarDecl_Title">
<source>Range variable is assumed to be of type Object because its type cannot be inferred</source>
<target state="translated">範圍變數已假設為 Object 類型,因為無法推斷其類型</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultilineLambdaMissingFunction">
<source>Multiline lambda expression is missing 'End Function'.</source>
<target state="translated">多行 Lambda 運算式遺漏 'End Function'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultilineLambdaMissingSub">
<source>Multiline lambda expression is missing 'End Sub'.</source>
<target state="translated">多行 Lambda 運算式遺漏 'End Sub'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeOnLambdaReturnType">
<source>Attributes cannot be applied to return types of lambda expressions.</source>
<target state="translated">屬性無法套用至 Lambda 運算式的傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubDisallowsStatement">
<source>Statement is not valid inside a single-line statement lambda.</source>
<target state="translated">單行陳述式 Lambda 內的陳述式無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresParenthesesBang">
<source>This single-line statement lambda must be enclosed in parentheses. For example: (Sub() <statement>)!key</source>
<target state="translated">這個單行陳述式 Lambda 必須放在括號之中。例如: (Sub() <statement>)!key</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresParenthesesDot">
<source>This single-line statement lambda must be enclosed in parentheses. For example: (Sub() <statement>).Invoke()</source>
<target state="translated">這個單行陳述式 Lambda 必須放在括號之中。例如: (Sub() <statement>).Invoke()</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresParenthesesLParen">
<source>This single-line statement lambda must be enclosed in parentheses. For example: Call (Sub() <statement>) ()</source>
<target state="translated">這個單行陳述式 Lambda 必須放在括號之中。例如: Call (Sub() <statement>) ()</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresSingleStatement">
<source>Single-line statement lambdas must include exactly one statement.</source>
<target state="translated">單行陳述式 Lambda 只能有一個陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StaticInLambda">
<source>Static local variables cannot be declared inside lambda expressions.</source>
<target state="translated">Lambda 運算式中不能宣告靜態區域變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializedExpandedProperty">
<source>Expanded Properties cannot be initialized.</source>
<target state="translated">無法初始化展開的屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AutoPropertyCantHaveParams">
<source>Auto-implemented properties cannot have parameters.</source>
<target state="translated">自動實作的屬性不能有參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AutoPropertyCantBeWriteOnly">
<source>Auto-implemented properties cannot be WriteOnly.</source>
<target state="translated">自動實作的屬性不可為 WriteOnly。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFCount">
<source>'If' operator requires either two or three operands.</source>
<target state="translated">'If' 運算子需要兩個或三個運算元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NotACollection1">
<source>Cannot initialize the type '{0}' with a collection initializer because it is not a collection type.</source>
<target state="translated">因為類型 '{0}' 並非集合類型,所以無法利用集合初始設定式初始化該類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAddMethod1">
<source>Cannot initialize the type '{0}' with a collection initializer because it does not have an accessible 'Add' method.</source>
<target state="translated">無法初始化具有集合初始設定式的類型 '{0}',因為它沒有可存取的 'Add' 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantCombineInitializers">
<source>An Object Initializer and a Collection Initializer cannot be combined in the same initialization.</source>
<target state="translated">物件初始設定式和集合初始設定式不能合併在相同的初始設定中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EmptyAggregateInitializer">
<source>An aggregate collection initializer entry must contain at least one element.</source>
<target state="translated">彙總集合初始設定式項目 (Entry) 至少必須包含一個項目 (Element)。</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlEndElementNoMatchingStart">
<source>XML end element must be preceded by a matching start element.</source>
<target state="translated">XML 結束元素之前必須搭配對稱的起始元素。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultilineLambdasCannotContainOnError">
<source>'On Error' and 'Resume' cannot appear inside a lambda expression.</source>
<target state="translated">'On Error' 和 'Resume' 不能出現在 Lambda 運算式內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceDisallowedHere">
<source>Keywords 'Out' and 'In' can only be used in interface and delegate declarations.</source>
<target state="translated">關鍵字 'Out' 和 'In' 只能用於介面和委派宣告中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlEndCDataNotAllowedInContent">
<source>The literal string ']]>' is not allowed in element content.</source>
<target state="translated">常值字串 ']]>' 不可用在元素內容中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadsModifierInModule">
<source>Inappropriate use of '{0}' keyword in a module.</source>
<target state="translated">在模組中使用 '{0}' 關鍵字的方法不適當。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UndefinedTypeOrNamespace1">
<source>Type or namespace '{0}' is not defined.</source>
<target state="translated">未定義類型或命名空間 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IdentityDirectCastForFloat">
<source>Using DirectCast operator to cast a floating-point value to the same type is not supported.</source>
<target state="translated">不支援使用 DirectCast 運算子將浮點值轉型為相同類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObsoleteIdentityDirectCastForValueType">
<source>Using DirectCast operator to cast a value-type to the same type is obsolete.</source>
<target state="translated">使用 DirectCast 運算子將實值類型轉型為相同類型的做法已過時。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObsoleteIdentityDirectCastForValueType_Title">
<source>Using DirectCast operator to cast a value-type to the same type is obsolete</source>
<target state="translated">使用 DirectCast 運算子將實值類型轉型為相同類型的做法已過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnreachableCode">
<source>Unreachable code detected.</source>
<target state="translated">偵測到無法執行到的程式碼。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnreachableCode_Title">
<source>Unreachable code detected</source>
<target state="translated">偵測到執行不到的程式碼</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncVal1">
<source>Function '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">函式 '{0}' 並未傳回有關所有程式碼路徑的值。是否遺漏了 'Return' 陳述式?</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncVal1_Title">
<source>Function doesn't return a value on all code paths</source>
<target state="translated">函式在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpVal1">
<source>Operator '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">運算子 '{0}' 並未傳回有關所有程式碼路徑的值。是否遺漏了 'Return' 陳述式?</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpVal1_Title">
<source>Operator doesn't return a value on all code paths</source>
<target state="translated">運算子在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropVal1">
<source>Property '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">屬性 '{0}' 並未傳回有關所有程式碼路徑的值。是否遺漏了 'Return' 陳述式?</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropVal1_Title">
<source>Property doesn't return a value on all code paths</source>
<target state="translated">屬性在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedGlobalNamespace">
<source>Global namespace may not be nested in another namespace.</source>
<target state="translated">全域命名空間不能以巢狀方式放在另一個命名空間中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatch6">
<source>'{0}' cannot expose type '{1}' in {2} '{3}' through {4} '{5}'.</source>
<target state="translated">'{0}' 無法經由 {4} '{5}',在 {2} '{3}' 中公開類型 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadMetaDataReference1">
<source>'{0}' cannot be referenced because it is not a valid assembly.</source>
<target state="translated">'無法參考 '{0}',因為它不是有效的組件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyDoesntImplementAllAccessors">
<source>'{0}' cannot be implemented by a {1} property.</source>
<target state="translated">'{1} 屬性無法實作 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnimplementedMustOverride">
<source>
{0}: {1}</source>
<target state="translated">
{0}: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_IfTooManyTypesObjectDisallowed">
<source>Cannot infer a common type because more than one type is possible.</source>
<target state="translated">無法推斷一般類型,因為可能的類型不止一種。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfTooManyTypesObjectAssumed">
<source>Cannot infer a common type because more than one type is possible; 'Object' assumed.</source>
<target state="translated">無法推斷一般類型,因為可能的類型不止一種; 假設是 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfTooManyTypesObjectAssumed_Title">
<source>Cannot infer a common type because more than one type is possible</source>
<target state="translated">無法推斷一般類型,因為可能的類型不止一種</target>
<note />
</trans-unit>
<trans-unit id="ERR_IfNoTypeObjectDisallowed">
<source>Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed.</source>
<target state="translated">無法推斷一般類型,而 Option Strict 為 On 不允許假設為 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfNoTypeObjectAssumed">
<source>Cannot infer a common type; 'Object' assumed.</source>
<target state="translated">無法推斷一般類型; 已假設是 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfNoTypeObjectAssumed_Title">
<source>Cannot infer a common type</source>
<target state="translated">無法推斷一般類型</target>
<note />
</trans-unit>
<trans-unit id="ERR_IfNoType">
<source>Cannot infer a common type.</source>
<target state="translated">無法推斷一般類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicKeyFileFailure">
<source>Error extracting public key from file '{0}': {1}</source>
<target state="translated">從檔案 '{0}' 擷取公開金鑰時發生錯誤: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicKeyContainerFailure">
<source>Error extracting public key from container '{0}': {1}</source>
<target state="translated">從容器 '{0}' 擷取公開金鑰時發生錯誤: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendRefNotEqualToThis">
<source>Friend access was granted by '{0}', but the public key of the output assembly does not match that specified by the attribute in the granting assembly.</source>
<target state="translated">'{0}' 已授與 Friend 存取權限,但輸出組件的公開金鑰不符合授與之組件中屬性所指定的公開金鑰。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendRefSigningMismatch">
<source>Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly.</source>
<target state="translated">'{0}' 已授與 Friend 存取權限,但輸出組件的強式名稱簽署狀態不符合授與組件的強式名稱簽署狀態。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicSignNoKey">
<source>Public sign was specified and requires a public key, but no public key was specified</source>
<target state="translated">公用符號已指定並需要公開金鑰,但未指定公開金鑰</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicSignNetModule">
<source>Public signing is not supported for netmodules.</source>
<target state="translated">對 netmodule 不支援公開簽署。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeIgnoredWhenPublicSigning">
<source>Attribute '{0}' is ignored when public signing is specified.</source>
<target state="translated">如有指定公用簽章,屬性 '{0}' 將予忽略。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeIgnoredWhenPublicSigning_Title">
<source>Attribute is ignored when public signing is specified.</source>
<target state="translated">如有指定公用簽章,屬性將予忽略。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DelaySignButNoKey">
<source>Delay signing was specified and requires a public key, but no public key was specified.</source>
<target state="translated">已指定延遲簽署,並需要一個公開金鑰,但並未指定任何公開金鑰。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DelaySignButNoKey_Title">
<source>Delay signing was specified and requires a public key, but no public key was specified</source>
<target state="translated">指定了延遲簽署且需要公開金鑰,但未指定任何公開金鑰</target>
<note />
</trans-unit>
<trans-unit id="ERR_SignButNoPrivateKey">
<source>Key file '{0}' is missing the private key needed for signing.</source>
<target state="translated">金鑰檔 '{0}' 遺漏簽署所需的私密金鑰。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FailureSigningAssembly">
<source>Error signing assembly '{0}': {1}</source>
<target state="translated">簽署組件 '{0}' 時發生錯誤: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidVersionFormat">
<source>The specified version string does not conform to the required format - major[.minor[.build|*[.revision|*]]]</source>
<target state="translated">指定的版本字串不符合所需的格式 - major[.minor[.build|*[.revision|*]]]</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidVersionFormat">
<source>The specified version string does not conform to the recommended format - major.minor.build.revision</source>
<target state="translated">指定的版本字串不符合建議的格式 - major.minor.build.revision</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidVersionFormat_Title">
<source>The specified version string does not conform to the recommended format</source>
<target state="translated">指定的版本字串不符合建議的格式</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidVersionFormat2">
<source>The specified version string does not conform to the recommended format - major.minor.build.revision</source>
<target state="translated">指定的版本字串不符合建議的格式 - major.minor.build.revision</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyCultureForExe">
<source>Executables cannot be satellite assemblies; culture should always be empty</source>
<target state="translated">可執行檔不可為附屬組件; 文化特性需保留為空白</target>
<note />
</trans-unit>
<trans-unit id="WRN_MainIgnored">
<source>The entry point of the program is global script code; ignoring '{0}' entry point.</source>
<target state="translated">程式的進入點為全域指令碼; 將略過 '{0}' 進入點。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MainIgnored_Title">
<source>The entry point of the program is global script code; ignoring entry point</source>
<target state="translated">程式的進入點是全域指令碼; 將忽略進入點</target>
<note />
</trans-unit>
<trans-unit id="WRN_EmptyPrefixAndXmlnsLocalName">
<source>The xmlns attribute has special meaning and should not be written with a prefix.</source>
<target state="translated">xmlns 屬性具有特殊意義,寫入時不應該有前置詞。</target>
<note />
</trans-unit>
<trans-unit id="WRN_EmptyPrefixAndXmlnsLocalName_Title">
<source>The xmlns attribute has special meaning and should not be written with a prefix</source>
<target state="translated">xmlns 屬性具有特殊意義,寫入時不應該有前置詞</target>
<note />
</trans-unit>
<trans-unit id="WRN_PrefixAndXmlnsLocalName">
<source>It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:{0}' to define a prefix named '{0}'?</source>
<target state="translated">不建議使用名為 xmlns 的屬性。是否原本希望寫入 'xmlns:{0}' 以定義名為 '{0}' 的前置詞?</target>
<note />
</trans-unit>
<trans-unit id="WRN_PrefixAndXmlnsLocalName_Title">
<source>It is not recommended to have attributes named xmlns</source>
<target state="translated">不建議將屬性命名為 xmlns</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSingleScript">
<source>Expected a single script (.vbx file)</source>
<target state="translated">必須是單一指令碼 (.vbx 檔)</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReservedAssemblyName">
<source>The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session</source>
<target state="translated">組件名稱 '{0}' 已保留,不可用做為互動工作階段中的參考</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReferenceDirectiveOnlyAllowedInScripts">
<source>#R is only allowed in scripts</source>
<target state="translated">#R 只可用於指令碼中</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamespaceNotAllowedInScript">
<source>You cannot declare Namespace in script code</source>
<target state="translated">您無法在指令碼中宣告 Namespace</target>
<note />
</trans-unit>
<trans-unit id="ERR_KeywordNotAllowedInScript">
<source>You cannot use '{0}' in top-level script code</source>
<target state="translated">您無法在最上層指令碼中使用 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNoType">
<source>Cannot infer a return type. Consider adding an 'As' clause to specify the return type.</source>
<target state="translated">無法推斷傳回類型。請考慮加入 'As' 子句來指定傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaNoTypeObjectAssumed">
<source>Cannot infer a return type; 'Object' assumed.</source>
<target state="translated">無法推斷傳回類型; 假設是 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaNoTypeObjectAssumed_Title">
<source>Cannot infer a return type</source>
<target state="translated">無法推斷傳回類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaTooManyTypesObjectAssumed">
<source>Cannot infer a return type because more than one type is possible; 'Object' assumed.</source>
<target state="translated">無法推斷傳回類型,因為可能有一個以上的類型; 假設是 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaTooManyTypesObjectAssumed_Title">
<source>Cannot infer a return type because more than one type is possible</source>
<target state="translated">無法推斷傳回類型,因為可能的類型不止一種</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNoTypeObjectDisallowed">
<source>Cannot infer a return type. Consider adding an 'As' clause to specify the return type.</source>
<target state="translated">無法推斷傳回類型。請考慮加上 'As' 子句來指定傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaTooManyTypesObjectDisallowed">
<source>Cannot infer a return type because more than one type is possible. Consider adding an 'As' clause to specify the return type.</source>
<target state="translated">無法推斷傳回類型,因為可能的類型不止一種。請考慮加上 'As' 子句來指定傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnimplementedCommandLineSwitch">
<source>The command line switch '{0}' is not yet implemented and was ignored.</source>
<target state="translated">命令列參數 '{0}' 尚未獲實作,已忽略。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnimplementedCommandLineSwitch_Title">
<source>Command line switch is not yet implemented</source>
<target state="translated">尚未實作命令列參數</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitNoTypeObjectDisallowed">
<source>Cannot infer an element type, and Option Strict On does not allow 'Object' to be assumed. Specifying the type of the array might correct this error.</source>
<target state="translated">無法推斷項目類型,而且 Option Strict 為 On 則不允許假設為 'Object'。指定陣列類型或許可以改正這項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitNoType">
<source>Cannot infer an element type. Specifying the type of the array might correct this error.</source>
<target state="translated">無法推斷項目類型。指定陣列類型或許可以改正這項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitTooManyTypesObjectDisallowed">
<source>Cannot infer an element type because more than one type is possible. Specifying the type of the array might correct this error.</source>
<target state="translated">無法推斷項目類型,因為可能有一種以上的類型。指定陣列類型或許可以改正這項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitNoTypeObjectAssumed">
<source>Cannot infer an element type; 'Object' assumed.</source>
<target state="translated">無法推斷項目類型; 假設是 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitNoTypeObjectAssumed_Title">
<source>Cannot infer an element type</source>
<target state="translated">無法推斷項目類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitTooManyTypesObjectAssumed">
<source>Cannot infer an element type because more than one type is possible; 'Object' assumed.</source>
<target state="translated">無法推斷項目類型,因為可能有一種以上的類型; 假設是 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitTooManyTypesObjectAssumed_Title">
<source>Cannot infer an element type because more than one type is possible</source>
<target state="translated">無法推斷項目類型,因為可能的類型不止一種</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeInferenceAssumed3">
<source>Data type of '{0}' in '{1}' could not be inferred. '{2}' assumed.</source>
<target state="translated">無法推斷 '{1}' 中 '{0}' 的資料類型。已假設是 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeInferenceAssumed3_Title">
<source>Data type could not be inferred</source>
<target state="translated">無法推斷資料類型</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousCastConversion2">
<source>Option Strict On does not allow implicit conversions from '{0}' to '{1}' because the conversion is ambiguous.</source>
<target state="translated">Option Strict 為 On 時,不可從 '{0}' 隱含轉換至 '{1}',因為轉換模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AmbiguousCastConversion2">
<source>Conversion from '{0}' to '{1}' may be ambiguous.</source>
<target state="translated">從 '{0}' 至 '{1}' 的轉換可能模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AmbiguousCastConversion2_Title">
<source>Conversion may be ambiguous</source>
<target state="translated">轉換可能模稜兩可</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceIEnumerableSuggestion3">
<source>'{0}' cannot be converted to '{1}'. Consider using '{2}' instead.</source>
<target state="translated">'{0}' 無法轉換成 '{1}'。請考慮改用 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceIEnumerableSuggestion3">
<source>'{0}' cannot be converted to '{1}'. Consider using '{2}' instead.</source>
<target state="translated">'{0}' 無法轉換成 '{1}'。請考慮改用 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceIEnumerableSuggestion3_Title">
<source>Type cannot be converted to target collection type</source>
<target state="translated">無法將類型轉換成目標集合類型</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedIn6">
<source>'{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'.</source>
<target state="translated">'{4}' 無法轉換成 '{5}',因為依 '{3}' 中 'In' 泛型參數 '{2}' 的需求,'{0}' 並非衍生自 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedOut6">
<source>'{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'.</source>
<target state="translated">'{4}' 無法轉換成 '{5}',因為依 '{3}' 中 'Out' 泛型參數 '{2}' 的需求,'{0}' 並非衍生自 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedIn6">
<source>Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'.</source>
<target state="translated">從 '{4}' 隱含轉換成 '{5}'; 此轉換可能會失敗,因為依 '{3}' 中 'In' 泛型參數 '{2}' 之需求,'{0}' 並非衍生自 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedIn6_Title">
<source>Implicit conversion; this conversion may fail because the target type is not derived from the source type, as required for 'In' generic parameter</source>
<target state="translated">隱含轉換; 這個轉換可能會失敗,因為目標類型並非衍生自來源類型,如此不符合 'In' 泛型參數的要求</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedOut6">
<source>Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'.</source>
<target state="translated">從 '{4}' 隱含轉換成 '{5}'; 此轉換可能會失敗,因為依 '{3}' 中 'Out' 泛型參數 '{2}' 之需求,'{0}' 並非衍生自 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedOut6_Title">
<source>Implicit conversion; this conversion may fail because the target type is not derived from the source type, as required for 'Out' generic parameter</source>
<target state="translated">隱含轉換; 這個轉換可能失敗,因為目標類型並非衍生自來源類型,如此不符合 'Out' 泛型參數的要求</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedTryIn4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'.</source>
<target state="translated">'{0}' 無法轉換成 '{1}'。請考慮將 '{3}' 之定義中的 '{2}',變更為 In 類型參數 'In {2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedTryOut4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'.</source>
<target state="translated">'{0}' 無法轉換成 '{1}'。請考慮將 '{3}' 之定義中的 '{2}',變更為 Out 類型參數 'Out {2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryIn4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'.</source>
<target state="translated">'{0}' 無法轉換成 '{1}'。請考慮將 '{3}' 之定義中的 '{2}',變更為 In 類型參數 'In {2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryIn4_Title">
<source>Type cannot be converted to target type</source>
<target state="translated">無法將類型轉換成目標類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryOut4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'.</source>
<target state="translated">'{0}' 無法轉換成 '{1}'。請考慮將 '{3}' 之定義中的 '{2}',變更為 Out 類型參數 'Out {2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryOut4_Title">
<source>Type cannot be converted to target type</source>
<target state="translated">無法將類型轉換成目標類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceDeclarationAmbiguous3">
<source>Interface '{0}' is ambiguous with another implemented interface '{1}' due to the 'In' and 'Out' parameters in '{2}'.</source>
<target state="translated">因為 '{2}' 中 'In' 和 'Out' 參數而造成介面 '{0}' 與另一個實作介面 '{1}' 之間模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceDeclarationAmbiguous3_Title">
<source>Interface is ambiguous with another implemented interface due to 'In' and 'Out' parameters</source>
<target state="translated">因為 'In' 和 'Out' 參數的關係,介面與另一個已實作的介面之間模稜兩可</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInterfaceNesting">
<source>Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.</source>
<target state="translated">無法在有 'In' 或 'Out' 類型參數的介面中宣告列舉、類別和結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VariancePreventsSynthesizedEvents2">
<source>Event definitions with parameters are not allowed in an interface such as '{0}' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within '{0}'. For example, 'Event {1} As Action(Of ...)'.</source>
<target state="translated">具有 'In' 或 'Out' 類型參數的介面 (例如 '{0}') 中,不可使用參數進行事件定義。請考慮使用未定義於 '{0}' 內的委派類型,來宣告事件。例如 'Event {1} As Action(Of ...)'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInByRefDisallowed1">
<source>Type '{0}' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 無法用於此內容中,因為 'In' 和 'Out' 類型參數無法用於 ByRef 參數類型,且 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInNullableDisallowed2">
<source>Type '{0}' cannot be used in '{1}' because 'In' and 'Out' type parameters cannot be made nullable, and '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 無法用於 '{1}' 中,因為 'In' 和 'Out' 類型參數不可變成可為 Null,且 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowed1">
<source>Type '{0}' cannot be used in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 無法用在此內容中,因為 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowedForGeneric3">
<source>Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{2}' 中的 '{1}',因為 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowedHere2">
<source>Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{1}',因為 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowedHereForGeneric4">
<source>Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{1}' 中 '{3}' 的 '{2}',因為 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInPropertyDisallowed1">
<source>Type '{0}' cannot be used as a property type in this context because '{0}' is an 'In' type parameter and the property is not marked WriteOnly.</source>
<target state="translated">類型 '{0}' 在此內容中不能用做為屬性類型,因為 '{0}' 是 'In' 類型參數且屬性未標記為 WriteOnly。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInReadOnlyPropertyDisallowed1">
<source>Type '{0}' cannot be used as a ReadOnly property type because '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 不能用做為 ReadOnly 屬性類型,因為 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInReturnDisallowed1">
<source>Type '{0}' cannot be used as a return type because '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 不能用做為傳回類型,因為 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutByRefDisallowed1">
<source>Type '{0}' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 無法用於此內容中,因為 'In' 和 'Out' 類型參數無法用於 ByRef 參數類型,且 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutByValDisallowed1">
<source>Type '{0}' cannot be used as a ByVal parameter type because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 不能用做為 ByVal 參數類型,因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutConstraintDisallowed1">
<source>Type '{0}' cannot be used as a generic type constraint because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 不能用做為泛型類型條件約束,因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutNullableDisallowed2">
<source>Type '{0}' cannot be used in '{1}' because 'In' and 'Out' type parameters cannot be made nullable, and '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 無法用於 '{1}',因為 'In' 和 'Out' 類型參數不能變成可為 Null,且 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowed1">
<source>Type '{0}' cannot be used in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 無法用於此內容中,因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowedForGeneric3">
<source>Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{2}' 中的 '{1}',因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowedHere2">
<source>Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{1}',因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowedHereForGeneric4">
<source>Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{1}' 中 '{3}' 的 '{2}',因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutPropertyDisallowed1">
<source>Type '{0}' cannot be used as a property type in this context because '{0}' is an 'Out' type parameter and the property is not marked ReadOnly.</source>
<target state="translated">類型 '{0}' 在此內容中不能用做為屬性類型,因為 '{0}' 是 'Out' 類型參數,且屬性未標記為 ReadOnly。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutWriteOnlyPropertyDisallowed1">
<source>Type '{0}' cannot be used as a WriteOnly property type because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 不能用做為 WriteOnly 屬性類型,因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowed2">
<source>Type '{0}' cannot be used in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">類型 '{0}' 無法用於此內容中,因為該內容和 '{0}' 的定義都位於介面 '{1}' 的巢狀內,且 '{1}' 具有 'In' 或 'Out' 類型參數。請考慮將 '{0}' 的定義移到 '{1}' 之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowedForGeneric4">
<source>Type '{0}' cannot be used for the '{2}' in '{3}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{3}' 中之 '{2}',因為該內容和 '{0}' 的定義都位於介面 '{1}' 的巢狀內,且 '{1}' 具有 'In' 或 'Out' 類型參數。請考慮將 '{0}' 的定義移到 '{1}' 之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowedHere3">
<source>Type '{0}' cannot be used in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{2}',因為該內容和 '{0}' 的定義都位於介面 '{1}' 的巢狀內,且 '{1}' 具有 'In' 或 'Out' 類型參數。請考慮將 '{0}' 的定義移到 '{1}' 之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowedHereForGeneric5">
<source>Type '{0}' cannot be used for the '{3}' of '{4}' in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{2}' 中 '{4}' 的 '{3}',因為該內容和 '{0}' 的定義都位於介面 '{1}' 的巢狀內,且 '{1}' 具有 'In' 或 'Out' 類型參數。請考慮將 '{0}' 的定義移到 '{1}' 之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParameterNotValidForType">
<source>Parameter not valid for the specified unmanaged type.</source>
<target state="translated">參數對於指定的 Unmanaged 類型無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MarshalUnmanagedTypeNotValidForFields">
<source>Unmanaged type '{0}' not valid for fields.</source>
<target state="translated">Unmanaged 類型 '{0}' 對欄位無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MarshalUnmanagedTypeOnlyValidForFields">
<source>Unmanaged type '{0}' is only valid for fields.</source>
<target state="translated">Unmanaged 類型 '{0}' 只對欄位有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeParameterRequired1">
<source>Attribute parameter '{0}' must be specified.</source>
<target state="translated">必須指定屬性參數 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeParameterRequired2">
<source>Attribute parameter '{0}' or '{1}' must be specified.</source>
<target state="translated">必須指定屬性參數 '{0}' 或 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MemberConflictWithSynth4">
<source>Conflicts with '{0}', which is implicitly declared for '{1}' in {2} '{3}'.</source>
<target state="translated">與 {2} '{3}' 中為 '{1}' 所隱含宣告的 '{0}' 互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="IDS_ProjectSettingsLocationName">
<source><project settings></source>
<target state="translated"><專案設定></target>
<note />
</trans-unit>
<trans-unit id="WRN_ReturnTypeAttributeOnWriteOnlyProperty">
<source>Attributes applied on a return type of a WriteOnly Property have no effect.</source>
<target state="translated">在 WriteOnly 屬性的傳回類型上套用之屬性沒有作用。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ReturnTypeAttributeOnWriteOnlyProperty_Title">
<source>Attributes applied on a return type of a WriteOnly Property have no effect</source>
<target state="translated">在 WriteOnly 屬性的傳回類型上套用的屬性沒有作用</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidTarget">
<source>Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations.</source>
<target state="translated">安全屬性 '{0}' 在此宣告類型上無效。安全屬性只有在組件、類型和方法宣告上才有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AbsentReferenceToPIA1">
<source>Cannot find the interop type that matches the embedded type '{0}'. Are you missing an assembly reference?</source>
<target state="translated">找不到符合內嵌類型 '{0}' 的 Interop 類型。是否遺漏組件參考?</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLinkClassWithNoPIA1">
<source>Reference to class '{0}' is not allowed when its assembly is configured to embed interop types.</source>
<target state="translated">在類別 '{0}' 的組件設定為內嵌 Interop 類型時,不可使用該類別的參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidStructMemberNoPIA1">
<source>Embedded interop structure '{0}' can contain only public instance fields.</source>
<target state="translated">內嵌的 Interop 結構 '{0}' 只可包含公用執行個體欄位。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoPIAAttributeMissing2">
<source>Interop type '{0}' cannot be embedded because it is missing the required '{1}' attribute.</source>
<target state="translated">無法內嵌 Interop 類型 '{0}',因為其遺漏必要的 '{1}' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PIAHasNoAssemblyGuid1">
<source>Cannot embed interop types from assembly '{0}' because it is missing the '{1}' attribute.</source>
<target state="translated">無法從組件 '{0}' 內嵌 Interop 類型,因為其遺漏了 '{1}' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateLocalTypes3">
<source>Cannot embed interop type '{0}' found in both assembly '{1}' and '{2}'. Consider disabling the embedding of interop types.</source>
<target state="translated">無法內嵌在組件 '{1}' 和 '{2}' 中所找到的 Interop 類型 '{0}'。請考慮停用內嵌 Interop 類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PIAHasNoTypeLibAttribute1">
<source>Cannot embed interop types from assembly '{0}' because it is missing either the '{1}' attribute or the '{2}' attribute.</source>
<target state="translated">無法從組件 '{0}' 內嵌 Interop 類型,因為其遺漏了 '{1}' 屬性或 '{2}' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SourceInterfaceMustBeInterface">
<source>Interface '{0}' has an invalid source interface which is required to embed event '{1}'.</source>
<target state="translated">介面 '{0}' 的來源介面無效,但內嵌事件 '{1}' 需要該介面。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventNoPIANoBackingMember">
<source>Source interface '{0}' is missing method '{1}', which is required to embed event '{2}'.</source>
<target state="translated">來源介面 '{0}' 遺漏內嵌事件 '{2}' 所需的方法 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedInteropType">
<source>Nested type '{0}' cannot be embedded.</source>
<target state="translated">無法內嵌巢狀類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalTypeNameClash2">
<source>Embedding the interop type '{0}' from assembly '{1}' causes a name clash in the current assembly. Consider disabling the embedding of interop types.</source>
<target state="translated">從組件 '{1}' 內嵌 Interop 類型 '{0}',會造成目前組件中的名稱衝突。請考慮停用內嵌 Interop 類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InteropMethodWithBody1">
<source>Embedded interop method '{0}' contains a body.</source>
<target state="translated">內嵌 Interop 方法 '{0}' 包含主體。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncInQuery">
<source>'Await' may only be used in a query expression within the first collection expression of the initial 'From' clause or within the collection expression of a 'Join' clause.</source>
<target state="translated">'Await' 只能使用於初始 'From' 子句第一個集合運算式內的查詢運算式,或 'Join' 子句集合運算式內的查詢運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadGetAwaiterMethod1">
<source>'Await' requires that the type '{0}' have a suitable GetAwaiter method.</source>
<target state="translated">'Await' 要求類型 '{0}' 必須具有合適的 GetAwaiter 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIsCompletedOnCompletedGetResult2">
<source>'Await' requires that the return type '{0}' of '{1}.GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.</source>
<target state="translated">'Await' 要求 '{1}.GetAwaiter()' 的傳回類型 '{0}',必須具有合適的 IsCompleted、OnCompleted 和 GetResult 成員,且實作 INotifyCompletion 或 ICriticalNotifyCompletion。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DoesntImplementAwaitInterface2">
<source>'{0}' does not implement '{1}'.</source>
<target state="translated">'{0}' 未實作 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitNothing">
<source>Cannot await Nothing. Consider awaiting 'Task.Yield()' instead.</source>
<target state="translated">無法等候 Nothing。請考慮改為等候 'Task.Yield()'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncByRefParam">
<source>Async methods cannot have ByRef parameters.</source>
<target state="translated">Async 方法不可以有 ByRef 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAsyncIteratorModifiers">
<source>'Async' and 'Iterator' modifiers cannot be used together.</source>
<target state="translated">'Async' 和 'Iterator' 修飾元不可以同時使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadResumableAccessReturnVariable">
<source>The implicit return variable of an Iterator or Async method cannot be accessed.</source>
<target state="translated">無法存取 Iterator 或 Async 方法的隱含傳回變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReturnFromNonGenericTaskAsync">
<source>'Return' statements in this Async method cannot return a value since the return type of the function is 'Task'. Consider changing the function's return type to 'Task(Of T)'.</source>
<target state="translated">'這個 Async 方法中的 'Return' 陳述式無法傳回值,因為函式的傳回類型為 'Task'。請考慮將函式的傳回類型變更為 'Task(Of T)'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncReturnOperand1">
<source>Since this is an async method, the return expression must be of type '{0}' rather than 'Task(Of {0})'.</source>
<target state="translated">因為此為 Async 方法,所以傳回運算式必須是 '{0}' 類型,而非 'Task(Of {0})'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncReturn">
<source>The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).</source>
<target state="translated">Async' 修飾元只能用在傳回 Task 或 Task(Of T) 的子函數或函式上。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantAwaitAsyncSub1">
<source>'{0}' does not return a Task and cannot be awaited. Consider changing it to an Async Function.</source>
<target state="translated">'{0}' 不會傳回 Task 且無法等候。請考慮將其變更為 Async 函式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidLambdaModifier">
<source>'Only the 'Async' or 'Iterator' modifier is valid on a lambda.</source>
<target state="translated">'Lambda 上只有 'Async' 或 'Iterator' 修飾元有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInNonAsyncMethod">
<source>'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task(Of {0})'.</source>
<target state="translated">'Await' 只可用於 Async 方法中。請考慮以 'Async' 修飾元標記此方法,並將其傳回類型變更為 'Task(Of {0})'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInNonAsyncVoidMethod">
<source>'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task'.</source>
<target state="translated">'Await' 只能在非同步方法使用。請考慮以 'Async' 修飾元標記此方法,並將它的傳回類型變更為 'Task'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInNonAsyncLambda">
<source>'Await' can only be used within an Async lambda expression. Consider marking this lambda expression with the 'Async' modifier.</source>
<target state="translated">'Await' 只能在非同步 Lambda 運算式使用。請考慮以 'Async' 修飾元標記此 Lambda 運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitNotInAsyncMethodOrLambda">
<source>'Await' can only be used when contained within a method or lambda expression marked with the 'Async' modifier.</source>
<target state="translated">'Await' 只有在包含於以 'Async' 修飾元標記的方法或 Lambda 運算式時才能使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StatementLambdaInExpressionTree">
<source>Statement lambdas cannot be converted to expression trees.</source>
<target state="translated">陳述式 Lambda 無法轉換成運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableExpression">
<source>Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.</source>
<target state="translated">因為未等候此呼叫,所以在呼叫完成之前會繼續執行目前方法。請考慮將 Await 運算子套用至呼叫的結果。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableExpression_Title">
<source>Because this call is not awaited, execution of the current method continues before the call is completed</source>
<target state="translated">因為未等待此呼叫,所以在完成呼叫之前會繼續執行目前方法</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopControlMustNotAwait">
<source>Loop control variable cannot include an 'Await'.</source>
<target state="translated">迴圈控制變數不可包含 'Await'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadStaticInitializerInResumable">
<source>Static variables cannot appear inside Async or Iterator methods.</source>
<target state="translated">靜態變數不可出現在 Async 或 Iterator 方法中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedResumableType1">
<source>'{0}' cannot be used as a parameter type for an Iterator or Async method.</source>
<target state="translated">'{0}' 不能用做為 Iterator 或 Async 方法的參數類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorAsync">
<source>Constructor must not have the 'Async' modifier.</source>
<target state="translated">建構函式不可以有 'Async' 修飾元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodsMustNotBeAsync1">
<source>'{0}' cannot be declared 'Partial' because it has the 'Async' modifier.</source>
<target state="translated">'{0}' 不可宣告為 'Partial',因為其具有 'Async' 修飾元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ResumablesCannotContainOnError">
<source>'On Error' and 'Resume' cannot appear inside async or iterator methods.</source>
<target state="translated">'On Error' 和 'Resume' 不可以出現在 async 或 iterator 方法內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ResumableLambdaInExpressionTree">
<source>Lambdas with the 'Async' or 'Iterator' modifiers cannot be converted to expression trees.</source>
<target state="translated">具有 'Async' 或 'Iterator' 修飾元的 Lambda,無法轉換為運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftRestrictedTypeResumable1">
<source>Variable of restricted type '{0}' cannot be declared in an Async or Iterator method.</source>
<target state="translated">無法在 Async 或 Iterator 方法中宣告受限制之類型 '{0}' 的變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInTryHandler">
<source>'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.</source>
<target state="translated">'Await' 不能用在 'Catch' 陳述式、'Finally' 陳述式或 'SyncLock' 陳述式內。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncLacksAwaits">
<source>This async method lacks 'Await' operators and so will run synchronously. Consider using the 'Await' operator to await non-blocking API calls, or 'Await Task.Run(...)' to do CPU-bound work on a background thread.</source>
<target state="translated">這個 async 方法缺少 'Await' 運算子,因此將以同步方式執行。請考慮使用 'Await' 運算子等候未封鎖的應用程式開發介面呼叫,或使用 'Await Task.Run(...)' 在背景執行緒上執行 CPU-bound 工作。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncLacksAwaits_Title">
<source>This async method lacks 'Await' operators and so will run synchronously</source>
<target state="translated">這個 async 方法缺少 'Await' 運算子,因此將以同步方式執行</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableDelegate">
<source>The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.</source>
<target state="translated">將刪除從這個 Async 函式傳回的 Task,並且忽略其中的任何例外狀況。請考慮將它變更為 Async 子函數,以便傳播例外狀況。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableDelegate_Title">
<source>The Task returned from this Async Function will be dropped, and any exceptions in it ignored</source>
<target state="translated">將會卸除從這個 Async 函式傳回的 Task,且會忽略其中的所有例外狀況</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityCriticalAsyncInClassOrStruct">
<source>Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.</source>
<target state="translated">具有 'SecurityCritical' 或 'SecuritySafeCritical' 屬性的 [Class|Structure|Interface|Module] 中,不可使用 Async 和 Iterator 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityCriticalAsync">
<source>Security attribute '{0}' cannot be applied to an Async or Iterator method.</source>
<target state="translated">安全屬性 '{0}' 無法套用至 Async 或 Iterator 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnResumableMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至 Async 或 Iterator 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynchronizedAsyncMethod">
<source>'MethodImplOptions.Synchronized' cannot be applied to an Async method.</source>
<target state="translated">'MethodImplOptions.Synchronized' 無法套用至 Async 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AsyncSubMain">
<source>The 'Main' method cannot be marked 'Async'.</source>
<target state="translated">Main' 方法不能標記為 'Async。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncSubCouldBeFunction">
<source>Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.</source>
<target state="translated">這裡的有些多載會接受 Async 函式,而非 Async 子函數。請考慮使用 Async 函式,或者將這個 Async 子函數明確地轉型為想要的類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncSubCouldBeFunction_Title">
<source>Some overloads here take an Async Function rather than an Async Sub</source>
<target state="translated">有些此處的多載接受 Async 函式但不接受 Async 子函式</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyGroupCollectionAttributeCycle">
<source>MyGroupCollectionAttribute cannot be applied to itself.</source>
<target state="translated">MyGroupCollectionAttribute 無法套用至本身。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LiteralExpected">
<source>Literal expected.</source>
<target state="translated">必須是常值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_WinRTEventWithoutDelegate">
<source>Event declarations that target WinMD must specify a delegate type. Add an As clause to the event declaration.</source>
<target state="translated">目標為 WinMD 的事件宣告必須指定委派類型。請將 As 子句加入至事件宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MixingWinRTAndNETEvents">
<source>Event '{0}' cannot implement a Windows Runtime event '{1}' and a regular .NET event '{2}'</source>
<target state="translated">事件 '{0}' 無法實作 Windows 執行階段事件 '{1}' 和一般 .NET 事件 '{2}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventImplRemoveHandlerParamWrong">
<source>Event '{0}' cannot implement event '{1}' on interface '{2}' because the parameters of their 'RemoveHandler' methods do not match.</source>
<target state="translated">事件 '{0}' 無法在介面 '{2}' 上實作事件 '{1}',因為其 'RemoveHandler' 方法的參數不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddParamWrongForWinRT">
<source>The type of the 'AddHandler' method's parameter must be the same as the type of the event.</source>
<target state="translated">AddHandler' 方法參數的類型必須與事件的類型相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RemoveParamWrongForWinRT">
<source>In a Windows Runtime event, the type of the 'RemoveHandler' method parameter must be 'EventRegistrationToken'</source>
<target state="translated">在 Windows 執行階段事件中,'RemoveHandler' 方法參數的類型必須是 'EventRegistrationToken'</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReImplementingWinRTInterface5">
<source>'{0}.{1}' from 'implements {2}' is already implemented by the base class '{3}'. Re-implementation of Windows Runtime Interface '{4}' is not allowed</source>
<target state="translated">'基底類別 '{3}' 已實作 'implements {2}' 中的 '{0}.{1}'。不允許重新實作 Windows 執行階段介面 '{4}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReImplementingWinRTInterface4">
<source>'{0}.{1}' is already implemented by the base class '{2}'. Re-implementation of Windows Runtime Interface '{3}' is not allowed</source>
<target state="translated">'基底類別 '{2}' 已實作 '{0}.{1}'。不允許重新實作 Windows 執行階段介面 '{3}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIteratorByRefParam">
<source>Iterator methods cannot have ByRef parameters.</source>
<target state="translated">Iterator 方法不可有 ByRef 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIteratorExpressionLambda">
<source>Single-line lambdas cannot have the 'Iterator' modifier. Use a multiline lambda instead.</source>
<target state="translated">單行 Lambda 不能有 'Iterator' 修飾元。請改用多行 Lambda。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIteratorReturn">
<source>Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.</source>
<target state="translated">Iterator 函式必須傳回 IEnumerable(Of T) 或 IEnumerator(Of T),或是非泛型表單 IEnumerable 或 IEnumerator。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadReturnValueInIterator">
<source>To return a value from an Iterator function, use 'Yield' rather than 'Return'.</source>
<target state="translated">若要從 Iterator 函式傳回值,請使用 'Yield' 而不要使用 'Return'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadYieldInNonIteratorMethod">
<source>'Yield' can only be used in a method marked with the 'Iterator' modifier.</source>
<target state="translated">'Yield' 只能用在標記為 'Iterator' 修飾元的方法中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadYieldInTryHandler">
<source>'Yield' cannot be used inside a 'Catch' statement or a 'Finally' statement.</source>
<target state="translated">'Yield' 不能用在 'Catch' 陳述式或 'Finally' 陳述式內。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValWinRtEventVal1">
<source>The AddHandler for Windows Runtime event '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">Windows 執行階段事件 '{0}' 的 AddHandler,並未傳回有關所有程式碼路徑的值。是否遺漏了 'Return' 陳述式?</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValWinRtEventVal1_Title">
<source>The AddHandler for Windows Runtime event doesn't return a value on all code paths</source>
<target state="translated">Windows 執行階段事件的 AddHandler 在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodDefaultParameterValueMismatch2">
<source>Optional parameter of a method '{0}' does not have the same default value as the corresponding parameter of the partial method '{1}'.</source>
<target state="translated">方法 '{0}' 的選擇性參數,與部分方法 '{1}' 的對應參數沒有相同的預設值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodParamArrayMismatch2">
<source>Parameter of a method '{0}' differs by ParamArray modifier from the corresponding parameter of the partial method '{1}'.</source>
<target state="translated">方法 '{0}' 的參數與部分方法 '{1}' 的對應參數間之差異,在於 ParamArray 的修飾元不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NetModuleNameMismatch">
<source>Module name '{0}' stored in '{1}' must match its filename.</source>
<target state="translated">儲存在 '{1}' 中的模組名稱 '{0}',必須符合其檔案名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadModuleName">
<source>Invalid module name: {0}</source>
<target state="translated">模組名稱 {0} 無效</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden">
<source>Attribute '{0}' from module '{1}' will be ignored in favor of the instance appearing in source.</source>
<target state="translated">將會忽略模組 '{1}' 中的屬性 '{0}',改用出現在來源中的執行個體。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden_Title">
<source>Attribute from module will be ignored in favor of the instance appearing in source</source>
<target state="translated">將會忽略模組中的屬性,改用出現在來源中的執行個體</target>
<note />
</trans-unit>
<trans-unit id="ERR_CmdOptionConflictsSource">
<source>Attribute '{0}' given in a source file conflicts with option '{1}'.</source>
<target state="translated">原始程式檔中所提供的屬性 '{0}',與選項 '{1}' 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName">
<source>Referenced assembly '{0}' does not have a strong name.</source>
<target state="translated">參考組件 '{0}' 沒有強式名稱。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName_Title">
<source>Referenced assembly does not have a strong name</source>
<target state="translated">參考的組件沒有強式名稱</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSignaturePublicKey">
<source>Invalid signature public key specified in AssemblySignatureKeyAttribute.</source>
<target state="translated">AssemblySignatureKeyAttribute 中指定的簽章公開金鑰無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CollisionWithPublicTypeInModule">
<source>Type '{0}' conflicts with public type defined in added module '{1}'.</source>
<target state="translated">類型 '{0}' 與加入的模組 '{1}' 中所定義的公用類型相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExportedTypeConflictsWithDeclaration">
<source>Type '{0}' exported from module '{1}' conflicts with type declared in primary module of this assembly.</source>
<target state="translated">從模組 '{1}' 匯出的類型 '{0}' 與此組件的主要模組中所宣告之類型相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExportedTypesConflict">
<source>Type '{0}' exported from module '{1}' conflicts with type '{2}' exported from module '{3}'.</source>
<target state="translated">從模組 '{1}' 匯出的類型 '{0}' 與從模組 '{3}' 匯出的類型 '{2}' 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RefCultureMismatch">
<source>Referenced assembly '{0}' has different culture setting of '{1}'.</source>
<target state="translated">參考組件 '{0}' 有不同的文化特性設定 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RefCultureMismatch_Title">
<source>Referenced assembly has different culture setting</source>
<target state="translated">參考的組件具有不同文化特性設定</target>
<note />
</trans-unit>
<trans-unit id="ERR_AgnosticToMachineModule">
<source>Agnostic assembly cannot have a processor specific module '{0}'.</source>
<target state="translated">無從驗證的組件不可有處理器專屬的模組 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictingMachineModule">
<source>Assembly and module '{0}' cannot target different processors.</source>
<target state="translated">組件與模組 '{0}' 的目標處理器不可不同。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConflictingMachineAssembly">
<source>Referenced assembly '{0}' targets a different processor.</source>
<target state="translated">參考組件 '{0}' 以不同的處理器為目標。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConflictingMachineAssembly_Title">
<source>Referenced assembly targets a different processor</source>
<target state="translated">參考的組件以不同的處理器為目標</target>
<note />
</trans-unit>
<trans-unit id="ERR_CryptoHashFailed">
<source>Cryptographic failure while creating hashes.</source>
<target state="translated">建立雜湊時密碼編譯失敗。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantHaveWin32ResAndManifest">
<source>Conflicting options specified: Win32 resource file; Win32 manifest.</source>
<target state="translated">指定的選項相衝突: Win32 資源檔; Win32 資訊清單。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypeConflictsWithDeclaration">
<source>Forwarded type '{0}' conflicts with type declared in primary module of this assembly.</source>
<target state="translated">轉送的類型 '{0}' 與此組件主要模組中所宣告的類型相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypesConflict">
<source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' forwarded to assembly '{3}'.</source>
<target state="translated">轉送到組件 '{1}' 的類型 '{0}' 與轉送到組件 '{3}' 的類型 '{2}' 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooLongMetadataName">
<source>Name '{0}' exceeds the maximum length allowed in metadata.</source>
<target state="translated">名稱 '{0}' 超過中繼資料內所允許的長度上限。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingNetModuleReference">
<source>Reference to '{0}' netmodule missing.</source>
<target state="translated">遺漏 '{0}' netmodule 的參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NetModuleNameMustBeUnique">
<source>Module '{0}' is already defined in this assembly. Each module must have a unique filename.</source>
<target state="translated">模組 '{0}' 已定義在此組件中。每個模組都必須要有不重複的檔案名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypeConflictsWithExportedType">
<source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' exported from module '{3}'.</source>
<target state="translated">轉送到組件 '{1}' 的類型 '{0}' 與從模組 '{3}' 匯出的類型 '{2}' 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="IDS_MSG_ADDREFERENCE">
<source>Adding assembly reference '{0}'</source>
<target state="translated">正在加入組件參考 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="IDS_MSG_ADDLINKREFERENCE">
<source>Adding embedded assembly reference '{0}'</source>
<target state="translated">正在加入內嵌組件參考 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="IDS_MSG_ADDMODULE">
<source>Adding module reference '{0}'</source>
<target state="translated">正在加入模組參考 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestingViolatesCLS1">
<source>Type '{0}' does not inherit the generic type parameters of its container.</source>
<target state="translated">類型 '{0}' 沒有繼承其容器的泛型類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PDBWritingFailed">
<source>Failure writing debug information: {0}</source>
<target state="translated">寫入偵錯資訊時失敗: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamDefaultValueDiffersFromAttribute">
<source>The parameter has multiple distinct default values.</source>
<target state="translated">此參數有多個相異的預設值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FieldHasMultipleDistinctConstantValues">
<source>The field has multiple distinct constant values.</source>
<target state="translated">此欄位有多個相異的常數值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncNoPIAReference">
<source>Cannot continue since the edit includes a reference to an embedded type: '{0}'.</source>
<target state="translated">無法繼續,因為編輯包含內嵌類型的參考: '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncReferenceToAddedMember">
<source>Member '{0}' added during the current debug session can only be accessed from within its declaring assembly '{1}'.</source>
<target state="translated">在目前偵錯工作階段期間加入的成員 '{0}',只能從其宣告組件中 '{1}' 存取。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedModule1">
<source>'{0}' is an unsupported .NET module.</source>
<target state="translated">'{0}' 不是支援的 .NET 模組。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedEvent1">
<source>'{0}' is an unsupported event.</source>
<target state="translated">'{0}' 是不支援的事件。</target>
<note />
</trans-unit>
<trans-unit id="PropertiesCanNotHaveTypeArguments">
<source>Properties can not have type arguments</source>
<target state="translated">屬性不可有類型引數</target>
<note />
</trans-unit>
<trans-unit id="IdentifierSyntaxNotWithinSyntaxTree">
<source>IdentifierSyntax not within syntax tree</source>
<target state="translated">IdentifierSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="AnonymousObjectCreationExpressionSyntaxNotWithinTree">
<source>AnonymousObjectCreationExpressionSyntax not within syntax tree</source>
<target state="translated">AnonymousObjectCreationExpressionSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="FieldInitializerSyntaxNotWithinSyntaxTree">
<source>FieldInitializerSyntax not within syntax tree</source>
<target state="translated">FieldInitializerSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="IDS_TheSystemCannotFindThePathSpecified">
<source>The system cannot find the path specified</source>
<target state="translated">系統找不到指定的路徑</target>
<note />
</trans-unit>
<trans-unit id="ThereAreNoPointerTypesInVB">
<source>There are no pointer types in VB.</source>
<target state="translated">VB 中沒有指標類型。</target>
<note />
</trans-unit>
<trans-unit id="ThereIsNoDynamicTypeInVB">
<source>There is no dynamic type in VB.</source>
<target state="translated">VB 中沒有動態類型。</target>
<note />
</trans-unit>
<trans-unit id="VariableSyntaxNotWithinSyntaxTree">
<source>variableSyntax not within syntax tree</source>
<target state="translated">variableSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="AggregateSyntaxNotWithinSyntaxTree">
<source>AggregateSyntax not within syntax tree</source>
<target state="translated">AggregateSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="FunctionSyntaxNotWithinSyntaxTree">
<source>FunctionSyntax not within syntax tree</source>
<target state="translated">FunctionSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="PositionIsNotWithinSyntax">
<source>Position is not within syntax tree</source>
<target state="translated">Position 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="RangeVariableSyntaxNotWithinSyntaxTree">
<source>RangeVariableSyntax not within syntax tree</source>
<target state="translated">RangeVariableSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="DeclarationSyntaxNotWithinSyntaxTree">
<source>DeclarationSyntax not within syntax tree</source>
<target state="translated">DeclarationSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="StatementOrExpressionIsNotAValidType">
<source>StatementOrExpression is not an ExecutableStatementSyntax or an ExpressionSyntax</source>
<target state="translated">StatementOrExpression 不是 ExecutableStatementSyntax 或 ExpressionSyntax</target>
<note />
</trans-unit>
<trans-unit id="DeclarationSyntaxNotWithinTree">
<source>DeclarationSyntax not within tree</source>
<target state="translated">DeclarationSyntax 不在樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="TypeParameterNotWithinTree">
<source>TypeParameter not within tree</source>
<target state="translated">TypeParameter 不在樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="NotWithinTree">
<source> not within tree</source>
<target state="translated"> 不在樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="LocationMustBeProvided">
<source>Location must be provided in order to provide minimal type qualification.</source>
<target state="translated">必須提供位置,才可提供最基本的類型限定性條件。</target>
<note />
</trans-unit>
<trans-unit id="SemanticModelMustBeProvided">
<source>SemanticModel must be provided in order to provide minimal type qualification.</source>
<target state="translated">必須提供 SemanticModel,才可提供最基本的類型限定性條件。</target>
<note />
</trans-unit>
<trans-unit id="NumberOfTypeParametersAndArgumentsMustMatch">
<source>the number of type parameters and arguments should be the same</source>
<target state="translated">類型參數和引數的數目應相同</target>
<note />
</trans-unit>
<trans-unit id="ERR_ResourceInModule">
<source>Cannot link resource files when building a module</source>
<target state="translated">建立模組時無法連結資源檔案</target>
<note />
</trans-unit>
<trans-unit id="NotAVbSymbol">
<source>Not a VB symbol.</source>
<target state="translated">不是 VB 符號。</target>
<note />
</trans-unit>
<trans-unit id="ElementsCannotBeNull">
<source>Elements cannot be null.</source>
<target state="translated">項目不可為 null。</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportClause">
<source>Unused import clause.</source>
<target state="translated">未使用的匯入子句。</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportStatement">
<source>Unused import statement.</source>
<target state="translated">未使用的匯入陳述式。</target>
<note />
</trans-unit>
<trans-unit id="WrongSemanticModelType">
<source>Expected a {0} SemanticModel.</source>
<target state="translated">必須是 {0} SemanticModel。</target>
<note />
</trans-unit>
<trans-unit id="PositionNotWithinTree">
<source>Position must be within span of the syntax tree.</source>
<target state="translated">位置必須在語法樹狀結構的範圍內。</target>
<note />
</trans-unit>
<trans-unit id="SpeculatedSyntaxNodeCannotBelongToCurrentCompilation">
<source>Syntax node to be speculated cannot belong to a syntax tree from the current compilation.</source>
<target state="translated">要推測的語法節點,不可屬於目前編譯的語法樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ChainingSpeculativeModelIsNotSupported">
<source>Chaining speculative semantic model is not supported. You should create a speculative model from the non-speculative ParentModel.</source>
<target state="translated">不支援鏈結理論式語意模型。應從非理論式 ParentModel 建立理論式模型。</target>
<note />
</trans-unit>
<trans-unit id="IDS_ToolName">
<source>Microsoft (R) Visual Basic Compiler</source>
<target state="translated">Microsoft (R) Visual Basic 編譯器</target>
<note />
</trans-unit>
<trans-unit id="IDS_LogoLine1">
<source>{0} version {1}</source>
<target state="translated">{0} 版 {1}</target>
<note />
</trans-unit>
<trans-unit id="IDS_LogoLine2">
<source>Copyright (C) Microsoft Corporation. All rights reserved.</source>
<target state="translated">Copyright (C) Microsoft Corporation. 著作權所有,並保留一切權利。</target>
<note />
</trans-unit>
<trans-unit id="IDS_LangVersions">
<source>Supported language versions:</source>
<target state="translated">支援的語言版本:</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbLocalNameTooLong">
<source>Local name '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source>
<target state="translated">區域變數名稱 '{0}' 對 PDB 而言太長。請考慮將其縮短,或在編譯時不要使用 /debug。</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbLocalNameTooLong_Title">
<source>Local name is too long for PDB</source>
<target state="translated">PDB 的本機名稱太長</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbUsingNameTooLong">
<source>Import string '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source>
<target state="translated">匯入字串 '{0}' 對 PDB 而言太長。請考慮縮短長度或不使用 /debug 進行編譯。</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbUsingNameTooLong_Title">
<source>Import string is too long for PDB</source>
<target state="translated">Import 字串對於 PDB 而言太長</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefToTypeParameter">
<source>XML comment has a tag with a 'cref' attribute '{0}' that bound to a type parameter. Use the <typeparamref> tag instead.</source>
<target state="translated">XML 註解的標記具有繫結至類型參數的 'cref' 屬性 '{0}'。請改用 <typeparamref> 標記。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefToTypeParameter_Title">
<source>XML comment has a tag with a 'cref' attribute that bound to a type parameter</source>
<target state="translated">XML 註解的標記具有與類型參數繫結的 'cref' 屬性</target>
<note />
</trans-unit>
<trans-unit id="ERR_LinkedNetmoduleMetadataMustProvideFullPEImage">
<source>Linked netmodule metadata must provide a full PE image: '{0}'.</source>
<target state="translated">連結的 netmodule 中繼資料必須提供完整的 PE 影像: '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AnalyzerCannotBeCreated">
<source>An instance of analyzer {0} cannot be created from {1} : {2}.</source>
<target state="translated">不可從 {1} 建立分析器 {0} 的執行個體: {2}。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AnalyzerCannotBeCreated_Title">
<source>Instance of analyzer cannot be created</source>
<target state="translated">無法建立分析器的執行個體</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoAnalyzerInAssembly">
<source>The assembly {0} does not contain any analyzers.</source>
<target state="translated">組件 {0} 不包含任何分析器。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoAnalyzerInAssembly_Title">
<source>Assembly does not contain any analyzers</source>
<target state="translated">組件不包含任何分析器</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnableToLoadAnalyzer">
<source>Unable to load analyzer assembly {0} : {1}.</source>
<target state="translated">無法載入分析器組件 {0} : {1}。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnableToLoadAnalyzer_Title">
<source>Unable to load analyzer assembly</source>
<target state="translated">無法載入分析器組件</target>
<note />
</trans-unit>
<trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer">
<source>Skipping some types in analyzer assembly {0} due to a ReflectionTypeLoadException : {1}.</source>
<target state="translated">因為 ReflectionTypeLoadException 之故,所以略過分析器組件 {0} 中的某些類型: {1}。</target>
<note />
</trans-unit>
<trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer_Title">
<source>Skip loading types in analyzer assembly that fail due to a ReflectionTypeLoadException</source>
<target state="translated">跳過載入分析器組件中因 ReflectionTypeLoadException 而失敗的類型</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantReadRulesetFile">
<source>Error reading ruleset file {0} - {1}</source>
<target state="translated">讀取規則集檔案 {0} 時發生錯誤 - {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_PlatformDoesntSupport">
<source>{0} is not supported in current project type.</source>
<target state="translated">目前的專案類型不支援 {0}。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantUseRequiredAttribute">
<source>The RequiredAttribute attribute is not permitted on Visual Basic types.</source>
<target state="translated">Visual Basic 類型上不可出現 RequiredAttribute 屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncodinglessSyntaxTree">
<source>Cannot emit debug information for a source text without encoding.</source>
<target state="translated">無法在不編碼的情況下,對原始程式文字發出偵錯資訊。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidFormatSpecifier">
<source>'{0}' is not a valid format specifier</source>
<target state="translated">'{0}' 不是有效的格式規範</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidPreprocessorConstantType">
<source>Preprocessor constant '{0}' of type '{1}' is not supported, only primitive types are allowed.</source>
<target state="translated">不支援類型為 '{1}' 的前置處理器常數 '{0}',只可使用基本類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedWarningKeyword">
<source>'Warning' expected.</source>
<target state="translated">'必須是 'Warning'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotBeMadeNullable1">
<source>'{0}' cannot be made nullable.</source>
<target state="translated">'{0}' 不可為 Null。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadConditionalWithRef">
<source>Leading '?' can only appear inside a 'With' statement, but not inside an object member initializer.</source>
<target state="translated">前置的 '?' 只可出現在 'With' 陳述式中,但不能出現在物件成員初始設定式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullPropagatingOpInExpressionTree">
<source>A null propagating operator cannot be converted into an expression tree.</source>
<target state="translated">Null 散佈運算子無法轉換為運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooLongOrComplexExpression">
<source>An expression is too long or complex to compile</source>
<target state="translated">運算式太長或太複雜,造成編譯困難</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpressionDoesntHaveName">
<source>This expression does not have a name.</source>
<target state="translated">此運算式沒有名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidNameOfSubExpression">
<source>This sub-expression cannot be used inside NameOf argument.</source>
<target state="translated">NameOf 引數中不可使用這個子運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodTypeArgsUnexpected">
<source>Method type arguments unexpected.</source>
<target state="translated">未預期的方法類型引數。</target>
<note />
</trans-unit>
<trans-unit id="NoNoneSearchCriteria">
<source>SearchCriteria is expected.</source>
<target state="translated">必須是 SearchCriteria。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyCulture">
<source>Assembly culture strings may not contain embedded NUL characters.</source>
<target state="translated">組件文化特性字串可能不包含內嵌的 NUL 字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InReferencedAssembly">
<source>There is an error in a referenced assembly '{0}'.</source>
<target state="translated">參考組件 '{0}' 中有錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterpolationFormatWhitespace">
<source>Format specifier may not contain trailing whitespace.</source>
<target state="translated">格式指定器尾端不得有空格。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterpolationAlignmentOutOfRange">
<source>Alignment value is outside of the supported range.</source>
<target state="translated">對齊值超出支援的範圍。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterpolatedStringFactoryError">
<source>There were one or more errors emitting a call to {0}.{1}. Method or its return type may be missing or malformed.</source>
<target state="translated">對 {0}.{1} 發出呼叫時發生一或多項錯誤。方法或其傳回類型可能遺漏或格式錯誤。</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportClause_Title">
<source>Unused import clause</source>
<target state="translated">未使用的匯入子句</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportStatement_Title">
<source>Unused import statement</source>
<target state="translated">未使用的匯入陳述式</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstantStringTooLong">
<source>Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.</source>
<target state="translated">從串連產生的字串常數長度超過 System.Int32.MaxValue。請嘗試將字串分割為多個常數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LanguageVersion">
<source>Visual Basic {0} does not support {1}.</source>
<target state="translated">Visual Basic {0} 不支援 {1}。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPdbData">
<source>Error reading debug information for '{0}'</source>
<target state="translated">讀取 '{0}' 的偵錯資訊時發生錯誤</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_ArrayLiterals">
<source>array literal expressions</source>
<target state="translated">陣列常值運算式</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_AsyncExpressions">
<source>async methods or lambdas</source>
<target state="translated">async 方法或 Lambda</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_AutoProperties">
<source>auto-implemented properties</source>
<target state="translated">自動實作的屬性</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_ReadonlyAutoProperties">
<source>readonly auto-implemented properties</source>
<target state="translated">自動實作的唯讀屬性</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CoContraVariance">
<source>variance</source>
<target state="translated">變異數</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CollectionInitializers">
<source>collection initializers</source>
<target state="translated">集合初始設定式</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_GlobalNamespace">
<source>declaring a Global namespace</source>
<target state="translated">宣告全域命名空間</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_Iterators">
<source>iterators</source>
<target state="translated">迭代器</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_LineContinuation">
<source>implicit line continuation</source>
<target state="translated">隱含行接續符號</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_StatementLambdas">
<source>multi-line lambda expressions</source>
<target state="translated">多行 Lambda 運算式</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_SubLambdas">
<source>'Sub' lambda expressions</source>
<target state="translated">'Sub' Lambda 運算式</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_NullPropagatingOperator">
<source>null conditional operations</source>
<target state="translated">null 條件運算</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_NameOfExpressions">
<source>'nameof' expressions</source>
<target state="translated">'nameof' 運算式</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_RegionsEverywhere">
<source>region directives within method bodies or regions crossing boundaries of declaration blocks</source>
<target state="translated">方法主體內的區域指示詞,或跨宣告區塊界限的區域</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_MultilineStringLiterals">
<source>multiline string literals</source>
<target state="translated">多行字串常值</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CObjInAttributeArguments">
<source>CObj in attribute arguments</source>
<target state="translated">屬性引數中的 CObj</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_LineContinuationComments">
<source>line continuation comments</source>
<target state="translated">行接續符號註解</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_TypeOfIsNot">
<source>TypeOf IsNot expression</source>
<target state="translated">TypeOf IsNot 運算式</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_YearFirstDateLiterals">
<source>year-first date literals</source>
<target state="translated">以年起始的日期常值</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_WarningDirectives">
<source>warning directives</source>
<target state="translated">警告指示詞</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_PartialModules">
<source>partial modules</source>
<target state="translated">部分模組</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_PartialInterfaces">
<source>partial interfaces</source>
<target state="translated">部分介面</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_ImplementingReadonlyOrWriteonlyPropertyWithReadwrite">
<source>implementing read-only or write-only property with read-write property</source>
<target state="translated">實作唯讀或唯寫屬性以及讀寫屬性</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_DigitSeparators">
<source>digit separators</source>
<target state="translated">數字分隔符號</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_BinaryLiterals">
<source>binary literals</source>
<target state="translated">二進位常值</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_Tuples">
<source>tuples</source>
<target state="translated">元組</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_PrivateProtected">
<source>Private Protected</source>
<target state="translated">Private Protected</target>
<note />
</trans-unit>
<trans-unit id="ERR_DebugEntryPointNotSourceMethodDefinition">
<source>Debug entry point must be a definition of a method declared in the current compilation.</source>
<target state="translated">偵錯進入點必須是目前編譯中所宣告方法的定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidPathMap">
<source>The pathmap option was incorrectly formatted.</source>
<target state="translated">pathmap 選項格式不正確。</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTreeIsNotASubmission">
<source>Syntax tree should be created from a submission.</source>
<target state="translated">提交時就應該建立語法樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyUserStrings">
<source>Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string or XML literals.</source>
<target state="translated">程式所使用的使用者字串加起來長度超過允許限制。請嘗試減少使用字串或 XML 常值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PeWritingFailure">
<source>An error occurred while writing the output file: {0}</source>
<target state="translated">寫入輸出檔案時發生錯誤: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionMustBeAbsolutePath">
<source>Option '{0}' must be an absolute path.</source>
<target state="translated">選項 '{0}' 必須是絕對路徑。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SourceLinkRequiresPdb">
<source>/sourcelink switch is only supported when emitting PDB.</source>
<target state="translated">只有在發出 PDB 時才支援 /sourcelink 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleDuplicateElementName">
<source>Tuple element names must be unique.</source>
<target state="translated">元組元素名稱不得重複。</target>
<note />
</trans-unit>
<trans-unit id="WRN_TupleLiteralNameMismatch">
<source>The tuple element name '{0}' is ignored because a different name or no name is specified by the target type '{1}'.</source>
<target state="translated">因為目標類型 '{1}' 指定了不同的名稱或未指定名稱,所以會忽略元組項目名稱 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_TupleLiteralNameMismatch_Title">
<source>The tuple element name is ignored because a different name or no name is specified by the assignment target.</source>
<target state="translated">因為指派目標指定了不同的名稱或未指定名稱,所以會忽略元組項目名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleReservedElementName">
<source>Tuple element name '{0}' is only allowed at position {1}.</source>
<target state="translated">只有位置 {1} 允許元組元素名稱 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleReservedElementNameAnyPosition">
<source>Tuple element name '{0}' is disallowed at any position.</source>
<target state="translated">任何位置都不允許元組元素名稱 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleTooFewElements">
<source>Tuple must contain at least two elements.</source>
<target state="translated">元組必須包含至少兩個項目。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleElementNamesAttributeMissing">
<source>Cannot define a class or member that utilizes tuples because the compiler required type '{0}' cannot be found. Are you missing a reference?</source>
<target state="translated">因為找不到編譯器所需的類型 '{0}',所以無法定義利用元組的類別或成員。是否遺漏參考?</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExplicitTupleElementNamesAttribute">
<source>Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names.</source>
<target state="translated">無法明確參考 'System.Runtime.CompilerServices.TupleElementNamesAttribute'。請使用元組語法定義元組名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RefReturningCallInExpressionTree">
<source>An expression tree may not contain a call to a method or property that returns by reference.</source>
<target state="translated">運算式樹狀架構不能包含藉傳址所傳回的方法或屬性呼叫。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotEmbedWithoutPdb">
<source>/embed switch is only supported when emitting a PDB.</source>
<target state="translated">只有在發出 PDB 時才支援 /embed 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidInstrumentationKind">
<source>Invalid instrumentation kind: {0}</source>
<target state="translated">檢測設備種類無效: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_DocFileGen">
<source>Error writing to XML documentation file: {0}</source>
<target state="translated">寫入 XML 文件檔案時發生錯誤: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAssemblyName">
<source>Invalid assembly name: {0}</source>
<target state="translated">組件名稱 {0} 無效</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeForwardedToMultipleAssemblies">
<source>Module '{0}' in assembly '{1}' is forwarding the type '{2}' to multiple assemblies: '{3}' and '{4}'.</source>
<target state="translated">組件 '{1}' 中的模組 '{0}' 正在將類型 '{2}' 轉送給多個組件: '{3}' 及 '{4}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_Merge_conflict_marker_encountered">
<source>Merge conflict marker encountered</source>
<target state="translated">偵測到合併衝突標記</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoRefOutWhenRefOnly">
<source>Do not use refout when using refonly.</source>
<target state="translated">使用 refonly 時,請勿使用 refout。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNetModuleOutputWhenRefOutOrRefOnly">
<source>Cannot compile net modules when using /refout or /refonly.</source>
<target state="translated">使用 /refout 或 /refonly 時無法編譯網路模組。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadNonTrailingNamedArgument">
<source>Named argument '{0}' is used out-of-position but is followed by an unnamed argument</source>
<target state="translated">具名引數 '{0}' 未用在正確的位置,但後面接著未命名引數</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDocumentationMode">
<source>Provided documentation mode is unsupported or invalid: '{0}'.</source>
<target state="translated">提供的文件模式不受支援或無效: '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadLanguageVersion">
<source>Provided language version is unsupported or invalid: '{0}'.</source>
<target state="translated">提供的語言版本不受支援或無效: '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadSourceCodeKind">
<source>Provided source code kind is unsupported or invalid: '{0}'</source>
<target state="translated">提供的原始程式碼類型不受支援或無效: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleInferredNamesNotAvailable">
<source>Tuple element name '{0}' is inferred. Please use language version {1} or greater to access an element by its inferred name.</source>
<target state="translated">元組項目名稱 '{0}' 從推斷而來。請使用語言版本 {1} 或更新版本,依推斷名稱存取項目。</target>
<note />
</trans-unit>
<trans-unit id="WRN_Experimental">
<source>'{0}' is for evaluation purposes only and is subject to change or removal in future updates.</source>
<target state="translated">'{0}' 僅供評估之用。後續更新時可能會有所變更或移除。</target>
<note />
</trans-unit>
<trans-unit id="WRN_Experimental_Title">
<source>Type is for evaluation purposes only and is subject to change or removal in future updates.</source>
<target state="translated">類型僅供評估之用。後續更新時可能會有所變更或移除。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidDebugInfo">
<source>Unable to read debug information of method '{0}' (token 0x{1}) from assembly '{2}'</source>
<target state="translated">無法從組件 '{2}' 讀取方法 '{0}' 的偵錯資訊 (權杖 0x{1})</target>
<note />
</trans-unit>
<trans-unit id="IConversionExpressionIsNotVisualBasicConversion">
<source>{0} is not a valid Visual Basic conversion expression</source>
<target state="translated">{0} 不是有效的 Visual Basic 轉換運算式</target>
<note />
</trans-unit>
<trans-unit id="IArgumentIsNotVisualBasicArgument">
<source>{0} is not a valid Visual Basic argument</source>
<target state="translated">{0} 不是有效的 Visual Basic 引數</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_LeadingDigitSeparator">
<source>leading digit separator</source>
<target state="translated">前置數字分隔符號</target>
<note />
</trans-unit>
<trans-unit id="ERR_ValueTupleResolutionAmbiguous3">
<source>Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}'</source>
<target state="translated">在多個參考組件中宣告了預先定義的類型 '{0}': '{1}' 與 '{2}'</target>
<note />
</trans-unit>
<trans-unit id="ICompoundAssignmentOperationIsNotVisualBasicCompoundAssignment">
<source>{0} is not a valid Visual Basic compound assignment operation</source>
<target state="translated">{0} 不是有效的 Visual Basic 複合指派作業</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidHashAlgorithmName">
<source>Invalid hash algorithm name: '{0}'</source>
<target state="translated">雜湊演算法名稱無效: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_InterpolatedStrings">
<source>interpolated strings</source>
<target state="translated">內插字串</target>
<note />
</trans-unit>
<trans-unit id="FTL_InvalidInputFileName">
<source>File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long</source>
<target state="translated">檔案名稱 '{0}' 是空的、包含了無效字元、指定了磁碟機但不是絕對路徑,或太長了</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeNotSupportedInVB">
<source>'{0}' is not supported in VB.</source>
<target state="translated">VB 中不支援 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeNotSupportedInVB_Title">
<source>Attribute is not supported in VB</source>
<target state="translated">VB 中不支援屬性</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../VBResources.resx">
<body>
<trans-unit id="ERR_AssignmentInitOnly">
<source>Init-only property '{0}' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor.</source>
<target state="translated">只有物件成員初始設定式,或在執行個體建構函式中的 'Me'、'MyClass' 或 'MyBase',才可指派僅限初始化的屬性 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadSwitchValue">
<source>Command-line syntax error: '{0}' is not a valid value for the '{1}' option. The value must be of the form '{2}'.</source>
<target state="translated">命令列語法錯誤: '{0}' 對 '{1}' 選項而言不是有效的值。此值的格式必須是 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CommentsAfterLineContinuationNotAvailable1">
<source>Please use language version {0} or greater to use comments after line continuation character.</source>
<target state="translated">若要在行接續字元後使用註解,請使用 {0} 或更高的語言版本。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultInterfaceImplementationInNoPIAType">
<source>Type '{0}' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false.</source>
<target state="translated">因為類型 '{0}' 有非抽象成員,所以無法內嵌。請考慮將 [內嵌 Interop 類型] 屬性設為 false。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleAnalyzerConfigsInSameDir">
<source>Multiple analyzer config files cannot be in the same directory ('{0}').</source>
<target state="translated">多個分析器組態檔無法處於相同目錄 ('{0}') 中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverridingInitOnlyProperty">
<source>'{0}' cannot override init-only '{1}'.</source>
<target state="translated">'{0}' 無法覆寫僅限初始化的 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyDoesntImplementInitOnly">
<source>Init-only '{0}' cannot be implemented.</source>
<target state="translated">無法實作僅限初始化的 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReAbstractionInNoPIAType">
<source>Type '{0}' cannot be embedded because it has a re-abstraction of a member from base interface. Consider setting the 'Embed Interop Types' property to false.</source>
<target state="translated">因為類型 '{0}' 有重新抽象成員 (來自基底介面),所以無法內嵌。請考慮將 [內嵌 Interop 類型] 屬性設為 false。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation">
<source>Target runtime doesn't support default interface implementation.</source>
<target state="translated">目標執行階段不支援預設介面實作。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember">
<source>Target runtime doesn't support 'Protected', 'Protected Friend', or 'Private Protected' accessibility for a member of an interface.</source>
<target state="translated">目標執行階段不支援對介面成員的 'Protected'、'Protected Friend' 或 'Private Protected' 存取範圍。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedEventNeedsHandlerInTheSameType">
<source>Events of shared WithEvents variables cannot be handled by methods in a different type.</source>
<target state="translated">無法使用其他類型的方法,處理共用 WithEvents 變數的事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnmanagedCallersOnlyNotSupported">
<source>'UnmanagedCallersOnly' attribute is not supported.</source>
<target state="translated">不支援 'UnmanagedCallersOnly' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CallerArgumentExpression">
<source>caller argument expression</source>
<target state="new">caller argument expression</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CommentsAfterLineContinuation">
<source>comments after line continuation</source>
<target state="translated">行接續符號後註解</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_InitOnlySettersUsage">
<source>assigning to or passing 'ByRef' properties with init-only setters</source>
<target state="translated">使用僅限初始化的 setter,指派或傳遞 'ByRef' 屬性</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_UnconstrainedTypeParameterInConditional">
<source>unconstrained type parameters in binary conditional expressions</source>
<target state="translated">二進位條件運算式中的非限制式型別參數</target>
<note />
</trans-unit>
<trans-unit id="IDS_VBCHelp">
<source> Visual Basic Compiler Options
- OUTPUT FILE -
-out:<file> Specifies the output file name.
-target:exe Create a console application (default).
(Short form: -t)
-target:winexe Create a Windows application.
-target:library Create a library assembly.
-target:module Create a module that can be added to an
assembly.
-target:appcontainerexe Create a Windows application that runs in
AppContainer.
-target:winmdobj Create a Windows Metadata intermediate file
-doc[+|-] Generates XML documentation file.
-doc:<file> Generates XML documentation file to <file>.
-refout:<file> Reference assembly output to generate
- INPUT FILES -
-addmodule:<file_list> Reference metadata from the specified modules
-link:<file_list> Embed metadata from the specified interop
assembly. (Short form: -l)
-recurse:<wildcard> Include all files in the current directory
and subdirectories according to the
wildcard specifications.
-reference:<file_list> Reference metadata from the specified
assembly. (Short form: -r)
-analyzer:<file_list> Run the analyzers from this assembly
(Short form: -a)
-additionalfile:<file list> Additional files that don't directly affect code
generation but may be used by analyzers for producing
errors or warnings.
- RESOURCES -
-linkresource:<resinfo> Links the specified file as an external
assembly resource.
resinfo:<file>[,<name>[,public|private]]
(Short form: -linkres)
-nowin32manifest The default manifest should not be embedded
in the manifest section of the output PE.
-resource:<resinfo> Adds the specified file as an embedded
assembly resource.
resinfo:<file>[,<name>[,public|private]]
(Short form: -res)
-win32icon:<file> Specifies a Win32 icon file (.ico) for the
default Win32 resources.
-win32manifest:<file> The provided file is embedded in the manifest
section of the output PE.
-win32resource:<file> Specifies a Win32 resource file (.res).
- CODE GENERATION -
-optimize[+|-] Enable optimizations.
-removeintchecks[+|-] Remove integer checks. Default off.
-debug[+|-] Emit debugging information.
-debug:full Emit full debugging information (default).
-debug:pdbonly Emit full debugging information.
-debug:portable Emit cross-platform debugging information.
-debug:embedded Emit cross-platform debugging information into
the target .dll or .exe.
-deterministic Produce a deterministic assembly
(including module version GUID and timestamp)
-refonly Produce a reference assembly in place of the main output
-instrument:TestCoverage Produce an assembly instrumented to collect
coverage information
-sourcelink:<file> Source link info to embed into PDB.
- ERRORS AND WARNINGS -
-nowarn Disable all warnings.
-nowarn:<number_list> Disable a list of individual warnings.
-warnaserror[+|-] Treat all warnings as errors.
-warnaserror[+|-]:<number_list> Treat a list of warnings as errors.
-ruleset:<file> Specify a ruleset file that disables specific
diagnostics.
-errorlog:<file>[,version=<sarif_version>]
Specify a file to log all compiler and analyzer
diagnostics in SARIF format.
sarif_version:{1|2|2.1} Default is 1. 2 and 2.1
both mean SARIF version 2.1.0.
-reportanalyzer Report additional analyzer information, such as
execution time.
-skipanalyzers[+|-] Skip execution of diagnostic analyzers.
- LANGUAGE -
-define:<symbol_list> Declare global conditional compilation
symbol(s). symbol_list:name=value,...
(Short form: -d)
-imports:<import_list> Declare global Imports for namespaces in
referenced metadata files.
import_list:namespace,...
-langversion:? Display the allowed values for language version
-langversion:<string> Specify language version such as
`default` (latest major version), or
`latest` (latest version, including minor versions),
or specific versions like `14` or `15.3`
-optionexplicit[+|-] Require explicit declaration of variables.
-optioninfer[+|-] Allow type inference of variables.
-rootnamespace:<string> Specifies the root Namespace for all type
declarations.
-optionstrict[+|-] Enforce strict language semantics.
-optionstrict:custom Warn when strict language semantics are not
respected.
-optioncompare:binary Specifies binary-style string comparisons.
This is the default.
-optioncompare:text Specifies text-style string comparisons.
- MISCELLANEOUS -
-help Display this usage message. (Short form: -?)
-noconfig Do not auto-include VBC.RSP file.
-nologo Do not display compiler copyright banner.
-quiet Quiet output mode.
-verbose Display verbose messages.
-parallel[+|-] Concurrent build.
-version Display the compiler version number and exit.
- ADVANCED -
-baseaddress:<number> The base address for a library or module
(hex).
-checksumalgorithm:<alg> Specify algorithm for calculating source file
checksum stored in PDB. Supported values are:
SHA1 or SHA256 (default).
-codepage:<number> Specifies the codepage to use when opening
source files.
-delaysign[+|-] Delay-sign the assembly using only the public
portion of the strong name key.
-publicsign[+|-] Public-sign the assembly using only the public
portion of the strong name key.
-errorreport:<string> Specifies how to handle internal compiler
errors; must be prompt, send, none, or queue
(default).
-filealign:<number> Specify the alignment used for output file
sections.
-highentropyva[+|-] Enable high-entropy ASLR.
-keycontainer:<string> Specifies a strong name key container.
-keyfile:<file> Specifies a strong name key file.
-libpath:<path_list> List of directories to search for metadata
references. (Semi-colon delimited.)
-main:<class> Specifies the Class or Module that contains
Sub Main. It can also be a Class that
inherits from System.Windows.Forms.Form.
(Short form: -m)
-moduleassemblyname:<string> Name of the assembly which this module will
be a part of.
-netcf Target the .NET Compact Framework.
-nostdlib Do not reference standard libraries
(system.dll and VBC.RSP file).
-pathmap:<K1>=<V1>,<K2>=<V2>,...
Specify a mapping for source path names output by
the compiler.
-platform:<string> Limit which platforms this code can run on;
must be x86, x64, Itanium, arm, arm64
AnyCPU32BitPreferred or anycpu (default).
-preferreduilang Specify the preferred output language name.
-nosdkpath Disable searching the default SDK path for standard library assemblies.
-sdkpath:<path> Location of the .NET Framework SDK directory
(mscorlib.dll).
-subsystemversion:<version> Specify subsystem version of the output PE.
version:<number>[.<number>]
-utf8output[+|-] Emit compiler output in UTF8 character
encoding.
@<file> Insert command-line settings from a text file
-vbruntime[+|-|*] Compile with/without the default Visual Basic
runtime.
-vbruntime:<file> Compile with the alternate Visual Basic
runtime in <file>.
</source>
<target state="translated"> Visual Basic 編譯器選項
- 輸出檔案 -
-out:<file> 指定輸出檔名稱。
-target:exe 建立主控台應用程式 (預設)。
(簡短形式: -t)
-target:winexe 建立 Windows 應用程式。
-target:library 建立程式庫組件。
-target:module 建立可以新增至組件的
模組。
-target:appcontainerexe 建立可在 AppContainer 中執行的
Windows 應用程式。
-target:winmdobj 建立 Windows Metadata 中繼檔案
-doc[+|-] 產生 XML 文件檔。
-doc:<file> 產生 XML 文件檔至 <file>。
-refout:<file> 要產生的參考組件輸出
- 輸入檔 -
-addmodule:<file_list> 從指定的模組來參考中繼資料
-link:<file_list> 從指定的 Interop 組件內嵌
中繼資料。(簡短形式: -l)
-recurse:<wildcard> 根據萬用字元規格
來加入目前目錄和子目錄中的
所有檔案。
-reference:<file_list> 從指定的組件參考
中繼資料。(簡短形式: -r)
-analyzer:<file_list> 從此組件執行分析器
(簡短形式: -a)
-additionalfile:<file list> 不直接影響程式碼產生,
但分析器可能用於產生錯誤或警告的
其他檔案。
- 資源 -
-linkresource:<resinfo> 連結指定的檔案作為外部
組件資源。
resinfo:<file>[,<name>[,public|private]]
(簡短形式: -linkres)
-nowin32manifest 預設資訊清單不應內嵌於
輸出 PE 的資訊清單區段中。
-resource:<resinfo> 將指定的檔案新增為內嵌的
組件資源。
resinfo:<file>[,<name>[,public|private]]
(簡短形式: -res)
-win32icon:<file> 指定某一個 Win32 圖示檔 (.ico) 給
預設的 Win32 資源。
-win32manifest:<file> 提供的檔案內嵌於輸出 PE 的
資訊清單區段中。
-win32resource:<file> 指定 Win32 資源檔 (.res)。
- 程式碼產生 -
-optimize[+|-] 啟用最佳化。
-removeintchecks[+|-] 不檢查整數。預設為關閉。
-debug[+|-] 發出偵錯資訊。
-debug:full 發出完整偵錯資訊 (預設)。
-debug:pdbonly 發出完整偵錯資訊。
-debug:portable 發出跨平台的偵錯資訊。
-debug:embedded 對目標 .dll 或 .exe 發出
跨平台偵錯資訊。
-deterministic 產生確定性組件
(含模組版本 GUID 與時間戳記)
-refonly 產生取代主要輸出的參考組件
-instrument:TestCoverage 產生經檢測的組件,以收集
涵蓋範圍資訊
-sourcelink:<file> 要內嵌至 PDB 的來源連結資訊。
- 錯誤與警告 -
-nowarn 停用所有警告。
-nowarn:<number_list> 停用個別警告清單。
-warnaserror[+|-] 將所有警告視為錯誤。
-warnaserror[+|-]:<number_list> 將警告清單視為錯誤。
-ruleset:<file> 指定規則集檔案,以停用特定的
診斷。
-errorlog:<file>[,version=<sarif_version>]
指定檔案,以 SARIF 的格式記錄所有編譯器
與分析器診斷。
sarif_version:{1|2|2.1} 預設為 1、2 與 2.1
兩者皆表示 SARIF 2.1.0 版。
-reportanalyzer 回報其他分析器資訊,例如
執行時間。
-skipanalyzers[+|-] 略過診斷分析器的執行。
- 語言 -
-define:<symbol_list> 宣告全域條件式編譯的
符號。symbol_list:name=value,...
(簡短形式: -d)
-imports:<import_list> 在參考的中繼資料檔案中宣告命名空間的
全域匯入。
import_list:namespace,...
-langversion:? 顯示允許的語言版本值
-langversion:<string> 指定語言版本,例如
`default` (最新的主要版本) 或
`latest` (最新版本,包括次要版本)
或特定的版本,例如 `14` 或 `15.3`
-optionexplicit[+|-] 變數必須明確宣告。
-optioninfer[+|-] 允許變數的類型推斷。
-rootnamespace:<string> 指定所有類型宣告的
根命名空間。
-optionstrict[+|-] 強制採用嚴格的語意。
-optionstrict:custom 未遵守嚴格的語意時
發出警告。
-optioncompare:binary 採用二進位樣式來比較字串。
這是預設值。
-optioncompare:text 採用文字樣式來比較字串。
- 其他 -
-help 顯示此使用方式訊息。(簡短形式: -?)
-noconfig 不要自動納入 VBC.RSP 檔。
-nologo 不要顯示編譯器著作權橫幅。
-quiet 無對話輸出模式。
-verbose 顯示詳細訊息。
-parallel[+|-] 並行組建。
-version 顯示編譯器版本編號然後結束。
- 進階 -
-baseaddress:<number> 程式庫或模組的基底位置
(十六進位)。
-checksumalgorithm:<alg> 指定演算法,以計算儲存於 PDB 的
來源檔案總和檢查碼。支援的值有:
SHA1 或 SHA256 (預設)。
-codepage:<number> 指定開啟原始程式檔時所要使用的
字碼頁。
-delaysign[+|-] 僅使用強式名稱金鑰的公開
部分延遲簽署組件。
-publicsign[+|-] 僅使用強式名稱金鑰的公開
部分公開簽署組件。
-errorreport:<string> 指定如何處理內部編譯器
錯誤;必須是 prompt、send、none 或 queue
(預設)。
-filealign:<number> 指定用於輸出檔案區段的對齊
方式。
-highentropyva[+|-] 啟用高熵 ASLR。
-keycontainer:<string> 指定強式名稱金鑰容器。
-keyfile:<file> 指定強式名稱金鑰檔。
-libpath:<path_list> 搜尋中繼資料參考的
目錄清單 (以分號分隔)。
-main:<class> 指定包含 Sub Main 的
Class 或 Module。也可以是繼承自
System.Windows.Forms.Form 的 Class。
(簡短形式: -m)
-moduleassemblyname:<string> 這個模組將成為其一部分的
組件名稱。
-netcf 以 .NET Compact Framework 為目標。
-nostdlib 不要參考標準程式庫
(system.dll 與 VBC.RSP 檔)。
-pathmap:<K1>=<V1>,<K2>=<V2>,...
指定由編譯器輸出的來源路徑名稱對應
對應。
-platform:<string> 限制這個程式碼可以在哪些平台執行;
必須是 x86、x64、Itanium、arm、arm64
AnyCPU32BitPreferred 或 anycpu (預設)。
-preferreduilang 指定慣用的輸出語言名稱。
-nosdkpath 禁止搜尋預設 SDK 路徑的標準程式庫組件。
-sdkpath:<path> .NET Framework SDK 目錄
(mscorlib.dll) 的位置。
-subsystemversion:<version> 指定輸出 PE 的子系統版本。
版本:<number>[.<number>]
-utf8output[+|-] 以 UTF8 字元編碼發出編譯器
輸出。
@<file> 從文字檔插入命令列設定
-vbruntime[+|-|*] 使用 (或不使用) 預設 Visual Basic
執行階段編譯。
-vbruntime:<file> 使用 <file> 中的其他 Visual Basic
執行階段編譯。
</target>
<note />
</trans-unit>
<trans-unit id="ThereAreNoFunctionPointerTypesInVB">
<source>There are no function pointer types in VB.</source>
<target state="translated">VB 中沒有函式指標類型。</target>
<note />
</trans-unit>
<trans-unit id="ThereAreNoNativeIntegerTypesInVB">
<source>There are no native integer types in VB.</source>
<target state="translated">VB 中沒有任何原生整數類型。</target>
<note />
</trans-unit>
<trans-unit id="Trees0">
<source>trees({0})</source>
<target state="translated">trees({0})</target>
<note />
</trans-unit>
<trans-unit id="TreesMustHaveRootNode">
<source>trees({0}) must have root node with SyntaxKind.CompilationUnit.</source>
<target state="translated">trees({0}) 必須要有具備 SyntaxKind.CompilationUnit 的根節點。</target>
<note />
</trans-unit>
<trans-unit id="CannotAddCompilerSpecialTree">
<source>Cannot add compiler special tree</source>
<target state="translated">無法加入編譯器特殊樹狀結構</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTreeAlreadyPresent">
<source>Syntax tree already present</source>
<target state="translated">語法樹狀結構已存在</target>
<note />
</trans-unit>
<trans-unit id="SubmissionCanHaveAtMostOneSyntaxTree">
<source>Submission can have at most one syntax tree.</source>
<target state="translated">提交最多可以有一個語法樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="CannotRemoveCompilerSpecialTree">
<source>Cannot remove compiler special tree</source>
<target state="translated">無法移除編譯器特殊樹狀結構</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTreeNotFoundToRemove">
<source>SyntaxTree '{0}' not found to remove</source>
<target state="translated">找不到要移除的語法樹狀結構 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="TreeMustHaveARootNodeWithCompilationUnit">
<source>Tree must have a root node with SyntaxKind.CompilationUnit</source>
<target state="translated">樹狀結構必須要有具備 SyntaxKind.CompilationUnit 的根節點</target>
<note />
</trans-unit>
<trans-unit id="CompilationVisualBasic">
<source>Compilation (Visual Basic): </source>
<target state="translated">編譯 (Visual Basic): </target>
<note />
</trans-unit>
<trans-unit id="NodeIsNotWithinSyntaxTree">
<source>Node is not within syntax tree</source>
<target state="translated">Node 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="CantReferenceCompilationFromTypes">
<source>Can't reference compilation of type '{0}' from {1} compilation.</source>
<target state="translated">無法從 {1} 編譯來參考類型為 '{0}' 的編譯</target>
<note />
</trans-unit>
<trans-unit id="PositionOfTypeParameterTooLarge">
<source>position of type parameter too large</source>
<target state="translated">類型參數的位置太大</target>
<note />
</trans-unit>
<trans-unit id="AssociatedTypeDoesNotHaveTypeParameters">
<source>Associated type does not have type parameters</source>
<target state="translated">相關聯的類型沒有類型參數</target>
<note />
</trans-unit>
<trans-unit id="IDS_FunctionReturnType">
<source>function return type</source>
<target state="translated">函式傳回類型</target>
<note />
</trans-unit>
<trans-unit id="TypeArgumentCannotBeNothing">
<source>Type argument cannot be Nothing</source>
<target state="translated">類型引數不可為 Nothing</target>
<note />
</trans-unit>
<trans-unit id="WRN_AnalyzerReferencesFramework">
<source>The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported.</source>
<target state="translated">包含類型 '{1}' 的組件 '{0}' 參考了 .NET Framework,此情形不受支援。</target>
<note>{1} is the type that was loaded, {0} is the containing assembly.</note>
</trans-unit>
<trans-unit id="WRN_AnalyzerReferencesFramework_Title">
<source>The loaded assembly references .NET Framework, which is not supported.</source>
<target state="translated">載入的組件參考了 .NET Framework,此情形不受支援。</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName">
<source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName_Title">
<source>The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect. It is applied with an invalid parameter name.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential">
<source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</target>
<note />
</trans-unit>
<trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential_Title">
<source>The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.</source>
<target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-referential.</target>
<note />
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringGeneration">
<source>Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source>
<target state="translated">產生器 '{0}' 無法產生來源。其不會提供給輸出,並可能導致編譯錯誤。例外狀況的類型為 '{1}',訊息為 '{2}'</target>
<note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringGeneration_Description">
<source>Generator threw the following exception:
'{0}'.</source>
<target state="translated">產生器擲回了下列例外狀況:
'{0}'。</target>
<note>{0} is the string representation of the exception that was thrown.</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringGeneration_Title">
<source>Generator failed to generate source.</source>
<target state="translated">產生器無法產生來源。</target>
<note />
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringInitialization">
<source>Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source>
<target state="translated">產生器 '{0}' 無法初始化。其不會提供給輸出,並可能導致編譯錯誤。例外狀況的類型為 '{1}',訊息為 '{2}'</target>
<note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringInitialization_Description">
<source>Generator threw the following exception:
'{0}'.</source>
<target state="translated">產生器擲回了下列例外狀況:
'{0}'。</target>
<note>{0} is the string representation of the exception that was thrown.</note>
</trans-unit>
<trans-unit id="WRN_GeneratorFailedDuringInitialization_Title">
<source>Generator failed to initialize.</source>
<target state="translated">產生器無法初始化。</target>
<note />
</trans-unit>
<trans-unit id="WrongNumberOfTypeArguments">
<source>Wrong number of type arguments</source>
<target state="translated">類型引數的數目錯誤</target>
<note />
</trans-unit>
<trans-unit id="ERR_FileNotFound">
<source>file '{0}' could not be found</source>
<target state="translated">找不到檔案 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoResponseFile">
<source>unable to open response file '{0}'</source>
<target state="translated">無法開啟回應檔 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentRequired">
<source>option '{0}' requires '{1}'</source>
<target state="translated">選項 '{0}' 需要 '{1}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_SwitchNeedsBool">
<source>option '{0}' can be followed only by '+' or '-'</source>
<target state="translated">選項 '{0}' 之後只可接著 '+' 或 '-'</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSwitchValue">
<source>the value '{1}' is invalid for option '{0}'</source>
<target state="translated">值 '{1}' 對選項 '{0}' 無效</target>
<note />
</trans-unit>
<trans-unit id="ERR_MutuallyExclusiveOptions">
<source>Compilation options '{0}' and '{1}' can't both be specified at the same time.</source>
<target state="translated">不得同時指定編輯選項 '{0}' 與 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadUILang">
<source>The language name '{0}' is invalid.</source>
<target state="translated">語言名稱 '{0}' 無效。</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadUILang_Title">
<source>The language name for /preferreduilang is invalid</source>
<target state="translated">/preferreduilang 的語言名稱無效</target>
<note />
</trans-unit>
<trans-unit id="ERR_VBCoreNetModuleConflict">
<source>The options /vbruntime* and /target:module cannot be combined.</source>
<target state="translated">無法結合選項 /vbruntime* 和 /target:module。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidFormatForGuidForOption">
<source>Command-line syntax error: Invalid Guid format '{0}' for option '{1}'</source>
<target state="translated">命令列語法錯誤: 選項 '{1}' 的 Guid 格式 '{0}' 無效</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingGuidForOption">
<source>Command-line syntax error: Missing Guid for option '{1}'</source>
<target state="translated">命令列語法錯誤: 遺漏選項 '{1}' 的 Guid</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadChecksumAlgorithm">
<source>Algorithm '{0}' is not supported</source>
<target state="translated">不支援演算法 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadSwitch">
<source>unrecognized option '{0}'; ignored</source>
<target state="translated">無法辨認的選項 '{0}'; 已經忽略</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadSwitch_Title">
<source>Unrecognized command-line option</source>
<target state="translated">無法辨認的命令列選項</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSources">
<source>no input sources specified</source>
<target state="translated">未指定輸入來源</target>
<note />
</trans-unit>
<trans-unit id="WRN_FileAlreadyIncluded">
<source>source file '{0}' specified multiple times</source>
<target state="translated">已經多次指定原始程式檔 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="WRN_FileAlreadyIncluded_Title">
<source>Source file specified multiple times</source>
<target state="translated">已指定多次原始程式檔</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOpenFileWrite">
<source>can't open '{0}' for writing: {1}</source>
<target state="translated">無法開啟 '{0}' 進行寫入: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadCodepage">
<source>code page '{0}' is invalid or not installed</source>
<target state="translated">字碼頁 '{0}' 無效或尚未安裝</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryFile">
<source>the file '{0}' is not a text file</source>
<target state="translated">檔案 '{0}' 不是文字檔</target>
<note />
</trans-unit>
<trans-unit id="ERR_LibNotFound">
<source>could not find library '{0}'</source>
<target state="translated">找不到程式庫 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetadataReferencesNotSupported">
<source>Metadata references not supported.</source>
<target state="translated">不支援中繼資料參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IconFileAndWin32ResFile">
<source>cannot specify both /win32icon and /win32resource</source>
<target state="translated">無法同時指定 /win32icon 和 /win32resource</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoConfigInResponseFile">
<source>ignoring /noconfig option because it was specified in a response file</source>
<target state="translated">忽略 /noconfig 選項,因為在回應檔中已指定</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoConfigInResponseFile_Title">
<source>Ignoring /noconfig option because it was specified in a response file</source>
<target state="translated">因為在回應檔中已指定 /noconfig 選項,所以將會忽略該選項</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidWarningId">
<source>warning number '{0}' for the option '{1}' is either not configurable or not valid</source>
<target state="translated">選項 '{1}' 的警告編號 '{0}' 無法設定或其無效</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidWarningId_Title">
<source>Warning number is either not configurable or not valid</source>
<target state="translated">警告編號可能無法設定或是無效</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSourcesOut">
<source>cannot infer an output file name from resource only input files; provide the '/out' option</source>
<target state="translated">無法從只有輸入檔的資源推斷輸出檔名,請提供 '/out' 選項</target>
<note />
</trans-unit>
<trans-unit id="ERR_NeedModule">
<source>the /moduleassemblyname option may only be specified when building a target of type 'module'</source>
<target state="translated">/moduleassemblyname 選項只能在建置 'module' 類型的目標時指定</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyName">
<source>'{0}' is not a valid value for /moduleassemblyname</source>
<target state="translated">'{0}' 不是 /moduleassemblyname 的有效值</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictingManifestSwitches">
<source>Error embedding Win32 manifest: Option /win32manifest conflicts with /nowin32manifest.</source>
<target state="translated">內嵌 Win32 資訊清單時發生錯誤: 選項 /win32manifest 與 /nowin32manifest 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IgnoreModuleManifest">
<source>Option /win32manifest ignored. It can be specified only when the target is an assembly.</source>
<target state="translated">已忽略選項 /win32manifest。只能在目標為組件時指定此選項。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IgnoreModuleManifest_Title">
<source>Option /win32manifest ignored</source>
<target state="translated">已忽略 /win32manifest 選項</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidInNamespace">
<source>Statement is not valid in a namespace.</source>
<target state="translated">命名空間中的陳述式無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UndefinedType1">
<source>Type '{0}' is not defined.</source>
<target state="translated">類型 '{0}' 未定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingNext">
<source>'Next' expected.</source>
<target state="translated">'必須是 'Next'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalCharConstant">
<source>Character constant must contain exactly one character.</source>
<target state="translated">字元常數必須剛好包含一個字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedAssemblyEvent3">
<source>Reference required to assembly '{0}' containing the definition for event '{1}'. Add one to your project.</source>
<target state="translated">組件 '{0}' (包含事件 '{1}' 的定義) 需要參考。請在您的專案中加入一個參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedModuleEvent3">
<source>Reference required to module '{0}' containing the definition for event '{1}'. Add one to your project.</source>
<target state="translated">模組 '{0}' (包含事件 '{1}' 的定義) 需要參考。請在您的專案中加入一個參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbExpectedEndIf">
<source>'#If' block must end with a matching '#End If'.</source>
<target state="translated">'#If' 區塊之後必須搭配相對應的 '#End If'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbNoMatchingIf">
<source>'#ElseIf', '#Else', or '#End If' must be preceded by a matching '#If'.</source>
<target state="translated">'#ElseIf'、'#Else' 或 '#End If' 之前必須搭配相對應的 '#If'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbBadElseif">
<source>'#ElseIf' must be preceded by a matching '#If' or '#ElseIf'.</source>
<target state="translated">'#ElseIf' 之前必須搭配相對應的 '#If' 或 '#ElseIf'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromRestrictedType1">
<source>Inheriting from '{0}' is not valid.</source>
<target state="translated">從 '{0}' 繼承無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvOutsideProc">
<source>Labels are not valid outside methods.</source>
<target state="translated">方法外的標籤無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateCantImplement">
<source>Delegates cannot implement interface methods.</source>
<target state="translated">委派 (Delegate) 無法實作介面方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateCantHandleEvents">
<source>Delegates cannot handle events.</source>
<target state="translated">委派 (Delegate) 無法處理事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsOperatorRequiresReferenceTypes1">
<source>'Is' operator does not accept operands of type '{0}'. Operands must be reference or nullable types.</source>
<target state="translated">'Is' 運算子不接受類型 '{0}' 的運算元。運算元必須是參考或可為 Null 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOfRequiresReferenceType1">
<source>'TypeOf ... Is' requires its left operand to have a reference type, but this operand has the value type '{0}'.</source>
<target state="translated">'TypeOf ... Is' 的左運算元必須是參考類型,但此運算元是實值類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyHasSet">
<source>Properties declared 'ReadOnly' cannot have a 'Set'.</source>
<target state="translated">宣告為 'ReadOnly' 的屬性無法擁有 'Set'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_WriteOnlyHasGet">
<source>Properties declared 'WriteOnly' cannot have a 'Get'.</source>
<target state="translated">宣告為 'WriteOnly' 的屬性無法擁有 'Get'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideProc">
<source>Statement is not valid inside a method.</source>
<target state="translated">方法內的陳述式無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideBlock">
<source>Statement is not valid inside '{0}' block.</source>
<target state="translated">'{0}' 區塊內的陳述式無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnexpectedExpressionStatement">
<source>Expression statement is only allowed at the end of an interactive submission.</source>
<target state="translated">只有在互動提交結束時,才可出現運算式陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndProp">
<source>Property missing 'End Property'.</source>
<target state="translated">屬性遺漏了 'End Property'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndSubExpected">
<source>'End Sub' expected.</source>
<target state="translated">'必須有 'End Sub'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndFunctionExpected">
<source>'End Function' expected.</source>
<target state="translated">'必須有 'End Function'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbElseNoMatchingIf">
<source>'#Else' must be preceded by a matching '#If' or '#ElseIf'.</source>
<target state="translated">'#Else' 之前必須搭配相對應的 '#If' 或 '#ElseIf'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantRaiseBaseEvent">
<source>Derived classes cannot raise base class events.</source>
<target state="translated">衍生的類別無法引發基底類別事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryWithoutCatchOrFinally">
<source>Try must have at least one 'Catch' or a 'Finally'.</source>
<target state="translated">Try 至少必須有一個 'Catch' 或 'Finally'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventsCantBeFunctions">
<source>Events cannot have a return type.</source>
<target state="translated">事件不可以有傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndBrack">
<source>Bracketed identifier is missing closing ']'.</source>
<target state="translated">有括號的識別項遺漏右括號 ']'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_Syntax">
<source>Syntax error.</source>
<target state="translated">語法錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_Overflow">
<source>Overflow.</source>
<target state="translated">溢位。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalChar">
<source>Character is not valid.</source>
<target state="translated">字元無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StdInOptionProvidedButConsoleInputIsNotRedirected">
<source>stdin argument '-' is specified, but input has not been redirected from the standard input stream.</source>
<target state="translated">已指定 stdin 引數 '-',但尚未從標準輸入資料流重新導向輸入。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsObjectOperand1">
<source>Option Strict On prohibits operands of type Object for operator '{0}'.</source>
<target state="translated">Option Strict 為 On 時,禁止為運算子 '{0}' 使用 Object 類型的運算元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopControlMustNotBeProperty">
<source>Loop control variable cannot be a property or a late-bound indexed array.</source>
<target state="translated">迴圈控制變數不可以是屬性或晚期繫結索引陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodBodyNotAtLineStart">
<source>First statement of a method body cannot be on the same line as the method declaration.</source>
<target state="translated">方法主體的第一個陳述式不可以和方法宣告在同一行上。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MaximumNumberOfErrors">
<source>Maximum number of errors has been exceeded.</source>
<target state="translated">已超過錯誤上限數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfKeywordNotInInstanceMethod1">
<source>'{0}' is valid only within an instance method.</source>
<target state="translated">'{0}' 只在執行個體方法中有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfKeywordFromStructure1">
<source>'{0}' is not valid within a structure.</source>
<target state="translated">'{0}' 在結構中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeConstructor1">
<source>Attribute constructor has a parameter of type '{0}', which is not an integral, floating-point or Enum type or one of Object, Char, String, Boolean, System.Type or 1-dimensional array of these types.</source>
<target state="translated">屬性建構函式的參數類型為 '{0}',其非整數、浮點或列舉類型,也不是 Object、Char、String、Boolean、System.Type 或這些類型的一維陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayWithOptArgs">
<source>Method cannot have both a ParamArray and Optional parameters.</source>
<target state="translated">方法不可以同時有 ParamArray 和 Optional 引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedArray1">
<source>'{0}' statement requires an array.</source>
<target state="translated">'{0}' 陳述式需要陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayNotArray">
<source>ParamArray parameter must be an array.</source>
<target state="translated">ParamArray 參數必須為陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayRank">
<source>ParamArray parameter must be a one-dimensional array.</source>
<target state="translated">ParamArray 參數必須是一維陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayRankLimit">
<source>Array exceeds the limit of 32 dimensions.</source>
<target state="translated">陣列超過 32 個維度的限制。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AsNewArray">
<source>Arrays cannot be declared with 'New'.</source>
<target state="translated">不可使用 'New' 宣告陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyArgs1">
<source>Too many arguments to '{0}'.</source>
<target state="translated">'{0}' 的引數太多。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedCase">
<source>Statements and labels are not valid between 'Select Case' and first 'Case'.</source>
<target state="translated">在 'Select Case' 與第一個 'Case' 間,不可以使用陳述式和標籤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredConstExpr">
<source>Constant expression is required.</source>
<target state="translated">必須是常數運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredConstConversion2">
<source>Conversion from '{0}' to '{1}' cannot occur in a constant expression.</source>
<target state="translated">常數運算式中不可進行從 '{0}' 到 '{1}' 的轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMe">
<source>'Me' cannot be the target of an assignment.</source>
<target state="translated">'Me' 不可以是指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyAssignment">
<source>'ReadOnly' variable cannot be the target of an assignment.</source>
<target state="translated">'ReadOnly' 變數不可以是指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitSubOfFunc">
<source>'Exit Sub' is not valid in a Function or Property.</source>
<target state="translated">'Function 或 Property 中的 'Exit Sub' 無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitPropNot">
<source>'Exit Property' is not valid in a Function or Sub.</source>
<target state="translated">'Function 或 Sub 中的 'Exit Property' 無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitFuncOfSub">
<source>'Exit Function' is not valid in a Sub or Property.</source>
<target state="translated">'Sub 或 Property 中的 'Exit Function' 無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LValueRequired">
<source>Expression is a value and therefore cannot be the target of an assignment.</source>
<target state="translated">運算式是一個數值,不可以是指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForIndexInUse1">
<source>For loop control variable '{0}' already in use by an enclosing For loop.</source>
<target state="translated">For 迴圈控制變數 '{0}' 已由封閉式 For 迴圈所使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NextForMismatch1">
<source>Next control variable does not match For loop control variable '{0}'.</source>
<target state="translated">Next 控制變數與 For 迴圈控制變數 '{0}' 不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CaseElseNoSelect">
<source>'Case Else' can only appear inside a 'Select Case' statement.</source>
<target state="translated">'Case Else' 只可出現在 'Select Case' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CaseNoSelect">
<source>'Case' can only appear inside a 'Select Case' statement.</source>
<target state="translated">'Case' 只可出現在 'Select Case' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantAssignToConst">
<source>Constant cannot be the target of an assignment.</source>
<target state="translated">常數不可以當做指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedSubscript">
<source>Named arguments are not valid as array subscripts.</source>
<target state="translated">具名引數不可以當做陣列註標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndIf">
<source>'If' must end with a matching 'End If'.</source>
<target state="translated">'If' 之後必須搭配相對應的 'End If'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndWhile">
<source>'While' must end with a matching 'End While'.</source>
<target state="translated">'While' 之後必須搭配相對應的 'End While'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLoop">
<source>'Do' must end with a matching 'Loop'.</source>
<target state="translated">'Do' 之後必須搭配相對應的 'Loop'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedNext">
<source>'For' must end with a matching 'Next'.</source>
<target state="translated">'For' 之後必須搭配相對應的 'Next'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndWith">
<source>'With' must end with a matching 'End With'.</source>
<target state="translated">'With' 之後必須搭配相對應的 'End With'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ElseNoMatchingIf">
<source>'Else' must be preceded by a matching 'If' or 'ElseIf'.</source>
<target state="translated">'Else' 之前必須搭配相對應的 'If' 或 'ElseIf'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndIfNoMatchingIf">
<source>'End If' must be preceded by a matching 'If'.</source>
<target state="translated">'End If' 之前必須搭配相對應的 'If'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndSelectNoSelect">
<source>'End Select' must be preceded by a matching 'Select Case'.</source>
<target state="translated">'End Select' 之前必須搭配相對應的 'Select Case'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitDoNotWithinDo">
<source>'Exit Do' can only appear inside a 'Do' statement.</source>
<target state="translated">'Exit Do' 只可以在 'Do' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndWhileNoWhile">
<source>'End While' must be preceded by a matching 'While'.</source>
<target state="translated">'End While' 之前必須搭配相對應的 'While'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopNoMatchingDo">
<source>'Loop' must be preceded by a matching 'Do'.</source>
<target state="translated">'Loop' 之前必須搭配相對應的 'Do'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NextNoMatchingFor">
<source>'Next' must be preceded by a matching 'For'.</source>
<target state="translated">'Next' 之前必須搭配相對應的 'For'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndWithWithoutWith">
<source>'End With' must be preceded by a matching 'With'.</source>
<target state="translated">'End With' 之前必須搭配相對應的 'With'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultiplyDefined1">
<source>Label '{0}' is already defined in the current method.</source>
<target state="translated">標籤 '{0}' 已定義在目前的方法中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndSelect">
<source>'Select Case' must end with a matching 'End Select'.</source>
<target state="translated">'Select Case' 的結尾必須是相對應的 'End Select'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitForNotWithinFor">
<source>'Exit For' can only appear inside a 'For' statement.</source>
<target state="translated">'Exit For' 只可以在 'For' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitWhileNotWithinWhile">
<source>'Exit While' can only appear inside a 'While' statement.</source>
<target state="translated">'Exit While' 只可以在 'While' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyProperty1">
<source>'ReadOnly' property '{0}' cannot be the target of an assignment.</source>
<target state="translated">'ReadOnly' 屬性 '{0}' 不可為指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitSelectNotWithinSelect">
<source>'Exit Select' can only appear inside a 'Select' statement.</source>
<target state="translated">'Exit Select' 只可以在 'Select' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BranchOutOfFinally">
<source>Branching out of a 'Finally' is not valid.</source>
<target state="translated">Finally' 的分支無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QualNotObjectRecord1">
<source>'!' requires its left operand to have a type parameter, class or interface type, but this operand has the type '{0}'.</source>
<target state="translated">'!' 左側的運算元必須是類型參數、類別或介面類型,但此運算元是 '{0}' 類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooFewIndices">
<source>Number of indices is less than the number of dimensions of the indexed array.</source>
<target state="translated">索引數目少於索引陣列維度的數目。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyIndices">
<source>Number of indices exceeds the number of dimensions of the indexed array.</source>
<target state="translated">索引數目超過索引陣列維度的數目。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EnumNotExpression1">
<source>'{0}' is an Enum type and cannot be used as an expression.</source>
<target state="translated">'{0}' 是列舉類型,無法用做為運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeNotExpression1">
<source>'{0}' is a type and cannot be used as an expression.</source>
<target state="translated">'{0}' 為類型,無法用做為運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassNotExpression1">
<source>'{0}' is a class type and cannot be used as an expression.</source>
<target state="translated">'{0}' 是類別類型,無法用做為運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructureNotExpression1">
<source>'{0}' is a structure type and cannot be used as an expression.</source>
<target state="translated">'{0}' 是結構類型,無法用做為運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceNotExpression1">
<source>'{0}' is an interface type and cannot be used as an expression.</source>
<target state="translated">'{0}' 是介面類型,無法用做為運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamespaceNotExpression1">
<source>'{0}' is a namespace and cannot be used as an expression.</source>
<target state="translated">'{0}' 是命名空間,無法用做為運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadNamespaceName1">
<source>'{0}' is not a valid name and cannot be used as the root namespace name.</source>
<target state="translated">'{0}' 不是有效的名稱,且無法用做為根命名空間名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlPrefixNotExpression">
<source>'{0}' is an XML prefix and cannot be used as an expression. Use the GetXmlNamespace operator to create a namespace object.</source>
<target state="translated">'{0}' 為 XML 前置詞,不可用做為運算式。請使用 GetXmlNamespace 運算子建立命名空間物件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleExtends">
<source>'Inherits' can appear only once within a 'Class' statement and can only specify one class.</source>
<target state="translated">'Inherits' 只可以在 'Class' 陳述式中出現一次,並且只能指定一個類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropMustHaveGetSet">
<source>Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.</source>
<target state="translated">沒有 'ReadOnly' 或 'WriteOnly' 規範的屬性必須提供 'Get' 和 'Set'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_WriteOnlyHasNoWrite">
<source>'WriteOnly' property must provide a 'Set'.</source>
<target state="translated">'WriteOnly' 屬性必須提供 'Set'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyHasNoGet">
<source>'ReadOnly' property must provide a 'Get'.</source>
<target state="translated">'ReadOnly' 屬性必須提供 'Get'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttribute1">
<source>Attribute '{0}' is not valid: Incorrect argument value.</source>
<target state="translated">屬性 '{0}' 無效: 引數值不正確。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LabelNotDefined1">
<source>Label '{0}' is not defined.</source>
<target state="translated">標籤 '{0}' 未定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ErrorCreatingWin32ResourceFile">
<source>Error creating Win32 resources: {0}</source>
<target state="translated">建立 Win32 資源時發生錯誤: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnableToCreateTempFile">
<source>Cannot create temporary file: {0}</source>
<target state="translated">無法建立暫存檔: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNewCall2">
<source>First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' does not have an accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">此 'Sub New' 的第一個陳述式,必須呼叫 'MyBase.New' 或 'MyClass.New',因為 '{1}' 的基底類別 '{0}' 沒有不使用引數即可呼叫的可存取 'Sub New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnimplementedMember3">
<source>{0} '{1}' must implement '{2}' for interface '{3}'.</source>
<target state="translated">{0} '{1}' 必須為介面 '{3}' 實作 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadWithRef">
<source>Leading '.' or '!' can only appear inside a 'With' statement.</source>
<target state="translated">前置的 '.' 或 '!' 只可以在 'With' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAccessCategoryUsed">
<source>Only one of 'Public', 'Private', 'Protected', 'Friend', 'Protected Friend', or 'Private Protected' can be specified.</source>
<target state="translated">只可指定 'Public'、'Private'、'Protected'、'Friend'、'Protected Friend' 或 'Private Protected' 其中之一。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateModifierCategoryUsed">
<source>Only one of 'NotOverridable', 'MustOverride', or 'Overridable' can be specified.</source>
<target state="translated">只可以指定 'NotOverridable'、'MustOverride' 或 'Overridable' 其中之一。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateSpecifier">
<source>Specifier is duplicated.</source>
<target state="translated">重複規範。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeConflict6">
<source>{0} '{1}' and {2} '{3}' conflict in {4} '{5}'.</source>
<target state="translated">{0} '{1}' 和 {2} '{3}' 在 {4} '{5}' 中互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedTypeKeyword">
<source>Keyword does not name a type.</source>
<target state="translated">關鍵字無法為類型命名。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtraSpecifiers">
<source>Specifiers valid only at the beginning of a declaration.</source>
<target state="translated">規範只在宣告的開頭有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedType">
<source>Type expected.</source>
<target state="translated">應有類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidUseOfKeyword">
<source>Keyword is not valid as an identifier.</source>
<target state="translated">以關鍵字做為識別項無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndEnum">
<source>'End Enum' must be preceded by a matching 'Enum'.</source>
<target state="translated">'End Enum' 之前必須搭配相對應的 'Enum'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndEnum">
<source>'Enum' must end with a matching 'End Enum'.</source>
<target state="translated">'Enum' 之後必須搭配相對應的 'End Enum'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDeclaration">
<source>Declaration expected.</source>
<target state="translated">應有宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayMustBeLast">
<source>End of parameter list expected. Cannot define parameters after a paramarray parameter.</source>
<target state="translated">必須是參數清單的結尾。無法在 paramarray 參數之後定義參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SpecifiersInvalidOnInheritsImplOpt">
<source>Specifiers and attributes are not valid on this statement.</source>
<target state="translated">在此陳述式上的規範和屬性無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSpecifier">
<source>Expected one of 'Dim', 'Const', 'Public', 'Private', 'Protected', 'Friend', 'Shadows', 'ReadOnly' or 'Shared'.</source>
<target state="translated">必須是 'Dim'、'Const'、'Public'、'Private'、'Protected'、'Friend'、'Shadows'、'ReadOnly' 或 'Shared' 其中之一。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedComma">
<source>Comma expected.</source>
<target state="translated">必須有逗號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAs">
<source>'As' expected.</source>
<target state="translated">'必須有 'As'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedRparen">
<source>')' expected.</source>
<target state="translated">'必須有 ')'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLparen">
<source>'(' expected.</source>
<target state="translated">'必須有 '('。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidNewInType">
<source>'New' is not valid in this context.</source>
<target state="translated">'New' 在此內容中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedExpression">
<source>Expression expected.</source>
<target state="translated">應有運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedOptional">
<source>'Optional' expected.</source>
<target state="translated">'必須有 'Optional'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIdentifier">
<source>Identifier expected.</source>
<target state="translated">應有識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIntLiteral">
<source>Integer constant expected.</source>
<target state="translated">必須有整數常數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEOS">
<source>End of statement expected.</source>
<target state="translated">必須有陳述式結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedForOptionStmt">
<source>'Option' must be followed by 'Compare', 'Explicit', 'Infer', or 'Strict'.</source>
<target state="translated">'Option' 必須在 'Compare'、'Explicit'、'Infer' 或 'Strict' 之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionCompare">
<source>'Option Compare' must be followed by 'Text' or 'Binary'.</source>
<target state="translated">'Option Compare' 必須在 'Text' 或 'Binary' 之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedOptionCompare">
<source>'Compare' expected.</source>
<target state="translated">'必須有 'Compare'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowImplicitObject">
<source>Option Strict On requires all variable declarations to have an 'As' clause.</source>
<target state="translated">Option Strict 為 On 時,對於所有變數宣告,都要求要有 'As' 子句。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsImplicitProc">
<source>Option Strict On requires all Function, Property, and Operator declarations to have an 'As' clause.</source>
<target state="translated">Option Strict 為 On 時,對所有函式、屬性及運算子宣告,都要求要有 'As' 子句。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsImplicitArgs">
<source>Option Strict On requires that all method parameters have an 'As' clause.</source>
<target state="translated">Option Strict 為 On 時,對所有方法參數,都要求要有 'As' 子句。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidParameterSyntax">
<source>Comma or ')' expected.</source>
<target state="translated">必須是逗號或 ')'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSubFunction">
<source>'Sub' or 'Function' expected.</source>
<target state="translated">'必須有 'Sub' 或 'Function'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedStringLiteral">
<source>String constant expected.</source>
<target state="translated">必須有字串常數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingLibInDeclare">
<source>'Lib' expected.</source>
<target state="translated">'必須有 'Lib'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateNoInvoke1">
<source>Delegate class '{0}' has no Invoke method, so an expression of this type cannot be the target of a method call.</source>
<target state="translated">委派類別 '{0}' 沒有 Invoke 方法,因此這個類型的運算式不可成為方法呼叫的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingIsInTypeOf">
<source>'Is' expected.</source>
<target state="translated">'必須是 'Is'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateOption1">
<source>'Option {0}' statement can only appear once per file.</source>
<target state="translated">'每個檔案只能出現一次 'Option {0}' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantInherit">
<source>'Inherits' not valid in Modules.</source>
<target state="translated">'Inherits' 在模組中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantImplement">
<source>'Implements' not valid in Modules.</source>
<target state="translated">'Implements' 在模組中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadImplementsType">
<source>Implemented type must be an interface.</source>
<target state="translated">實作類型必須是介面。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadConstFlags1">
<source>'{0}' is not valid on a constant declaration.</source>
<target state="translated">'{0}' 在常數宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadWithEventsFlags1">
<source>'{0}' is not valid on a WithEvents declaration.</source>
<target state="translated">'{0}' 在 WithEvents 宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDimFlags1">
<source>'{0}' is not valid on a member variable declaration.</source>
<target state="translated">'{0}' 在成員變數宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateParamName1">
<source>Parameter already declared with name '{0}'.</source>
<target state="translated">參數已使用名稱 '{0}' 進行宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopDoubleCondition">
<source>'Loop' cannot have a condition if matching 'Do' has one.</source>
<target state="translated">'如果對稱的 'Do' 有條件,'Loop' 就不可有條件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedRelational">
<source>Relational operator expected.</source>
<target state="translated">必須有關係運算子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedExitKind">
<source>'Exit' must be followed by 'Sub', 'Function', 'Property', 'Do', 'For', 'While', 'Select', or 'Try'.</source>
<target state="translated">'Exit' 必須在 'Sub'、'Function'、'Property'、'Do'、'For'、'While'、'Select' 或 'Try' 之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedNamedArgumentInAttributeList">
<source>Named argument expected.</source>
<target state="translated">必須是具名引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgumentSpecificationBeforeFixedArgumentInLateboundInvocation">
<source>Named argument specifications must appear after all fixed arguments have been specified in a late bound invocation.</source>
<target state="translated">必須在所有固定引數皆已在晚期繫結引動過程中指定之後,具名引數規格才可出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedNamedArgument">
<source>Named argument expected. Please use language version {0} or greater to use non-trailing named arguments.</source>
<target state="translated">必須是具名引數。請使用語言版本 {0} 或更高版本,以使用非後置的具名引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadMethodFlags1">
<source>'{0}' is not valid on a method declaration.</source>
<target state="translated">'{0}' 在方法宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadEventFlags1">
<source>'{0}' is not valid on an event declaration.</source>
<target state="translated">'{0}' 在事件宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDeclareFlags1">
<source>'{0}' is not valid on a Declare.</source>
<target state="translated">'{0}' 在 Declare 中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadLocalConstFlags1">
<source>'{0}' is not valid on a local constant declaration.</source>
<target state="translated">'{0}' 在區域常數宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadLocalDimFlags1">
<source>'{0}' is not valid on a local variable declaration.</source>
<target state="translated">'{0}' 在區域變數宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedConditionalDirective">
<source>'If', 'ElseIf', 'Else', 'Const', 'Region', 'ExternalSource', 'ExternalChecksum', 'Enable', 'Disable', 'End' or 'R' expected.</source>
<target state="translated">'必須是 'If'、'ElseIf'、'Else'、'Const'、'Region'、'ExternalSource'、'ExternalChecksum'、'Enable'、'Disable'、'End' 或 'R'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEQ">
<source>'=' expected.</source>
<target state="translated">'必須有 '='。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorNotFound1">
<source>Type '{0}' has no constructors.</source>
<target state="translated">類型 '{0}' 沒有建構函式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndInterface">
<source>'End Interface' must be preceded by a matching 'Interface'.</source>
<target state="translated">'End Interface' 之前必須搭配相對應的 'Interface'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndInterface">
<source>'Interface' must end with a matching 'End Interface'.</source>
<target state="translated">'Interface' 之後必須搭配相對應的 'End Interface'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFrom2">
<source>
'{0}' inherits from '{1}'.</source>
<target state="translated">
'{0}' 繼承自 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNestedIn2">
<source>
'{0}' is nested in '{1}'.</source>
<target state="translated">
'{0}' 巢狀於 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceCycle1">
<source>Class '{0}' cannot inherit from itself: {1}</source>
<target state="translated">類別 '{0}' 無法繼承其本身: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromNonClass">
<source>Classes can inherit only from other classes.</source>
<target state="translated">類別只能繼承自其他類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultiplyDefinedType3">
<source>'{0}' is already declared as '{1}' in this {2}.</source>
<target state="translated">'{0}' 在此 {2} 中已宣告為 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadOverrideAccess2">
<source>'{0}' cannot override '{1}' because they have different access levels.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為它們的存取層級不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOverrideNotOverridable2">
<source>'{0}' cannot override '{1}' because it is declared 'NotOverridable'.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其宣告為 'NotOverridable'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateProcDef1">
<source>'{0}' has multiple definitions with identical signatures.</source>
<target state="translated">'{0}' 有多個具相同簽章的定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateProcDefWithDifferentTupleNames2">
<source>'{0}' has multiple definitions with identical signatures with different tuple element names, including '{1}'.</source>
<target state="translated">'{0}' 具有多個定義,且這些定義的簽章相同,但卻有不同的 Tuple 項目名稱,包括 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceMethodFlags1">
<source>'{0}' is not valid on an interface method declaration.</source>
<target state="translated">'{0}' 在介面方法宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamNotFound2">
<source>'{0}' is not a parameter of '{1}'.</source>
<target state="translated">'{0}' 不是 '{1}' 的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfacePropertyFlags1">
<source>'{0}' is not valid on an interface property declaration.</source>
<target state="translated">'{0}' 在介面屬性宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgUsedTwice2">
<source>Parameter '{0}' of '{1}' already has a matching argument.</source>
<target state="translated">'{1}' 的參數 '{0}' 已有相符的引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceCantUseEventSpecifier1">
<source>'{0}' is not valid on an interface event declaration.</source>
<target state="translated">'{0}' 在介面事件宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypecharNoMatch2">
<source>Type character '{0}' does not match declared data type '{1}'.</source>
<target state="translated">類型字元 '{0}' 不符合宣告的資料類型 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSubOrFunction">
<source>'Sub' or 'Function' expected after 'Delegate'.</source>
<target state="translated">'Delegate' 之後必須有 'Sub' 或 'Function'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadEmptyEnum1">
<source>Enum '{0}' must contain at least one member.</source>
<target state="translated">列舉 '{0}' 至少必須包含一個成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidConstructorCall">
<source>Constructor call is valid only as the first statement in an instance constructor.</source>
<target state="translated">只在當做執行個體建構函式中第一個陳述式時,建構函式呼叫才有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOverrideConstructor">
<source>'Sub New' cannot be declared 'Overrides'.</source>
<target state="translated">'無法將 'Sub New' 宣告為 'Overrides'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorCannotBeDeclaredPartial">
<source>'Sub New' cannot be declared 'Partial'.</source>
<target state="translated">'Sub New' 不可宣告為 'Partial'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleEmitFailure">
<source>Failed to emit module '{0}': {1}</source>
<target state="translated">無法發出模組 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncUpdateFailedMissingAttribute">
<source>Cannot update '{0}'; attribute '{1}' is missing.</source>
<target state="translated">無法更新 '{0}'; 缺少屬性 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideNotNeeded3">
<source>{0} '{1}' cannot be declared 'Overrides' because it does not override a {0} in a base class.</source>
<target state="translated">{0} '{1}' 不可宣告為 'Overrides',因為其在基底類別中不會覆寫 {0}。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDot">
<source>'.' expected.</source>
<target state="translated">'必須有 '.'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateLocals1">
<source>Local variable '{0}' is already declared in the current block.</source>
<target state="translated">目前區塊中已宣告過區域變數 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsProc">
<source>Statement cannot appear within a method body. End of method assumed.</source>
<target state="translated">陳述式不可以在方法主體中出現。已假設是方法結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalSameAsFunc">
<source>Local variable cannot have the same name as the function containing it.</source>
<target state="translated">區域變數不可以和包含它的函式具有相同名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RecordEmbeds2">
<source>
'{0}' contains '{1}' (variable '{2}').</source>
<target state="translated">
'{0}' 包含 '{1}' (變數 '{2}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RecordCycle2">
<source>Structure '{0}' cannot contain an instance of itself: {1}</source>
<target state="translated">結構 '{0}' 不可包含本身的執行個體: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceCycle1">
<source>Interface '{0}' cannot inherit from itself: {1}</source>
<target state="translated">介面 '{0}' 無法繼承其本身: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubNewCycle2">
<source>
'{0}' calls '{1}'.</source>
<target state="translated">
'{0}' 呼叫 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubNewCycle1">
<source>Constructor '{0}' cannot call itself: {1}</source>
<target state="translated">建構函式 '{0}' 不可呼叫其本身: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromCantInherit3">
<source>'{0}' cannot inherit from {2} '{1}' because '{1}' is declared 'NotInheritable'.</source>
<target state="translated">'{0}' 無法從 {2} '{1}' 繼承,因為 '{1}' 已宣告為 'NotInheritable'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithOptional2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by optional parameters.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為它們的差異只在於選擇性參數不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithReturnType2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by return types.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為它們的差異只在於傳回類型不同而已。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharWithType1">
<source>Type character '{0}' cannot be used in a declaration with an explicit type.</source>
<target state="translated">類型字元 '{0}' 不可用在明確類型的宣告中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharOnSub">
<source>Type character cannot be used in a 'Sub' declaration because a 'Sub' doesn't return a value.</source>
<target state="translated">由於 'Sub' 不會傳回值,類型字元不可以在 'Sub' 宣告中使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithDefault2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by the default values of optional parameters.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為它們的差異只在於選擇性參數的預設值不同而已。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingSubscript">
<source>Array subscript expression missing.</source>
<target state="translated">遺漏陣列註標運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithDefault2">
<source>'{0}' cannot override '{1}' because they differ by the default values of optional parameters.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其選擇性參數的預設值不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithOptional2">
<source>'{0}' cannot override '{1}' because they differ by optional parameters.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其選擇性參數不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FieldOfValueFieldOfMarshalByRef3">
<source>Cannot refer to '{0}' because it is a member of the value-typed field '{1}' of class '{2}' which has 'System.MarshalByRefObject' as a base class.</source>
<target state="translated">無法參考 '{0}',因為其為類別 '{2}' 之實值類型欄位 '{1}' 的成員,其基底類別為 'System.MarshalByRefObject'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeMismatch2">
<source>Value of type '{0}' cannot be converted to '{1}'.</source>
<target state="translated">類型 '{0}' 的值無法轉換成 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CaseAfterCaseElse">
<source>'Case' cannot follow a 'Case Else' in the same 'Select' statement.</source>
<target state="translated">'在相同的 'Select' 陳述式中,'Case' 不可接在 'Case Else' 之後。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvertArrayMismatch4">
<source>Value of type '{0}' cannot be converted to '{1}' because '{2}' is not derived from '{3}'.</source>
<target state="translated">類型 '{0}' 的值無法轉換成 '{1}',因為 '{2}' 並非衍生自 '{3}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvertObjectArrayMismatch3">
<source>Value of type '{0}' cannot be converted to '{1}' because '{2}' is not a reference type.</source>
<target state="translated">類型 '{0}' 的值無法轉換成 '{1}',因為 '{2}' 不是參考類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForLoopType1">
<source>'For' loop control variable cannot be of type '{0}' because the type does not support the required operators.</source>
<target state="translated">'For' 迴圈控制變數不可為類型 '{0}',因為此類型不支援所需的運算子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithByref2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為它們的差異只在於宣告為 'ByRef' 或 'ByVal' 的參數不同而已。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsFromNonInterface">
<source>Interface can inherit only from another interface.</source>
<target state="translated">介面只可以繼承自另一個介面。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceOrderOnInherits">
<source>'Inherits' statements must precede all declarations in an interface.</source>
<target state="translated">'Inherits' 陳述式必須位於介面中的所有宣告之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateDefaultProps1">
<source>'Default' can be applied to only one property name in a {0}.</source>
<target state="translated">'Default' 只可以套用至 {0} 中的一個屬性名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultMissingFromProperty2">
<source>'{0}' and '{1}' cannot overload each other because only one is declared 'Default'.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為只有一個宣告為 'Default'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverridingPropertyKind2">
<source>'{0}' cannot override '{1}' because they differ by 'ReadOnly' or 'WriteOnly'.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其出現 'ReadOnly' 或 'WriteOnly' 的差異。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewInInterface">
<source>'Sub New' cannot be declared in an interface.</source>
<target state="translated">'無法在介面中宣告 'Sub New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnNew1">
<source>'Sub New' cannot be declared '{0}'.</source>
<target state="translated">'Sub New' 不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadingPropertyKind2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by 'ReadOnly' or 'WriteOnly'.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為它們的差異只在於 'ReadOnly' 或 'WriteOnly' 不同而已。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoDefaultNotExtend1">
<source>Class '{0}' cannot be indexed because it has no default property.</source>
<target state="translated">無法對類別 '{0}' 編製索引,因為其無預設屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadWithArrayVsParamArray2">
<source>'{0}' and '{1}' cannot overload each other because they differ only by parameters declared 'ParamArray'.</source>
<target state="translated">'{0}' 和 '{1}' 無法互相多載,因為它們的差異只在於宣告為 'ParamArray' 的參數不同而已。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInstanceMemberAccess">
<source>Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.</source>
<target state="translated">沒有類別的明確執行個體,因此無法從共用方法或共用成員初始設定式中參考至類別的執行個體成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedRbrace">
<source>'}' expected.</source>
<target state="translated">'必須有 '}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleAsType1">
<source>Module '{0}' cannot be used as a type.</source>
<target state="translated">模組 '{0}' 不能用做為類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewIfNullOnNonClass">
<source>'New' cannot be used on an interface.</source>
<target state="translated">'New' 無法在介面上使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchAfterFinally">
<source>'Catch' cannot appear after 'Finally' within a 'Try' statement.</source>
<target state="translated">'在 'Try' 陳述式中,'Catch' 不可以出現在 'Finally' 之後。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchNoMatchingTry">
<source>'Catch' cannot appear outside a 'Try' statement.</source>
<target state="translated">'Catch' 不可以出現在 'Try' 陳述式之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FinallyAfterFinally">
<source>'Finally' can only appear once in a 'Try' statement.</source>
<target state="translated">'Finally' 只能在 'Try' 陳述式中出現一次。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FinallyNoMatchingTry">
<source>'Finally' cannot appear outside a 'Try' statement.</source>
<target state="translated">'Finally' 不可以出現在 'Try' 陳述式之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndTryNoTry">
<source>'End Try' must be preceded by a matching 'Try'.</source>
<target state="translated">'End Try' 之前必須搭配相對應的 'Try'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndTry">
<source>'Try' must end with a matching 'End Try'.</source>
<target state="translated">'Try' 之後必須搭配相對應的 'End Try'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDelegateFlags1">
<source>'{0}' is not valid on a Delegate declaration.</source>
<target state="translated">'{0}' 在 Delegate 宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoConstructorOnBase2">
<source>Class '{0}' must declare a 'Sub New' because its base class '{1}' does not have an accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">類別 '{0}' 必須宣告 'Sub New',因為其基底類別 '{1}' 沒有不用引數即可呼叫之可存取的 'Sub New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InaccessibleSymbol2">
<source>'{0}' is not accessible in this context because it is '{1}'.</source>
<target state="translated">'無法在此內容中存取 '{0}',因為它是 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InaccessibleMember3">
<source>'{0}.{1}' is not accessible in this context because it is '{2}'.</source>
<target state="translated">'無法在此內容中存取 '{0}.{1}',因為其為 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchNotException1">
<source>'Catch' cannot catch type '{0}' because it is not 'System.Exception' or a class that inherits from 'System.Exception'.</source>
<target state="translated">'Catch' 無法攔截類型 '{0}',因為其非 'System.Exception' 或繼承自 'System.Exception' 的類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitTryNotWithinTry">
<source>'Exit Try' can only appear inside a 'Try' statement.</source>
<target state="translated">'Exit Try' 只能在 'Try' 陳述式內出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadRecordFlags1">
<source>'{0}' is not valid on a Structure declaration.</source>
<target state="translated">'{0}' 在 Structure 宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadEnumFlags1">
<source>'{0}' is not valid on an Enum declaration.</source>
<target state="translated">'{0}' 在列舉宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceFlags1">
<source>'{0}' is not valid on an Interface declaration.</source>
<target state="translated">'{0}' 在 Interface 宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithByref2">
<source>'{0}' cannot override '{1}' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為它們的差異只在於參數標記為 'ByRef' 或 'ByVal' 而已。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyBaseAbstractCall1">
<source>'MyBase' cannot be used with method '{0}' because it is declared 'MustOverride'.</source>
<target state="translated">'無法以方法 '{0}' 使用 'MyBase',因為其已宣告為 'MustOverride'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IdentNotMemberOfInterface4">
<source>'{0}' cannot implement '{1}' because there is no matching {2} on interface '{3}'.</source>
<target state="translated">'{0}' 無法實作 '{1}',因為在介面 '{3}' 上沒有相符的 {2}。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementingInterfaceWithDifferentTupleNames5">
<source>'{0}' cannot implement {1} '{2}' on interface '{3}' because the tuple element names in '{4}' do not match those in '{5}'.</source>
<target state="translated">'因為 '{4}' 中的 Tuple 項目名稱與 '{5}' 中的 Tuple 項目名稱不相符,導致 '{0}' 無法在介面 '{3}' 上實作 {1} '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_WithEventsRequiresClass">
<source>'WithEvents' variables must have an 'As' clause.</source>
<target state="translated">'WithEvents' 變數必須要有 'As' 子句。</target>
<note />
</trans-unit>
<trans-unit id="ERR_WithEventsAsStruct">
<source>'WithEvents' variables can only be typed as classes, interfaces or type parameters with class constraints.</source>
<target state="translated">'WithEvents' 變數類型只能設定為具有類別條件約束的類別、介面或類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvertArrayRankMismatch2">
<source>Value of type '{0}' cannot be converted to '{1}' because the array types have different numbers of dimensions.</source>
<target state="translated">類型 '{0}' 的值無法轉換成 '{1}',因為陣列類型的維度數目不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RedimRankMismatch">
<source>'ReDim' cannot change the number of dimensions of an array.</source>
<target state="translated">'ReDim' 無法變更陣列的維度數目。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StartupCodeNotFound1">
<source>'Sub Main' was not found in '{0}'.</source>
<target state="translated">'在 '{0}' 中找不到 'Sub Main'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstAsNonConstant">
<source>Constants must be of an intrinsic or enumerated type, not a class, structure, type parameter, or array type.</source>
<target state="translated">常數必須是內建或列舉類型,而不是類別、結構、類型參數或陣列類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndSub">
<source>'End Sub' must be preceded by a matching 'Sub'.</source>
<target state="translated">'End Sub' 之前必須搭配相對應的 'Sub'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndFunction">
<source>'End Function' must be preceded by a matching 'Function'.</source>
<target state="translated">'End Function' 之前必須搭配相對應的 'Function'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndProperty">
<source>'End Property' must be preceded by a matching 'Property'.</source>
<target state="translated">'End Property' 之前必須搭配相對應的 'Property'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseMethodSpecifier1">
<source>Methods in a Module cannot be declared '{0}'.</source>
<target state="translated">Module 中的方法不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseEventSpecifier1">
<source>Events in a Module cannot be declared '{0}'.</source>
<target state="translated">Module 中的事件不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructCantUseVarSpecifier1">
<source>Members in a Structure cannot be declared '{0}'.</source>
<target state="translated">結構中的成員不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOverrideDueToReturn2">
<source>'{0}' cannot override '{1}' because they differ by their return types.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為它們的傳回類型不同。</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidOverrideDueToTupleNames2">
<source>'{0}' cannot override '{1}' because they differ by their tuple element names.</source>
<target state="translated">'因為 '{0}' 的 Tuple 項目名稱各不相同,所以無法覆寫 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidOverrideDueToTupleNames2_Title">
<source>Member cannot override because it differs by its tuple element names.</source>
<target state="translated">因為成員的 Tuple 項目名稱各不相同,所以無法覆寫。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstantWithNoValue">
<source>Constants must have a value.</source>
<target state="translated">必須有常數值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpressionOverflow1">
<source>Constant expression not representable in type '{0}'.</source>
<target state="translated">在類型 '{0}' 中無法呈現常數運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicatePropertyGet">
<source>'Get' is already declared.</source>
<target state="translated">'Get' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicatePropertySet">
<source>'Set' is already declared.</source>
<target state="translated">'Set' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotDeclared1">
<source>'{0}' is not declared. It may be inaccessible due to its protection level.</source>
<target state="translated">'{0}' 未宣告。由於其保護層級,可能無法對其進行存取。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryOperands3">
<source>Operator '{0}' is not defined for types '{1}' and '{2}'.</source>
<target state="translated">未對類型 '{1}' 和 '{2}' 定義運算子 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedProcedure">
<source>Expression is not a method.</source>
<target state="translated">運算式不是方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedArgument2">
<source>Argument not specified for parameter '{0}' of '{1}'.</source>
<target state="translated">未對 '{1}' 的參數 '{0}' 指定引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotMember2">
<source>'{0}' is not a member of '{1}'.</source>
<target state="translated">'{0}' 不是 '{1}' 的成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndClassNoClass">
<source>'End Class' must be preceded by a matching 'Class'.</source>
<target state="translated">'End Class' 之前必須搭配相對應的 'Class'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadClassFlags1">
<source>Classes cannot be declared '{0}'.</source>
<target state="translated">類別不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImportsMustBeFirst">
<source>'Imports' statements must precede any declarations.</source>
<target state="translated">'Imports' 陳述式必須在任何宣告之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NonNamespaceOrClassOnImport2">
<source>'{1}' for the Imports '{0}' does not refer to a Namespace, Class, Structure, Enum or Module.</source>
<target state="translated">'Imports '{0}' 的 '{1}' 並未參考 Namespace、Class、Structure、Enum 或 Module。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypecharNotallowed">
<source>Type declaration characters are not valid in this context.</source>
<target state="translated">類型宣告字元在此內容中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObjectReferenceNotSupplied">
<source>Reference to a non-shared member requires an object reference.</source>
<target state="translated">參考非共用成員需要物件參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyClassNotInClass">
<source>'MyClass' cannot be used outside of a class.</source>
<target state="translated">'MyClass' 無法在類別外使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IndexedNotArrayOrProc">
<source>Expression is not an array or a method, and cannot have an argument list.</source>
<target state="translated">運算式不是陣列或方法,所以不可以有引數清單。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventSourceIsArray">
<source>'WithEvents' variables cannot be typed as arrays.</source>
<target state="translated">'WithEvents' 變數的類型不可以是陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedConstructorWithParams">
<source>Shared 'Sub New' cannot have any parameters.</source>
<target state="translated">共用的 'Sub New' 不可以有任何參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedConstructorIllegalSpec1">
<source>Shared 'Sub New' cannot be declared '{0}'.</source>
<target state="translated">共用的 'Sub New' 不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndClass">
<source>'Class' statement must end with a matching 'End Class'.</source>
<target state="translated">'Class' 陳述式之後必須搭配相對應的 'End Class'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnaryOperand2">
<source>Operator '{0}' is not defined for type '{1}'.</source>
<target state="translated">未對類型 '{1}' 定義運算子 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsWithDefault1">
<source>'Default' cannot be combined with '{0}'.</source>
<target state="translated">'Default' 無法和 '{0}' 相結合。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VoidValue">
<source>Expression does not produce a value.</source>
<target state="translated">運算式沒有產生值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorFunction">
<source>Constructor must be declared as a Sub, not as a Function.</source>
<target state="translated">建構函式必須宣告為 Sub,而不是 Function。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidLiteralExponent">
<source>Exponent is not valid.</source>
<target state="translated">指數無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewCannotHandleEvents">
<source>'Sub New' cannot handle events.</source>
<target state="translated">'Sub New' 無法處理事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CircularEvaluation1">
<source>Constant '{0}' cannot depend on its own value.</source>
<target state="translated">常數 '{0}' 無法相依其本身的值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnSharedMeth1">
<source>'Shared' cannot be combined with '{0}' on a method declaration.</source>
<target state="translated">'Shared' 無法在方法宣告上和 '{0}' 相結合。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnSharedProperty1">
<source>'Shared' cannot be combined with '{0}' on a property declaration.</source>
<target state="translated">'Shared' 無法在屬性宣告上與 '{0}' 相結合。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnStdModuleProperty1">
<source>Properties in a Module cannot be declared '{0}'.</source>
<target state="translated">模組中的屬性不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedOnProcThatImpl">
<source>Methods or events that implement interface members cannot be declared 'Shared'.</source>
<target state="translated">實作介面成員的方法或事件不可以宣告為 'Shared'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoWithEventsVarOnHandlesList">
<source>Handles clause requires a WithEvents variable defined in the containing type or one of its base types.</source>
<target state="translated">Handles 子句需要 WithEvents 變數,該變數定義於包含類型或它的一種基底類型中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceAccessMismatch5">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} to {3} '{4}'.</source>
<target state="translated">'{0}' 無法繼承自 {1} '{2}',因為它會將基底 {1} 的存取展開至 {3} '{4}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NarrowingConversionDisallowed2">
<source>Option Strict On disallows implicit conversions from '{0}' to '{1}'.</source>
<target state="translated">Option Strict 為 On 時,不可進行 '{0}' 至 '{1}' 的隱含轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoArgumentCountOverloadCandidates1">
<source>Overload resolution failed because no accessible '{0}' accepts this number of arguments.</source>
<target state="translated">因為沒有可存取的 '{0}' 接受此引數數目,所以多載解析失敗。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoViableOverloadCandidates1">
<source>Overload resolution failed because no '{0}' is accessible.</source>
<target state="translated">因為沒有任何可存取的 '{0}',所以多載解析失敗。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoCallableOverloadCandidates2">
<source>Overload resolution failed because no accessible '{0}' can be called with these arguments:{1}</source>
<target state="translated">因為沒有可利用這些引數呼叫之可存取的 '{0}',所以多載解析失敗: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadOverloadCandidates2">
<source>Overload resolution failed because no accessible '{0}' can be called:{1}</source>
<target state="translated">多載解析失敗,因為無法呼叫可存取的 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonNarrowingOverloadCandidates2">
<source>Overload resolution failed because no accessible '{0}' can be called without a narrowing conversion:{1}</source>
<target state="translated">因為沒有不需要縮減轉換即可呼叫之可存取的 '{0}',所以多載解析失敗: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentNarrowing3">
<source>Argument matching parameter '{0}' narrows from '{1}' to '{2}'.</source>
<target state="translated">與參數 '{0}' 對應的引數,從 '{1}' 縮減 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoMostSpecificOverload2">
<source>Overload resolution failed because no accessible '{0}' is most specific for these arguments:{1}</source>
<target state="translated">因為沒有可存取的 '{0}' 對這些引數而言是最適合的,所以多載解析失敗: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_NotMostSpecificOverload">
<source>Not most specific.</source>
<target state="translated">並非最適合。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadCandidate2">
<source>
'{0}': {1}</source>
<target state="translated">
'{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoGetProperty1">
<source>Property '{0}' is 'WriteOnly'.</source>
<target state="translated">屬性 '{0}' 是 'WriteOnly'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSetProperty1">
<source>Property '{0}' is 'ReadOnly'.</source>
<target state="translated">屬性 '{0}' 是 'ReadOnly'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamTypingInconsistency">
<source>All parameters must be explicitly typed if any of them are explicitly typed.</source>
<target state="translated">如果明確輸入任何一個參數,則必須明確輸入所有參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamNameFunctionNameCollision">
<source>Parameter cannot have the same name as its defining function.</source>
<target state="translated">函式名稱不可同時做為參數名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DateToDoubleConversion">
<source>Conversion from 'Date' to 'Double' requires calling the 'Date.ToOADate' method.</source>
<target state="translated">要將 'Date' 轉換成 'Double' 需要呼叫 'Date.ToOADate' 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DoubleToDateConversion">
<source>Conversion from 'Double' to 'Date' requires calling the 'Date.FromOADate' method.</source>
<target state="translated">要將 'Double' 轉換成 'Date' 需要呼叫 'Date.FromOADate' 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ZeroDivide">
<source>Division by zero occurred while evaluating this expression.</source>
<target state="translated">評估此運算式時發生除數為零的情形。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryAndOnErrorDoNotMix">
<source>Method cannot contain both a 'Try' statement and an 'On Error' or 'Resume' statement.</source>
<target state="translated">方法不可以同時包含 'Try' 陳述式以及 'On Error' 或 'Resume' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyAccessIgnored">
<source>Property access must assign to the property or use its value.</source>
<target state="translated">屬性的存取必須是指定值給屬性或使用屬性值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceNoDefault1">
<source>'{0}' cannot be indexed because it has no default property.</source>
<target state="translated">'無法對 '{0}' 編製索引,因為其無預設屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyAttribute1">
<source>Attribute '{0}' cannot be applied to an assembly.</source>
<target state="translated">無法將屬性 '{0}' 套用至組件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidModuleAttribute1">
<source>Attribute '{0}' cannot be applied to a module.</source>
<target state="translated">無法將屬性 '{0}' 套用至模組。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInUnnamedNamespace1">
<source>'{0}' is ambiguous.</source>
<target state="translated">'{0}' 模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultMemberNotProperty1">
<source>Default member of '{0}' is not a property.</source>
<target state="translated">'{0}' 的預設成員並非屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInNamespace2">
<source>'{0}' is ambiguous in the namespace '{1}'.</source>
<target state="translated">'{0}' 在命名空間 '{1}' 中模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInImports2">
<source>'{0}' is ambiguous, imported from the namespaces or types '{1}'.</source>
<target state="translated">'從命名空間或類型 '{1}' 匯入的 '{0}' 模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInModules2">
<source>'{0}' is ambiguous between declarations in Modules '{1}'.</source>
<target state="translated">'{0}' 在模組 '{1}' 中的宣告之間模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousInNamespaces2">
<source>'{0}' is ambiguous between declarations in namespaces '{1}'.</source>
<target state="translated">'{0}' 在命名空間 '{1}' 中的宣告之間模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitializerTooFewDimensions">
<source>Array initializer has too few dimensions.</source>
<target state="translated">陣列初始設定式的維度太少。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitializerTooManyDimensions">
<source>Array initializer has too many dimensions.</source>
<target state="translated">陣列初始設定式的維度太多。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerTooFewElements1">
<source>Array initializer is missing {0} elements.</source>
<target state="translated">陣列初始設定式遺漏 {0} 個元素。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerTooManyElements1">
<source>Array initializer has {0} too many elements.</source>
<target state="translated">陣列初始設定式有 {0} 太多元素。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewOnAbstractClass">
<source>'New' cannot be used on a class that is declared 'MustInherit'.</source>
<target state="translated">'New' 不可以使用在宣告為 'MustInherit' 的類別上。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateNamedImportAlias1">
<source>Alias '{0}' is already declared.</source>
<target state="translated">別名 '{0}' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicatePrefix">
<source>XML namespace prefix '{0}' is already declared.</source>
<target state="translated">XML 命名空間前置詞 '{0}' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsLateBinding">
<source>Option Strict On disallows late binding.</source>
<target state="translated">Option Strict 為 On 時,不可使用晚期繫結。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfOperandNotMethod">
<source>'AddressOf' operand must be the name of a method (without parentheses).</source>
<target state="translated">'AddressOf' 運算元必須是方法名稱 (沒有括號)。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndExternalSource">
<source>'#End ExternalSource' must be preceded by a matching '#ExternalSource'.</source>
<target state="translated">'#End ExternalSource' 之前必須搭配相對應的 '#ExternalSource'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndExternalSource">
<source>'#ExternalSource' statement must end with a matching '#End ExternalSource'.</source>
<target state="translated">'#ExternalSource' 之後必須搭配相對應的 '#End ExternalSource'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedExternalSource">
<source>'#ExternalSource' directives cannot be nested.</source>
<target state="translated">'#ExternalSource' 指示詞不可以是巢狀。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfNotDelegate1">
<source>'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.</source>
<target state="translated">'因為 '{0}' 不是委派類型,所以 'AddressOf' 運算式無法轉換成 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SyncLockRequiresReferenceType1">
<source>'SyncLock' operand cannot be of type '{0}' because '{0}' is not a reference type.</source>
<target state="translated">'SyncLock' 運算元不可是類型 '{0}',因為 '{0}' 不是參考類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodAlreadyImplemented2">
<source>'{0}.{1}' cannot be implemented more than once.</source>
<target state="translated">'{0}.{1}' 只能實作一次。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateInInherits1">
<source>'{0}' cannot be inherited more than once.</source>
<target state="translated">'{0}' 不能繼承一次以上。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamArrayArgument">
<source>Named argument cannot match a ParamArray parameter.</source>
<target state="translated">具名引數無法符合 ParamArray 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedParamArrayArgument">
<source>Omitted argument cannot match a ParamArray parameter.</source>
<target state="translated">省略的引數無法符合 ParamArray 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayArgumentMismatch">
<source>Argument cannot match a ParamArray parameter.</source>
<target state="translated">引數無法符合 ParamArray 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventNotFound1">
<source>Event '{0}' cannot be found.</source>
<target state="translated">找不到事件 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseVariableSpecifier1">
<source>Variables in Modules cannot be declared '{0}'.</source>
<target state="translated">Module 中的變數不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedEventNeedsSharedHandler">
<source>Events of shared WithEvents variables cannot be handled by non-shared methods.</source>
<target state="translated">共用 WithEvents 變數的事件不能由非共用的方法處理。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedMinus">
<source>'-' expected.</source>
<target state="translated">'必須有 '-'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceMemberSyntax">
<source>Interface members must be methods, properties, events, or type definitions.</source>
<target state="translated">介面成員必須是方法、屬性、事件或類型定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideInterface">
<source>Statement cannot appear within an interface body.</source>
<target state="translated">陳述式不能出現在介面主體內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsInterface">
<source>Statement cannot appear within an interface body. End of interface assumed.</source>
<target state="translated">陳述式不可以在介面主體中出現。已假設是介面結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsInNotInheritableClass1">
<source>'NotInheritable' classes cannot have members declared '{0}'.</source>
<target state="translated">'NotInheritable' 類別不可有宣告為 '{0}' 的成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseOnlyClassesMustBeExplicit2">
<source>Class '{0}' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): {1}.</source>
<target state="translated">類別 '{0}' 必須宣告為 'MustInherit',或是覆寫下列繼承的 'MustOverride' 成員: {1}。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustInheritEventNotOverridden">
<source>'{0}' is a MustOverride event in the base class '{1}'. Visual Basic does not support event overriding. You must either provide an implementation for the event in the base class, or make class '{2}' MustInherit.</source>
<target state="translated">'{0}' 是基底類別 '{1}' 中的 MustOverride 事件。Visual Basic 不支援事件覆寫。您必須提供基底類別中的事件實作,或將類別 '{2}' 設為 MustInherit。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NegativeArraySize">
<source>Array dimensions cannot have a negative size.</source>
<target state="translated">陣列維度大小不可以是負數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyClassAbstractCall1">
<source>'MustOverride' method '{0}' cannot be called with 'MyClass'.</source>
<target state="translated">'無法以 'MyClass' 呼叫 'MustOverride' 方法 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndDisallowedInDllProjects">
<source>'End' statement cannot be used in class library projects.</source>
<target state="translated">'不可以在類別庫專案中使用 'End' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BlockLocalShadowing1">
<source>Variable '{0}' hides a variable in an enclosing block.</source>
<target state="translated">變數 '{0}' 在封閉區塊中隱藏了變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleNotAtNamespace">
<source>'Module' statements can occur only at file or namespace level.</source>
<target state="translated">'Module' 陳述式只可以發生在檔案或命名空間層級。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamespaceNotAtNamespace">
<source>'Namespace' statements can occur only at file or namespace level.</source>
<target state="translated">'Namespace' 陳述式只可以發生在檔案或命名空間層級。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEnum">
<source>Statement cannot appear within an Enum body.</source>
<target state="translated">陳述式不可出現在列舉主體中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsEnum">
<source>Statement cannot appear within an Enum body. End of Enum assumed.</source>
<target state="translated">陳述式不可以在列舉主體中出現。已假設是列舉結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionStrict">
<source>'Option Strict' can be followed only by 'On' or 'Off'.</source>
<target state="translated">'Option Strict' 之後只能是 'On' 或 'Off'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndStructureNoStructure">
<source>'End Structure' must be preceded by a matching 'Structure'.</source>
<target state="translated">'End Structure' 之前必須搭配相對應的 'Structure'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndModuleNoModule">
<source>'End Module' must be preceded by a matching 'Module'.</source>
<target state="translated">'End Module' 之前必須搭配相對應的 'Module'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndNamespaceNoNamespace">
<source>'End Namespace' must be preceded by a matching 'Namespace'.</source>
<target state="translated">'End Namespace' 之前必須搭配相對應的 'Namespace'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndStructure">
<source>'Structure' statement must end with a matching 'End Structure'.</source>
<target state="translated">'Structure' 陳述式之後必須搭配相對應的 'End Structure'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndModule">
<source>'Module' statement must end with a matching 'End Module'.</source>
<target state="translated">'Module' 陳述式之後必須搭配相對應的 'End Module'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndNamespace">
<source>'Namespace' statement must end with a matching 'End Namespace'.</source>
<target state="translated">'Namespace' 陳述式之後必須搭配相對應的 'End Namespace'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionStmtWrongOrder">
<source>'Option' statements must precede any declarations or 'Imports' statements.</source>
<target state="translated">'Option' 陳述式必須在所有的宣告或 'Imports' 陳述式之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructCantInherit">
<source>Structures cannot have 'Inherits' statements.</source>
<target state="translated">結構不可出現 'Inherits' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewInStruct">
<source>Structures cannot declare a non-shared 'Sub New' with no parameters.</source>
<target state="translated">結構無法宣告非共用且無參數的 'Sub New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndGet">
<source>'End Get' must be preceded by a matching 'Get'.</source>
<target state="translated">'End Get' 之前必須搭配相對應的 'Get'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndGet">
<source>'Get' statement must end with a matching 'End Get'.</source>
<target state="translated">'Get' 陳述式之後必須搭配相對應的 'End Get'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndSet">
<source>'End Set' must be preceded by a matching 'Set'.</source>
<target state="translated">'End Set' 之前必須搭配相對應的 'Set'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndSet">
<source>'Set' statement must end with a matching 'End Set'.</source>
<target state="translated">'Set' 陳述式之後必須搭配相對應的 'End Set'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsProperty">
<source>Statement cannot appear within a property body. End of property assumed.</source>
<target state="translated">陳述式不可以在屬性主體中出現。已假設是屬性結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateWriteabilityCategoryUsed">
<source>'ReadOnly' and 'WriteOnly' cannot be combined.</source>
<target state="translated">'無法結合 'ReadOnly' 和 'WriteOnly'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedGreater">
<source>'>' expected.</source>
<target state="translated">'必須有 '>'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeStmtWrongOrder">
<source>Assembly or Module attribute statements must precede any declarations in a file.</source>
<target state="translated">組件或模組屬性陳述式必須在檔案中任何宣告之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoExplicitArraySizes">
<source>Array bounds cannot appear in type specifiers.</source>
<target state="translated">陣列界限的宣告不可以出現在類型規範中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyFlags1">
<source>Properties cannot be declared '{0}'.</source>
<target state="translated">屬性不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionExplicit">
<source>'Option Explicit' can be followed only by 'On' or 'Off'.</source>
<target state="translated">'Option Explicit' 之後只能是 'On' 或 'Off'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleParameterSpecifiers">
<source>'ByVal' and 'ByRef' cannot be combined.</source>
<target state="translated">'無法結合 'ByVal' 和 'ByRef'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleOptionalParameterSpecifiers">
<source>'Optional' and 'ParamArray' cannot be combined.</source>
<target state="translated">'無法結合 'Optional' 和 'ParamArray'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedProperty1">
<source>Property '{0}' is of an unsupported type.</source>
<target state="translated">屬性 '{0}' 是不支援的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionalParameterUsage1">
<source>Attribute '{0}' cannot be applied to a method with optional parameters.</source>
<target state="translated">無法將屬性 '{0}' 套用至具有選擇性參數的方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReturnFromNonFunction">
<source>'Return' statement in a Sub or a Set cannot return a value.</source>
<target state="translated">'在 Sub 或 Set 中的 'Return' 陳述式無法傳回值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnterminatedStringLiteral">
<source>String constants must end with a double quote.</source>
<target state="translated">字串常數必須以雙引號結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedType1">
<source>'{0}' is an unsupported type.</source>
<target state="translated">'{0}' 是不支援的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEnumBase">
<source>Enums must be declared as an integral type.</source>
<target state="translated">列舉必須宣告為整數類資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ByRefIllegal1">
<source>{0} parameters cannot be declared 'ByRef'.</source>
<target state="translated">{0} 參數不可宣告為 'ByRef'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedAssembly3">
<source>Reference required to assembly '{0}' containing the type '{1}'. Add one to your project.</source>
<target state="translated">組件 '{0}' (包含類型 '{1}') 需要參考。請在您的專案中加入一個參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnreferencedModule3">
<source>Reference required to module '{0}' containing the type '{1}'. Add one to your project.</source>
<target state="translated">模組 '{0}' (包含類型 '{1}') 需要參考。請在您的專案中加入一個參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReturnWithoutValue">
<source>'Return' statement in a Function, Get, or Operator must return a value.</source>
<target state="translated">'在 Function、Get 或 Operator 中的 'Return' 陳述式必須傳回值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedField1">
<source>Field '{0}' is of an unsupported type.</source>
<target state="translated">欄位 '{0}' 是不支援的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedMethod1">
<source>'{0}' has a return type that is not supported or parameter types that are not supported.</source>
<target state="translated">'{0}' 含有不支援的傳回類型或多個不支援的參數類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonIndexProperty1">
<source>Property '{0}' with no parameters cannot be found.</source>
<target state="translated">找不到不含有參數的屬性 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributePropertyType1">
<source>Property or field '{0}' does not have a valid attribute type.</source>
<target state="translated">屬性或欄位 '{0}' 不具備有效的屬性類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalsCannotHaveAttributes">
<source>Attributes cannot be applied to local variables.</source>
<target state="translated">屬性不可以套用至區域變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyOrFieldNotDefined1">
<source>Field or property '{0}' is not found.</source>
<target state="translated">找不到欄位或屬性 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeUsage2">
<source>Attribute '{0}' cannot be applied to '{1}' because the attribute is not valid on this declaration type.</source>
<target state="translated">無法將屬性 '{0}' 套用至 '{1}',因為該屬性在此宣告類型上無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeUsageOnAccessor">
<source>Attribute '{0}' cannot be applied to '{1}' of '{2}' because the attribute is not valid on this declaration type.</source>
<target state="translated">無法將屬性 '{0}' 套用至 '{2}' 的 '{1}',因為該屬性在此宣告類型上無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedTypeInInheritsClause2">
<source>Class '{0}' cannot reference its nested type '{1}' in Inherits clause.</source>
<target state="translated">類別 '{0}' 無法參考其在 Inherits 子句中的巢狀類型 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInItsInheritsClause1">
<source>Class '{0}' cannot reference itself in Inherits clause.</source>
<target state="translated">類別 '{0}' 無法在 Inherits 子句中參考自己本身。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseTypeReferences2">
<source>
Base type of '{0}' needs '{1}' to be resolved.</source>
<target state="translated">
'{0}' 的基底類型需要解析 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalBaseTypeReferences3">
<source>Inherits clause of {0} '{1}' causes cyclic dependency: {2}</source>
<target state="translated">{0} '{1}' 的 Inherits 子句造成了循環依存性: {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMultipleAttributeUsage1">
<source>Attribute '{0}' cannot be applied multiple times.</source>
<target state="translated">屬性 '{0}' 不可多次套用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMultipleAttributeUsageInNetModule2">
<source>Attribute '{0}' in '{1}' cannot be applied multiple times.</source>
<target state="translated">'{1}' 中的屬性 '{0}' 不可多次套用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantThrowNonException">
<source>'Throw' operand must derive from 'System.Exception'.</source>
<target state="translated">'Throw' 運算元必須衍生自 'System.Exception'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustBeInCatchToRethrow">
<source>'Throw' statement cannot omit operand outside a 'Catch' statement or inside a 'Finally' statement.</source>
<target state="translated">'Throw' 陳述式不可以在 'Catch' 陳述式外或 'Finally' 陳述式內省略運算元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayMustBeByVal">
<source>ParamArray parameters must be declared 'ByVal'.</source>
<target state="translated">ParamArray 參數必須宣告為 'ByVal'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoleteSymbol2">
<source>'{0}' is obsolete: '{1}'.</source>
<target state="translated">'{0}' 已經過時: '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RedimNoSizes">
<source>'ReDim' statements require a parenthesized list of the new bounds of each dimension of the array.</source>
<target state="translated">'ReDim' 陳述式需要每個陣列維度新界限的小括號內清單。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitWithMultipleDeclarators">
<source>Explicit initialization is not permitted with multiple variables declared with a single type specifier.</source>
<target state="translated">以單一類型規範來宣告多個變數時不允許明確初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitWithExplicitArraySizes">
<source>Explicit initialization is not permitted for arrays declared with explicit bounds.</source>
<target state="translated">以明確的界限來宣告陣列時不允許明確初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndSyncLockNoSyncLock">
<source>'End SyncLock' must be preceded by a matching 'SyncLock'.</source>
<target state="translated">'End SyncLock' 之前必須搭配相對應的 'SyncLock'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndSyncLock">
<source>'SyncLock' statement must end with a matching 'End SyncLock'.</source>
<target state="translated">'SyncLock' 之後必須搭配相對應的 'End SyncLock'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotEvent2">
<source>'{0}' is not an event of '{1}'.</source>
<target state="translated">'{0}' 不是 '{1}' 的事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddOrRemoveHandlerEvent">
<source>'AddHandler' or 'RemoveHandler' statement event operand must be a dot-qualified expression or a simple name.</source>
<target state="translated">'AddHandler' 或 'RemoveHandler' 陳述式事件運算元必須是點限定運算式 (Dot-qualified Expression) 或是簡單名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedEnd">
<source>'End' statement not valid.</source>
<target state="translated">'End' 陳述式無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitForNonArray2">
<source>Array initializers are valid only for arrays, but the type of '{0}' is '{1}'.</source>
<target state="translated">陣列初始設定式只對陣列有效,但 '{0}' 的類型是 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndRegionNoRegion">
<source>'#End Region' must be preceded by a matching '#Region'.</source>
<target state="translated">'#End Region' 之前必須搭配相對應的 '#Region'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndRegion">
<source>'#Region' statement must end with a matching '#End Region'.</source>
<target state="translated">'#Region' 之後必須搭配相對應的 '#End Region'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsStmtWrongOrder">
<source>'Inherits' statement must precede all declarations in a class.</source>
<target state="translated">'Inherits' 陳述式必須在類別中所有宣告之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousAcrossInterfaces3">
<source>'{0}' is ambiguous across the inherited interfaces '{1}' and '{2}'.</source>
<target state="translated">'跨繼承介面 '{1}' 和 '{2}' 的 '{0}' 模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultPropertyAmbiguousAcrossInterfaces4">
<source>Default property access is ambiguous between the inherited interface members '{0}' of interface '{1}' and '{2}' of interface '{3}'.</source>
<target state="translated">在介面 '{1}' 的繼承介面成員 '{0}' 以及介面 '{3}' 的 '{2}' 之間,預設屬性存取模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceEventCantUse1">
<source>Events in interfaces cannot be declared '{0}'.</source>
<target state="translated">介面中的事件不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExecutableAsDeclaration">
<source>Statement cannot appear outside of a method body.</source>
<target state="translated">陳述式不可出現在方法主體之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructureNoDefault1">
<source>Structure '{0}' cannot be indexed because it has no default property.</source>
<target state="translated">無法對結構 '{0}' 編製索引,因為其無預設屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustShadow2">
<source>{0} '{1}' must be declared 'Shadows' because another member with this name is declared 'Shadows'.</source>
<target state="translated">{0} '{1}' 必須宣告為 'Shadows',因為使用此名稱的另一個成員已宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithOptionalTypes2">
<source>'{0}' cannot override '{1}' because they differ by the types of optional parameters.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其選擇性參數類型不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndOfExpression">
<source>End of expression expected.</source>
<target state="translated">必須是運算式結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructsCannotHandleEvents">
<source>Methods declared in structures cannot have 'Handles' clauses.</source>
<target state="translated">結構中宣告的方法不能有 'Handles' 子句。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverridesImpliesOverridable">
<source>Methods declared 'Overrides' cannot be declared 'Overridable' because they are implicitly overridable.</source>
<target state="translated">宣告為 'Overrides' 的方法無法宣告為 'Overridable',因為它們可以被隱含地覆寫。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalNamedSameAsParam1">
<source>'{0}' is already declared as a parameter of this method.</source>
<target state="translated">'{0}' 已經宣告為此方法的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalNamedSameAsParamInLambda1">
<source>Variable '{0}' is already declared as a parameter of this or an enclosing lambda expression.</source>
<target state="translated">變數 '{0}' 已宣告為此運算式或封閉式 Lambda 運算式的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseTypeSpecifier1">
<source>Type in a Module cannot be declared '{0}'.</source>
<target state="translated">Module 中的類型不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InValidSubMainsFound1">
<source>No accessible 'Main' method with an appropriate signature was found in '{0}'.</source>
<target state="translated">在 '{0}' 中找不到具有適當簽章的可存取 'Main' 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MoreThanOneValidMainWasFound2">
<source>'Sub Main' is declared more than once in '{0}': {1}</source>
<target state="translated">'在 '{0}' 中已重複宣告 'Sub Main': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotConvertValue2">
<source>Value '{0}' cannot be converted to '{1}'.</source>
<target state="translated">值 '{0}' 無法轉換成 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnErrorInSyncLock">
<source>'On Error' statements are not valid within 'SyncLock' statements.</source>
<target state="translated">'SyncLock' 陳述式中的 'On Error' 陳述式無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NarrowingConversionCollection2">
<source>Option Strict On disallows implicit conversions from '{0}' to '{1}'; the Visual Basic 6.0 collection type is not compatible with the .NET Framework collection type.</source>
<target state="translated">Option Strict 為 On 時,不可進行 '{0}' 至 '{1}' 的隱含轉換。Visual Basic 6.0 集合類型與 .NET Framework 集合類型不相容。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoTryHandler">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'Try', 'Catch' or 'Finally' statement that does not contain this statement.</source>
<target state="translated">'GoTo {0}' 無效,因為 '{0}' 位於不包含此陳述式的 'Try'、'Catch' 或 'Finally' 陳述式內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoSyncLock">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'SyncLock' statement that does not contain this statement.</source>
<target state="translated">'GoTo {0}' 無效,因為 '{0}' 位於不包含此陳述式的 'SyncLock' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoWith">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'With' statement that does not contain this statement.</source>
<target state="translated">'GoTo {0}' 無效,因為 '{0}' 位於不包含此陳述式的 'With' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoFor">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'For' or 'For Each' statement that does not contain this statement.</source>
<target state="translated">'GoTo {0}' 無效,因為 '{0}' 位於不包含此陳述式的 'For' 或 'For Each' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicConstructor">
<source>Attribute cannot be used because it does not have a Public constructor.</source>
<target state="translated">無法使用屬性,因為它沒有 Public 建構函式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultEventNotFound1">
<source>Event '{0}' specified by the 'DefaultEvent' attribute is not a publicly accessible event for this class.</source>
<target state="translated">DefaultEvent' 屬性所指定的 '{0}' 事件,對此類別而言並非可公開存取的事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidNonSerializedUsage">
<source>'NonSerialized' attribute will not have any effect on this member because its containing class is not exposed as 'Serializable'.</source>
<target state="translated">'NonSerialized' 屬性對這個成員將沒有任何作用,因為它的包含類別並未公開為 'Serializable'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedContinueKind">
<source>'Continue' must be followed by 'Do', 'For' or 'While'.</source>
<target state="translated">'Continue' 必須在 'Do'、'For' 或 'While' 之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ContinueDoNotWithinDo">
<source>'Continue Do' can only appear inside a 'Do' statement.</source>
<target state="translated">'Continue Do' 只可以在 'Do' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ContinueForNotWithinFor">
<source>'Continue For' can only appear inside a 'For' statement.</source>
<target state="translated">'Continue For' 只可以在 'For' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ContinueWhileNotWithinWhile">
<source>'Continue While' can only appear inside a 'While' statement.</source>
<target state="translated">'Continue While' 只可以在 'While' 陳述式中出現。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateParameterSpecifier">
<source>Parameter specifier is duplicated.</source>
<target state="translated">參數規範重複。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleCantUseDLLDeclareSpecifier1">
<source>'Declare' statements in a Module cannot be declared '{0}'.</source>
<target state="translated">'Module 中的 'Declare' 陳述式不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructCantUseDLLDeclareSpecifier1">
<source>'Declare' statements in a structure cannot be declared '{0}'.</source>
<target state="translated">'結構中的 'Declare' 陳述式不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryCastOfValueType1">
<source>'TryCast' operand must be reference type, but '{0}' is a value type.</source>
<target state="translated">'TryCast' 運算元必須要是參考類型,但 '{0}' 是實值類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TryCastOfUnconstrainedTypeParam1">
<source>'TryCast' operands must be class-constrained type parameter, but '{0}' has no class constraint.</source>
<target state="translated">'TryCast' 運算元必須是具備類別條件約束的類型參數,但 '{0}' 沒有類別條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousDelegateBinding2">
<source>No accessible '{0}' is most specific: {1}</source>
<target state="translated">沒有最適用的 '{0}' 可供存取: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedStructMemberCannotSpecifyNew">
<source>Non-shared members in a Structure cannot be declared 'New'.</source>
<target state="translated">Structure 中的非共用成員不可以宣告為 'New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericSubMainsFound1">
<source>None of the accessible 'Main' methods with the appropriate signatures found in '{0}' can be the startup method since they are all either generic or nested in generic types.</source>
<target state="translated">在 '{0}' 中所找到具有適當簽章之可存取的 'Main' 方法,沒有任何一個可做為啟動方法,因為所有這些方法都可能是泛型類型或是泛型類型中的巢狀類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GeneralProjectImportsError3">
<source>Error in project-level import '{0}' at '{1}' : {2}</source>
<target state="translated">專案層級的匯入 '{0}' 在 '{1}' 發生錯誤: {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidTypeForAliasesImport2">
<source>'{1}' for the Imports alias to '{0}' does not refer to a Namespace, Class, Structure, Interface, Enum or Module.</source>
<target state="translated">'Imports 別名為 '{0}' 的 '{1}',並未參考 Namespace、Class、Structure、Interface、Enum 或 Module。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedConstant2">
<source>Field '{0}.{1}' has an invalid constant value.</source>
<target state="translated">欄位 '{0}.{1}' 的常數值無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteArgumentsNeedParens">
<source>Method arguments must be enclosed in parentheses.</source>
<target state="translated">方法引數必須放在括號之中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteLineNumbersAreLabels">
<source>Labels that are numbers must be followed by colons.</source>
<target state="translated">內容為數字的標籤之後必須跟隨冒號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteStructureNotType">
<source>'Type' statements are no longer supported; use 'Structure' statements instead.</source>
<target state="translated">'不再支援 'Type' 陳述式。請使用 'Structure' 陳述式代替。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteObjectNotVariant">
<source>'Variant' is no longer a supported type; use the 'Object' type instead.</source>
<target state="translated">'不再支援 'Variant' 類型。請使用 'Object' 類型代替。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteLetSetNotNeeded">
<source>'Let' and 'Set' assignment statements are no longer supported.</source>
<target state="translated">'不再支援 'Let' 和 'Set' 指派陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoletePropertyGetLetSet">
<source>Property Get/Let/Set are no longer supported; use the new Property declaration syntax.</source>
<target state="translated">不再支援 Property Get/Let/Set; 請使用新的 Property 宣告語法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteWhileWend">
<source>'Wend' statements are no longer supported; use 'End While' statements instead.</source>
<target state="translated">'不再支援 'Wend' 陳述式; 請使用 'End While' 陳述式代替。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteRedimAs">
<source>'ReDim' statements can no longer be used to declare array variables.</source>
<target state="translated">'無法再使用 'ReDim' 陳述式來宣告陣列變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteOptionalWithoutValue">
<source>Optional parameters must specify a default value.</source>
<target state="translated">選擇性參數必須指定預設值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteGosub">
<source>'GoSub' statements are no longer supported.</source>
<target state="translated">'不再支援 'GoSub' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteOnGotoGosub">
<source>'On GoTo' and 'On GoSub' statements are no longer supported.</source>
<target state="translated">'不再支援 'On GoTo' 和 'On GoSub' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteEndIf">
<source>'EndIf' statements are no longer supported; use 'End If' instead.</source>
<target state="translated">'不再支援 'EndIf' 陳述式; 請使用 'End If' 代替。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteExponent">
<source>'D' can no longer be used to indicate an exponent, use 'E' instead.</source>
<target state="translated">'不再使用 'D' 來表示指數,請使用 'E' 代替。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteAsAny">
<source>'As Any' is not supported in 'Declare' statements.</source>
<target state="translated">'Declare' 陳述式中不支援 'As Any'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteGetStatement">
<source>'Get' statements are no longer supported. File I/O functionality is available in the 'Microsoft.VisualBasic' namespace.</source>
<target state="translated">'不再支援 'Get' 陳述式。檔案 I/O 的功能可以在 'Microsoft.VisualBasic' 命名空間中使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithArrayVsParamArray2">
<source>'{0}' cannot override '{1}' because they differ by parameters declared 'ParamArray'.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其宣告為 'ParamArray' 的參數不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CircularBaseDependencies4">
<source>This inheritance causes circular dependencies between {0} '{1}' and its nested or base type '{2}'.</source>
<target state="translated">此繼承會導致 {0} '{1}' 與其巢狀或基底類型 '{2}' 之間發生循環相依。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedBase2">
<source>{0} '{1}' cannot inherit from a type nested within it.</source>
<target state="translated">{0} '{1}' 無法繼承自其內部的巢狀類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatchOutsideAssembly4">
<source>'{0}' cannot expose type '{1}' outside the project through {2} '{3}'.</source>
<target state="translated">'{0}' 無法經由 {2} '{3}',在專案外公開類型 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceAccessMismatchOutside3">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of the base {1} outside the assembly.</source>
<target state="translated">'{0}' 無法繼承自 {1} '{2}',因為其會在組件外展開基底 {1} 的存取。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoletePropertyAccessor3">
<source>'{0}' accessor of '{1}' is obsolete: '{2}'.</source>
<target state="translated">'{1}' 的 '{0}' 存取子已經過時: '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoletePropertyAccessor2">
<source>'{0}' accessor of '{1}' is obsolete.</source>
<target state="translated">'{1}' 的 '{0}' 存取子已經過時。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatchImplementedEvent6">
<source>'{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing to {2} '{3}' through {4} '{5}'.</source>
<target state="translated">'{0}' 無法將其實作之事件的基礎委派類型 '{1}',經由 {4} '{5}' 公開至 {2} '{3}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatchImplementedEvent4">
<source>'{0}' cannot expose the underlying delegate type '{1}' of the event it is implementing outside the project through {2} '{3}'.</source>
<target state="translated">'{0}' 無法將其實作之事件的基礎委派類型 '{1}',經由 {2} '{3}' 公開於專案之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritanceCycleInImportedType1">
<source>Type '{0}' is not supported because it either directly or indirectly inherits from itself.</source>
<target state="translated">因為類型 '{0}' 直接或間接繼承其本身,所以不受支援。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonObsoleteConstructorOnBase3">
<source>Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete.</source>
<target state="translated">類別 '{0}' 必須宣告 'Sub New',因為基底類別 '{2}' 中的 '{1}' 已標記為過時。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNonObsoleteConstructorOnBase4">
<source>Class '{0}' must declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'.</source>
<target state="translated">類別 '{0}' 必須宣告 'Sub New',因為基底類別 '{2}' 中的 '{1}' 已標記為過時: '{3}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNonObsoleteNewCall3">
<source>First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete.</source>
<target state="translated">此 'Sub New' 的第一個陳述式,必須是對 'MyBase.New' 或 'MyClass.New' 的明確呼叫,因為 '{2}' 的基底類別 '{1}' 中之 '{0}' 已標記為過時。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNonObsoleteNewCall4">
<source>First statement of this 'Sub New' must be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'.</source>
<target state="translated">此 'Sub New' 的第一個陳述式,必須是對 'MyBase.New' 或 'MyClass.New' 的明確呼叫,因為 '{2}' 的基底類別 '{1}' 中之 '{0}' 已標記為過時: '{3}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsTypeArgAccessMismatch7">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' to {4} '{5}'.</source>
<target state="translated">'{0}' 無法繼承自 {1} '{2}',因為它會將類型 '{3}' 的存取展開至 {4} '{5}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InheritsTypeArgAccessMismatchOutside5">
<source>'{0}' cannot inherit from {1} '{2}' because it expands the access of type '{3}' outside the assembly.</source>
<target state="translated">'{0}' 無法繼承自 {1} '{2}',因為它會在組件外展開類型 '{3}' 的存取。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeAccessMismatch3">
<source>Specified access '{0}' for '{1}' does not match the access '{2}' specified on one of its other partial types.</source>
<target state="translated">對於某個其他部分類型所指定的存取 '{2}' 而言,為 '{1}' 所指定的存取 '{0}' 不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeBadMustInherit1">
<source>'MustInherit' cannot be specified for partial type '{0}' because it cannot be combined with 'NotInheritable' specified for one of its other partial types.</source>
<target state="translated">'不可為部分類型 '{0}' 指定 'MustInherit',因為其無法與針對某個其他部分類型所指定的 'NotInheritable' 相結合。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustOverOnNotInheritPartClsMem1">
<source>'MustOverride' cannot be specified on this member because it is in a partial type that is declared 'NotInheritable' in another partial definition.</source>
<target state="translated">'因為成員所屬的部分類型,在另一個部分定義中已宣告為 'NotInheritable',所以無法對該成員指定 'MustOverride',</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseMismatchForPartialClass3">
<source>Base class '{0}' specified for class '{1}' cannot be different from the base class '{2}' of one of its other partial types.</source>
<target state="translated">為類別 '{1}' 指定的基底類別 '{0}',不可與其任一其他部分類型的基底類別 '{2}' 不相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeTypeParamNameMismatch3">
<source>Type parameter name '{0}' does not match the name '{1}' of the corresponding type parameter defined on one of the other partial types of '{2}'.</source>
<target state="translated">對於 '{2}' 的某個其他部分類型所定義之對應類型參數的 '{1}' 名稱而言,類型參數名稱 '{0}' 不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialTypeConstraintMismatch1">
<source>Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of '{0}'.</source>
<target state="translated">對於 '{0}' 的某個其他部分類型所定義之相對應類型參數的條件約束而言,此類型參數的條件約束不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LateBoundOverloadInterfaceCall1">
<source>Late bound overload resolution cannot be applied to '{0}' because the accessing instance is an interface type.</source>
<target state="translated">因為進行存取的執行個體為介面類型,所以晚期繫結多載解析無法套用至 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredAttributeConstConversion2">
<source>Conversion from '{0}' to '{1}' cannot occur in a constant expression used as an argument to an attribute.</source>
<target state="translated">用做為屬性的引數之常數運算式中,不可進行從 '{0}' 到 '{1}' 的轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousOverrides3">
<source>Member '{0}' that matches this signature cannot be overridden because the class '{1}' contains multiple members with this same name and signature: {2}</source>
<target state="translated">無法覆寫與此簽章相符的成員 '{0}',因為類別 '{1}' 包含多位具有此相同名稱與簽章的成員: {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverriddenCandidate1">
<source>
'{0}'</source>
<target state="translated">
'{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousImplements3">
<source>Member '{0}.{1}' that matches this signature cannot be implemented because the interface '{2}' contains multiple members with this same name and signature:
'{3}'
'{4}'</source>
<target state="translated">無法實作與此簽章相符的成員 '{0}.{1}',因為介面 '{2}' 包含多位具有此相同名稱與簽章的成員:
'{3}'
'{4}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfNotCreatableDelegate1">
<source>'AddressOf' expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.</source>
<target state="translated">'因為類型 '{0}' 宣告為 'MustInherit' 但卻無法建立,所以 'AddressOf' 運算式無法轉換成 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassGenericMethod">
<source>Generic methods cannot be exposed to COM.</source>
<target state="translated">泛型方法不可以公開至 COM。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SyntaxInCastOp">
<source>Syntax error in cast operator; two arguments separated by comma are required.</source>
<target state="translated">轉型運算子中的語法錯誤; 兩個引數之間必須以逗號分隔。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitializerForNonConstDim">
<source>Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'.</source>
<target state="translated">無法指定非常數維度的陣列初始設定式; 請使用空的初始設定式 '{}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingFailure3">
<source>No accessible method '{0}' has a signature compatible with delegate '{1}':{2}</source>
<target state="translated">沒有任何可存取的方法 '{0}' 具備與委派 '{1}' 相容的簽章: {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructLayoutAttributeNotAllowed">
<source>Attribute 'StructLayout' cannot be applied to a generic type.</source>
<target state="translated">屬性 'StructLayout' 不能套用到泛型類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IterationVariableShadowLocal1">
<source>Range variable '{0}' hides a variable in an enclosing block or a range variable previously defined in the query expression.</source>
<target state="translated">範圍變數 '{0}' 可隱藏封閉區塊中的變數,或查詢運算式中預先定義的範圍變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionInfer">
<source>'Option Infer' can be followed only by 'On' or 'Off'.</source>
<target state="translated">'Option Infer' 之後只能是 'On' 或 'Off'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CircularInference1">
<source>Type of '{0}' cannot be inferred from an expression containing '{0}'.</source>
<target state="translated">無法從包含 '{0}' 的運算式推斷 '{0}' 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InAccessibleOverridingMethod5">
<source>'{0}' in class '{1}' cannot override '{2}' in class '{3}' because an intermediate class '{4}' overrides '{2}' in class '{3}' but is not accessible.</source>
<target state="translated">'類別 '{1}' 中的 '{0}' 無法覆寫類別 '{3}' 中的 '{2}',因為中繼類別 '{4}' 會覆寫類別 '{3}' 中的 '{2}',但無法存取。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSuitableWidestType1">
<source>Type of '{0}' cannot be inferred because the loop bounds and the step clause do not convert to the same type.</source>
<target state="translated">因為迴圈繫結和 step 子句不會轉換成相同類型,所以無法推斷 '{0}' 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousWidestType3">
<source>Type of '{0}' is ambiguous because the loop bounds and the step clause do not convert to the same type.</source>
<target state="translated">類型 '{0}' 模稜兩可,因為迴圈繫結和 step 子句不會轉換成相同的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAssignmentOperatorInInit">
<source>'=' expected (object initializer).</source>
<target state="translated">'必須是 '=' (物件初始設定式)。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedQualifiedNameInInit">
<source>Name of field or property being initialized in an object initializer must start with '.'.</source>
<target state="translated">在物件初始設定式中初始化的欄位或屬性,其名稱開頭必須是 '.'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLbrace">
<source>'{' expected.</source>
<target state="translated">'必須是 '{'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnrecognizedTypeOrWith">
<source>Type or 'With' expected.</source>
<target state="translated">必須是類型或 'With'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAggrMemberInit1">
<source>Multiple initializations of '{0}'. Fields and properties can be initialized only once in an object initializer expression.</source>
<target state="translated">'{0}' 的多個初始設定。欄位和屬性只能在一個物件初始設定式運算式中初始化一次。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NonFieldPropertyAggrMemberInit1">
<source>Member '{0}' cannot be initialized in an object initializer expression because it is not a field or property.</source>
<target state="translated">成員 '{0}' 因為不是欄位或屬性,所以無法在物件初始設定式運算式中進行初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SharedMemberAggrMemberInit1">
<source>Member '{0}' cannot be initialized in an object initializer expression because it is shared.</source>
<target state="translated">因為成員 '{0}' 為共用成員,所以無法在物件初始設定式運算式中進行初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParameterizedPropertyInAggrInit1">
<source>Property '{0}' cannot be initialized in an object initializer expression because it requires arguments.</source>
<target state="translated">因為屬性 '{0}' 需要有引數,所以無法在物件初始設定式運算式中進行初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoZeroCountArgumentInitCandidates1">
<source>Property '{0}' cannot be initialized in an object initializer expression because all accessible overloads require arguments.</source>
<target state="translated">因為所有可存取的多載都需要有引數,所以屬性 '{0}' 無法在物件初始設定式運算式中進行初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AggrInitInvalidForObject">
<source>Object initializer syntax cannot be used to initialize an instance of 'System.Object'.</source>
<target state="translated">物件初始設定式語法無法用來初始化 'System.Object' 的執行個體。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerExpected">
<source>Initializer expected.</source>
<target state="translated">必須是初始設定式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LineContWithCommentOrNoPrecSpace">
<source>The line continuation character '_' must be preceded by at least one white space and it must be followed by a comment or the '_' must be the last character on the line.</source>
<target state="translated">行接續字元 '_' 前面必須至少有一個空白字元,後面必須接著註解,否則 '_' 必須是該行的最後一個字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadModuleFile1">
<source>Unable to load module file '{0}': {1}</source>
<target state="translated">無法載入模組檔 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadRefLib1">
<source>Unable to load referenced library '{0}': {1}</source>
<target state="translated">無法載入參考的程式庫 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventHandlerSignatureIncompatible2">
<source>Method '{0}' cannot handle event '{1}' because they do not have a compatible signature.</source>
<target state="translated">方法 '{0}' 因為沒有相容的簽章,所以無法處理事件 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConditionalCompilationConstantNotValid">
<source>Conditional compilation constant '{1}' is not valid: {0}</source>
<target state="translated">條件式編譯常數 '{1}' 無效: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwice1">
<source>Interface '{0}' can be implemented only once by this type.</source>
<target state="translated">介面 '{0}' 只可由此類型實作一次。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames2">
<source>Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}'.</source>
<target state="translated">此類型只可在介面 '{0}' 上實作一次,但卻已有不同的 Tuple 項目名稱 ('{1}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames3">
<source>Interface '{0}' can be implemented only once by this type, but already appears with different tuple element names, as '{1}' (via '{2}').</source>
<target state="translated">此類型只可在介面 '{0}' 上實作一次,但卻已有不同的 Tuple 項目名稱 ('{1}',經由 '{2}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNamesReverse3">
<source>Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}'.</source>
<target state="translated">此類型只可在介面 '{0}' 上實作一次 (經由 '{1}'),但卻已有不同的 Tuple 項目名稱 ('{2}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceImplementedTwiceWithDifferentTupleNames4">
<source>Interface '{0}' (via '{1}') can be implemented only once by this type, but already appears with different tuple element names, as '{2}' (via '{3}').</source>
<target state="translated">此類型只可在介面 '{0}' 上實作一次 (經由 '{1}'),但卻已有不同的 Tuple 項目名稱 ('{2}',經由 '{3}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames2">
<source>Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}'.</source>
<target state="translated">此介面只可繼承介面 '{0}' 一次,但卻已有不同的 Tuple 項目名稱 ('{1}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames3">
<source>Interface '{0}' can be inherited only once by this interface, but already appears with different tuple element names, as '{1}' (via '{2}').</source>
<target state="translated">此介面只可繼承介面 '{0}' 一次,但卻已有不同的 Tuple 項目名稱 ('{1}',經由 '{2}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNamesReverse3">
<source>Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}'.</source>
<target state="translated">此介面只可繼承介面 '{0}' 一次 (經由 '{1}'),但卻已有不同的 Tuple 項目名稱 ('{2}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceInheritedTwiceWithDifferentTupleNames4">
<source>Interface '{0}' (via '{1}') can be inherited only once by this interface, but already appears with different tuple element names, as '{2}' (via '{3}').</source>
<target state="translated">此介面只可繼承介面 '{0}' 一次 (經由 '{1}'),但卻已有不同的 Tuple 項目名稱 ('{2}',經由 '{3}')。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceNotImplemented1">
<source>Interface '{0}' is not implemented by this class.</source>
<target state="translated">介面 '{0}' 尚未由此類別實作。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousImplementsMember3">
<source>'{0}' exists in multiple base interfaces. Use the name of the interface that declares '{0}' in the 'Implements' clause instead of the name of the derived interface.</source>
<target state="translated">'{0}' 存在於多個基底介面中。請使用 'Implements' 子句中宣告 '{0}' 的介面名稱,來取代衍生介面的名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsOnNew">
<source>'Sub New' cannot implement interface members.</source>
<target state="translated">'Sub New' 無法實作介面成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitInStruct">
<source>Arrays declared as structure members cannot be declared with an initial size.</source>
<target state="translated">宣告為結構成員的陣列無法以初始大小宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventTypeNotDelegate">
<source>Events declared with an 'As' clause must have a delegate type.</source>
<target state="translated">使用 'As' 子句宣告的事件必須有委派類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ProtectedTypeOutsideClass">
<source>Protected types can only be declared inside of a class.</source>
<target state="translated">只可以在類別內宣告 Protected 類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultPropertyWithNoParams">
<source>Properties with no required parameters cannot be declared 'Default'.</source>
<target state="translated">沒有必要參數的屬性不可以宣告為 'Default'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializerInStruct">
<source>Initializers on structure members are valid only for 'Shared' members and constants.</source>
<target state="translated">結構成員上的初始設定式只有對 'Shared' 成員和常數有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateImport1">
<source>Namespace or type '{0}' has already been imported.</source>
<target state="translated">命名空間或類型 '{0}' 已經匯入。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadModuleFlags1">
<source>Modules cannot be declared '{0}'.</source>
<target state="translated">模組不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsStmtWrongOrder">
<source>'Implements' statements must follow any 'Inherits' statement and precede all declarations in a class.</source>
<target state="translated">'Implements' 陳述式必須位在所有 'Inherits' 陳述式之後,並且必須在類別中的所有宣告之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynthMemberClashesWithSynth7">
<source>{0} '{1}' implicitly defines '{2}', which conflicts with a member implicitly declared for {3} '{4}' in {5} '{6}'.</source>
<target state="translated">{0} '{1}' 隱含定義 '{2}',其與 {5} '{6}' 中為 {3} '{4}' 所隱含宣告的成員互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynthMemberClashesWithMember5">
<source>{0} '{1}' implicitly defines '{2}', which conflicts with a member of the same name in {3} '{4}'.</source>
<target state="translated">{0} '{1}' 隱含定義 '{2}',其與 {3} '{4}' 中相同名稱的成員互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MemberClashesWithSynth6">
<source>{0} '{1}' conflicts with a member implicitly declared for {2} '{3}' in {4} '{5}'.</source>
<target state="translated">{0} '{1}' 與 {4} '{5}' 中為 {2} '{3}' 所隱含宣告的成員互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeClashesWithVbCoreType4">
<source>{0} '{1}' conflicts with a Visual Basic Runtime {2} '{3}'.</source>
<target state="translated">{0} '{1}' 與 Visual Basic 執行階段 {2} '{3}' 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeMissingAction">
<source>First argument to a security attribute must be a valid SecurityAction.</source>
<target state="translated">安全屬性的第一個引數,必須是有效的 SecurityAction。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidAction">
<source>Security attribute '{0}' has an invalid SecurityAction value '{1}'.</source>
<target state="translated">安全屬性 '{0}' 的 SecurityAction 值 '{1}' 無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidActionAssembly">
<source>SecurityAction value '{0}' is invalid for security attributes applied to an assembly.</source>
<target state="translated">SecurityAction 值 '{0}' 對套用至組件的安全屬性無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidActionTypeOrMethod">
<source>SecurityAction value '{0}' is invalid for security attributes applied to a type or a method.</source>
<target state="translated">SecurityAction 值 '{0}' 對套用至類型或方法的安全屬性無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PrincipalPermissionInvalidAction">
<source>SecurityAction value '{0}' is invalid for PrincipalPermission attribute.</source>
<target state="translated">SecurityAction 值 '{0}' 對 PrincipalPermission 屬性無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PermissionSetAttributeInvalidFile">
<source>Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute.</source>
<target state="translated">無法解析指定給 PermissionSet 屬性之具名引數 '{1}' 的檔案路徑 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PermissionSetAttributeFileReadError">
<source>Error reading file '{0}' specified for the named argument '{1}' for PermissionSet attribute: '{2}'.</source>
<target state="translated">讀取指定給 PermissionSet 屬性之具名引數 '{1}' 的檔案 '{0}' 時發生錯誤: '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SetHasOnlyOneParam">
<source>'Set' method cannot have more than one parameter.</source>
<target state="translated">'Set' 方法不可以有多個參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SetValueNotPropertyType">
<source>'Set' parameter must have the same type as the containing property.</source>
<target state="translated">'Set' 參數必須和包含的屬性具有相同的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SetHasToBeByVal1">
<source>'Set' parameter cannot be declared '{0}'.</source>
<target state="translated">'Set' 參數不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StructureCantUseProtected">
<source>Method in a structure cannot be declared 'Protected', 'Protected Friend', or 'Private Protected'.</source>
<target state="translated">在結構中的方法不可宣告為 'Protected'、'Protected Friend' 或 'Private Protected'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceDelegateSpecifier1">
<source>Delegate in an interface cannot be declared '{0}'.</source>
<target state="translated">介面中的委派不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceEnumSpecifier1">
<source>Enum in an interface cannot be declared '{0}'.</source>
<target state="translated">介面中的列舉不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceClassSpecifier1">
<source>Class in an interface cannot be declared '{0}'.</source>
<target state="translated">介面中的類別不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceStructSpecifier1">
<source>Structure in an interface cannot be declared '{0}'.</source>
<target state="translated">介面中的結構不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadInterfaceInterfaceSpecifier1">
<source>Interface in an interface cannot be declared '{0}'.</source>
<target state="translated">介面中的介面不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfObsoleteSymbolNoMessage1">
<source>'{0}' is obsolete.</source>
<target state="translated">'{0}' 已經過時。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetaDataIsNotAssembly">
<source>'{0}' is a module and cannot be referenced as an assembly.</source>
<target state="translated">'{0}' 是一個模組,且無法當做組件來參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetaDataIsNotModule">
<source>'{0}' is an assembly and cannot be referenced as a module.</source>
<target state="translated">'{0}' 是一個組件,且無法當做模組來參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReferenceComparison3">
<source>Operator '{0}' is not defined for types '{1}' and '{2}'. Use 'Is' operator to compare two reference types.</source>
<target state="translated">未定義類型 '{1}' 和 '{2}' 的運算子 '{0}'。請使用 'Is' 運算子比較兩個參考類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CatchVariableNotLocal1">
<source>'{0}' is not a local variable or parameter, and so cannot be used as a 'Catch' variable.</source>
<target state="translated">'{0}' 不是區域變數或參數,所以不能用做為 'Catch' 變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModuleMemberCantImplement">
<source>Members in a Module cannot implement interface members.</source>
<target state="translated">模組中的成員不可以實作介面成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventDelegatesCantBeFunctions">
<source>Events cannot be declared with a delegate type that has a return type.</source>
<target state="translated">事件不可以宣告為具有傳回類型的委派類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidDate">
<source>Date constant is not valid.</source>
<target state="translated">日期常數無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantOverride4">
<source>'{0}' cannot override '{1}' because it is not declared 'Overridable'.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其未宣告為 'Overridable'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyArraysOnBoth">
<source>Array modifiers cannot be specified on both a variable and its type.</source>
<target state="translated">無法同時在變數及其類型上指定陣列修飾元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NotOverridableRequiresOverrides">
<source>'NotOverridable' cannot be specified for methods that do not override another method.</source>
<target state="translated">'NotOverridable' 無法指定給不覆寫其他方法的方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PrivateTypeOutsideType">
<source>Types declared 'Private' must be inside another type.</source>
<target state="translated">宣告為 'Private' 的類型必須在另一個類型內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeRefResolutionError3">
<source>Import of type '{0}' from assembly or module '{1}' failed.</source>
<target state="translated">從組件或模組 '{1}' 匯入類型 '{0}' 失敗。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ValueTupleTypeRefResolutionError1">
<source>Predefined type '{0}' is not defined or imported.</source>
<target state="translated">預先定義的類型 '{0}' 未經定義或匯入。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayWrongType">
<source>ParamArray parameters must have an array type.</source>
<target state="translated">ParamArray 參數必須有陣列類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CoClassMissing2">
<source>Implementing class '{0}' for interface '{1}' cannot be found.</source>
<target state="translated">找不到介面 '{1}' 的實作類別 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidCoClass1">
<source>Type '{0}' cannot be used as an implementing class.</source>
<target state="translated">類型 '{0}' 無法用做為實作類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidMeReference">
<source>Reference to object under construction is not valid when calling another constructor.</source>
<target state="translated">呼叫其他建構函式時,參考建構中的物件是無效的。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidImplicitMeReference">
<source>Implicit reference to object under construction is not valid when calling another constructor.</source>
<target state="translated">呼叫其他建構函式時,隱含參考建構中的物件是無效的。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RuntimeMemberNotFound2">
<source>Member '{0}' cannot be found in class '{1}'. This condition is usually the result of a mismatched 'Microsoft.VisualBasic.dll'.</source>
<target state="translated">在類別 '{1}' 中找不到成員 '{0}'。這種情況通常是 'Microsoft.VisualBasic.dll' 不相符的結果。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags">
<source>Property accessors cannot be declared '{0}'.</source>
<target state="translated">屬性存取子不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlagsRestrict">
<source>Access modifier '{0}' is not valid. The access modifier of 'Get' and 'Set' should be more restrictive than the property access level.</source>
<target state="translated">存取修飾詞 '{0}' 無效。'Get' 和 'Set' 的存取修飾詞,應較屬性存取層級有更多限制。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyOneAccessorForGetSet">
<source>Access modifier can only be applied to either 'Get' or 'Set', but not both.</source>
<target state="translated">存取修飾詞只能套用至 'Get' 或 'Set',但不能同時套用至兩者。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAccessibleSet">
<source>'Set' accessor of property '{0}' is not accessible.</source>
<target state="translated">'無法存取屬性 '{0}' 的 'Set' 存取子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAccessibleGet">
<source>'Get' accessor of property '{0}' is not accessible.</source>
<target state="translated">'無法存取屬性 '{0}' 的 'Get' 存取子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_WriteOnlyNoAccessorFlag">
<source>'WriteOnly' properties cannot have an access modifier on 'Set'.</source>
<target state="translated">'WriteOnly' 屬性在 'Set' 上不能有存取修飾詞。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyNoAccessorFlag">
<source>'ReadOnly' properties cannot have an access modifier on 'Get'.</source>
<target state="translated">'ReadOnly' 屬性在 'Get' 上不能有存取修飾詞。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags1">
<source>Property accessors cannot be declared '{0}' in a 'NotOverridable' property.</source>
<target state="translated">屬性存取子在 'NotOverridable' 屬性中不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags2">
<source>Property accessors cannot be declared '{0}' in a 'Default' property.</source>
<target state="translated">屬性存取子在 'Default' 屬性中不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPropertyAccessorFlags3">
<source>Property cannot be declared '{0}' because it contains a 'Private' accessor.</source>
<target state="translated">屬性不可宣告為 '{0}',因為它包含 'Private' 存取子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InAccessibleCoClass3">
<source>Implementing class '{0}' for interface '{1}' is not accessible in this context because it is '{2}'.</source>
<target state="translated">無法在此內容中存取介面 '{1}' 的實作類別 '{0}',因為其為 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingValuesForArraysInApplAttrs">
<source>Arrays used as attribute arguments are required to explicitly specify values for all elements.</source>
<target state="translated">明確指定所有元素的值時,用做為屬性引數的陣列為必要項目。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitEventMemberNotInvalid">
<source>'Exit AddHandler', 'Exit RemoveHandler' and 'Exit RaiseEvent' are not valid. Use 'Return' to exit from event members.</source>
<target state="translated">'Exit AddHandler'、'Exit RemoveHandler' 和 'Exit RaiseEvent' 無效。請使用 'Return' 結束事件成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvInsideEndsEvent">
<source>Statement cannot appear within an event body. End of event assumed.</source>
<target state="translated">陳述式不能出現在事件主體內。假設是事件結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndEvent">
<source>'Custom Event' must end with a matching 'End Event'.</source>
<target state="translated">'Custom Event' 結尾必須是對應的 'End Event'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndAddHandler">
<source>'AddHandler' declaration must end with a matching 'End AddHandler'.</source>
<target state="translated">'AddHandler' 宣告之後必須搭配相對應的 'End AddHandler'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndRemoveHandler">
<source>'RemoveHandler' declaration must end with a matching 'End RemoveHandler'.</source>
<target state="translated">'RemoveHandler' 宣告之後必須搭配相對應的 'End RemoveHandler'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingEndRaiseEvent">
<source>'RaiseEvent' declaration must end with a matching 'End RaiseEvent'.</source>
<target state="translated">'RaiseEvent' 宣告之後必須搭配相對應的 'End RaiseEvent'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CustomEventInvInInterface">
<source>'Custom' modifier is not valid on events declared in interfaces.</source>
<target state="translated">'Custom' 修飾元在以介面宣告的事件中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CustomEventRequiresAs">
<source>'Custom' modifier is not valid on events declared without explicit delegate types.</source>
<target state="translated">'Custom' 修飾元在沒有以明確委派類型宣告的事件中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndEvent">
<source>'End Event' must be preceded by a matching 'Custom Event'.</source>
<target state="translated">'End Event' 之前必須搭配相對應的 'Custom Event'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndAddHandler">
<source>'End AddHandler' must be preceded by a matching 'AddHandler' declaration.</source>
<target state="translated">'End AddHandler' 之前必須搭配相對應的 'AddHandler' 宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndRemoveHandler">
<source>'End RemoveHandler' must be preceded by a matching 'RemoveHandler' declaration.</source>
<target state="translated">'End RemoveHandler' 之前必須搭配相對應的 'RemoveHandler' 宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndRaiseEvent">
<source>'End RaiseEvent' must be preceded by a matching 'RaiseEvent' declaration.</source>
<target state="translated">'End RaiseEvent' 之前必須搭配相對應的 'RaiseEvent' 宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAddHandlerDef">
<source>'AddHandler' is already declared.</source>
<target state="translated">'AddHandler' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateRemoveHandlerDef">
<source>'RemoveHandler' is already declared.</source>
<target state="translated">'RemoveHandler' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateRaiseEventDef">
<source>'RaiseEvent' is already declared.</source>
<target state="translated">'RaiseEvent' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingAddHandlerDef1">
<source>'AddHandler' definition missing for event '{0}'.</source>
<target state="translated">'事件 '{0}' 遺漏 'AddHandler' 定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingRemoveHandlerDef1">
<source>'RemoveHandler' definition missing for event '{0}'.</source>
<target state="translated">'事件 '{0}' 遺漏 'RemoveHandler' 定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingRaiseEventDef1">
<source>'RaiseEvent' definition missing for event '{0}'.</source>
<target state="translated">'事件 '{0}' 遺漏 'RaiseEvent' 定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventAddRemoveHasOnlyOneParam">
<source>'AddHandler' and 'RemoveHandler' methods must have exactly one parameter.</source>
<target state="translated">'AddHandler' 和 'RemoveHandler' 方法必須剛好有一個參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventAddRemoveByrefParamIllegal">
<source>'AddHandler' and 'RemoveHandler' method parameters cannot be declared 'ByRef'.</source>
<target state="translated">'AddHandler' 和 'RemoveHandler' 方法參數不可以宣告為 'ByRef'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SpecifiersInvOnEventMethod">
<source>Specifiers are not valid on 'AddHandler', 'RemoveHandler' and 'RaiseEvent' methods.</source>
<target state="translated">AddHandler'、'RemoveHandler' 和 'RaiseEvent' 方法上的規範無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddRemoveParamNotEventType">
<source>'AddHandler' and 'RemoveHandler' method parameters must have the same delegate type as the containing event.</source>
<target state="translated">'AddHandler' 和 'RemoveHandler' 方法參數必須與包含事件擁有相同的委派類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RaiseEventShapeMismatch1">
<source>'RaiseEvent' method must have the same signature as the containing event's delegate type '{0}'.</source>
<target state="translated">'RaiseEvent' 方法必須與包含的事件委派類型 '{0}',擁有相同的簽章。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventMethodOptionalParamIllegal1">
<source>'AddHandler', 'RemoveHandler' and 'RaiseEvent' method parameters cannot be declared '{0}'.</source>
<target state="translated">'AddHandler'、'RemoveHandler' 和 'RaiseEvent' 方法參數不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantReferToMyGroupInsideGroupType1">
<source>'{0}' cannot refer to itself through its default instance; use 'Me' instead.</source>
<target state="translated">'{0}' 不可透過其預設執行個體參考本身; 請改用 'Me'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidUseOfCustomModifier">
<source>'Custom' modifier can only be used immediately before an 'Event' declaration.</source>
<target state="translated">'Custom' 修飾元只能緊接地用於 'Event' 宣告的前面。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOptionStrictCustom">
<source>Option Strict Custom can only be used as an option to the command-line compiler (vbc.exe).</source>
<target state="translated">Option Strict Custom 只能當做命令列編譯器 (vbc.exe) 選項使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObsoleteInvalidOnEventMember">
<source>'{0}' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event.</source>
<target state="translated">'{0}' 無法套用至 'AddHandler'、'RemoveHandler' 或 'RaiseEvent' 定義。必要時,請將屬性直接套用至事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingIncompatible2">
<source>Method '{0}' does not have a signature compatible with delegate '{1}'.</source>
<target state="translated">方法 '{0}' 沒有與委派 '{1}' 相容的簽章。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlName">
<source>XML name expected.</source>
<target state="translated">必須是 XML 名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UndefinedXmlPrefix">
<source>XML namespace prefix '{0}' is not defined.</source>
<target state="translated">XML 命名空間前置詞 '{0}' 未定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateXmlAttribute">
<source>Duplicate XML attribute '{0}'.</source>
<target state="translated">重複的 XML 屬性 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MismatchedXmlEndTag">
<source>End tag </{0}{1}{2}> expected.</source>
<target state="translated">必須是結束標記 </{0}{1}{2}>。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingXmlEndTag">
<source>Element is missing an end tag.</source>
<target state="translated">項目中遺漏結束標記。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReservedXmlPrefix">
<source>XML namespace prefix '{0}' is reserved for use by XML and the namespace URI cannot be changed.</source>
<target state="translated">XML 命名空間前置詞 '{0}' 已保留供 XML 使用,且不可變更命名空間 URI。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingVersionInXmlDecl">
<source>Required attribute 'version' missing from XML declaration.</source>
<target state="translated">XML 宣告遺漏必要的屬性 'version'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalAttributeInXmlDecl">
<source>XML declaration does not allow attribute '{0}{1}{2}'.</source>
<target state="translated">XML 宣告不可使用屬性 '{0}{1}{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QuotedEmbeddedExpression">
<source>Embedded expression cannot appear inside a quoted attribute value. Try removing quotes.</source>
<target state="translated">有引號的屬性值中不能出現內嵌運算式。請移除引號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VersionMustBeFirstInXmlDecl">
<source>XML attribute 'version' must be the first attribute in XML declaration.</source>
<target state="translated">XML 屬性 'version' 必須是 XML 宣告中的第一個屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeOrder">
<source>XML attribute '{0}' must appear before XML attribute '{1}'.</source>
<target state="translated">XML 屬性 '{0}' 必須出現在 XML 屬性 '{1}' 之前。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndEmbedded">
<source>Expected closing '%>' for embedded expression.</source>
<target state="translated">內嵌運算式必須以 '%>' 結尾</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndPI">
<source>Expected closing '?>' for XML processor instruction.</source>
<target state="translated">XML 處理器指示必須以 '?>' 結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndComment">
<source>Expected closing '-->' for XML comment.</source>
<target state="translated">XML 註解必須以 '-->' 結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlEndCData">
<source>Expected closing ']]>' for XML CDATA section.</source>
<target state="translated">XML CDATA 區段必須以 ']]>' 結尾。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSQuote">
<source>Expected matching closing single quote for XML attribute value.</source>
<target state="translated">XML 屬性值的結束單引號必須相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedQuote">
<source>Expected matching closing double quote for XML attribute value.</source>
<target state="translated">必須是對應的 XML 屬性值右雙引號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedLT">
<source>Expected beginning '<' for an XML tag.</source>
<target state="translated">XML 標記應以 '<' 開頭。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StartAttributeValue">
<source>Expected quoted XML attribute value or embedded expression.</source>
<target state="translated">必須為引號 XML 屬性值或內嵌運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDiv">
<source>Expected '/' for XML end tag.</source>
<target state="translated">XML 結束標記必須是 '/'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoXmlAxesLateBinding">
<source>XML axis properties do not support late binding.</source>
<target state="translated">XML 軸屬性不支援晚期繫結。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlStartNameChar">
<source>Character '{0}' ({1}) is not allowed at the beginning of an XML name.</source>
<target state="translated">XML 名稱的開頭不可使用字元 '{0}' ({1})。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlNameChar">
<source>Character '{0}' ({1}) is not allowed in an XML name.</source>
<target state="translated">XML 名稱中不可使用字元 '{0}' ({1})。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlCommentChar">
<source>Character sequence '--' is not allowed in an XML comment.</source>
<target state="translated">XML 註解中不可有字元順序 '--'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EmbeddedExpression">
<source>An embedded expression cannot be used here.</source>
<target state="translated">內嵌運算式不能用在這裡。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlWhiteSpace">
<source>Missing required white space.</source>
<target state="translated">遺漏必要的空白字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalProcessingInstructionName">
<source>XML processing instruction name '{0}' is not valid.</source>
<target state="translated">XML 處理指示名稱 '{0}' 無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DTDNotSupported">
<source>XML DTDs are not supported.</source>
<target state="translated">不支援 XML DTD。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlWhiteSpace">
<source>White space cannot appear here.</source>
<target state="translated">空白字元不可出現在這裡。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSColon">
<source>Expected closing ';' for XML entity.</source>
<target state="translated">XML 實體必須以 ';' 結尾</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlBeginEmbedded">
<source>Expected '%=' at start of an embedded expression.</source>
<target state="translated">內嵌運算式的開頭必須是 '%='。</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlEntityReference">
<source>XML entity references are not supported.</source>
<target state="translated">不支援 XML 實體參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeValue1">
<source>Attribute value is not valid; expecting '{0}'.</source>
<target state="translated">屬性值無效,必須是 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAttributeValue2">
<source>Attribute value is not valid; expecting '{0}' or '{1}'.</source>
<target state="translated">屬性值無效,必須是 '{0}' 或 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReservedXmlNamespace">
<source>Prefix '{0}' cannot be bound to namespace name reserved for '{1}'.</source>
<target state="translated">前置詞 '{0}' 無法繫結至為 '{1}' 保留的命名空間名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalDefaultNamespace">
<source>Namespace declaration with prefix cannot have an empty value inside an XML literal.</source>
<target state="translated">具有前置字元的命名空間宣告在 XML 常值中不能有空值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QualifiedNameNotAllowed">
<source>':' is not allowed. XML qualified names cannot be used in this context.</source>
<target state="translated">'不允許 ':'。XML 限定名稱不能用在此內容中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedXmlns">
<source>Namespace declaration must start with 'xmlns'.</source>
<target state="translated">命名空間宣告必須要使用 'xmlns' 開頭。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalXmlnsPrefix">
<source>Element names cannot use the 'xmlns' prefix.</source>
<target state="translated">項目名稱不能使用 'xmlns' 前置字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlFeaturesNotAvailable">
<source>XML literals and XML axis properties are not available. Add references to System.Xml, System.Xml.Linq, and System.Core or other assemblies declaring System.Linq.Enumerable, System.Xml.Linq.XElement, System.Xml.Linq.XName, System.Xml.Linq.XAttribute and System.Xml.Linq.XNamespace types.</source>
<target state="translated">無法使用 XML 常值與 XML 軸屬性。請將參考加入 System.Xml、System.Xml.Linq、System.Core,或其他宣告 System.Linq.Enumerable、System.Xml.Linq.XElement、System.Xml.Linq.XName、System.Xml.Linq.XAttribute 和 System.Xml.Linq.XNamespace 類型的組件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnableToReadUacManifest2">
<source>Unable to open Win32 manifest file '{0}' : {1}</source>
<target state="translated">無法開啟 Win32 資訊清單檔 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseValueForXmlExpression3">
<source>Cannot convert '{0}' to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'.</source>
<target state="translated">無法將 '{0}' 轉換成 '{1}'。您可使用 'Value' 屬性來取得 '{2}' 第一個元素之字串值。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseValueForXmlExpression3_Title">
<source>Cannot convert IEnumerable(Of XElement) to String</source>
<target state="translated">無法將 IEnumerable(Of XElement) 轉換成字串</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeMismatchForXml3">
<source>Value of type '{0}' cannot be converted to '{1}'. You can use the 'Value' property to get the string value of the first element of '{2}'.</source>
<target state="translated">類型 '{0}' 的值無法轉換成 '{1}'。您可以使用 'Value' 屬性,取得 '{2}' 第一個元素的字串值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryOperandsForXml4">
<source>Operator '{0}' is not defined for types '{1}' and '{2}'. You can use the 'Value' property to get the string value of the first element of '{3}'.</source>
<target state="translated">未對類型 '{1}' 和 '{2}' 定義運算子 '{0}'。您可使用 'Value' 屬性取得 '{3}' 第一個元素的字串值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FullWidthAsXmlDelimiter">
<source>Full width characters are not valid as XML delimiters.</source>
<target state="translated">全形字元不能做為 XML 分隔符號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSubsystemVersion">
<source>The value '{0}' is not a valid subsystem version. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise.</source>
<target state="translated">值 '{0}' 不是有效的子系統版本。ARM 或 AppContainerExe 的版本必須是 6.02 (含) 以上,而其他則必須是 4.00 (含) 以上。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidFileAlignment">
<source>Invalid file section alignment '{0}'</source>
<target state="translated">無效的檔案區段記憶體對齊 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidOutputName">
<source>Invalid output name: {0}</source>
<target state="translated">無效的輸出名稱: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidDebugInformationFormat">
<source>Invalid debug information format: {0}</source>
<target state="translated">無效的偵錯資訊格式: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_LibAnycpu32bitPreferredConflict">
<source>/platform:anycpu32bitpreferred can only be used with /t:exe, /t:winexe and /t:appcontainerexe.</source>
<target state="translated">/platform:anycpu32bitpreferred 只能搭配 /t:exe、/t:winexe 和 /t:appcontainerexe 一起使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedAccess">
<source>Expression has the type '{0}' which is a restricted type and cannot be used to access members inherited from 'Object' or 'ValueType'.</source>
<target state="translated">運算式的類型為 '{0}',其為受限制的類型且不可用以存取繼承自 'Object' 或 'ValueType' 的成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedConversion1">
<source>Expression of type '{0}' cannot be converted to 'Object' or 'ValueType'.</source>
<target state="translated">類型 '{0}' 的運算式無法轉換成 'Object' 或 'ValueType'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoTypecharInLabel">
<source>Type characters are not allowed in label identifiers.</source>
<target state="translated">標籤識別項中不允許類型字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedType1">
<source>'{0}' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement.</source>
<target state="translated">'{0}' 不可為 Null,且不可用做為陣列元素、欄位、匿名類型成員、類型引數、'ByRef' 參數或傳回陳述式的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoTypecharInAlias">
<source>Type characters are not allowed on Imports aliases.</source>
<target state="translated">Imports 別名上不允許類型字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAccessibleConstructorOnBase">
<source>Class '{0}' has no accessible 'Sub New' and cannot be inherited.</source>
<target state="translated">類別 '{0}' 沒有可存取的 'Sub New',且無法被繼承。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadStaticLocalInStruct">
<source>Local variables within methods of structures cannot be declared 'Static'.</source>
<target state="translated">結構方法中的區域變數無法宣告為 'Static'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateLocalStatic1">
<source>Static local variable '{0}' is already declared.</source>
<target state="translated">靜態區域變數 '{0}' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImportAliasConflictsWithType2">
<source>Imports alias '{0}' conflicts with '{1}' declared in the root namespace.</source>
<target state="translated">Imports 別名 '{0}' 和根命名空間中宣告的 '{1}' 衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantShadowAMustOverride1">
<source>'{0}' cannot shadow a method declared 'MustOverride'.</source>
<target state="translated">'{0}' 不可遮蔽宣告為 'MustOverride' 的方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleEventImplMismatch3">
<source>Event '{0}' cannot implement event '{2}.{1}' because its delegate type does not match the delegate type of another event implemented by '{0}'.</source>
<target state="translated">事件 '{0}' 無法實作事件 '{2}.{1}',因為其委派類型與其他以 '{0}' 實作的事件之委派類型不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadSpecifierCombo2">
<source>'{0}' and '{1}' cannot be combined.</source>
<target state="translated">'無法結合 '{0}' 和 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustBeOverloads2">
<source>{0} '{1}' must be declared 'Overloads' because another '{1}' is declared 'Overloads' or 'Overrides'.</source>
<target state="translated">{0} '{1}' 必須宣告為 'Overloads',因為另一個 '{1}' 已宣告為 'Overloads' 或 'Overrides'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustOverridesInClass1">
<source>'{0}' must be declared 'MustInherit' because it contains methods declared 'MustOverride'.</source>
<target state="translated">'{0}' 必須宣告為 'MustInherit',因為其包含宣告為 'MustOverride' 的方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_HandlesSyntaxInClass">
<source>'Handles' in classes must specify a 'WithEvents' variable, 'MyBase', 'MyClass' or 'Me' qualified with a single identifier.</source>
<target state="translated">'類別中的 'Handles' 必須指定以單一識別項限定的 'WithEvents' 變數、'MyBase'、'MyClass' 或 'Me'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynthMemberShadowsMustOverride5">
<source>'{0}', implicitly declared for {1} '{2}', cannot shadow a 'MustOverride' method in the base {3} '{4}'.</source>
<target state="translated">'為 {1} '{2}' 隱含宣告的 '{0}',無法遮蔽基底 {3} '{4}' 中的 'MustOverride' 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotOverrideInAccessibleMember">
<source>'{0}' cannot override '{1}' because it is not accessible in this context.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為在此內容中無法存取它。</target>
<note />
</trans-unit>
<trans-unit id="ERR_HandlesSyntaxInModule">
<source>'Handles' in modules must specify a 'WithEvents' variable qualified with a single identifier.</source>
<target state="translated">'模組中的 'Handles' 必須指定以單一識別項限定的 'WithEvents' 變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNotOpRequiresReferenceTypes1">
<source>'IsNot' requires operands that have reference types, but this operand has the value type '{0}'.</source>
<target state="translated">'IsNot' 需要具有參考類型的運算元,但此運算元為實值類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClashWithReservedEnumMember1">
<source>'{0}' conflicts with the reserved member by this name that is implicitly declared in all enums.</source>
<target state="translated">'{0}' 與使用此名稱的保留成員互相衝突,此名稱已在所有列舉中隱含宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultiplyDefinedEnumMember2">
<source>'{0}' is already declared in this {1}.</source>
<target state="translated">'在此 {1} 中已宣告 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadUseOfVoid">
<source>'System.Void' can only be used in a GetType expression.</source>
<target state="translated">'System.Void' 只能使用於 GetType 運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventImplMismatch5">
<source>Event '{0}' cannot implement event '{1}' on interface '{2}' because their delegate types '{3}' and '{4}' do not match.</source>
<target state="translated">事件 '{0}' 無法在介面 '{2}' 上實作事件 '{1}',因為它們的委派類型 '{3}' 和 '{4}' 不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypeUnavailable3">
<source>Type '{0}' in assembly '{1}' has been forwarded to assembly '{2}'. Either a reference to '{2}' is missing from your project or the type '{0}' is missing from assembly '{2}'.</source>
<target state="translated">組件 '{1}' 中的類型 '{0}',已轉送至組件 '{2}'。專案中遺漏對 '{2}' 的參考,或者組件 '{2}' 中遺漏類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeFwdCycle2">
<source>'{0}' in assembly '{1}' has been forwarded to itself and so is an unsupported type.</source>
<target state="translated">'組件 '{1}' 中的 '{0}' 已轉送至其本身,所以不支援該類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeInCCExpression">
<source>Non-intrinsic type names are not allowed in conditional compilation expressions.</source>
<target state="translated">條件式編譯運算式中不允許非內建的類型名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadCCExpression">
<source>Syntax error in conditional compilation expression.</source>
<target state="translated">條件式編譯運算式中的語法錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VoidArrayDisallowed">
<source>Arrays of type 'System.Void' are not allowed in this expression.</source>
<target state="translated">此運算式中不允許類型 'System.Void' 的陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MetadataMembersAmbiguous3">
<source>'{0}' is ambiguous because multiple kinds of members with this name exist in {1} '{2}'.</source>
<target state="translated">'因為在 {1} '{2}' 中有多種具備此名稱的成員,因而 '{0}' 模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOfExprAlwaysFalse2">
<source>Expression of type '{0}' can never be of type '{1}'.</source>
<target state="translated">類型 '{0}' 的運算式不能為類型 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyPrivatePartialMethods1">
<source>Partial methods must be declared 'Private' instead of '{0}'.</source>
<target state="translated">部分方法必須宣告為 'Private',而非 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodsMustBePrivate">
<source>Partial methods must be declared 'Private'.</source>
<target state="translated">部分方法必須宣告為 'Private'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyOnePartialMethodAllowed2">
<source>Method '{0}' cannot be declared 'Partial' because only one method '{1}' can be marked 'Partial'.</source>
<target state="translated">方法 '{0}' 不可宣告為 'Partial',因為只有一個方法 '{1}' 可標記為 'Partial'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyOneImplementingMethodAllowed3">
<source>Method '{0}' cannot implement partial method '{1}' because '{2}' already implements it. Only one method can implement a partial method.</source>
<target state="translated">方法 '{0}' 無法實作部分方法 '{1}',因為 '{2}' 已實作該方法。只有一個方法可實作部分方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodMustBeEmpty">
<source>Partial methods must have empty method bodies.</source>
<target state="translated">部分方法的方法主體必須是空的。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodsMustBeSub1">
<source>'{0}' cannot be declared 'Partial' because partial methods must be Subs.</source>
<target state="translated">'{0}' 不可宣告為 'Partial',因為部分方法必須是 Sub。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodGenericConstraints2">
<source>Method '{0}' does not have the same generic constraints as the partial method '{1}'.</source>
<target state="translated">方法 '{0}' 沒有與部分方法 '{1}' 相同的泛型條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialDeclarationImplements1">
<source>Partial method '{0}' cannot use the 'Implements' keyword.</source>
<target state="translated">部分方法 '{0}' 不可使用 'Implements' 關鍵字。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoPartialMethodInAddressOf1">
<source>'AddressOf' cannot be applied to '{0}' because '{0}' is a partial method without an implementation.</source>
<target state="translated">'AddressOf' 無法套用至 '{0}',因為 '{0}' 是沒有實作的部分方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementationMustBePrivate2">
<source>Method '{0}' must be declared 'Private' in order to implement partial method '{1}'.</source>
<target state="translated">方法 '{0}' 必須宣告為 'Private',才能實作部分方法 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodParamNamesMustMatch3">
<source>Parameter name '{0}' does not match the name of the corresponding parameter, '{1}', defined on the partial method declaration '{2}'.</source>
<target state="translated">參數名稱 '{0}' 與部分方法宣告 '{2}' 中所定義之對應參數 '{1}' 的名稱不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodTypeParamNameMismatch3">
<source>Name of type parameter '{0}' does not match '{1}', the corresponding type parameter defined on the partial method declaration '{2}'.</source>
<target state="translated">類型參數 '{0}' 的名稱,與部分方法宣告 '{2}' 中所定義的對應類型參數 '{1}' 不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeSharedProperty1">
<source>'Shared' attribute property '{0}' cannot be the target of an assignment.</source>
<target state="translated">'Shared' 屬性 (Attribute) 的屬性 (Property) '{0}',不可是指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeReadOnlyProperty1">
<source>'ReadOnly' attribute property '{0}' cannot be the target of an assignment.</source>
<target state="translated">'ReadOnly' 屬性 (Attribute) 的屬性 (Property) '{0}',不可是指派的目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateResourceName1">
<source>Resource name '{0}' cannot be used more than once.</source>
<target state="translated">資源名稱 '{0}' 不可重複使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateResourceFileName1">
<source>Each linked resource and module must have a unique filename. Filename '{0}' is specified more than once in this assembly.</source>
<target state="translated">每個連結的資源與模組,都必須要有不重複的檔名。檔名 '{0}' 在此組件中指定了一次以上。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeMustBeClassNotStruct1">
<source>'{0}' cannot be used as an attribute because it is not a class.</source>
<target state="translated">'無法將 '{0}' 用做為屬性,因為其非類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeMustInheritSysAttr">
<source>'{0}' cannot be used as an attribute because it does not inherit from 'System.Attribute'.</source>
<target state="translated">'無法將 '{0}' 用做為屬性,因為其非繼承自 'System.Attribute'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeCannotBeAbstract">
<source>'{0}' cannot be used as an attribute because it is declared 'MustInherit'.</source>
<target state="translated">'無法將 '{0}' 用做為屬性,因為其宣告為 'MustInherit'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnableToOpenResourceFile1">
<source>Unable to open resource file '{0}': {1}</source>
<target state="translated">無法開啟資源檔 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicProperty1">
<source>Attribute member '{0}' cannot be the target of an assignment because it is not declared 'Public'.</source>
<target state="translated">屬性成員 '{0}' 不可是指派的目標,因為其未宣告為 'Public'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_STAThreadAndMTAThread0">
<source>'System.STAThreadAttribute' and 'System.MTAThreadAttribute' cannot both be applied to the same method.</source>
<target state="translated">'System.STAThreadAttribute' 和 'System.MTAThreadAttribute' 無法同時套用至同一個方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IndirectUnreferencedAssembly4">
<source>Project '{0}' makes an indirect reference to assembly '{1}', which contains '{2}'. Add a file reference to '{3}' to your project.</source>
<target state="translated">專案 '{0}' 會間接參考含有 '{2}' 的組件 '{1}'。請在您的專案中加入 '{3}' 的檔案參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicType1">
<source>Type '{0}' cannot be used in an attribute because it is not declared 'Public'.</source>
<target state="translated">無法在屬性中使用類型 '{0}',因為其未宣告為 'Public'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeNonPublicContType2">
<source>Type '{0}' cannot be used in an attribute because its container '{1}' is not declared 'Public'.</source>
<target state="translated">無法在屬性中使用類型 '{0}',因為其容器 '{1}' 未宣告為 'Public'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnNonEmptySubOrFunction">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Sub, Function, or Operator with a non-empty body.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至非空白主體的 Sub、Function 或 Operator。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportNotLegalOnDeclare">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Declare.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至 Declare。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportNotLegalOnGetOrSet">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a Get or Set.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至 Get 或 Set。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnGenericSubOrFunction">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to a method that is generic or contained in a generic type.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至泛型方法,或套用至包含在泛型類型中的方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassOnGeneric">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type.</source>
<target state="translated">'Microsoft.VisualBasic.ComClassAttribute' 無法套用至泛型類別,或套用至包含在泛型類型內的類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnInstanceMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to instance method.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至執行個體方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnInterfaceMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to interface methods.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至介面方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportNotLegalOnEventMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to 'AddHandler', 'RemoveHandler' or 'RaiseEvent' method.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至 'AddHandler'、'RemoveHandler' 或 'RaiseEvent' 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyBadArguments">
<source>Friend assembly reference '{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified.</source>
<target state="translated">Friend 組件參考 '{0}' 無效。InternalsVisibleTo 宣告不可指定版本、文化特性、公開金鑰語彙基元或處理器架構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyStrongNameRequired">
<source>Friend assembly reference '{0}' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations.</source>
<target state="translated">Friend 組件參考 '{0}' 無效。以強式名稱簽署的組件,在其 InternalsVisibleTo 宣告中必須指定公開金鑰。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyNameInvalid">
<source>Friend declaration '{0}' is invalid and cannot be resolved.</source>
<target state="translated">Friend 宣告 '{0}' 無效,無法解析。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendAssemblyBadAccessOverride2">
<source>Member '{0}' cannot override member '{1}' defined in another assembly/project because the access modifier 'Protected Friend' expands accessibility. Use 'Protected' instead.</source>
<target state="translated">成員 '{0}' 無法覆寫在另一個組件/專案中定義的成員 '{1}',因為存取修飾詞 'Protected Friend' 會展開存取範圍。請改用 'Protected'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfLocalBeforeDeclaration1">
<source>Local variable '{0}' cannot be referred to before it is declared.</source>
<target state="translated">在宣告區域變數 '{0}' 之前,無法參考該區域變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UseOfKeywordFromModule1">
<source>'{0}' is not valid within a Module.</source>
<target state="translated">'{0}' 在 Module 中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BogusWithinLineIf">
<source>Statement cannot end a block outside of a line 'If' statement.</source>
<target state="translated">陳述式不能在 'If' 陳述式行之外結束區塊。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CharToIntegralTypeMismatch1">
<source>'Char' values cannot be converted to '{0}'. Use 'Microsoft.VisualBasic.AscW' to interpret a character as a Unicode value or 'Microsoft.VisualBasic.Val' to interpret it as a digit.</source>
<target state="translated">'Char' 的值無法轉換成 '{0}'。請使用 'Microsoft.VisualBasic.AscW' 將字元解譯為 Unicode 值,或使用 'Microsoft.VisualBasic.Val' 將其解譯為數字。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IntegralToCharTypeMismatch1">
<source>'{0}' values cannot be converted to 'Char'. Use 'Microsoft.VisualBasic.ChrW' to interpret a numeric value as a Unicode character or first convert it to 'String' to produce a digit.</source>
<target state="translated">'{0}' 的值無法轉換成 'Char'。請使用 'Microsoft.VisualBasic.ChrW' 將數值解譯為 Unicode 字元,或先將其轉換成 'String',以產生數字。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoDirectDelegateConstruction1">
<source>Delegate '{0}' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.</source>
<target state="translated">委派 '{0}' 必須使用 'AddressOf' 運算式或 Lambda 運算式,做為其建構函式唯一的引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodMustBeFirstStatementOnLine">
<source>Method declaration statements must be the first statement on a logical line.</source>
<target state="translated">方法宣告陳述式必須是邏輯程式敘述行中的第一個陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttrAssignmentNotFieldOrProp1">
<source>'{0}' cannot be named as a parameter in an attribute specifier because it is not a field or property.</source>
<target state="translated">'{0}' 不是欄位或屬性 (Property),所以無法命名為屬性 (Attribute) 規範中的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowsObjectComparison1">
<source>Option Strict On disallows operands of type Object for operator '{0}'. Use the 'Is' operator to test for object identity.</source>
<target state="translated">Option Strict 為 On 時,不可為運算子 '{0}' 使用 Object 類型的運算元。請使用 'Is' 運算子來測試物件識別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoConstituentArraySizes">
<source>Bounds can be specified only for the top-level array when initializing an array of arrays.</source>
<target state="translated">在初始化陣列的陣列時,只可以指定最上層陣列的界限。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FileAttributeNotAssemblyOrModule">
<source>'Assembly' or 'Module' expected.</source>
<target state="translated">'必須是 'Assembly' 或 'Module'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FunctionResultCannotBeIndexed1">
<source>'{0}' has no parameters and its return type cannot be indexed.</source>
<target state="translated">'{0}' 沒有參數,且無法對其傳回類型編製索引。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentSyntax">
<source>Comma, ')', or a valid expression continuation expected.</source>
<target state="translated">必須是逗號、')' 或有效的運算式接續符號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedResumeOrGoto">
<source>'Resume' or 'GoTo' expected.</source>
<target state="translated">'必須是 'Resume' 或 'GoTo'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAssignmentOperator">
<source>'=' expected.</source>
<target state="translated">'必須有 '='。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgAlsoOmitted2">
<source>Parameter '{0}' in '{1}' already has a matching omitted argument.</source>
<target state="translated">'{1}' 中的參數 '{0}' 已有相符的省略引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotCallEvent1">
<source>'{0}' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.</source>
<target state="translated">'{0}' 為一事件,不可直接呼叫。請使用 'RaiseEvent' 陳述式引發事件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForEachCollectionDesignPattern1">
<source>Expression is of type '{0}', which is not a collection type.</source>
<target state="translated">運算式類型為 '{0}',非集合類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DefaultValueForNonOptionalParam">
<source>Default values cannot be supplied for parameters that are not declared 'Optional'.</source>
<target state="translated">無法提供預設值給未宣告為 'Optional' 的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDotAfterMyBase">
<source>'MyBase' must be followed by '.' and an identifier.</source>
<target state="translated">'在 'MyBase' 之後必須接著 '.' 及一個識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDotAfterMyClass">
<source>'MyClass' must be followed by '.' and an identifier.</source>
<target state="translated">'在 'MyClass' 之後必須接著 '.' 及一個識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictArgumentCopyBackNarrowing3">
<source>Option Strict On disallows narrowing from type '{1}' to type '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument.</source>
<target state="translated">Option Strict 為 On 時,不可將 'ByRef' 參數 '{0}' 的值複製回相對應的引數,而將類型 '{1}' 縮減為類型 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LbElseifAfterElse">
<source>'#ElseIf' cannot follow '#Else' as part of a '#If' block.</source>
<target state="translated">'#ElseIf' 不可以跟隨在 '#Else' 之後做為 '#If' 區塊的一部分。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StandaloneAttribute">
<source>Attribute specifier is not a complete statement. Use a line continuation to apply the attribute to the following statement.</source>
<target state="translated">屬性規範不是完整的陳述式。請使用行接續符號將屬性套用至下列陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoUniqueConstructorOnBase2">
<source>Class '{0}' must declare a 'Sub New' because its base class '{1}' has more than one accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">類別 '{0}' 必須宣告 'Sub New',因為其基底類別 '{1}' 有一個以上不用引數即可呼叫的可存取 'Sub New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtraNextVariable">
<source>'Next' statement names more variables than there are matching 'For' statements.</source>
<target state="translated">'Next' 陳述式命名超過符合 'For' 陳述式的變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RequiredNewCallTooMany2">
<source>First statement of this 'Sub New' must be a call to 'MyBase.New' or 'MyClass.New' because base class '{0}' of '{1}' has more than one accessible 'Sub New' that can be called with no arguments.</source>
<target state="translated">此 'Sub New' 的第一個陳述式,必須呼叫 'MyBase.New' 或 'MyClass.New',因為 '{1}' 的基底類別 '{0}' 有一個以上不使用引數即可呼叫的可存取 'Sub New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForCtlVarArraySizesSpecified">
<source>Array declared as for loop control variable cannot be declared with an initial size.</source>
<target state="translated">宣告為 for 迴圈控制變數的陣列不能宣告它的初始大小。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadFlagsOnNewOverloads">
<source>The '{0}' keyword is used to overload inherited members; do not use the '{0}' keyword when overloading 'Sub New'.</source>
<target state="translated">'{0}' 關鍵字是用以多載繼承的成員; 當多載 'Sub New' 時,請勿使用 '{0}' 關鍵字。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharOnGenericParam">
<source>Type character cannot be used in a type parameter declaration.</source>
<target state="translated">類型字元無法在類型參數宣告中使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooFewGenericArguments1">
<source>Too few type arguments to '{0}'.</source>
<target state="translated">'{0}' 的類型引數太少。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyGenericArguments1">
<source>Too many type arguments to '{0}'.</source>
<target state="translated">'{0}' 的類型引數太多。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericConstraintNotSatisfied2">
<source>Type argument '{0}' does not inherit from or implement the constraint type '{1}'.</source>
<target state="translated">類型引數 '{0}' 並未繼承或實作條件約束類型 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOrMemberNotGeneric1">
<source>'{0}' has no type parameters and so cannot have type arguments.</source>
<target state="translated">'{0}' 沒有類型參數,因此不可有類型引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewIfNullOnGenericParam">
<source>'New' cannot be used on a type parameter that does not have a 'New' constraint.</source>
<target state="translated">'New' 無法在沒有 'New' 條件約束的類型參數上使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleClassConstraints1">
<source>Type parameter '{0}' can only have one constraint that is a class.</source>
<target state="translated">類型參數 '{0}' 只可有一個為類別的條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstNotClassInterfaceOrTypeParam1">
<source>Type constraint '{0}' must be either a class, interface or type parameter.</source>
<target state="translated">類型條件約束 '{0}' 必須是類別、介面或類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateTypeParamName1">
<source>Type parameter already declared with name '{0}'.</source>
<target state="translated">類型參數已使用名稱 '{0}' 進行宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnboundTypeParam2">
<source>Type parameter '{0}' for '{1}' cannot be inferred.</source>
<target state="translated">無法推斷 '{1}' 的類型參數 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsOperatorGenericParam1">
<source>'Is' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a type parameter with no class constraint.</source>
<target state="translated">'類型 '{0}' 的 'Is' 運算元只能與 'Nothing' 進行比較,因為 '{0}' 是沒有類別條件約束的類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentCopyBackNarrowing3">
<source>Copying the value of 'ByRef' parameter '{0}' back to the matching argument narrows from type '{1}' to type '{2}'.</source>
<target state="translated">將 'ByRef' 參數的值 '{0}' 複製回對稱的引數,會從類型 '{1}' 縮減到 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ShadowingGenericParamWithMember1">
<source>'{0}' has the same name as a type parameter.</source>
<target state="translated">'{0}' 與類型參數擁有相同的名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericParamBase2">
<source>{0} '{1}' cannot inherit from a type parameter.</source>
<target state="translated">{0} '{1}' 無法繼承自類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsGenericParam">
<source>Type parameter not allowed in 'Implements' clause.</source>
<target state="translated">Implements' 子句中不允許類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnlyNullLowerBound">
<source>Array lower bounds can be only '0'.</source>
<target state="translated">陣列的下限只能是 '0'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassConstraintNotInheritable1">
<source>Type constraint cannot be a 'NotInheritable' class.</source>
<target state="translated">類型條件約束不可以為 'NotInheritable' 類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintIsRestrictedType1">
<source>'{0}' cannot be used as a type constraint.</source>
<target state="translated">'{0}' 不能用做為類型條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericParamsOnInvalidMember">
<source>Type parameters cannot be specified on this declaration.</source>
<target state="translated">不可以在這個宣告上指定類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericArgsOnAttributeSpecifier">
<source>Type arguments are not valid because attributes cannot be generic.</source>
<target state="translated">類型引數無效,因為屬性不可以是泛型的。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttrCannotBeGenerics">
<source>Type parameters, generic types or types contained in generic types cannot be used as attributes.</source>
<target state="translated">類型參數、泛型類型或泛型類型中所包含的類型不能當做屬性使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadStaticLocalInGenericMethod">
<source>Local variables within generic methods cannot be declared 'Static'.</source>
<target state="translated">泛型方法內的區域變數不可以宣告為 'Static'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SyntMemberShadowsGenericParam3">
<source>{0} '{1}' implicitly defines a member '{2}' which has the same name as a type parameter.</source>
<target state="translated">{0} '{1}' 隱含定義成員 '{2}',該成員與類型參數擁有相同的名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintAlreadyExists1">
<source>Constraint type '{0}' already specified for this type parameter.</source>
<target state="translated">已為此類型參數指定條件約束類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfacePossiblyImplTwice2">
<source>Cannot implement interface '{0}' because its implementation could conflict with the implementation of another implemented interface '{1}' for some type arguments.</source>
<target state="translated">無法實作介面 '{0}',因為它的實作可能與某些類型引數的另一個實作介面 '{1}' 之實作互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ModulesCannotBeGeneric">
<source>Modules cannot be generic.</source>
<target state="translated">模組不可以是泛型的。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GenericClassCannotInheritAttr">
<source>Classes that are generic or contained in a generic type cannot inherit from an attribute class.</source>
<target state="translated">泛型類別或包含在泛型類型中的類別不可以繼承自屬性類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DeclaresCantBeInGeneric">
<source>'Declare' statements are not allowed in generic types or types contained in generic types.</source>
<target state="translated">'泛型類型或包含在泛型類型中的類型,不可使用 'Declare' 陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverrideWithConstraintMismatch2">
<source>'{0}' cannot override '{1}' because they differ by type parameter constraints.</source>
<target state="translated">'{0}' 無法覆寫 '{1}',因為其類型參數條件約束不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ImplementsWithConstraintMismatch3">
<source>'{0}' cannot implement '{1}.{2}' because they differ by type parameter constraints.</source>
<target state="translated">'{0}' 無法實作 '{1}.{2}',因為它們的類型參數條件約束不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OpenTypeDisallowed">
<source>Type parameters or types constructed with type parameters are not allowed in attribute arguments.</source>
<target state="translated">屬性引數中不允許類型參數或以類型參數建構的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_HandlesInvalidOnGenericMethod">
<source>Generic methods cannot use 'Handles' clause.</source>
<target state="translated">泛型方法不可以使用 'Handles' 子句。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleNewConstraints">
<source>'New' constraint cannot be specified multiple times for the same type parameter.</source>
<target state="translated">'不能針對相同的類型參數多次指定 'New' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MustInheritForNewConstraint2">
<source>Type argument '{0}' is declared 'MustInherit' and does not satisfy the 'New' constraint for type parameter '{1}'.</source>
<target state="translated">類型引數 '{0}' 宣告為 'MustInherit',且不符合類型參數 '{1}' 的 'New' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoSuitableNewForNewConstraint2">
<source>Type argument '{0}' must have a public parameterless instance constructor to satisfy the 'New' constraint for type parameter '{1}'.</source>
<target state="translated">類型引數 '{0}' 必須擁有公用的無參數執行個體建構函式,才能滿足類型參數 '{1}' 的 'New' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadGenericParamForNewConstraint2">
<source>Type parameter '{0}' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New' constraint for type parameter '{1}'.</source>
<target state="translated">類型參數 '{0}' 必須擁有 'New' 條件約束或 'Structure' 條件約束,才能符合類型參數 '{1}' 的 'New' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewArgsDisallowedForTypeParam">
<source>Arguments cannot be passed to a 'New' used on a type parameter.</source>
<target state="translated">引數無法傳遞至類型參數上所使用的 'New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateRawGenericTypeImport1">
<source>Generic type '{0}' cannot be imported more than once.</source>
<target state="translated">不可匯入一次以上的泛型類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoTypeArgumentCountOverloadCand1">
<source>Overload resolution failed because no accessible '{0}' accepts this number of type arguments.</source>
<target state="translated">因為沒有可存取的 '{0}' 接受此數目的類型引數,所以多載解析失敗。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeArgsUnexpected">
<source>Type arguments unexpected.</source>
<target state="translated">未預期的類型引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameSameAsMethodTypeParam1">
<source>'{0}' is already declared as a type parameter of this method.</source>
<target state="translated">'{0}' 已經宣告為此方法的類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamNameFunctionNameCollision">
<source>Type parameter cannot have the same name as its defining function.</source>
<target state="translated">類型參數不可以與其定義函式擁有相同的名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadConstraintSyntax">
<source>Type or 'New' expected.</source>
<target state="translated">必須是類型或 'New'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OfExpected">
<source>'Of' required when specifying type arguments for a generic type or method.</source>
<target state="translated">'為泛型類型或方法指定類型引數時需要 'Of'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayOfRawGenericInvalid">
<source>'(' unexpected. Arrays of uninstantiated generic types are not allowed.</source>
<target state="translated">'出現未預期的 '('。不可使用未執行個體化的泛型類型陣列。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForEachAmbiguousIEnumerable1">
<source>'For Each' on type '{0}' is ambiguous because the type implements multiple instantiations of 'System.Collections.Generic.IEnumerable(Of T)'.</source>
<target state="translated">'類型 '{0}' 上的 'For Each' 模稜兩可,因為該類型實作了多個 'System.Collections.Generic.IEnumerable(Of T)' 具現化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNotOperatorGenericParam1">
<source>'IsNot' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a type parameter with no class constraint.</source>
<target state="translated">'類型 '{0}' 的 'IsNot' 運算元只能與 'Nothing' 進行比較,因為 '{0}' 是沒有類別條件約束的類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamQualifierDisallowed">
<source>Type parameters cannot be used as qualifiers.</source>
<target state="translated">類型參數不能當做限定詞使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamMissingCommaOrRParen">
<source>Comma or ')' expected.</source>
<target state="translated">必須是逗號或 ')'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamMissingAsCommaOrRParen">
<source>'As', comma or ')' expected.</source>
<target state="translated">'必須是 'As'、逗號或 ')'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleReferenceConstraints">
<source>'Class' constraint cannot be specified multiple times for the same type parameter.</source>
<target state="translated">'不能針對相同的類型參數多次指定 'Class' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultipleValueConstraints">
<source>'Structure' constraint cannot be specified multiple times for the same type parameter.</source>
<target state="translated">'不能針對相同的類型參數多次指定 'Structure' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewAndValueConstraintsCombined">
<source>'New' constraint and 'Structure' constraint cannot be combined.</source>
<target state="translated">'無法合併 'New' 條件約束和 'Structure' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RefAndValueConstraintsCombined">
<source>'Class' constraint and 'Structure' constraint cannot be combined.</source>
<target state="translated">'無法合併 'Class' 條件約束和 'Structure' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeArgForStructConstraint2">
<source>Type argument '{0}' does not satisfy the 'Structure' constraint for type parameter '{1}'.</source>
<target state="translated">類型引數 '{0}' 不符合類型參數 '{1}' 的 'Structure' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeArgForRefConstraint2">
<source>Type argument '{0}' does not satisfy the 'Class' constraint for type parameter '{1}'.</source>
<target state="translated">類型引數 '{0}' 不符合類型參數 '{1}' 的 'Class' 條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RefAndClassTypeConstrCombined">
<source>'Class' constraint and a specific class type constraint cannot be combined.</source>
<target state="translated">'無法合併 'Class' 條件約束和特定類別的類型條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ValueAndClassTypeConstrCombined">
<source>'Structure' constraint and a specific class type constraint cannot be combined.</source>
<target state="translated">'無法合併 'Structure' 條件約束和特定類別的類型條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintClashIndirectIndirect4">
<source>Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the indirect constraint '{2}' obtained from the type parameter constraint '{3}'.</source>
<target state="translated">從類型參數條件約束 '{1}' 取得的間接條件約束 '{0}',與從類型參數條件約束 '{3}' 取得的間接條件約束 '{2}',互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintClashDirectIndirect3">
<source>Constraint '{0}' conflicts with the indirect constraint '{1}' obtained from the type parameter constraint '{2}'.</source>
<target state="translated">條件約束 '{0}' 與從類型參數條件約束 '{2}' 取得的間接條件約束 '{1}' 互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintClashIndirectDirect3">
<source>Indirect constraint '{0}' obtained from the type parameter constraint '{1}' conflicts with the constraint '{2}'.</source>
<target state="translated">從類型參數條件約束 '{1}' 取得的間接條件約束 '{0}',與條件約束 '{2}' 互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintCycleLink2">
<source>
'{0}' is constrained to '{1}'.</source>
<target state="translated">
'{0}' 已限制為 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstraintCycle2">
<source>Type parameter '{0}' cannot be constrained to itself: {1}</source>
<target state="translated">類型參數 '{0}' 不可限制為其本身: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeParamWithStructConstAsConst">
<source>Type parameter with a 'Structure' constraint cannot be used as a constraint.</source>
<target state="translated">具有 'Structure' 條件約束的類型參數不可以當做條件約束使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableDisallowedForStructConstr1">
<source>'System.Nullable' does not satisfy the 'Structure' constraint for type parameter '{0}'. Only non-nullable 'Structure' types are allowed.</source>
<target state="translated">'System.Nullable' 不符合類型參數 '{0}' 的 'Structure' 條件約束。只可使用不可為 null 的 'Structure' 類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictingDirectConstraints3">
<source>Constraint '{0}' conflicts with the constraint '{1}' already specified for type parameter '{2}'.</source>
<target state="translated">條件約束 '{0}' 與已經指定給類型參數 '{2}' 的條件約束 '{1}' 互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceUnifiesWithInterface2">
<source>Cannot inherit interface '{0}' because it could be identical to interface '{1}' for some type arguments.</source>
<target state="translated">無法繼承介面 '{0}',因為它可能與某些類型引數的介面 '{1}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BaseUnifiesWithInterfaces3">
<source>Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' for some type arguments.</source>
<target state="translated">無法繼承介面 '{0}',因為它所繼承的介面 '{1}' 可能與某些類型引數之介面 '{2}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceBaseUnifiesWithBase4">
<source>Cannot inherit interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the interface '{3}' inherits for some type arguments.</source>
<target state="translated">無法繼承介面 '{0}',因為它所繼承的介面 '{1}' 可能與某些類型引數的介面 '{3}' 所繼承之介面 '{2}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterfaceUnifiesWithBase3">
<source>Cannot inherit interface '{0}' because it could be identical to interface '{1}' from which the interface '{2}' inherits for some type arguments.</source>
<target state="translated">無法繼承介面 '{0}',因為它可能與某些類型引數的介面 '{2}' 所繼承之介面 '{1}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassInheritsBaseUnifiesWithInterfaces3">
<source>Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to implemented interface '{2}' for some type arguments.</source>
<target state="translated">無法實作介面 '{0}',因為它所繼承的介面 '{1}' 可能與某些類型引數之實作介面 '{2}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassInheritsInterfaceBaseUnifiesWithBase4">
<source>Cannot implement interface '{0}' because the interface '{1}' from which it inherits could be identical to interface '{2}' from which the implemented interface '{3}' inherits for some type arguments.</source>
<target state="translated">無法實作介面 '{0}',因為它所繼承的介面 '{1}' 可能與某些類型引數的實作介面 '{3}' 所繼承之介面 '{2}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ClassInheritsInterfaceUnifiesWithBase3">
<source>Cannot implement interface '{0}' because it could be identical to interface '{1}' from which the implemented interface '{2}' inherits for some type arguments.</source>
<target state="translated">無法實作介面 '{0}',因為它可能與某些類型引數的實作介面 '{2}' 所繼承之介面 '{1}' 相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionalsCantBeStructGenericParams">
<source>Generic parameters used as optional parameter types must be class constrained.</source>
<target state="translated">用以做為選擇性參數類型的泛型參數,必須受到類別條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfNullableMethod">
<source>Methods of 'System.Nullable(Of T)' cannot be used as operands of the 'AddressOf' operator.</source>
<target state="translated">System.Nullable(Of T)' 的方法無法做為 'AddressOf' 運算子的運算元</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsOperatorNullable1">
<source>'Is' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a nullable type.</source>
<target state="translated">'類型 '{0}' 的 'Is' 運算元只能與 'Nothing' 進行比較,因為 '{0}' 是可為 Null 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IsNotOperatorNullable1">
<source>'IsNot' operand of type '{0}' can be compared only to 'Nothing' because '{0}' is a nullable type.</source>
<target state="translated">'類型 '{0}' 的 'IsNot' 運算元只能與 'Nothing' 進行比較,因為 '{0}' 是可為 Null 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ShadowingTypeOutsideClass1">
<source>'{0}' cannot be declared 'Shadows' outside of a class, structure, or interface.</source>
<target state="translated">'{0}' 不可在類別、結構或介面外部宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertySetParamCollisionWithValue">
<source>Property parameters cannot have the name 'Value'.</source>
<target state="translated">屬性參數的名稱不可為 'Value'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SxSIndirectRefHigherThanDirectRef3">
<source>The project currently contains references to more than one version of '{0}', a direct reference to version {2} and an indirect reference to version {1}. Change the direct reference to use version {1} (or higher) of {0}.</source>
<target state="translated">專案目前包含一個以上版本之 '{0}' 的參考、版本 {2} 的直接參考,以及版本 {1} 的間接參考。請變更直接參考以使用 {0} 的版本 {1} (或更新版本)。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateReferenceStrong">
<source>Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references.</source>
<target state="translated">已匯入具有相同識別的多個組件: '{0}' 和 '{1}'。請移除其中一個重複的參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateReference2">
<source>Project already has a reference to assembly '{0}'. A second reference to '{1}' cannot be added.</source>
<target state="translated">專案已經有組件 '{0}' 的參考。無法對 '{1}' 加入第二個參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalCallOrIndex">
<source>Illegal call expression or index expression.</source>
<target state="translated">不合法的呼叫運算式或索引運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictDefaultPropertyAttribute">
<source>Conflict between the default property and the 'DefaultMemberAttribute' defined on '{0}'.</source>
<target state="translated">預設屬性與 '{0}' 上定義的 'DefaultMemberAttribute' 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeUuid2">
<source>'{0}' cannot be applied because the format of the GUID '{1}' is not correct.</source>
<target state="translated">'無法套用 '{0}',因為 GUID '{1}' 的格式不正確。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassAndReservedAttribute1">
<source>'Microsoft.VisualBasic.ComClassAttribute' and '{0}' cannot both be applied to the same class.</source>
<target state="translated">'無法將 'Microsoft.VisualBasic.ComClassAttribute' 和 '{0}' 同時套用至相同的類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassRequiresPublicClass2">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because its container '{1}' is not declared 'Public'.</source>
<target state="translated">'Microsoft.VisualBasic.ComClassAttribute' 無法套用至 '{0}',因為其容器 '{1}' 未宣告為 'Public'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassReservedDispIdZero1">
<source>'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property.</source>
<target state="translated">'System.Runtime.InteropServices.DispIdAttribute' 無法套用至 '{0}',因為 'Microsoft.VisualBasic.ComClassAttribute' 為預設屬性保留的值為零。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassReservedDispId1">
<source>'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to '{0}' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero.</source>
<target state="translated">'System.Runtime.InteropServices.DispIdAttribute' 無法套用至 '{0}',因為 'Microsoft.VisualBasic.ComClassAttribute' 保留的值小於零。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassDuplicateGuids1">
<source>'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on '{0}' cannot have the same value.</source>
<target state="translated">'位於 '{0}' 的 'Microsoft.VisualBasic.ComClassAttribute' 之 'InterfaceId' 與 'EventsId' 參數,不可有相同的值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassCantBeAbstract0">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is declared 'MustInherit'.</source>
<target state="translated">'Microsoft.VisualBasic.ComClassAttribute' 無法套用至宣告為 'MustInherit' 的類別。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ComClassRequiresPublicClass1">
<source>'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to '{0}' because it is not declared 'Public'.</source>
<target state="translated">'Microsoft.VisualBasic.ComClassAttribute' 無法套用至 '{0}',因為其未宣告為 'Public'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnknownOperator">
<source>Operator declaration must be one of: +, -, *, \, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.</source>
<target state="translated">運算子宣告必須為下列其中之一: +、-、*、\、/、^、&、Like、Mod、And、Or、Xor、Not、<<、>>、=、<>、<、<=、>、>=、CType、IsTrue、IsFalse。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateConversionCategoryUsed">
<source>'Widening' and 'Narrowing' cannot be combined.</source>
<target state="translated">'無法合併 'Widening' 和 'Narrowing'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorNotOverloadable">
<source>Operator is not overloadable. Operator declaration must be one of: +, -, *, \, /, ^, &, Like, Mod, And, Or, Xor, Not, <<, >>, =, <>, <, <=, >, >=, CType, IsTrue, IsFalse.</source>
<target state="translated">運算子不可多載。運算子宣告必須為下列其中之一: +、-、*、\、/、^、&、Like、Mod、And、Or、Xor、Not、<<、>>、=、<>、<、<=、>、>=、CType、IsTrue、IsFalse。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidHandles">
<source>'Handles' is not valid on operator declarations.</source>
<target state="translated">'Handles' 在運算子宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidImplements">
<source>'Implements' is not valid on operator declarations.</source>
<target state="translated">'Implements' 在運算子宣告中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndOperatorExpected">
<source>'End Operator' expected.</source>
<target state="translated">'必須是 'End Operator'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndOperatorNotAtLineStart">
<source>'End Operator' must be the first statement on a line.</source>
<target state="translated">'End Operator' 必須是該行的第一個陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidEndOperator">
<source>'End Operator' must be preceded by a matching 'Operator'.</source>
<target state="translated">'End Operator' 之前必須搭配相對應的 'Operator'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExitOperatorNotValid">
<source>'Exit Operator' is not valid. Use 'Return' to exit an operator.</source>
<target state="translated">'Exit Operator' 無效。請使用 'Return' 結束運算子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamArrayIllegal1">
<source>'{0}' parameters cannot be declared 'ParamArray'.</source>
<target state="translated">'{0}' 參數不可宣告為 'ParamArray'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionalIllegal1">
<source>'{0}' parameters cannot be declared 'Optional'.</source>
<target state="translated">'{0}' 參數不可宣告為 'Optional'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorMustBePublic">
<source>Operators must be declared 'Public'.</source>
<target state="translated">運算子必須宣告為 'Public'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorMustBeShared">
<source>Operators must be declared 'Shared'.</source>
<target state="translated">運算子必須宣告為 'Shared'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadOperatorFlags1">
<source>Operators cannot be declared '{0}'.</source>
<target state="translated">運算子不可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OneParameterRequired1">
<source>Operator '{0}' must have one parameter.</source>
<target state="translated">運算子 '{0}' 必須要有一個參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TwoParametersRequired1">
<source>Operator '{0}' must have two parameters.</source>
<target state="translated">運算子 '{0}' 必須要有兩個參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OneOrTwoParametersRequired1">
<source>Operator '{0}' must have either one or two parameters.</source>
<target state="translated">運算子 '{0}' 必須要有一個或兩個參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvMustBeWideningOrNarrowing">
<source>Conversion operators must be declared either 'Widening' or 'Narrowing'.</source>
<target state="translated">轉換運算子必須宣告為 'Widening' 或 'Narrowing'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorDeclaredInModule">
<source>Operators cannot be declared in modules.</source>
<target state="translated">不能在模組中宣告運算子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSpecifierOnNonConversion1">
<source>Only conversion operators can be declared '{0}'.</source>
<target state="translated">只有轉換運算子可宣告為 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnaryParamMustBeContainingType1">
<source>Parameter of this unary operator must be of the containing type '{0}'.</source>
<target state="translated">此一元運算子的參數必須屬於包含類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BinaryParamMustBeContainingType1">
<source>At least one parameter of this binary operator must be of the containing type '{0}'.</source>
<target state="translated">此二元運算子至少必須要有一個參數屬於包含類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConvParamMustBeContainingType1">
<source>Either the parameter type or the return type of this conversion operator must be of the containing type '{0}'.</source>
<target state="translated">此轉換運算子的參數類型或傳回類型,必須屬於包含類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorRequiresBoolReturnType1">
<source>Operator '{0}' must have a return type of Boolean.</source>
<target state="translated">運算子 '{0}' 必須要有布林的傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToSameType">
<source>Conversion operators cannot convert from a type to the same type.</source>
<target state="translated">轉換運算子無法從類型轉換為相同的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToInterfaceType">
<source>Conversion operators cannot convert to an interface type.</source>
<target state="translated">轉換運算子無法轉換為介面類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToBaseType">
<source>Conversion operators cannot convert from a type to its base type.</source>
<target state="translated">轉換運算子無法從類型轉換為其基底類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToDerivedType">
<source>Conversion operators cannot convert from a type to its derived type.</source>
<target state="translated">轉換運算子無法從類型轉換為其衍生類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionToObject">
<source>Conversion operators cannot convert to Object.</source>
<target state="translated">轉換運算子無法轉換為物件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromInterfaceType">
<source>Conversion operators cannot convert from an interface type.</source>
<target state="translated">轉換運算子無法從介面類型進行轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromBaseType">
<source>Conversion operators cannot convert from a base type.</source>
<target state="translated">轉換運算子無法從基底類型進行轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromDerivedType">
<source>Conversion operators cannot convert from a derived type.</source>
<target state="translated">轉換運算子無法從衍生類型進行轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConversionFromObject">
<source>Conversion operators cannot convert from Object.</source>
<target state="translated">轉換運算子無法從物件進行轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MatchingOperatorExpected2">
<source>Matching '{0}' operator is required for '{1}'.</source>
<target state="translated">'{1}' 必須要有對稱的 '{0}' 運算子。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnacceptableLogicalOperator3">
<source>Return and parameter types of '{0}' must be '{1}' to be used in a '{2}' expression.</source>
<target state="translated">'{0}' 的傳回類型與參數類型必須是 '{1}',才可用在 '{2}' 運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConditionOperatorRequired3">
<source>Type '{0}' must define operator '{1}' to be used in a '{2}' expression.</source>
<target state="translated">類型 '{0}' 必須定義要用於 '{2}' 運算式中的運算子 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CopyBackTypeMismatch3">
<source>Cannot copy the value of 'ByRef' parameter '{0}' back to the matching argument because type '{1}' cannot be converted to type '{2}'.</source>
<target state="translated">無法將 'ByRef' 參數的值 '{0}' 複製回相對應的引數,因為類型 '{1}' 無法轉換成類型 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForLoopOperatorRequired2">
<source>Type '{0}' must define operator '{1}' to be used in a 'For' statement.</source>
<target state="translated">類型 '{0}' 必須定義要用於 'For' 陳述式中的運算子 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnacceptableForLoopOperator2">
<source>Return and parameter types of '{0}' must be '{1}' to be used in a 'For' statement.</source>
<target state="translated">'{0}' 的傳回類型與參數類型必須是 '{1}',才可用在 'For' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnacceptableForLoopRelOperator2">
<source>Parameter types of '{0}' must be '{1}' to be used in a 'For' statement.</source>
<target state="translated">'{0}' 的參數類型必須是 '{1}',才可用在 'For' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OperatorRequiresIntegerParameter1">
<source>Operator '{0}' must have a second parameter of type 'Integer' or 'Integer?'.</source>
<target state="translated">運算子 '{0}' 的第二個參數類型必須為 'Integer' 或 'Integer?'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyNullableOnBoth">
<source>Nullable modifier cannot be specified on both a variable and its type.</source>
<target state="translated">無法同時在變數及其類型上指定可為 Null 的修飾元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadTypeArgForStructConstraintNull">
<source>Type '{0}' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.</source>
<target state="translated">類型 '{0}' 必須是實值類型或已限制為 'Structure' 的類型引數,才可與 'Nullable' 或可為 Null 的修飾元 '?' 搭配使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyArrayAndNullableOnBoth">
<source>Nullable modifier '?' and array modifiers '(' and ')' cannot be specified on both a variable and its type.</source>
<target state="translated">無法同時在變數及其類型上指定可為 Null 的修飾元 '?' 以及陣列修飾元 '(' 和 ')'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyTypeCharacterOnIIF">
<source>Expressions used with an 'If' expression cannot contain type characters.</source>
<target state="translated">與 'If' 運算式一併使用的運算式,不可包含類型字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFName">
<source>'If' operands cannot be named arguments.</source>
<target state="translated">'If' 運算元不能是具名引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFConversion">
<source>Cannot infer a common type for the second and third operands of the 'If' operator. One must have a widening conversion to the other.</source>
<target state="translated">無法推斷 'If' 運算子的第二個和第三個運算元之一般類型。一個運算元必須要能夠放大轉換成另一個運算元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalCondTypeInIIF">
<source>First operand in a binary 'If' expression must be a nullable value type, a reference type, or an unconstrained generic type.</source>
<target state="translated">二進位 'If' 運算式的第一個運算元必須是可為 Null 或是參考類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantCallIIF">
<source>'If' operator cannot be used in a 'Call' statement.</source>
<target state="translated">'If' 運算子無法用於 'Call' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyAsNewAndNullable">
<source>Nullable modifier cannot be specified in variable declarations with 'As New'.</source>
<target state="translated">包含 'As New' 的變數宣告中不能指定可為 Null 的修飾元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFConversion2">
<source>Cannot infer a common type for the first and second operands of the binary 'If' operator. One must have a widening conversion to the other.</source>
<target state="translated">無法推斷二元 'If' 運算子的第一個和第二個運算元之一般類型。一個運算元必須要能夠放大轉換成另一個運算元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadNullTypeInCCExpression">
<source>Nullable types are not allowed in conditional compilation expressions.</source>
<target state="translated">條件式編譯運算式中不可使用可為 Null 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableImplicit">
<source>Nullable modifier cannot be used with a variable whose implicit type is 'Object'.</source>
<target state="translated">可為 Null 的修飾元不能用於隱含類型為 'Object' 的變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingRuntimeHelper">
<source>Requested operation is not available because the runtime library function '{0}' is not defined.</source>
<target state="translated">因為未定義執行階段程式庫函式 '{0}',所以無法進行要求的作業。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedDotAfterGlobalNameSpace">
<source>'Global' must be followed by '.' and an identifier.</source>
<target state="translated">'在 'Global' 之後必須接著 '.' 及一個識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoGlobalExpectedIdentifier">
<source>'Global' not allowed in this context; identifier expected.</source>
<target state="translated">'此內容中不允許 'Global'; 必須是識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoGlobalInHandles">
<source>'Global' not allowed in handles; local name expected.</source>
<target state="translated">'控制代碼中不允許 'Global'; 必須是區域名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ElseIfNoMatchingIf">
<source>'ElseIf' must be preceded by a matching 'If' or 'ElseIf'.</source>
<target state="translated">'ElseIf' 之前必須搭配相對應的 'If' 或 'ElseIf'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAttributeConstructor2">
<source>Attribute constructor has a 'ByRef' parameter of type '{0}'; cannot use constructors with byref parameters to apply the attribute.</source>
<target state="translated">屬性建構函式的 'ByRef' 參數類型為 '{0}'; 不可使用具有 byref 參數的建構函式來套用屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EndUsingWithoutUsing">
<source>'End Using' must be preceded by a matching 'Using'.</source>
<target state="translated">'End Using' 之前必須搭配相對應的 'Using'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEndUsing">
<source>'Using' must end with a matching 'End Using'.</source>
<target state="translated">'Using' 之後必須搭配相對應的 'End Using'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_GotoIntoUsing">
<source>'GoTo {0}' is not valid because '{0}' is inside a 'Using' statement that does not contain this statement.</source>
<target state="translated">'GoTo {0}' 無效,因為 '{0}' 位於不包含此陳述式的 'Using' 陳述式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UsingRequiresDisposePattern">
<source>'Using' operand of type '{0}' must implement 'System.IDisposable'.</source>
<target state="translated">'類型 '{0}' 的 'Using' 運算元必須實作 'System.IDisposable'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UsingResourceVarNeedsInitializer">
<source>'Using' resource variable must have an explicit initialization.</source>
<target state="translated">'Using' 資源變數必須擁有明確的初始設定。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UsingResourceVarCantBeArray">
<source>'Using' resource variable type can not be array type.</source>
<target state="translated">'Using' 資源變數類型不能是陣列類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OnErrorInUsing">
<source>'On Error' statements are not valid within 'Using' statements.</source>
<target state="translated">'On Error' 陳述式在 'Using' 陳述式內無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyNameConflictInMyCollection">
<source>'{0}' has the same name as a member used for type '{1}' exposed in a 'My' group. Rename the type or its enclosing namespace.</source>
<target state="translated">'{0}' 與用在 'My' 群組中所公開之類型 '{1}' 的成員,有相同的名稱。請重新命名類型或其內含的命名空間。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidImplicitVar">
<source>Implicit variable '{0}' is invalid because of '{1}'.</source>
<target state="translated">隱含變數 '{0}' 無效,原因為 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ObjectInitializerRequiresFieldName">
<source>Object initializers require a field name to initialize.</source>
<target state="translated">物件初始設定式需要欄位名稱,才可進行初始化。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedFrom">
<source>'From' expected.</source>
<target state="translated">'必須是 'From'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaBindingMismatch1">
<source>Nested function does not have the same signature as delegate '{0}'.</source>
<target state="translated">巢狀函式與委派 '{0}' 沒有相同的簽章。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaBindingMismatch2">
<source>Nested sub does not have a signature that is compatible with delegate '{0}'.</source>
<target state="translated">巢狀 Sub 沒有與委派 '{0}' 相容的簽章。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftByRefParamQuery1">
<source>'ByRef' parameter '{0}' cannot be used in a query expression.</source>
<target state="translated">'ByRef' 參數 '{0}' 不可用在查詢運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpressionTreeNotSupported">
<source>Expression cannot be converted into an expression tree.</source>
<target state="translated">運算式不可轉換成運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftStructureMeQuery">
<source>Instance members and 'Me' cannot be used within query expressions in structures.</source>
<target state="translated">執行個體成員和 'Me' 不能用在結構的查詢運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InferringNonArrayType1">
<source>Variable cannot be initialized with non-array type '{0}'.</source>
<target state="translated">不能以非陣列類型 '{0}' 初始化變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ByRefParamInExpressionTree">
<source>References to 'ByRef' parameters cannot be converted to an expression tree.</source>
<target state="translated">ByRef' 參數的參考不可轉換成運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateAnonTypeMemberName1">
<source>Anonymous type member or property '{0}' is already declared.</source>
<target state="translated">匿名類型成員或屬性 '{0}' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAnonymousTypeForExprTree">
<source>Cannot convert anonymous type to an expression tree because a property of the type is used to initialize another property.</source>
<target state="translated">無法將匿名類型轉換成運算式樹狀結構,因為類型的屬性會用以初始化另一個屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftAnonymousType1">
<source>Anonymous type property '{0}' cannot be used in the definition of a lambda expression within the same initialization list.</source>
<target state="translated">匿名類型屬性 '{0}' 不可用在同一個初始設定清單中之 Lambda 運算式的定義內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionOnlyAllowedOnModuleSubOrFunction">
<source>'Extension' attribute can be applied only to 'Module', 'Sub', or 'Function' declarations.</source>
<target state="translated">'Extension' 屬性只能套用到 'Module'、'Sub' 或 'Function' 宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodNotInModule">
<source>Extension methods can be defined only in modules.</source>
<target state="translated">擴充方法只能在模組內定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodNoParams">
<source>Extension methods must declare at least one parameter. The first parameter specifies which type to extend.</source>
<target state="translated">擴充方法必須宣告至少一個參數。第一個參數會指定要擴充的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodOptionalFirstArg">
<source>'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.</source>
<target state="translated">'Optional' 不能套用至擴充方法的第一個參數。第一個參數會指定要擴充的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodParamArrayFirstArg">
<source>'ParamArray' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.</source>
<target state="translated">'ParamArray' 不能套用至擴充方法的第一個參數。第一個參數會指定要擴充的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeFieldNameInference">
<source>Anonymous type member name can be inferred only from a simple or qualified name with no arguments.</source>
<target state="translated">只能從不含引數的簡單或限定名稱來推斷匿名類型成員名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NameNotMemberOfAnonymousType2">
<source>'{0}' is not a member of '{1}'; it does not exist in the current context.</source>
<target state="translated">'{0}' 不是 '{1}' 的成員,其不存在於目前的內容中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionAttributeInvalid">
<source>The custom-designed version of 'System.Runtime.CompilerServices.ExtensionAttribute' found by the compiler is not valid. Its attribute usage flags must be set to allow assemblies, classes, and methods.</source>
<target state="translated">這個由編譯器所發現的 'System.Runtime.CompilerServices.ExtensionAttribute' 自訂版本無效。它的屬性使用方式旗標必須設定成允許組件、類別和方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypePropertyOutOfOrder1">
<source>Anonymous type member property '{0}' cannot be used to infer the type of another member property because the type of '{0}' is not yet established.</source>
<target state="translated">匿名類型成員屬性 '{0}' 無法用以推斷另一個成員屬性的類型,因為尚未建立類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeDisallowsTypeChar">
<source>Type characters cannot be used in anonymous type declarations.</source>
<target state="translated">匿名類型宣告中不能使用類型字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleLiteralDisallowsTypeChar">
<source>Type characters cannot be used in tuple literals.</source>
<target state="translated">元組常值中不得使用類型字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NewWithTupleTypeSyntax">
<source>'New' cannot be used with tuple type. Use a tuple literal expression instead.</source>
<target state="translated">'Tuple 類型不得使用 'New'。請改用 Tuple 常值運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PredefinedValueTupleTypeMustBeStruct">
<source>Predefined type '{0}' must be a structure.</source>
<target state="translated">預先定義的類型 '{0}' 必須是結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodUncallable1">
<source>Extension method '{0}' has type constraints that can never be satisfied.</source>
<target state="translated">擴充方法 '{0}' 有一直無法滿足的類型條件約束。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodOverloadCandidate3">
<source>
Extension method '{0}' defined in '{1}': {2}</source>
<target state="translated">
定義於 '{1}' 中的擴充方法 '{0}': {2}</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingMismatch">
<source>Method does not have a signature compatible with the delegate.</source>
<target state="translated">方法沒有與委派相容的簽章。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingTypeInferenceFails">
<source>Type arguments could not be inferred from the delegate.</source>
<target state="translated">無法從委派推斷類型引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyArgs">
<source>Too many arguments.</source>
<target state="translated">引數太多。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgAlsoOmitted1">
<source>Parameter '{0}' already has a matching omitted argument.</source>
<target state="translated">參數 '{0}' 已有相符的省略引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgUsedTwice1">
<source>Parameter '{0}' already has a matching argument.</source>
<target state="translated">參數 '{0}' 已有相符的引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamNotFound1">
<source>'{0}' is not a method parameter.</source>
<target state="translated">'{0}' 不是方法參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedArgument1">
<source>Argument not specified for parameter '{0}'.</source>
<target state="translated">參數 '{0}' 未指定引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnboundTypeParam1">
<source>Type parameter '{0}' cannot be inferred.</source>
<target state="translated">無法推斷類型參數 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodOverloadCandidate2">
<source>
Extension method '{0}' defined in '{1}'.</source>
<target state="translated">
定義於 '{1}' 中的擴充方法 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeNeedField">
<source>Anonymous type must contain at least one member.</source>
<target state="translated">匿名類型必須至少有一名成員。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeNameWithoutPeriod">
<source>Anonymous type member name must be preceded by a period.</source>
<target state="translated">匿名類型成員名稱前面必須有一個句號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonymousTypeExpectedIdentifier">
<source>Identifier expected, preceded with a period.</source>
<target state="translated">必須是識別項,前面加上句號。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyArgs2">
<source>Too many arguments to extension method '{0}' defined in '{1}'.</source>
<target state="translated">在 '{1}' 中定義的擴充方法 '{0}',有太多引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgAlsoOmitted3">
<source>Parameter '{0}' in extension method '{1}' defined in '{2}' already has a matching omitted argument.</source>
<target state="translated">'{2}' 中定義之擴充方法 '{1}' 內的參數 '{0}',已有相符的省略引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedArgUsedTwice3">
<source>Parameter '{0}' of extension method '{1}' defined in '{2}' already has a matching argument.</source>
<target state="translated">'{2}' 中定義之擴充方法 '{1}' 的參數 '{0}',已有相符的引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamedParamNotFound3">
<source>'{0}' is not a parameter of extension method '{1}' defined in '{2}'.</source>
<target state="translated">'{0}' 不是 '{2}' 中定義之擴充方法 '{1}' 的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OmittedArgument3">
<source>Argument not specified for parameter '{0}' of extension method '{1}' defined in '{2}'.</source>
<target state="translated">未對 '{2}' 中定義的擴充方法 '{1}' 之參數 '{0}' 指定引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnboundTypeParam3">
<source>Type parameter '{0}' for extension method '{1}' defined in '{2}' cannot be inferred.</source>
<target state="translated">無法推斷在 '{2}' 中定義之擴充方法 '{1}' 的類型參數 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooFewGenericArguments2">
<source>Too few type arguments to extension method '{0}' defined in '{1}'.</source>
<target state="translated">在 '{1}' 中定義的擴充方法 '{0}',類型引數太少。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyGenericArguments2">
<source>Too many type arguments to extension method '{0}' defined in '{1}'.</source>
<target state="translated">在 '{1}' 中定義的擴充方法 '{0}',有太多類型引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedInOrEq">
<source>'In' or '=' expected.</source>
<target state="translated">'必須是 'In' 或 '='。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedQueryableSource">
<source>Expression of type '{0}' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ provider.</source>
<target state="translated">類型 '{0}' 的運算式無法查詢。請確定您沒有遺漏組件參考及 (或) LINQ 提供者的命名空間匯入。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryOperatorNotFound">
<source>Definition of method '{0}' is not accessible in this context.</source>
<target state="translated">在此內容中無法存取方法 '{0}' 的定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotUseOnErrorGotoWithClosure">
<source>Method cannot contain both a '{0}' statement and a definition of a variable that is used in a lambda or query expression.</source>
<target state="translated">方法不可同時包含 '{0}' 陳述式以及用於 Lambda 或查詢運算式中的變數定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotGotoNonScopeBlocksWithClosure">
<source>'{0}{1}' is not valid because '{2}' is inside a scope that defines a variable that is used in a lambda or query expression.</source>
<target state="translated">'{0}{1}' 無效,因為 '{2}' 所在的範圍內,定義了用於 Lambda 或查詢運算式中的變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftRestrictedTypeQuery">
<source>Instance of restricted type '{0}' cannot be used in a query expression.</source>
<target state="translated">受限制的類型 '{0}' 之執行個體,不能用在查詢運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryAnonymousTypeFieldNameInference">
<source>Range variable name can be inferred only from a simple or qualified name with no arguments.</source>
<target state="translated">只能從不含引數的簡單或限定名稱來推斷範圍變數名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryDuplicateAnonTypeMemberName1">
<source>Range variable '{0}' is already declared.</source>
<target state="translated">範圍變數 '{0}' 已宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryAnonymousTypeDisallowsTypeChar">
<source>Type characters cannot be used in range variable declarations.</source>
<target state="translated">範圍變數宣告中不能使用類型字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReadOnlyInClosure">
<source>'ReadOnly' variable cannot be the target of an assignment in a lambda expression inside a constructor.</source>
<target state="translated">'ReadOnly' 變數不能做為建構函式內 Lambda 運算式中的指派目標。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExprTreeNoMultiDimArrayCreation">
<source>Multi-dimensional array cannot be converted to an expression tree.</source>
<target state="translated">多維陣列不可轉換成運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExprTreeNoLateBind">
<source>Late binding operations cannot be converted to an expression tree.</source>
<target state="translated">晚期繫結作業無法轉換成運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedBy">
<source>'By' expected.</source>
<target state="translated">'必須是 'By'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryInvalidControlVariableName1">
<source>Range variable name cannot match the name of a member of the 'Object' class.</source>
<target state="translated">範圍變數名稱無法符合 'Object' 類別成員的名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIn">
<source>'In' expected.</source>
<target state="translated">'必須是 'In'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryNameNotDeclared">
<source>Name '{0}' is either not declared or not in the current scope.</source>
<target state="translated">名稱 '{0}' 未宣告或不在目前的範圍內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedFunctionArgumentNarrowing3">
<source>Return type of nested function matching parameter '{0}' narrows from '{1}' to '{2}'.</source>
<target state="translated">與參數 '{0}' 相對應的巢狀函式之傳回類型,從 '{1}' 縮減到 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AnonTypeFieldXMLNameInference">
<source>Anonymous type member name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.</source>
<target state="translated">無法從非有效 Visual Basic 識別項的 XML 識別項來推斷匿名類型成員名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryAnonTypeFieldXMLNameInference">
<source>Range variable name cannot be inferred from an XML identifier that is not a valid Visual Basic identifier.</source>
<target state="translated">無法從非有效 Visual Basic 識別項的 XML 識別項來推斷範圍變數名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedInto">
<source>'Into' expected.</source>
<target state="translated">'必須是 'Into'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeCharOnAggregation">
<source>Aggregate function name cannot be used with a type character.</source>
<target state="translated">彙總函式名稱不能與類型字元一起使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedOn">
<source>'On' expected.</source>
<target state="translated">'必須是 'On'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedEquals">
<source>'Equals' expected.</source>
<target state="translated">'必須是 'Equals'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedAnd">
<source>'And' expected.</source>
<target state="translated">'必須是 'And'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EqualsTypeMismatch">
<source>'Equals' cannot compare a value of type '{0}' with a value of type '{1}'.</source>
<target state="translated">'Equals' 無法比較類型 '{0}' 的值與類型 '{1}' 的值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EqualsOperandIsBad">
<source>You must reference at least one range variable on both sides of the 'Equals' operator. Range variable(s) {0} must appear on one side of the 'Equals' operator, and range variable(s) {1} must appear on the other.</source>
<target state="translated">在 'Equals' 運算子的兩端,至少都必須都要參考一個範圍變數。範圍變數 {0} 必須出現在 'Equals' 運算子的一端,而範圍變數 {1} 則必須出現在另一端。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNotDelegate1">
<source>Lambda expression cannot be converted to '{0}' because '{0}' is not a delegate type.</source>
<target state="translated">Lambda 運算式無法轉換成 '{0}',因為 '{0}' 不是委派類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNotCreatableDelegate1">
<source>Lambda expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.</source>
<target state="translated">Lambda 運算式無法轉換成 '{0}',因為類型 '{0}' 宣告為 'MustInherit' 但卻無法建立。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotInferNullableForVariable1">
<source>A nullable type cannot be inferred for variable '{0}'.</source>
<target state="translated">無法為變數 '{0}' 推斷可為 Null 的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableTypeInferenceNotSupported">
<source>Nullable type inference is not supported in this context.</source>
<target state="translated">此處不支援可為 Null 的類型推斷。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedJoin">
<source>'Join' expected.</source>
<target state="translated">'必須是 'Join'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableParameterMustSpecifyType">
<source>Nullable parameters must specify a type.</source>
<target state="translated">可為 Null 的參數必須指定類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IterationVariableShadowLocal2">
<source>Range variable '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.</source>
<target state="translated">範圍變數 '{0}' 可隱藏封閉區塊中的變數、預先定義的範圍變數,或查詢運算式中隱含宣告的變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdasCannotHaveAttributes">
<source>Attributes cannot be applied to parameters of lambda expressions.</source>
<target state="translated">屬性無法套用到 Lambda 運算式的參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaInSelectCaseExpr">
<source>Lambda expressions are not valid in the first expression of a 'Select Case' statement.</source>
<target state="translated">Lambda 運算式在 'Select Case' 陳述式的第一個運算式中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddressOfInSelectCaseExpr">
<source>'AddressOf' expressions are not valid in the first expression of a 'Select Case' statement.</source>
<target state="translated">'AddressOf' 運算式在 'Select Case' 陳述式的第一個運算式中無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullableCharNotSupported">
<source>The '?' character cannot be used here.</source>
<target state="translated">?' 字元不能用在這裡。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftStructureMeLambda">
<source>Instance members and 'Me' cannot be used within a lambda expression in structures.</source>
<target state="translated">執行個體成員和 'Me' 不能用在結構的 Lambda 運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftByRefParamLambda1">
<source>'ByRef' parameter '{0}' cannot be used in a lambda expression.</source>
<target state="translated">'ByRef' 參數 '{0}' 不可用在 Lambda 運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftRestrictedTypeLambda">
<source>Instance of restricted type '{0}' cannot be used in a lambda expression.</source>
<target state="translated">受限制的類型 '{0}' 之執行個體,不能用在 Lambda 運算式中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaParamShadowLocal1">
<source>Lambda parameter '{0}' hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression.</source>
<target state="translated">Lambda 參數 '{0}' 隱藏了封閉區塊中的變數、預先定義的範圍變數,或查詢運算式中隱含宣告的變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StrictDisallowImplicitObjectLambda">
<source>Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred.</source>
<target state="translated">Option Strict 為 On 時,要求如果無法推斷每個 Lambda 運算式參數的類型,就必須以 'As' 子句宣告該參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantSpecifyParamsOnLambdaParamNoType">
<source>Array modifiers cannot be specified on lambda expression parameter name. They must be specified on its type.</source>
<target state="translated">不能在 Lambda 運算式參數名稱上指定陣列修飾元,而必須在其類型上指定。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailure1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">無法從這些引數推斷類型參數的資料類型。明確指定資料類型或許可以改正這項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailure2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">無法從這些引數推斷方法 '{0}' 中類型參數的資料類型。明確指定資料類型或許可更正此項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailure3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">無法從這些引數推斷定義在 '{1}' 中擴充方法 '{0}' 內類型參數的資料類型。明確指定資料類型或許可更正此項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicit1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments.</source>
<target state="translated">無法從這些引數推斷類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicit2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments.</source>
<target state="translated">無法從這些引數推斷方法 '{0}' 中類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicit3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments.</source>
<target state="translated">無法從這些引數推斷定義在 '{1}' 中擴充方法 '{0}' 內類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureAmbiguous1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">無法從這些引數推斷類型參數的資料類型,因為可能的類型不止一種。明確指定資料類型或許可以改正這項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureAmbiguous2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">因為可能的類型不只一種,所以無法從這些引數推斷方法 '{0}' 中類型參數的資料類型。明確指定資料類型或許可更正此項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureAmbiguous3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">因為可能的類型不只一種,所以無法從這些引數推斷定義在 '{1}' 中擴充方法 '{0}' 內類型參數的資料類型。明確指定資料類型或許可更正此項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because more than one type is possible.</source>
<target state="translated">無法從這些引數推斷類型參數的資料類型,因為可能會有一個以上的類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because more than one type is possible.</source>
<target state="translated">因為可能的類型不只一種,所以無法從這些引數推斷方法 '{0}' 中類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitAmbiguous3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because more than one type is possible.</source>
<target state="translated">因為可能的類型不只一種,所以無法從這些引數推斷定義在 '{1}' 中擴充方法 '{0}' 內類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoBest1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">無法從這些引數推斷類型參數的資料類型,因為它們不會轉換成相同類型。明確指定資料類型或許可以改正這項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoBest2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">因為引數不會轉換成相同類型,所以無法從這些引數推斷方法 '{0}' 中類型參數的資料類型。明確指定資料類型或許可更正此項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoBest3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error.</source>
<target state="translated">因為引數不會轉換成相同類型,所以無法從這些引數推斷定義在 '{1}' 中擴充方法 '{0}' 內類型參數的資料類型。明確指定資料類型或許可更正此項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest1">
<source>Data type(s) of the type parameter(s) cannot be inferred from these arguments because they do not convert to the same type.</source>
<target state="translated">無法從這些引數推斷類型參數的資料類型,因為它們不會轉換成相同類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest2">
<source>Data type(s) of the type parameter(s) in method '{0}' cannot be inferred from these arguments because they do not convert to the same type.</source>
<target state="translated">因為引數不會轉換成相同類型,所以無法從這些引數推斷方法 '{0}' 中類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceFailureNoExplicitNoBest3">
<source>Data type(s) of the type parameter(s) in extension method '{0}' defined in '{1}' cannot be inferred from these arguments because they do not convert to the same type.</source>
<target state="translated">因為引數不會轉換成相同類型,所以無法從這些引數推斷定義在 '{1}' 中擴充方法 '{0}' 內類型參數的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingMismatchStrictOff2">
<source>Option Strict On does not allow narrowing in implicit type conversions between method '{0}' and delegate '{1}'.</source>
<target state="translated">Option Strict 為 On 時,不可縮減方法 '{0}' 與委派 '{1}' 之間隱含的類型轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InaccessibleReturnTypeOfMember2">
<source>'{0}' is not accessible in this context because the return type is not accessible.</source>
<target state="translated">'無法在此內容中存取 '{0}',因為無法存取傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedIdentifierOrGroup">
<source>'Group' or an identifier expected.</source>
<target state="translated">'必須是 'Group' 或識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnexpectedGroup">
<source>'Group' not allowed in this context; identifier expected.</source>
<target state="translated">'此內容中不允許 'Group'; 必須是識別項。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingMismatchStrictOff3">
<source>Option Strict On does not allow narrowing in implicit type conversions between extension method '{0}' defined in '{2}' and delegate '{1}'.</source>
<target state="translated">Option Strict 為 On 時,不可縮減 '{2}' 中定義的擴充方法 '{0}' 與委派 '{1}' 之間隱含的類型轉換。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DelegateBindingIncompatible3">
<source>Extension Method '{0}' defined in '{2}' does not have a signature compatible with delegate '{1}'.</source>
<target state="translated">'{2}' 中定義的擴充方法 '{0}',沒有與委派 '{1}' 相容的簽章。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArgumentNarrowing2">
<source>Argument matching parameter '{0}' narrows to '{1}'.</source>
<target state="translated">與參數 '{0}' 對應的引數,縮減到 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadCandidate1">
<source>
{0}</source>
<target state="translated">
{0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_AutoPropertyInitializedInStructure">
<source>Auto-implemented Properties contained in Structures cannot have initializers unless they are marked 'Shared'.</source>
<target state="translated">結構中包含的自動實作屬性不能有初始設定式,除非標記為 'Shared'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeDisallowsElements">
<source>XML elements cannot be selected from type '{0}'.</source>
<target state="translated">無法從類型 '{0}' 選取 XML 元素。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeDisallowsAttributes">
<source>XML attributes cannot be selected from type '{0}'.</source>
<target state="translated">無法從類型 '{0}' 選取 XML 屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeDisallowsDescendants">
<source>XML descendant elements cannot be selected from type '{0}'.</source>
<target state="translated">無法從類型 '{0}' 選取 XML 子元素。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeOrMemberNotGeneric2">
<source>Extension method '{0}' defined in '{1}' is not generic (or has no free type parameters) and so cannot have type arguments.</source>
<target state="translated">在 '{1}' 中定義的擴充方法 '{0}' 不是泛型 (或沒有不受限的類型參數),因此不可有類型引數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExtensionMethodCannotBeLateBound">
<source>Late-bound extension methods are not supported.</source>
<target state="translated">不支援晚期繫結擴充方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeInferenceArrayRankMismatch1">
<source>Cannot infer a data type for '{0}' because the array dimensions do not match.</source>
<target state="translated">因為陣列維度不相符,所以無法推斷 '{0}' 的資料類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_QueryStrictDisallowImplicitObject">
<source>Type of the range variable cannot be inferred, and late binding is not allowed with Option Strict on. Use an 'As' clause to specify the type.</source>
<target state="translated">無法推斷範圍變數的類型,Option Strict 為 On 時不可使用晚期繫結。請使用 'As' 子句指定類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotEmbedInterfaceWithGeneric">
<source>Type '{0}' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.</source>
<target state="translated">無法內嵌類型 '{0}',因為它有泛型引數。請考慮停用內嵌 Interop 類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotUseGenericTypeAcrossAssemblyBoundaries">
<source>Type '{0}' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.</source>
<target state="translated">因為類型 '{0}' 有內嵌 Interop 類型的泛型類型引數,所以不可跨組件的界限使用。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbol2">
<source>'{0}' is obsolete: '{1}'.</source>
<target state="translated">'{0}' 已經過時: '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbol2_Title">
<source>Type or member is obsolete</source>
<target state="translated">類型或成員已經過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverloadBase4">
<source>{0} '{1}' shadows an overloadable member declared in the base {2} '{3}'. If you want to overload the base method, this method must be declared 'Overloads'.</source>
<target state="translated">{0} '{1}' 會遮蔽基底 {2} '{3}' 中宣告的可多載成員。若要多載基底方法,必須將此方法宣告為 'Overloads'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverloadBase4_Title">
<source>Member shadows an overloadable member declared in the base type</source>
<target state="translated">成員遮蔽了基底類型中所宣告的可多載成員</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverrideType5">
<source>{0} '{1}' conflicts with {2} '{1}' in the base {3} '{4}' and should be declared 'Shadows'.</source>
<target state="translated">{0} '{1}' 與基底 {3} '{4}' 中的 {2} '{1}' 互相衝突,因此應宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverrideType5_Title">
<source>Member conflicts with member in the base type and should be declared 'Shadows'</source>
<target state="translated">成員與基底類型中的成員互相衝突,因此應該宣告為 'Shadows'</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverride2">
<source>{0} '{1}' shadows an overridable method in the base {2} '{3}'. To override the base method, this method must be declared 'Overrides'.</source>
<target state="translated">{0} '{1}' 會遮蔽基底 {2} '{3}' 中可覆寫的方法。若要覆寫基底方法,必須將此方法宣告為 'Overrides'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustOverride2_Title">
<source>Member shadows an overridable method in the base type</source>
<target state="translated">成員遮蔽了基底類型中可覆寫的方法</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefaultnessShadowed4">
<source>Default property '{0}' conflicts with the default property '{1}' in the base {2} '{3}'. '{0}' will be the default property. '{0}' should be declared 'Shadows'.</source>
<target state="translated">預設屬性 '{0}' 與基底 {2} '{3}' 中的預設屬性 '{1}' 相互衝突。'{0}' 將成為預設屬性。'{0}' 應該宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefaultnessShadowed4_Title">
<source>Default property conflicts with the default property in the base type</source>
<target state="translated">預設屬性與基底類型中的預設屬性互相衝突</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbolNoMessage1">
<source>'{0}' is obsolete.</source>
<target state="translated">'{0}' 已經過時。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoleteSymbolNoMessage1_Title">
<source>Type or member is obsolete</source>
<target state="translated">類型或成員已經過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration0">
<source>Possible problem detected while building assembly: {0}</source>
<target state="translated">建置組件時偵測到的可能問題: {0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration0_Title">
<source>Possible problem detected while building assembly</source>
<target state="translated">建置組件時偵測的可能問題</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration1">
<source>Possible problem detected while building assembly '{0}': {1}</source>
<target state="translated">建置組件 '{0}' 時偵測到的可能問題: {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyGeneration1_Title">
<source>Possible problem detected while building assembly</source>
<target state="translated">建置組件時偵測的可能問題</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassNoMembers1">
<source>'Microsoft.VisualBasic.ComClassAttribute' is specified for class '{0}' but '{0}' has no public members that can be exposed to COM; therefore, no COM interfaces are generated.</source>
<target state="translated">'為類別 '{0}' 指定了 'Microsoft.VisualBasic.ComClassAttribute',但 '{0}' 沒有可公開至 COM 的公用成員。因此,未產生 COM 介面。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassNoMembers1_Title">
<source>'Microsoft.VisualBasic.ComClassAttribute' is specified for class but class has no public members that can be exposed to COM</source>
<target state="translated">'為類別指定了 'Microsoft.VisualBasic.ComClassAttribute',但類別沒有可對 COM 公開的 Public 成員</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsMember5">
<source>{0} '{1}' implicitly declares '{2}', which conflicts with a member in the base {3} '{4}', and so the {0} should be declared 'Shadows'.</source>
<target state="translated">{0} '{1}' 隱含宣告 '{2}',其與基底 {3} '{4}' 中的成員相衝突,因此 {0} 應宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsMember5_Title">
<source>Property or event implicitly declares type or member that conflicts with a member in the base type</source>
<target state="translated">屬性或事件隱含宣告了與基底類型中的成員互相衝突的類型或成員</target>
<note />
</trans-unit>
<trans-unit id="WRN_MemberShadowsSynthMember6">
<source>{0} '{1}' conflicts with a member implicitly declared for {2} '{3}' in the base {4} '{5}' and should be declared 'Shadows'.</source>
<target state="translated">{0} '{1}' 與基底 {4} '{5}' 中對 {2} '{3}' 隱含宣告的成員互相衝突,所以應宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MemberShadowsSynthMember6_Title">
<source>Member conflicts with a member implicitly declared for property or event in the base type</source>
<target state="translated">成員與針對基底類型中屬性或事件進行隱含宣告的成員互相衝突</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsSynthMember7">
<source>{0} '{1}' implicitly declares '{2}', which conflicts with a member implicitly declared for {3} '{4}' in the base {5} '{6}'. {0} should be declared 'Shadows'.</source>
<target state="translated">{0} '{1}' 隱含宣告 '{2}',其與基底 {5} '{6}' 中為 {3} '{4}' 所隱含宣告的成員相衝突。{0} 應宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_SynthMemberShadowsSynthMember7_Title">
<source>Property or event implicitly declares member, which conflicts with a member implicitly declared for property or event in the base type</source>
<target state="translated">屬性或事件所隱含宣告的成員,與基底類型中為屬性或事件隱含宣告的成員互相衝突</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor3">
<source>'{0}' accessor of '{1}' is obsolete: '{2}'.</source>
<target state="translated">'{1}' 的 '{0}' 存取子已經過時: '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor3_Title">
<source>Property accessor is obsolete</source>
<target state="translated">屬性存取子已過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor2">
<source>'{0}' accessor of '{1}' is obsolete.</source>
<target state="translated">'{1}' 的 '{0}' 存取子已經過時。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseOfObsoletePropertyAccessor2_Title">
<source>Property accessor is obsolete</source>
<target state="translated">屬性存取子已過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_FieldNotCLSCompliant1">
<source>Type of member '{0}' is not CLS-compliant.</source>
<target state="translated">成員 '{0}' 的類型不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_FieldNotCLSCompliant1_Title">
<source>Type of member is not CLS-compliant</source>
<target state="translated">成員的類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_BaseClassNotCLSCompliant2">
<source>'{0}' is not CLS-compliant because it derives from '{1}', which is not CLS-compliant.</source>
<target state="translated">'{0}' 不符合 CLS 規範,因為其衍生自不符合 CLS 規範的 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_BaseClassNotCLSCompliant2_Title">
<source>Type is not CLS-compliant because it derives from base type that is not CLS-compliant</source>
<target state="translated">類型不符合 CLS 規範,因為它是衍生自不符合 CLS 規範的基底類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_ProcTypeNotCLSCompliant1">
<source>Return type of function '{0}' is not CLS-compliant.</source>
<target state="translated">函式 '{0}' 的傳回類型不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ProcTypeNotCLSCompliant1_Title">
<source>Return type of function is not CLS-compliant</source>
<target state="translated">函式的傳回類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_ParamNotCLSCompliant1">
<source>Type of parameter '{0}' is not CLS-compliant.</source>
<target state="translated">參數 '{0}' 的類型不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ParamNotCLSCompliant1_Title">
<source>Type of parameter is not CLS-compliant</source>
<target state="translated">參數的類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_InheritedInterfaceNotCLSCompliant2">
<source>'{0}' is not CLS-compliant because the interface '{1}' it inherits from is not CLS-compliant.</source>
<target state="translated">'{0}' 不符合 CLS 規範,因為其繼承的介面 '{1}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_InheritedInterfaceNotCLSCompliant2_Title">
<source>Type is not CLS-compliant because the interface it inherits from is not CLS-compliant</source>
<target state="translated">類型不符合 CLS 規範,因為它所繼承的介面不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSMemberInNonCLSType3">
<source>{0} '{1}' cannot be marked CLS-compliant because its containing type '{2}' is not CLS-compliant.</source>
<target state="translated">{0} '{1}' 無法標記為符合 CLS 規範,因為其包含類型 '{2}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSMemberInNonCLSType3_Title">
<source>Member cannot be marked CLS-compliant because its containing type is not CLS-compliant</source>
<target state="translated">無法將成員標記為符合 CLS 規範,因為其包含類型並不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_NameNotCLSCompliant1">
<source>Name '{0}' is not CLS-compliant.</source>
<target state="translated">名稱 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NameNotCLSCompliant1_Title">
<source>Name is not CLS-compliant</source>
<target state="translated">名稱不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_EnumUnderlyingTypeNotCLS1">
<source>Underlying type '{0}' of Enum is not CLS-compliant.</source>
<target state="translated">列舉的基礎類型 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_EnumUnderlyingTypeNotCLS1_Title">
<source>Underlying type of Enum is not CLS-compliant</source>
<target state="translated">列舉的基礎類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMemberInCLSInterface1">
<source>Non CLS-compliant '{0}' is not allowed in a CLS-compliant interface.</source>
<target state="translated">符合 CLS 規範的介面中,不可出現不符合 CLS 規範的 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMemberInCLSInterface1_Title">
<source>Non CLS-compliant member is not allowed in a CLS-compliant interface</source>
<target state="translated">符合 CLS 規範的介面中不得有不符合 CLS 規範的成員</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMustOverrideInCLSType1">
<source>Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type '{0}'.</source>
<target state="translated">符合 CLS 規範的類型 '{0}' 中不能有不符合 CLS 規範的 'MustOverride' 成員。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NonCLSMustOverrideInCLSType1_Title">
<source>Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type</source>
<target state="translated">符合 CLS 規範的類型中不得有不符合 CLS 規範的 'MustOverride' 成員</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayOverloadsNonCLS2">
<source>'{0}' is not CLS-compliant because it overloads '{1}' which differs from it only by array of array parameter types or by the rank of the array parameter types.</source>
<target state="translated">'{0}' 不符合 CLS 規範,因為其多載了 '{1}',兩者的差別只在於陣列參數類型的陣列,或是陣列參數類型的陣序。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayOverloadsNonCLS2_Title">
<source>Method is not CLS-compliant because it overloads method which differs from it only by array of array parameter types or by the rank of the array parameter types</source>
<target state="translated">方法不符合 CLS 規範,因為它所多載的方法與其本身之間只有陣列參數類型的陣列或陣列參數類型的順位方面的差異</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant1">
<source>Root namespace '{0}' is not CLS-compliant.</source>
<target state="translated">根命名空間 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant1_Title">
<source>Root namespace is not CLS-compliant</source>
<target state="translated">根命名空間不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant2">
<source>Name '{0}' in the root namespace '{1}' is not CLS-compliant.</source>
<target state="translated">根命名空間 '{1}' 中的名稱 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RootNamespaceNotCLSCompliant2_Title">
<source>Part of the root namespace is not CLS-compliant</source>
<target state="translated">根命名空間有部分不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_GenericConstraintNotCLSCompliant1">
<source>Generic parameter constraint type '{0}' is not CLS-compliant.</source>
<target state="translated">泛型參數條件約束類型 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_GenericConstraintNotCLSCompliant1_Title">
<source>Generic parameter constraint type is not CLS-compliant</source>
<target state="translated">泛型參數條件約束類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeNotCLSCompliant1">
<source>Type '{0}' is not CLS-compliant.</source>
<target state="translated">類型 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeNotCLSCompliant1_Title">
<source>Type is not CLS-compliant</source>
<target state="translated">類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_OptionalValueNotCLSCompliant1">
<source>Type of optional value for optional parameter '{0}' is not CLS-compliant.</source>
<target state="translated">選擇性參數 '{0}' 的選擇性值類型不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_OptionalValueNotCLSCompliant1_Title">
<source>Type of optional value for optional parameter is not CLS-compliant</source>
<target state="translated">選用參數的選用值類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSAttrInvalidOnGetSet">
<source>System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.</source>
<target state="translated">System.CLSCompliantAttribute 無法套用至屬性 'Get' 或 'Set'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSAttrInvalidOnGetSet_Title">
<source>System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'</source>
<target state="translated">System.CLSCompliantAttribute 無法套用至屬性 'Get' 或 'Set'</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeConflictButMerged6">
<source>{0} '{1}' and partial {2} '{3}' conflict in {4} '{5}', but are being merged because one of them is declared partial.</source>
<target state="translated">{0} '{1}' 和部分 {2} '{3}' 在 {4} '{5}' 中互相衝突,但是因為其中一個宣告為部分,所以已合併。</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeConflictButMerged6_Title">
<source>Type and partial type conflict, but are being merged because one of them is declared partial</source>
<target state="translated">類型與部分類型相衝突,但將予以合併,因為其中一個已宣告為部分</target>
<note />
</trans-unit>
<trans-unit id="WRN_ShadowingGenericParamWithParam1">
<source>Type parameter '{0}' has the same name as a type parameter of an enclosing type. Enclosing type's type parameter will be shadowed.</source>
<target state="translated">類型參數 '{0}' 與封入類型的類型參數,擁有相同的名稱。將會遮蔽封入類型的類型參數。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ShadowingGenericParamWithParam1_Title">
<source>Type parameter has the same name as a type parameter of an enclosing type</source>
<target state="translated">類型參數與封入類型的類型參數擁有相同的名稱</target>
<note />
</trans-unit>
<trans-unit id="WRN_CannotFindStandardLibrary1">
<source>Could not find standard library '{0}'.</source>
<target state="translated">找不到標準程式庫 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_CannotFindStandardLibrary1_Title">
<source>Could not find standard library</source>
<target state="translated">找不到標準程式庫</target>
<note />
</trans-unit>
<trans-unit id="WRN_EventDelegateTypeNotCLSCompliant2">
<source>Delegate type '{0}' of event '{1}' is not CLS-compliant.</source>
<target state="translated">事件 '{1}' 的委派類型 '{0}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_EventDelegateTypeNotCLSCompliant2_Title">
<source>Delegate type of event is not CLS-compliant</source>
<target state="translated">事件的委派類型不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_DebuggerHiddenIgnoredOnProperties">
<source>System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition. Apply the attribute directly to the 'Get' and 'Set' procedures as appropriate.</source>
<target state="translated">當 System.Diagnostics.DebuggerHiddenAttribute 套用至屬性 (Property) 定義時,它並不會影響 'Get' 或 'Set'。請依適當的情況直接將屬性 (Attribute) 套用至 'Get' 和 'Set' 程序。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DebuggerHiddenIgnoredOnProperties_Title">
<source>System.Diagnostics.DebuggerHiddenAttribute does not affect 'Get' or 'Set' when applied to the Property definition</source>
<target state="translated">System.Diagnostics.DebuggerHiddenAttribute 在套用至 Property 定義時,並不會影響 'Get' 或 'Set'</target>
<note />
</trans-unit>
<trans-unit id="WRN_SelectCaseInvalidRange">
<source>Range specified for 'Case' statement is not valid. Make sure that the lower bound is less than or equal to the upper bound.</source>
<target state="translated">Case' 陳述式的指定範圍無效。請確定下限小於或等於上限。</target>
<note />
</trans-unit>
<trans-unit id="WRN_SelectCaseInvalidRange_Title">
<source>Range specified for 'Case' statement is not valid</source>
<target state="translated">Case' 陳述式的指定範圍無效</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSEventMethodInNonCLSType3">
<source>'{0}' method for event '{1}' cannot be marked CLS compliant because its containing type '{2}' is not CLS compliant.</source>
<target state="translated">'事件 '{1}' 的 '{0}' 方法無法標記為符合 CLS 規範,因為其包含類型 '{2}' 不符合 CLS 規範。</target>
<note />
</trans-unit>
<trans-unit id="WRN_CLSEventMethodInNonCLSType3_Title">
<source>AddHandler or RemoveHandler method for event cannot be marked CLS compliant because its containing type is not CLS compliant</source>
<target state="translated">無法將事件的 AddHandler 或 RemoveHandler 方法標記為符合 CLS 規範,因為其包含類型並不符合 CLS 規範</target>
<note />
</trans-unit>
<trans-unit id="WRN_ExpectedInitComponentCall2">
<source>'{0}' in designer-generated type '{1}' should call InitializeComponent method.</source>
<target state="translated">'設計工具所產生的類型 '{1}' 之 '{0}',應呼叫 InitializeComponent 方法。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ExpectedInitComponentCall2_Title">
<source>Constructor in designer-generated type should call InitializeComponent method</source>
<target state="translated">設計工具產生的類型中的建構函式,應該呼叫 InitializeComponent 方法</target>
<note />
</trans-unit>
<trans-unit id="WRN_NamespaceCaseMismatch3">
<source>Casing of namespace name '{0}' does not match casing of namespace name '{1}' in '{2}'.</source>
<target state="translated">命名空間名稱 '{0}' 的大小寫,與 '{2}' 中命名空間名稱 '{1}' 的大小寫不相符。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NamespaceCaseMismatch3_Title">
<source>Casing of namespace name does not match</source>
<target state="translated">命名空間名稱大小寫不相符</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyNamespaceOrClass1">
<source>Namespace or type specified in the Imports '{0}' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</source>
<target state="translated">Imports '{0}' 中指定的命名空間或類型,不包含任何 Public 成員,或是找不到該命名空間或類型。請確定已定義該命名空間或類型,且至少包含一個 Public 成員。請確定匯入的元素名稱沒有使用任何別名。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyNamespaceOrClass1_Title">
<source>Namespace or type specified in Imports statement doesn't contain any public member or cannot be found</source>
<target state="translated">Imports 陳述式中指定的命名空間或類型,不包含任何 Public 成員,或找不到該命名空間或類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyProjectNamespaceOrClass1">
<source>Namespace or type specified in the project-level Imports '{0}' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</source>
<target state="translated">在專案層級 Imports '{0}' 中指定的命名空間或類型不包含任何 Public 成員,或是找不到該命名空間或類型。請確定已定義命名空間或類型,而且其中包含至少一個 Public 成員。請確定匯入的項目名稱未使用任何別名。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UndefinedOrEmptyProjectNamespaceOrClass1_Title">
<source>Namespace or type imported at project level doesn't contain any public member or cannot be found</source>
<target state="translated">在專案層級匯入的命名空間或類型不包含任何 Public 成員,或是找不到該命名空間或類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_IndirectRefToLinkedAssembly2">
<source>A reference was created to embedded interop assembly '{0}' because of an indirect reference to that assembly from assembly '{1}'. Consider changing the 'Embed Interop Types' property on either assembly.</source>
<target state="translated">已建立內嵌 Interop 組件 '{0}' 的參考,因為該組件的間接參考來自組件 '{1}'。請考慮變更其中任一組件上的 [內嵌 Interop 類型] 屬性。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IndirectRefToLinkedAssembly2_Title">
<source>A reference was created to embedded interop assembly because of an indirect reference to that assembly</source>
<target state="translated">已建立內嵌 Interop 組件的參考,因為對該組件已有間接參考</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase3">
<source>Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete.</source>
<target state="translated">類別 '{0}' 應宣告 'Sub New',因為其基底類別 '{2}' 中的 '{1}' 已標記為過時。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase3_Title">
<source>Class should declare a 'Sub New' because the constructor in its base class is marked obsolete</source>
<target state="translated">類別應該宣告 'Sub New',因為其基底類別中的建構函式已標記為過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase4">
<source>Class '{0}' should declare a 'Sub New' because the '{1}' in its base class '{2}' is marked obsolete: '{3}'.</source>
<target state="translated">類別 '{0}' 應宣告 'Sub New',因為其基底類別 '{2}' 中的 '{1}' 已標記為過時: '{3}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoNonObsoleteConstructorOnBase4_Title">
<source>Class should declare a 'Sub New' because the constructor in its base class is marked obsolete</source>
<target state="translated">類別應該宣告 'Sub New',因為其基底類別中的建構函式已標記為過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall3">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete.</source>
<target state="translated">此 'Sub New' 的第一個陳述式,必須是對 'MyBase.New' 或 'MyClass.New' 的明確呼叫,因為 '{2}' 的基底類別 '{1}' 中之 '{0}' 已標記為過時。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall3_Title">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete</source>
<target state="translated">這個 'Sub New' 的第一個陳述式應明確呼叫 'MyBase.New' 或 'MyClass.New',因為基底類別中的建構函式已標記為過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall4">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the '{0}' in the base class '{1}' of '{2}' is marked obsolete: '{3}'</source>
<target state="translated">此 'Sub New' 的第一個陳述式,必須是對 'MyBase.New' 或 'MyClass.New' 的明確呼叫,因為 '{2}' 的基底類別 '{1}' 中之 '{0}' 已標記為過時: '{3}'</target>
<note />
</trans-unit>
<trans-unit id="WRN_RequiredNonObsoleteNewCall4_Title">
<source>First statement of this 'Sub New' should be an explicit call to 'MyBase.New' or 'MyClass.New' because the constructor in the base class is marked obsolete</source>
<target state="translated">這個 'Sub New' 的第一個陳述式應明確呼叫 'MyBase.New' 或 'MyClass.New',因為基底類別中的建構函式已標記為過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinOperator">
<source>Operator without an 'As' clause; type of Object assumed.</source>
<target state="translated">沒有 'As' 子句的運算子; 假設是 Object 的類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinOperator_Title">
<source>Operator without an 'As' clause</source>
<target state="translated">運算子沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConstraintsFailedForInferredArgs2">
<source>Type arguments inferred for method '{0}' result in the following warnings :{1}</source>
<target state="translated">方法 '{0}' 的推斷類型引數,導致下列錯誤 :{1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConstraintsFailedForInferredArgs2_Title">
<source>Type arguments inferred for method result in warnings</source>
<target state="translated">為方法推斷的類型引數引發了警告</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConditionalNotValidOnFunction">
<source>Attribute 'Conditional' is only valid on 'Sub' declarations.</source>
<target state="translated">屬性 'Conditional' 只在 'Sub' 宣告中有效。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConditionalNotValidOnFunction_Title">
<source>Attribute 'Conditional' is only valid on 'Sub' declarations</source>
<target state="translated">屬性 'Conditional' 只在 'Sub' 宣告中有效</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseSwitchInsteadOfAttribute">
<source>Use command-line option '{0}' or appropriate project settings instead of '{1}'.</source>
<target state="translated">使用命令列選項 '{0}' 或適當的專案設定代替 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UseSwitchInsteadOfAttribute_Title">
<source>Use command-line option /keyfile, /keycontainer, or /delaysign instead of AssemblyKeyFileAttribute, AssemblyKeyNameAttribute, or AssemblyDelaySignAttribute</source>
<target state="translated">使用命令列選項 /keyfile、/keycontainer 或 /delaysign 而非 AssemblyKeyFileAttribute、AssemblyKeyNameAttribute 或 AssemblyDelaySignAttribute</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveAddHandlerCall">
<source>Statement recursively calls the containing '{0}' for event '{1}'.</source>
<target state="translated">陳述式遞迴呼叫事件 '{1}' 的包含 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveAddHandlerCall_Title">
<source>Statement recursively calls the event's containing AddHandler</source>
<target state="translated">陳述式會遞迴呼叫事件的包含 AddHandler</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionCopyBack">
<source>Implicit conversion from '{1}' to '{2}' in copying the value of 'ByRef' parameter '{0}' back to the matching argument.</source>
<target state="translated">在將 'ByRef' 參數的值 '{0}' 複製回相對應的引數時,將 '{1}' 隱含轉換至 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionCopyBack_Title">
<source>Implicit conversion in copying the value of 'ByRef' parameter back to the matching argument</source>
<target state="translated">將 'ByRef' 參數的值複製回相符引數時的隱含轉換</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustShadowOnMultipleInheritance2">
<source>{0} '{1}' conflicts with other members of the same name across the inheritance hierarchy and so should be declared 'Shadows'.</source>
<target state="translated">{0} '{1}' 與其他跨繼承階層的同名成員互相衝突,所以應宣告為 'Shadows'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MustShadowOnMultipleInheritance2_Title">
<source>Method conflicts with other members of the same name across the inheritance hierarchy and so should be declared 'Shadows'</source>
<target state="translated">方法與繼承階層中的其他同名成員互相衝突,因此應該宣告為 'Shadows'</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveOperatorCall">
<source>Expression recursively calls the containing Operator '{0}'.</source>
<target state="translated">運算式遞迴呼叫包含運算子 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursiveOperatorCall_Title">
<source>Expression recursively calls the containing Operator</source>
<target state="translated">運算式會遞迴呼叫包含運算子</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversion2">
<source>Implicit conversion from '{0}' to '{1}'.</source>
<target state="translated">從 '{0}' 隱含轉換至 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversion2_Title">
<source>Implicit conversion</source>
<target state="translated">隱含轉換</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableStructureInUsing">
<source>Local variable '{0}' is read-only and its type is a structure. Invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block.</source>
<target state="translated">區域變數 '{0}' 是唯讀變數,且其類型為結構。叫用其成員或將 ByRef 傳遞給它,並不會變更其內容,但可能導致非預期的結果。請考慮在 'Using' 區塊外宣告此變數。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableStructureInUsing_Title">
<source>Local variable declared by Using statement is read-only and its type is a structure</source>
<target state="translated">Using 陳述式所宣告的區域變數是唯讀變數,且其類型為一結構</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableGenericStructureInUsing">
<source>Local variable '{0}' is read-only. When its type is a structure, invoking its members or passing it ByRef does not change its content and might lead to unexpected results. Consider declaring this variable outside of the 'Using' block.</source>
<target state="translated">區域變數 '{0}' 是唯讀變數。當其類型為結構時,叫用它的成員或將 ByRef 傳遞給它,並不會變更其內容,但可能導致非預期的結果。請考慮在 'Using' 區塊外宣告此變數。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MutableGenericStructureInUsing_Title">
<source>Local variable declared by Using statement is read-only and its type may be a structure</source>
<target state="translated">Using 陳述式所宣告的區域變數是唯讀變數,且其類型可能為一結構</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionSubst1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ImplicitConversionSubst1_Title">
<source>Implicit conversion</source>
<target state="translated">隱含轉換</target>
<note />
</trans-unit>
<trans-unit id="WRN_LateBindingResolution">
<source>Late bound resolution; runtime errors could occur.</source>
<target state="translated">晚期繫結解析; 可能發生執行階段錯誤。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LateBindingResolution_Title">
<source>Late bound resolution</source>
<target state="translated">晚期繫結解析</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1">
<source>Operands of type Object used for operator '{0}'; use the 'Is' operator to test object identity.</source>
<target state="translated">供運算子 '{0}' 使用之 Object 類型的運算元; 請使用 'Is' 運算子測試物件識別。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1_Title">
<source>Operands of type Object used for operator</source>
<target state="translated">對運算子使用了 Object 類型的運算元</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath2">
<source>Operands of type Object used for operator '{0}'; runtime errors could occur.</source>
<target state="translated">供運算子 '{0}' 使用之 Object 類型的運算元; 可能會發生執行階段錯誤。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath2_Title">
<source>Operands of type Object used for operator</source>
<target state="translated">對運算子使用了 Object 類型的運算元</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedVar1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedVar1_Title">
<source>Variable declaration without an 'As' clause</source>
<target state="translated">變數宣告沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumed1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumed1_Title">
<source>Function without an 'As' clause</source>
<target state="translated">函式沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedProperty1">
<source>{0}</source>
<target state="translated">{0}</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectAssumedProperty1_Title">
<source>Property without an 'As' clause</source>
<target state="translated">屬性沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinVarDecl">
<source>Variable declaration without an 'As' clause; type of Object assumed.</source>
<target state="translated">沒有 'As' 子句的變數宣告; 假設是 Object 的類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinVarDecl_Title">
<source>Variable declaration without an 'As' clause</source>
<target state="translated">變數宣告沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinFunction">
<source>Function without an 'As' clause; return type of Object assumed.</source>
<target state="translated">沒有 'As' 子句的函式; 假設是 Object 的傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinFunction_Title">
<source>Function without an 'As' clause</source>
<target state="translated">函式沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinProperty">
<source>Property without an 'As' clause; type of Object assumed.</source>
<target state="translated">沒有 'As' 子句的屬性; 假設是 Object 的類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MissingAsClauseinProperty_Title">
<source>Property without an 'As' clause</source>
<target state="translated">屬性沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocal">
<source>Unused local variable: '{0}'.</source>
<target state="translated">未使用的區域變數: '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocal_Title">
<source>Unused local variable</source>
<target state="translated">未使用的區域變數</target>
<note />
</trans-unit>
<trans-unit id="WRN_SharedMemberThroughInstance">
<source>Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.</source>
<target state="translated">透過執行個體存取共用成員、常數成員、列舉成員或巢狀類型。將不會評估合格的運算式。</target>
<note />
</trans-unit>
<trans-unit id="WRN_SharedMemberThroughInstance_Title">
<source>Access of shared member, constant member, enum member or nested type through an instance</source>
<target state="translated">透過執行個體存取共用成員、常數成員、列舉成員或巢狀類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursivePropertyCall">
<source>Expression recursively calls the containing property '{0}'.</source>
<target state="translated">運算式遞迴呼叫包含屬性 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RecursivePropertyCall_Title">
<source>Expression recursively calls the containing property</source>
<target state="translated">運算式會遞迴呼叫包含屬性</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverlappingCatch">
<source>'Catch' block never reached, because '{0}' inherits from '{1}'.</source>
<target state="translated">'因為 '{0}' 繼承自 '{1}',所以一律不會執行到 'Catch' 區塊。</target>
<note />
</trans-unit>
<trans-unit id="WRN_OverlappingCatch_Title">
<source>'Catch' block never reached; exception type's base type handled above in the same Try statement</source>
<target state="translated">'一律不會執行到 'Catch' 區塊; 例外狀況類型的基底類型已在相同的 Try 陳述式中處理過此項</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRef">
<source>Variable '{0}' is passed by reference before it has been assigned a value. A null reference exception could result at runtime.</source>
<target state="translated">為變數 '{0}' 指派值之前,已藉傳址方式傳遞該數數。可能會在執行階段產生 null 參考例外狀況。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRef_Title">
<source>Variable is passed by reference before it has been assigned a value</source>
<target state="translated">變數在獲派值之前就已藉傳址方式傳遞</target>
<note />
</trans-unit>
<trans-unit id="WRN_DuplicateCatch">
<source>'Catch' block never reached; '{0}' handled above in the same Try statement.</source>
<target state="translated">'{0}' 已在相同的 Try 陳述式中處理過上述項目,所以一律不會進行到 'Catch' 區塊。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DuplicateCatch_Title">
<source>'Catch' block never reached; exception type handled above in the same Try statement</source>
<target state="translated">'一律不會執行到 'Catch' 區塊; 例外狀況類型會在相同 Try 陳述式的上方處理</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1Not">
<source>Operands of type Object used for operator '{0}'; use the 'IsNot' operator to test object identity.</source>
<target state="translated">供運算子 '{0}' 使用之 Object 類型的運算元; 請使用 'IsNot' 運算子測試物件識別。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMath1Not_Title">
<source>Operands of type Object used for operator <></source>
<target state="translated">對運算子 <> 使用了 Object 類型的運算元</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadChecksumValExtChecksum">
<source>Bad checksum value, non hex digits or odd number of hex digits.</source>
<target state="translated">錯誤的總和檢查碼值、非十六進位數字或奇數的十六進位數字。</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadChecksumValExtChecksum_Title">
<source>Bad checksum value, non hex digits or odd number of hex digits</source>
<target state="translated">錯誤的總和檢查碼值,非十六進位數字或奇數的十六進位數字</target>
<note />
</trans-unit>
<trans-unit id="WRN_MultipleDeclFileExtChecksum">
<source>File name already declared with a different GUID and checksum value.</source>
<target state="translated">已使用不同 GUID 與總和檢查碼宣告的檔名。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MultipleDeclFileExtChecksum_Title">
<source>File name already declared with a different GUID and checksum value</source>
<target state="translated">已使用不同的 GUID 與總和檢查碼值宣告的檔名</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadGUIDFormatExtChecksum">
<source>Bad GUID format.</source>
<target state="translated">GUID 格式錯誤。</target>
<note />
</trans-unit>
<trans-unit id="WRN_BadGUIDFormatExtChecksum_Title">
<source>Bad GUID format</source>
<target state="translated">GUID 格式錯誤</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMathSelectCase">
<source>Operands of type Object used in expressions for 'Select', 'Case' statements; runtime errors could occur.</source>
<target state="translated">Select'、'Case' 陳述式的運算式中所使用的類型 Object 的運算元; 可能發生執行階段錯誤。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObjectMathSelectCase_Title">
<source>Operands of type Object used in expressions for 'Select', 'Case' statements</source>
<target state="translated">Select'、'Case' 陳述式的運算式中使用了 Object 類型的運算元</target>
<note />
</trans-unit>
<trans-unit id="WRN_EqualToLiteralNothing">
<source>This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'.</source>
<target state="translated">這個運算式永遠會評估為 Nothing (由於等號運算子的 null 傳播所造成)。若要檢查此值是否為 null,請考慮使用 'Is Nothing'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_EqualToLiteralNothing_Title">
<source>This expression will always evaluate to Nothing</source>
<target state="translated">這個運算式一律會評估為 Nothing</target>
<note />
</trans-unit>
<trans-unit id="WRN_NotEqualToLiteralNothing">
<source>This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is not null consider using 'IsNot Nothing'.</source>
<target state="translated">這個運算式永遠會評估為 Nothing (由於等號運算子的 null 傳播所造成)。若要檢查此值是否並非為 null,請考慮使用 'IsNot Nothing'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NotEqualToLiteralNothing_Title">
<source>This expression will always evaluate to Nothing</source>
<target state="translated">這個運算式一律會評估為 Nothing</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocalConst">
<source>Unused local constant: '{0}'.</source>
<target state="translated">未使用的區域常數: '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnusedLocalConst_Title">
<source>Unused local constant</source>
<target state="translated">未使用的區域常數</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassInterfaceShadows5">
<source>'Microsoft.VisualBasic.ComClassAttribute' on class '{0}' implicitly declares {1} '{2}', which conflicts with a member of the same name in {3} '{4}'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base {4}.</source>
<target state="translated">'在類別 '{0}' 上的 'Microsoft.VisualBasic.ComClassAttribute' 隱含宣告的 {1} '{2}',與 {3} '{4}' 中的同名成員互相衝突。若要隱藏基底 {4} 上的名稱,請使用 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassInterfaceShadows5_Title">
<source>'Microsoft.VisualBasic.ComClassAttribute' on class implicitly declares member, which conflicts with a member of the same name</source>
<target state="translated">'類別上的 'Microsoft.VisualBasic.ComClassAttribute' 隱含宣告了與同名成員互相衝突的成員</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassPropertySetObject1">
<source>'{0}' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement.</source>
<target state="translated">'{0}' 無法以屬性 'Let' 公開給 COM。您無法從 Visual Basic 6.0 使用 'Let' 陳述式,將非物件值 (例如數值或字串) 指定給此屬性。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ComClassPropertySetObject1_Title">
<source>Property cannot be exposed to COM as a property 'Let'</source>
<target state="translated">無法以屬性 'Let' 的形式將屬性公開給 COM</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRef">
<source>Variable '{0}' is used before it has been assigned a value. A null reference exception could result at runtime.</source>
<target state="translated">為變數 '{0}' 指派值之前,已使用該變數。可能會在執行階段產生 null 參考例外狀況。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRef_Title">
<source>Variable is used before it has been assigned a value</source>
<target state="translated">變數在獲派值之前就已使用</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncRef1">
<source>Function '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source>
<target state="translated">函式 '{0}' 並未傳回有關所有程式碼路徑的值。使用該結果時,可能會在執行階段發生 null 參考例外狀況。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncRef1_Title">
<source>Function doesn't return a value on all code paths</source>
<target state="translated">函式在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpRef1">
<source>Operator '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source>
<target state="translated">運算子 '{0}' 並未傳回有關所有程式碼路徑的值。使用該結果時,可能會在執行階段發生 null 參考例外狀況。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpRef1_Title">
<source>Operator doesn't return a value on all code paths</source>
<target state="translated">運算子在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropRef1">
<source>Property '{0}' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.</source>
<target state="translated">屬性 '{0}' 並未傳回有關所有程式碼路徑的值。使用該結果時,可能會在執行階段發生 null 參考例外狀況。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropRef1_Title">
<source>Property doesn't return a value on all code paths</source>
<target state="translated">屬性在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRefStr">
<source>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</source>
<target state="translated">為變數 '{0}' 指派值之前,已藉傳址方式傳遞該變數。可能會在執行階段產生 null 參考例外狀況。請確定結構或所有的參考成員,都在使用前進行過初始化。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefByRefStr_Title">
<source>Variable is passed by reference before it has been assigned a value</source>
<target state="translated">變數在獲派值之前就已藉傳址方式傳遞</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefStr">
<source>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</source>
<target state="translated">為變數 '{0}' 指派值之前,已使用該變數。可能會在執行階段產生 null 參考例外狀況。請確定結構或所有的參考成員,都在使用前進行過初始化。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgUseNullRefStr_Title">
<source>Variable is used before it has been assigned a value</source>
<target state="translated">變數在獲派值之前就已使用</target>
<note />
</trans-unit>
<trans-unit id="WRN_StaticLocalNoInference">
<source>Static variable declared without an 'As' clause; type of Object assumed.</source>
<target state="translated">沒有 'As' 子句的靜態變數宣告; 假設是 Object 的類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_StaticLocalNoInference_Title">
<source>Static variable declared without an 'As' clause</source>
<target state="translated">宣告的靜態變數沒有 'As' 子句</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidAssemblyName">
<source>Assembly reference '{0}' is invalid and cannot be resolved.</source>
<target state="translated">組件參考 '{0}' 無效,無法解析。</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidAssemblyName_Title">
<source>Assembly reference is invalid and cannot be resolved</source>
<target state="translated">組件參考無效,無法進行解析</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadXMLLine">
<source>XML comment block must immediately precede the language element to which it applies. XML comment will be ignored.</source>
<target state="translated">XML 註解區塊必須緊接在所套用的語言元素之前。將會忽略 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadXMLLine_Title">
<source>XML comment block must immediately precede the language element to which it applies</source>
<target state="translated">XML 註解區塊必須緊接在所套用的語言項目之前</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocMoreThanOneCommentBlock">
<source>Only one XML comment block is allowed per language element.</source>
<target state="translated">每個語言項目只允許一個 XML 註解區塊。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocMoreThanOneCommentBlock_Title">
<source>Only one XML comment block is allowed per language element</source>
<target state="translated">每個語言項目只允許一個 XML 註解區塊</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocNotFirstOnLine">
<source>XML comment must be the first statement on a line. XML comment will be ignored.</source>
<target state="translated">XML 註解必須是該行的第一個陳述式。將會忽略 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocNotFirstOnLine_Title">
<source>XML comment must be the first statement on a line</source>
<target state="translated">XML 註解必須是該行的第一個陳述式</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInsideMethod">
<source>XML comment cannot appear within a method or a property. XML comment will be ignored.</source>
<target state="translated">XML 註解不可出現在方法或屬性中。將會忽略 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInsideMethod_Title">
<source>XML comment cannot appear within a method or a property</source>
<target state="translated">XML 註解不得出現在方法或屬性中</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParseError1">
<source>XML documentation parse error: {0} XML comment will be ignored.</source>
<target state="translated">XML 文件剖析錯誤: {0} 將會忽略 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParseError1_Title">
<source>XML documentation parse error</source>
<target state="translated">XML 文件剖析錯誤</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocDuplicateXMLNode1">
<source>XML comment tag '{0}' appears with identical attributes more than once in the same XML comment block.</source>
<target state="translated">在同一個 XML 註解區塊中,XML 註解標記 '{0}' 使用相同的屬性出現多次。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocDuplicateXMLNode1_Title">
<source>XML comment tag appears with identical attributes more than once in the same XML comment block</source>
<target state="translated">在相同的 XML 註解區塊中,XML 註解標記以相同的屬性出現多次</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocIllegalTagOnElement2">
<source>XML comment tag '{0}' is not permitted on a '{1}' language element.</source>
<target state="translated">'{1}' 語言元素上不可使用 XML 註解標記 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocIllegalTagOnElement2_Title">
<source>XML comment tag is not permitted on language element</source>
<target state="translated">語言項目上不得有 XML 註解標記</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadParamTag2">
<source>XML comment parameter '{0}' does not match a parameter on the corresponding '{1}' statement.</source>
<target state="translated">XML 註解參數 '{0}' 與對應的 '{1}' 陳述式上之參數不相符。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadParamTag2_Title">
<source>XML comment parameter does not match a parameter on the corresponding declaration statement</source>
<target state="translated">XML 註解參數與對應的宣告陳述式上的參數不相符</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParamTagWithoutName">
<source>XML comment parameter must have a 'name' attribute.</source>
<target state="translated">XML 註解參數必須要有 'name' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocParamTagWithoutName_Title">
<source>XML comment parameter must have a 'name' attribute</source>
<target state="translated">XML 註解參數必須要有 'name' 屬性</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefAttributeNotFound1">
<source>XML comment has a tag with a 'cref' attribute '{0}' that could not be resolved.</source>
<target state="translated">XML 註解的標記具有無法解析的 'cref' 屬性 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefAttributeNotFound1_Title">
<source>XML comment has a tag with a 'cref' attribute that could not be resolved</source>
<target state="translated">XML 註解的標記具有無法解析的 'cref' 屬性</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLMissingFileOrPathAttribute1">
<source>XML comment tag 'include' must have a '{0}' attribute. XML comment will be ignored.</source>
<target state="translated">XML 註解標記 'include' 必須要有 '{0}' 屬性。將會忽略 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLMissingFileOrPathAttribute1_Title">
<source>XML comment tag 'include' must have 'file' and 'path' attributes</source>
<target state="translated">XML 註解標記 'include' 必須要有 'file' 和 'path' 屬性</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLCannotWriteToXMLDocFile2">
<source>Unable to create XML documentation file '{0}': {1}</source>
<target state="translated">無法建立 XML 文件檔 '{0}': {1}</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLCannotWriteToXMLDocFile2_Title">
<source>Unable to create XML documentation file</source>
<target state="translated">無法建立 XML 文件檔</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocWithoutLanguageElement">
<source>XML documentation comments must precede member or type declarations.</source>
<target state="translated">XML 文件註解必須在成員或類型宣告之前。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocWithoutLanguageElement_Title">
<source>XML documentation comments must precede member or type declarations</source>
<target state="translated">XML 文件註解必須在成員或類型宣告之前</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnWriteOnlyProperty">
<source>XML comment tag 'returns' is not permitted on a 'WriteOnly' Property.</source>
<target state="translated">WriteOnly' 屬性上不可使用 XML 註解標記 'returns'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnWriteOnlyProperty_Title">
<source>XML comment tag 'returns' is not permitted on a 'WriteOnly' Property</source>
<target state="translated">WriteOnly' 屬性上不得使用 XML 註解標記 'returns'</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocOnAPartialType">
<source>XML comment cannot be applied more than once on a partial {0}. XML comments for this {0} will be ignored.</source>
<target state="translated">在部分 {0} 上不可套用多次 XML 註解。將會忽略此 {0} 的 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocOnAPartialType_Title">
<source>XML comment cannot be applied more than once on a partial type</source>
<target state="translated">在部分類型上不可套用多次 XML 註解</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnADeclareSub">
<source>XML comment tag 'returns' is not permitted on a 'declare sub' language element.</source>
<target state="translated">declare sub' 語言元素上不可使用 XML 註解標記 'returns'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocReturnsOnADeclareSub_Title">
<source>XML comment tag 'returns' is not permitted on a 'declare sub' language element</source>
<target state="translated">declare sub' 語言項目上不可使用 XML 註解標記 'returns'</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocStartTagWithNoEndTag">
<source>XML documentation parse error: Start tag '{0}' doesn't have a matching end tag. XML comment will be ignored.</source>
<target state="translated">XML 文件剖析錯誤: 起始標記 '{0}' 並沒有對稱的結束標記。將會忽略 XML 註解。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocStartTagWithNoEndTag_Title">
<source>XML documentation parse error: Start tag doesn't have a matching end tag</source>
<target state="translated">XML 文件剖析錯誤: 起始標記並沒有對稱的結束標記</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadGenericParamTag2">
<source>XML comment type parameter '{0}' does not match a type parameter on the corresponding '{1}' statement.</source>
<target state="translated">XML 註解類型參數 '{0}' 與對應的 '{1}' 陳述式上之類型參數不相符。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadGenericParamTag2_Title">
<source>XML comment type parameter does not match a type parameter on the corresponding declaration statement</source>
<target state="translated">XML 註解類型參數與對應的宣告陳述式上的類型參數不相符</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocGenericParamTagWithoutName">
<source>XML comment type parameter must have a 'name' attribute.</source>
<target state="translated">XML 註解類型參數必須要有 'name' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocGenericParamTagWithoutName_Title">
<source>XML comment type parameter must have a 'name' attribute</source>
<target state="translated">XML 註解類型參數必須要有 'name' 屬性</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocExceptionTagWithoutCRef">
<source>XML comment exception must have a 'cref' attribute.</source>
<target state="translated">XML 註解例外狀況必須要有 'cref' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocExceptionTagWithoutCRef_Title">
<source>XML comment exception must have a 'cref' attribute</source>
<target state="translated">XML 註解例外狀況必須要有 'cref' 屬性</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInvalidXMLFragment">
<source>Unable to include XML fragment '{0}' of file '{1}'.</source>
<target state="translated">無法包含檔案 '{1}' 的 XML 片段 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocInvalidXMLFragment_Title">
<source>Unable to include XML fragment</source>
<target state="translated">無法包含 XML 片段</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadFormedXML">
<source>Unable to include XML fragment '{1}' of file '{0}'. {2}</source>
<target state="translated">無法包含檔案 '{0}' 的 XML 片段 '{1}'。{2}</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocBadFormedXML_Title">
<source>Unable to include XML fragment</source>
<target state="translated">無法包含 XML 片段</target>
<note />
</trans-unit>
<trans-unit id="WRN_InterfaceConversion2">
<source>Runtime errors might occur when converting '{0}' to '{1}'.</source>
<target state="translated">從 '{0}' 轉換至 '{1}' 時,可能會發生執行階段錯誤。</target>
<note />
</trans-unit>
<trans-unit id="WRN_InterfaceConversion2_Title">
<source>Runtime errors might occur when converting to or from interface type</source>
<target state="translated">對介面類型進行來回轉換時可能發生執行階段錯誤</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableLambda">
<source>Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.</source>
<target state="translated">在 Lambda 運算式中使用反覆運算變數可能會產生非預期的結果,請改成在迴圈中建立區域變數,並將反覆運算變數的值指派給它。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableLambda_Title">
<source>Using the iteration variable in a lambda expression may have unexpected results</source>
<target state="translated">在 Lambda 運算式中使用反覆運算變數可能會產生非預期的結果</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaPassedToRemoveHandler">
<source>Lambda expression will not be removed from this event handler. Assign the lambda expression to a variable and use the variable to add and remove the event.</source>
<target state="translated">Lambda 運算式將不會從這個事件處理常式中移除。請將 Lambda 運算式指派給變數,然後使用該變數來加入和移除事件。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaPassedToRemoveHandler_Title">
<source>Lambda expression will not be removed from this event handler</source>
<target state="translated">將不會從這個事件處理常式中移除 Lambda 運算式</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableQuery">
<source>Using the iteration variable in a query expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.</source>
<target state="translated">在查詢運算式中使用反覆運算變數可能會產生非預期的結果,請改成在迴圈中建立區域變數,並將反覆運算變數的值指派給它。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LiftControlVariableQuery_Title">
<source>Using the iteration variable in a query expression may have unexpected results</source>
<target state="translated">在查詢運算式中使用反覆運算變數可能會產生非預期的結果</target>
<note />
</trans-unit>
<trans-unit id="WRN_RelDelegatePassedToRemoveHandler">
<source>The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event. Assign the 'AddressOf' expression to a variable, and use the variable to add or remove the method as the handler.</source>
<target state="translated">AddressOf' 運算式在此內容中沒有作用,因為 'AddressOf' 的方法引數必須以寬鬆的方式轉換成事件的委派類型。請將 'AddressOf' 運算式指派給變數,然後使用該變數來加入或移除做為處理常式的方法。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RelDelegatePassedToRemoveHandler_Title">
<source>The 'AddressOf' expression has no effect in this context because the method argument to 'AddressOf' requires a relaxed conversion to the delegate type of the event</source>
<target state="translated">AddressOf' 運算式在這個內容中沒有作用,因為 'AddressOf' 的方法引數必須以寬鬆的方式轉換成事件的委派類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_QueryMissingAsClauseinVarDecl">
<source>Range variable is assumed to be of type Object because its type cannot be inferred. Use an 'As' clause to specify a different type.</source>
<target state="translated">因為無法推斷範圍變數的類型,所以會將其假設為 Object 類型。請使用 'As' 子句指定不同的類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_QueryMissingAsClauseinVarDecl_Title">
<source>Range variable is assumed to be of type Object because its type cannot be inferred</source>
<target state="translated">範圍變數已假設為 Object 類型,因為無法推斷其類型</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultilineLambdaMissingFunction">
<source>Multiline lambda expression is missing 'End Function'.</source>
<target state="translated">多行 Lambda 運算式遺漏 'End Function'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultilineLambdaMissingSub">
<source>Multiline lambda expression is missing 'End Sub'.</source>
<target state="translated">多行 Lambda 運算式遺漏 'End Sub'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeOnLambdaReturnType">
<source>Attributes cannot be applied to return types of lambda expressions.</source>
<target state="translated">屬性無法套用至 Lambda 運算式的傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubDisallowsStatement">
<source>Statement is not valid inside a single-line statement lambda.</source>
<target state="translated">單行陳述式 Lambda 內的陳述式無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresParenthesesBang">
<source>This single-line statement lambda must be enclosed in parentheses. For example: (Sub() <statement>)!key</source>
<target state="translated">這個單行陳述式 Lambda 必須放在括號之中。例如: (Sub() <statement>)!key</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresParenthesesDot">
<source>This single-line statement lambda must be enclosed in parentheses. For example: (Sub() <statement>).Invoke()</source>
<target state="translated">這個單行陳述式 Lambda 必須放在括號之中。例如: (Sub() <statement>).Invoke()</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresParenthesesLParen">
<source>This single-line statement lambda must be enclosed in parentheses. For example: Call (Sub() <statement>) ()</source>
<target state="translated">這個單行陳述式 Lambda 必須放在括號之中。例如: Call (Sub() <statement>) ()</target>
<note />
</trans-unit>
<trans-unit id="ERR_SubRequiresSingleStatement">
<source>Single-line statement lambdas must include exactly one statement.</source>
<target state="translated">單行陳述式 Lambda 只能有一個陳述式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StaticInLambda">
<source>Static local variables cannot be declared inside lambda expressions.</source>
<target state="translated">Lambda 運算式中不能宣告靜態區域變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InitializedExpandedProperty">
<source>Expanded Properties cannot be initialized.</source>
<target state="translated">無法初始化展開的屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AutoPropertyCantHaveParams">
<source>Auto-implemented properties cannot have parameters.</source>
<target state="translated">自動實作的屬性不能有參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AutoPropertyCantBeWriteOnly">
<source>Auto-implemented properties cannot be WriteOnly.</source>
<target state="translated">自動實作的屬性不可為 WriteOnly。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IllegalOperandInIIFCount">
<source>'If' operator requires either two or three operands.</source>
<target state="translated">'If' 運算子需要兩個或三個運算元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NotACollection1">
<source>Cannot initialize the type '{0}' with a collection initializer because it is not a collection type.</source>
<target state="translated">因為類型 '{0}' 並非集合類型,所以無法利用集合初始設定式初始化該類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoAddMethod1">
<source>Cannot initialize the type '{0}' with a collection initializer because it does not have an accessible 'Add' method.</source>
<target state="translated">無法初始化具有集合初始設定式的類型 '{0}',因為它沒有可存取的 'Add' 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantCombineInitializers">
<source>An Object Initializer and a Collection Initializer cannot be combined in the same initialization.</source>
<target state="translated">物件初始設定式和集合初始設定式不能合併在相同的初始設定中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EmptyAggregateInitializer">
<source>An aggregate collection initializer entry must contain at least one element.</source>
<target state="translated">彙總集合初始設定式項目 (Entry) 至少必須包含一個項目 (Element)。</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlEndElementNoMatchingStart">
<source>XML end element must be preceded by a matching start element.</source>
<target state="translated">XML 結束元素之前必須搭配對稱的起始元素。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MultilineLambdasCannotContainOnError">
<source>'On Error' and 'Resume' cannot appear inside a lambda expression.</source>
<target state="translated">'On Error' 和 'Resume' 不能出現在 Lambda 運算式內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceDisallowedHere">
<source>Keywords 'Out' and 'In' can only be used in interface and delegate declarations.</source>
<target state="translated">關鍵字 'Out' 和 'In' 只能用於介面和委派宣告中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_XmlEndCDataNotAllowedInContent">
<source>The literal string ']]>' is not allowed in element content.</source>
<target state="translated">常值字串 ']]>' 不可用在元素內容中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_OverloadsModifierInModule">
<source>Inappropriate use of '{0}' keyword in a module.</source>
<target state="translated">在模組中使用 '{0}' 關鍵字的方法不適當。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UndefinedTypeOrNamespace1">
<source>Type or namespace '{0}' is not defined.</source>
<target state="translated">未定義類型或命名空間 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_IdentityDirectCastForFloat">
<source>Using DirectCast operator to cast a floating-point value to the same type is not supported.</source>
<target state="translated">不支援使用 DirectCast 運算子將浮點值轉型為相同類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObsoleteIdentityDirectCastForValueType">
<source>Using DirectCast operator to cast a value-type to the same type is obsolete.</source>
<target state="translated">使用 DirectCast 運算子將實值類型轉型為相同類型的做法已過時。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ObsoleteIdentityDirectCastForValueType_Title">
<source>Using DirectCast operator to cast a value-type to the same type is obsolete</source>
<target state="translated">使用 DirectCast 運算子將實值類型轉型為相同類型的做法已過時</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnreachableCode">
<source>Unreachable code detected.</source>
<target state="translated">偵測到無法執行到的程式碼。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnreachableCode_Title">
<source>Unreachable code detected</source>
<target state="translated">偵測到執行不到的程式碼</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncVal1">
<source>Function '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">函式 '{0}' 並未傳回有關所有程式碼路徑的值。是否遺漏了 'Return' 陳述式?</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValFuncVal1_Title">
<source>Function doesn't return a value on all code paths</source>
<target state="translated">函式在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpVal1">
<source>Operator '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">運算子 '{0}' 並未傳回有關所有程式碼路徑的值。是否遺漏了 'Return' 陳述式?</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValOpVal1_Title">
<source>Operator doesn't return a value on all code paths</source>
<target state="translated">運算子在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropVal1">
<source>Property '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">屬性 '{0}' 並未傳回有關所有程式碼路徑的值。是否遺漏了 'Return' 陳述式?</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValPropVal1_Title">
<source>Property doesn't return a value on all code paths</source>
<target state="translated">屬性在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedGlobalNamespace">
<source>Global namespace may not be nested in another namespace.</source>
<target state="translated">全域命名空間不能以巢狀方式放在另一個命名空間中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AccessMismatch6">
<source>'{0}' cannot expose type '{1}' in {2} '{3}' through {4} '{5}'.</source>
<target state="translated">'{0}' 無法經由 {4} '{5}',在 {2} '{3}' 中公開類型 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadMetaDataReference1">
<source>'{0}' cannot be referenced because it is not a valid assembly.</source>
<target state="translated">'無法參考 '{0}',因為它不是有效的組件。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PropertyDoesntImplementAllAccessors">
<source>'{0}' cannot be implemented by a {1} property.</source>
<target state="translated">'{1} 屬性無法實作 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnimplementedMustOverride">
<source>
{0}: {1}</source>
<target state="translated">
{0}: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_IfTooManyTypesObjectDisallowed">
<source>Cannot infer a common type because more than one type is possible.</source>
<target state="translated">無法推斷一般類型,因為可能的類型不止一種。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfTooManyTypesObjectAssumed">
<source>Cannot infer a common type because more than one type is possible; 'Object' assumed.</source>
<target state="translated">無法推斷一般類型,因為可能的類型不止一種; 假設是 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfTooManyTypesObjectAssumed_Title">
<source>Cannot infer a common type because more than one type is possible</source>
<target state="translated">無法推斷一般類型,因為可能的類型不止一種</target>
<note />
</trans-unit>
<trans-unit id="ERR_IfNoTypeObjectDisallowed">
<source>Cannot infer a common type, and Option Strict On does not allow 'Object' to be assumed.</source>
<target state="translated">無法推斷一般類型,而 Option Strict 為 On 不允許假設為 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfNoTypeObjectAssumed">
<source>Cannot infer a common type; 'Object' assumed.</source>
<target state="translated">無法推斷一般類型; 已假設是 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_IfNoTypeObjectAssumed_Title">
<source>Cannot infer a common type</source>
<target state="translated">無法推斷一般類型</target>
<note />
</trans-unit>
<trans-unit id="ERR_IfNoType">
<source>Cannot infer a common type.</source>
<target state="translated">無法推斷一般類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicKeyFileFailure">
<source>Error extracting public key from file '{0}': {1}</source>
<target state="translated">從檔案 '{0}' 擷取公開金鑰時發生錯誤: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicKeyContainerFailure">
<source>Error extracting public key from container '{0}': {1}</source>
<target state="translated">從容器 '{0}' 擷取公開金鑰時發生錯誤: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendRefNotEqualToThis">
<source>Friend access was granted by '{0}', but the public key of the output assembly does not match that specified by the attribute in the granting assembly.</source>
<target state="translated">'{0}' 已授與 Friend 存取權限,但輸出組件的公開金鑰不符合授與之組件中屬性所指定的公開金鑰。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FriendRefSigningMismatch">
<source>Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly.</source>
<target state="translated">'{0}' 已授與 Friend 存取權限,但輸出組件的強式名稱簽署狀態不符合授與組件的強式名稱簽署狀態。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicSignNoKey">
<source>Public sign was specified and requires a public key, but no public key was specified</source>
<target state="translated">公用符號已指定並需要公開金鑰,但未指定公開金鑰</target>
<note />
</trans-unit>
<trans-unit id="ERR_PublicSignNetModule">
<source>Public signing is not supported for netmodules.</source>
<target state="translated">對 netmodule 不支援公開簽署。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeIgnoredWhenPublicSigning">
<source>Attribute '{0}' is ignored when public signing is specified.</source>
<target state="translated">如有指定公用簽章,屬性 '{0}' 將予忽略。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeIgnoredWhenPublicSigning_Title">
<source>Attribute is ignored when public signing is specified.</source>
<target state="translated">如有指定公用簽章,屬性將予忽略。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DelaySignButNoKey">
<source>Delay signing was specified and requires a public key, but no public key was specified.</source>
<target state="translated">已指定延遲簽署,並需要一個公開金鑰,但並未指定任何公開金鑰。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DelaySignButNoKey_Title">
<source>Delay signing was specified and requires a public key, but no public key was specified</source>
<target state="translated">指定了延遲簽署且需要公開金鑰,但未指定任何公開金鑰</target>
<note />
</trans-unit>
<trans-unit id="ERR_SignButNoPrivateKey">
<source>Key file '{0}' is missing the private key needed for signing.</source>
<target state="translated">金鑰檔 '{0}' 遺漏簽署所需的私密金鑰。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FailureSigningAssembly">
<source>Error signing assembly '{0}': {1}</source>
<target state="translated">簽署組件 '{0}' 時發生錯誤: {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidVersionFormat">
<source>The specified version string does not conform to the required format - major[.minor[.build|*[.revision|*]]]</source>
<target state="translated">指定的版本字串不符合所需的格式 - major[.minor[.build|*[.revision|*]]]</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidVersionFormat">
<source>The specified version string does not conform to the recommended format - major.minor.build.revision</source>
<target state="translated">指定的版本字串不符合建議的格式 - major.minor.build.revision</target>
<note />
</trans-unit>
<trans-unit id="WRN_InvalidVersionFormat_Title">
<source>The specified version string does not conform to the recommended format</source>
<target state="translated">指定的版本字串不符合建議的格式</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidVersionFormat2">
<source>The specified version string does not conform to the recommended format - major.minor.build.revision</source>
<target state="translated">指定的版本字串不符合建議的格式 - major.minor.build.revision</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyCultureForExe">
<source>Executables cannot be satellite assemblies; culture should always be empty</source>
<target state="translated">可執行檔不可為附屬組件; 文化特性需保留為空白</target>
<note />
</trans-unit>
<trans-unit id="WRN_MainIgnored">
<source>The entry point of the program is global script code; ignoring '{0}' entry point.</source>
<target state="translated">程式的進入點為全域指令碼; 將略過 '{0}' 進入點。</target>
<note />
</trans-unit>
<trans-unit id="WRN_MainIgnored_Title">
<source>The entry point of the program is global script code; ignoring entry point</source>
<target state="translated">程式的進入點是全域指令碼; 將忽略進入點</target>
<note />
</trans-unit>
<trans-unit id="WRN_EmptyPrefixAndXmlnsLocalName">
<source>The xmlns attribute has special meaning and should not be written with a prefix.</source>
<target state="translated">xmlns 屬性具有特殊意義,寫入時不應該有前置詞。</target>
<note />
</trans-unit>
<trans-unit id="WRN_EmptyPrefixAndXmlnsLocalName_Title">
<source>The xmlns attribute has special meaning and should not be written with a prefix</source>
<target state="translated">xmlns 屬性具有特殊意義,寫入時不應該有前置詞</target>
<note />
</trans-unit>
<trans-unit id="WRN_PrefixAndXmlnsLocalName">
<source>It is not recommended to have attributes named xmlns. Did you mean to write 'xmlns:{0}' to define a prefix named '{0}'?</source>
<target state="translated">不建議使用名為 xmlns 的屬性。是否原本希望寫入 'xmlns:{0}' 以定義名為 '{0}' 的前置詞?</target>
<note />
</trans-unit>
<trans-unit id="WRN_PrefixAndXmlnsLocalName_Title">
<source>It is not recommended to have attributes named xmlns</source>
<target state="translated">不建議將屬性命名為 xmlns</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedSingleScript">
<source>Expected a single script (.vbx file)</source>
<target state="translated">必須是單一指令碼 (.vbx 檔)</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReservedAssemblyName">
<source>The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session</source>
<target state="translated">組件名稱 '{0}' 已保留,不可用做為互動工作階段中的參考</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReferenceDirectiveOnlyAllowedInScripts">
<source>#R is only allowed in scripts</source>
<target state="translated">#R 只可用於指令碼中</target>
<note />
</trans-unit>
<trans-unit id="ERR_NamespaceNotAllowedInScript">
<source>You cannot declare Namespace in script code</source>
<target state="translated">您無法在指令碼中宣告 Namespace</target>
<note />
</trans-unit>
<trans-unit id="ERR_KeywordNotAllowedInScript">
<source>You cannot use '{0}' in top-level script code</source>
<target state="translated">您無法在最上層指令碼中使用 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNoType">
<source>Cannot infer a return type. Consider adding an 'As' clause to specify the return type.</source>
<target state="translated">無法推斷傳回類型。請考慮加入 'As' 子句來指定傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaNoTypeObjectAssumed">
<source>Cannot infer a return type; 'Object' assumed.</source>
<target state="translated">無法推斷傳回類型; 假設是 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaNoTypeObjectAssumed_Title">
<source>Cannot infer a return type</source>
<target state="translated">無法推斷傳回類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaTooManyTypesObjectAssumed">
<source>Cannot infer a return type because more than one type is possible; 'Object' assumed.</source>
<target state="translated">無法推斷傳回類型,因為可能有一個以上的類型; 假設是 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_LambdaTooManyTypesObjectAssumed_Title">
<source>Cannot infer a return type because more than one type is possible</source>
<target state="translated">無法推斷傳回類型,因為可能的類型不止一種</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaNoTypeObjectDisallowed">
<source>Cannot infer a return type. Consider adding an 'As' clause to specify the return type.</source>
<target state="translated">無法推斷傳回類型。請考慮加上 'As' 子句來指定傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LambdaTooManyTypesObjectDisallowed">
<source>Cannot infer a return type because more than one type is possible. Consider adding an 'As' clause to specify the return type.</source>
<target state="translated">無法推斷傳回類型,因為可能的類型不止一種。請考慮加上 'As' 子句來指定傳回類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnimplementedCommandLineSwitch">
<source>The command line switch '{0}' is not yet implemented and was ignored.</source>
<target state="translated">命令列參數 '{0}' 尚未獲實作,已忽略。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnimplementedCommandLineSwitch_Title">
<source>Command line switch is not yet implemented</source>
<target state="translated">尚未實作命令列參數</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitNoTypeObjectDisallowed">
<source>Cannot infer an element type, and Option Strict On does not allow 'Object' to be assumed. Specifying the type of the array might correct this error.</source>
<target state="translated">無法推斷項目類型,而且 Option Strict 為 On 則不允許假設為 'Object'。指定陣列類型或許可以改正這項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitNoType">
<source>Cannot infer an element type. Specifying the type of the array might correct this error.</source>
<target state="translated">無法推斷項目類型。指定陣列類型或許可以改正這項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ArrayInitTooManyTypesObjectDisallowed">
<source>Cannot infer an element type because more than one type is possible. Specifying the type of the array might correct this error.</source>
<target state="translated">無法推斷項目類型,因為可能有一種以上的類型。指定陣列類型或許可以改正這項錯誤。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitNoTypeObjectAssumed">
<source>Cannot infer an element type; 'Object' assumed.</source>
<target state="translated">無法推斷項目類型; 假設是 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitNoTypeObjectAssumed_Title">
<source>Cannot infer an element type</source>
<target state="translated">無法推斷項目類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitTooManyTypesObjectAssumed">
<source>Cannot infer an element type because more than one type is possible; 'Object' assumed.</source>
<target state="translated">無法推斷項目類型,因為可能有一種以上的類型; 假設是 'Object'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ArrayInitTooManyTypesObjectAssumed_Title">
<source>Cannot infer an element type because more than one type is possible</source>
<target state="translated">無法推斷項目類型,因為可能的類型不止一種</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeInferenceAssumed3">
<source>Data type of '{0}' in '{1}' could not be inferred. '{2}' assumed.</source>
<target state="translated">無法推斷 '{1}' 中 '{0}' 的資料類型。已假設是 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_TypeInferenceAssumed3_Title">
<source>Data type could not be inferred</source>
<target state="translated">無法推斷資料類型</target>
<note />
</trans-unit>
<trans-unit id="ERR_AmbiguousCastConversion2">
<source>Option Strict On does not allow implicit conversions from '{0}' to '{1}' because the conversion is ambiguous.</source>
<target state="translated">Option Strict 為 On 時,不可從 '{0}' 隱含轉換至 '{1}',因為轉換模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AmbiguousCastConversion2">
<source>Conversion from '{0}' to '{1}' may be ambiguous.</source>
<target state="translated">從 '{0}' 至 '{1}' 的轉換可能模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AmbiguousCastConversion2_Title">
<source>Conversion may be ambiguous</source>
<target state="translated">轉換可能模稜兩可</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceIEnumerableSuggestion3">
<source>'{0}' cannot be converted to '{1}'. Consider using '{2}' instead.</source>
<target state="translated">'{0}' 無法轉換成 '{1}'。請考慮改用 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceIEnumerableSuggestion3">
<source>'{0}' cannot be converted to '{1}'. Consider using '{2}' instead.</source>
<target state="translated">'{0}' 無法轉換成 '{1}'。請考慮改用 '{2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceIEnumerableSuggestion3_Title">
<source>Type cannot be converted to target collection type</source>
<target state="translated">無法將類型轉換成目標集合類型</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedIn6">
<source>'{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'.</source>
<target state="translated">'{4}' 無法轉換成 '{5}',因為依 '{3}' 中 'In' 泛型參數 '{2}' 的需求,'{0}' 並非衍生自 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedOut6">
<source>'{4}' cannot be converted to '{5}' because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'.</source>
<target state="translated">'{4}' 無法轉換成 '{5}',因為依 '{3}' 中 'Out' 泛型參數 '{2}' 的需求,'{0}' 並非衍生自 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedIn6">
<source>Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'In' generic parameter '{2}' in '{3}'.</source>
<target state="translated">從 '{4}' 隱含轉換成 '{5}'; 此轉換可能會失敗,因為依 '{3}' 中 'In' 泛型參數 '{2}' 之需求,'{0}' 並非衍生自 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedIn6_Title">
<source>Implicit conversion; this conversion may fail because the target type is not derived from the source type, as required for 'In' generic parameter</source>
<target state="translated">隱含轉換; 這個轉換可能會失敗,因為目標類型並非衍生自來源類型,如此不符合 'In' 泛型參數的要求</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedOut6">
<source>Implicit conversion from '{4}' to '{5}'; this conversion may fail because '{0}' is not derived from '{1}', as required for the 'Out' generic parameter '{2}' in '{3}'.</source>
<target state="translated">從 '{4}' 隱含轉換成 '{5}'; 此轉換可能會失敗,因為依 '{3}' 中 'Out' 泛型參數 '{2}' 之需求,'{0}' 並非衍生自 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedOut6_Title">
<source>Implicit conversion; this conversion may fail because the target type is not derived from the source type, as required for 'Out' generic parameter</source>
<target state="translated">隱含轉換; 這個轉換可能失敗,因為目標類型並非衍生自來源類型,如此不符合 'Out' 泛型參數的要求</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedTryIn4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'.</source>
<target state="translated">'{0}' 無法轉換成 '{1}'。請考慮將 '{3}' 之定義中的 '{2}',變更為 In 類型參數 'In {2}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceConversionFailedTryOut4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'.</source>
<target state="translated">'{0}' 無法轉換成 '{1}'。請考慮將 '{3}' 之定義中的 '{2}',變更為 Out 類型參數 'Out {2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryIn4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an In type parameter, 'In {2}'.</source>
<target state="translated">'{0}' 無法轉換成 '{1}'。請考慮將 '{3}' 之定義中的 '{2}',變更為 In 類型參數 'In {2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryIn4_Title">
<source>Type cannot be converted to target type</source>
<target state="translated">無法將類型轉換成目標類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryOut4">
<source>'{0}' cannot be converted to '{1}'. Consider changing the '{2}' in the definition of '{3}' to an Out type parameter, 'Out {2}'.</source>
<target state="translated">'{0}' 無法轉換成 '{1}'。請考慮將 '{3}' 之定義中的 '{2}',變更為 Out 類型參數 'Out {2}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceConversionFailedTryOut4_Title">
<source>Type cannot be converted to target type</source>
<target state="translated">無法將類型轉換成目標類型</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceDeclarationAmbiguous3">
<source>Interface '{0}' is ambiguous with another implemented interface '{1}' due to the 'In' and 'Out' parameters in '{2}'.</source>
<target state="translated">因為 '{2}' 中 'In' 和 'Out' 參數而造成介面 '{0}' 與另一個實作介面 '{1}' 之間模稜兩可。</target>
<note />
</trans-unit>
<trans-unit id="WRN_VarianceDeclarationAmbiguous3_Title">
<source>Interface is ambiguous with another implemented interface due to 'In' and 'Out' parameters</source>
<target state="translated">因為 'In' 和 'Out' 參數的關係,介面與另一個已實作的介面之間模稜兩可</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInterfaceNesting">
<source>Enumerations, classes, and structures cannot be declared in an interface that has an 'In' or 'Out' type parameter.</source>
<target state="translated">無法在有 'In' 或 'Out' 類型參數的介面中宣告列舉、類別和結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VariancePreventsSynthesizedEvents2">
<source>Event definitions with parameters are not allowed in an interface such as '{0}' that has 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which is not defined within '{0}'. For example, 'Event {1} As Action(Of ...)'.</source>
<target state="translated">具有 'In' 或 'Out' 類型參數的介面 (例如 '{0}') 中,不可使用參數進行事件定義。請考慮使用未定義於 '{0}' 內的委派類型,來宣告事件。例如 'Event {1} As Action(Of ...)'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInByRefDisallowed1">
<source>Type '{0}' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 無法用於此內容中,因為 'In' 和 'Out' 類型參數無法用於 ByRef 參數類型,且 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInNullableDisallowed2">
<source>Type '{0}' cannot be used in '{1}' because 'In' and 'Out' type parameters cannot be made nullable, and '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 無法用於 '{1}' 中,因為 'In' 和 'Out' 類型參數不可變成可為 Null,且 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowed1">
<source>Type '{0}' cannot be used in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 無法用在此內容中,因為 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowedForGeneric3">
<source>Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{2}' 中的 '{1}',因為 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowedHere2">
<source>Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{1}',因為 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInParamDisallowedHereForGeneric4">
<source>Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{1}' 中 '{3}' 的 '{2}',因為 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInPropertyDisallowed1">
<source>Type '{0}' cannot be used as a property type in this context because '{0}' is an 'In' type parameter and the property is not marked WriteOnly.</source>
<target state="translated">類型 '{0}' 在此內容中不能用做為屬性類型,因為 '{0}' 是 'In' 類型參數且屬性未標記為 WriteOnly。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInReadOnlyPropertyDisallowed1">
<source>Type '{0}' cannot be used as a ReadOnly property type because '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 不能用做為 ReadOnly 屬性類型,因為 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceInReturnDisallowed1">
<source>Type '{0}' cannot be used as a return type because '{0}' is an 'In' type parameter.</source>
<target state="translated">類型 '{0}' 不能用做為傳回類型,因為 '{0}' 是 'In' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutByRefDisallowed1">
<source>Type '{0}' cannot be used in this context because 'In' and 'Out' type parameters cannot be used for ByRef parameter types, and '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 無法用於此內容中,因為 'In' 和 'Out' 類型參數無法用於 ByRef 參數類型,且 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutByValDisallowed1">
<source>Type '{0}' cannot be used as a ByVal parameter type because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 不能用做為 ByVal 參數類型,因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutConstraintDisallowed1">
<source>Type '{0}' cannot be used as a generic type constraint because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 不能用做為泛型類型條件約束,因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutNullableDisallowed2">
<source>Type '{0}' cannot be used in '{1}' because 'In' and 'Out' type parameters cannot be made nullable, and '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 無法用於 '{1}',因為 'In' 和 'Out' 類型參數不能變成可為 Null,且 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowed1">
<source>Type '{0}' cannot be used in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 無法用於此內容中,因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowedForGeneric3">
<source>Type '{0}' cannot be used for the '{1}' in '{2}' in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{2}' 中的 '{1}',因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowedHere2">
<source>Type '{0}' cannot be used in '{1}' in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{1}',因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutParamDisallowedHereForGeneric4">
<source>Type '{0}' cannot be used for the '{2}' of '{3}' in '{1}' in this context because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{1}' 中 '{3}' 的 '{2}',因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutPropertyDisallowed1">
<source>Type '{0}' cannot be used as a property type in this context because '{0}' is an 'Out' type parameter and the property is not marked ReadOnly.</source>
<target state="translated">類型 '{0}' 在此內容中不能用做為屬性類型,因為 '{0}' 是 'Out' 類型參數,且屬性未標記為 ReadOnly。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceOutWriteOnlyPropertyDisallowed1">
<source>Type '{0}' cannot be used as a WriteOnly property type because '{0}' is an 'Out' type parameter.</source>
<target state="translated">類型 '{0}' 不能用做為 WriteOnly 屬性類型,因為 '{0}' 是 'Out' 類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowed2">
<source>Type '{0}' cannot be used in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">類型 '{0}' 無法用於此內容中,因為該內容和 '{0}' 的定義都位於介面 '{1}' 的巢狀內,且 '{1}' 具有 'In' 或 'Out' 類型參數。請考慮將 '{0}' 的定義移到 '{1}' 之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowedForGeneric4">
<source>Type '{0}' cannot be used for the '{2}' in '{3}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{3}' 中之 '{2}',因為該內容和 '{0}' 的定義都位於介面 '{1}' 的巢狀內,且 '{1}' 具有 'In' 或 'Out' 類型參數。請考慮將 '{0}' 的定義移到 '{1}' 之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowedHere3">
<source>Type '{0}' cannot be used in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{2}',因為該內容和 '{0}' 的定義都位於介面 '{1}' 的巢狀內,且 '{1}' 具有 'In' 或 'Out' 類型參數。請考慮將 '{0}' 的定義移到 '{1}' 之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_VarianceTypeDisallowedHereForGeneric5">
<source>Type '{0}' cannot be used for the '{3}' of '{4}' in '{2}' in this context because both the context and the definition of '{0}' are nested within interface '{1}', and '{1}' has 'In' or 'Out' type parameters. Consider moving the definition of '{0}' outside of '{1}'.</source>
<target state="translated">類型 '{0}' 在此內容中無法用於 '{2}' 中 '{4}' 的 '{3}',因為該內容和 '{0}' 的定義都位於介面 '{1}' 的巢狀內,且 '{1}' 具有 'In' 或 'Out' 類型參數。請考慮將 '{0}' 的定義移到 '{1}' 之外。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParameterNotValidForType">
<source>Parameter not valid for the specified unmanaged type.</source>
<target state="translated">參數對於指定的 Unmanaged 類型無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MarshalUnmanagedTypeNotValidForFields">
<source>Unmanaged type '{0}' not valid for fields.</source>
<target state="translated">Unmanaged 類型 '{0}' 對欄位無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MarshalUnmanagedTypeOnlyValidForFields">
<source>Unmanaged type '{0}' is only valid for fields.</source>
<target state="translated">Unmanaged 類型 '{0}' 只對欄位有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeParameterRequired1">
<source>Attribute parameter '{0}' must be specified.</source>
<target state="translated">必須指定屬性參數 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AttributeParameterRequired2">
<source>Attribute parameter '{0}' or '{1}' must be specified.</source>
<target state="translated">必須指定屬性參數 '{0}' 或 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MemberConflictWithSynth4">
<source>Conflicts with '{0}', which is implicitly declared for '{1}' in {2} '{3}'.</source>
<target state="translated">與 {2} '{3}' 中為 '{1}' 所隱含宣告的 '{0}' 互相衝突。</target>
<note />
</trans-unit>
<trans-unit id="IDS_ProjectSettingsLocationName">
<source><project settings></source>
<target state="translated"><專案設定></target>
<note />
</trans-unit>
<trans-unit id="WRN_ReturnTypeAttributeOnWriteOnlyProperty">
<source>Attributes applied on a return type of a WriteOnly Property have no effect.</source>
<target state="translated">在 WriteOnly 屬性的傳回類型上套用之屬性沒有作用。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ReturnTypeAttributeOnWriteOnlyProperty_Title">
<source>Attributes applied on a return type of a WriteOnly Property have no effect</source>
<target state="translated">在 WriteOnly 屬性的傳回類型上套用的屬性沒有作用</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityAttributeInvalidTarget">
<source>Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations.</source>
<target state="translated">安全屬性 '{0}' 在此宣告類型上無效。安全屬性只有在組件、類型和方法宣告上才有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AbsentReferenceToPIA1">
<source>Cannot find the interop type that matches the embedded type '{0}'. Are you missing an assembly reference?</source>
<target state="translated">找不到符合內嵌類型 '{0}' 的 Interop 類型。是否遺漏組件參考?</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLinkClassWithNoPIA1">
<source>Reference to class '{0}' is not allowed when its assembly is configured to embed interop types.</source>
<target state="translated">在類別 '{0}' 的組件設定為內嵌 Interop 類型時,不可使用該類別的參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidStructMemberNoPIA1">
<source>Embedded interop structure '{0}' can contain only public instance fields.</source>
<target state="translated">內嵌的 Interop 結構 '{0}' 只可包含公用執行個體欄位。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoPIAAttributeMissing2">
<source>Interop type '{0}' cannot be embedded because it is missing the required '{1}' attribute.</source>
<target state="translated">無法內嵌 Interop 類型 '{0}',因為其遺漏必要的 '{1}' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PIAHasNoAssemblyGuid1">
<source>Cannot embed interop types from assembly '{0}' because it is missing the '{1}' attribute.</source>
<target state="translated">無法從組件 '{0}' 內嵌 Interop 類型,因為其遺漏了 '{1}' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DuplicateLocalTypes3">
<source>Cannot embed interop type '{0}' found in both assembly '{1}' and '{2}'. Consider disabling the embedding of interop types.</source>
<target state="translated">無法內嵌在組件 '{1}' 和 '{2}' 中所找到的 Interop 類型 '{0}'。請考慮停用內嵌 Interop 類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PIAHasNoTypeLibAttribute1">
<source>Cannot embed interop types from assembly '{0}' because it is missing either the '{1}' attribute or the '{2}' attribute.</source>
<target state="translated">無法從組件 '{0}' 內嵌 Interop 類型,因為其遺漏了 '{1}' 屬性或 '{2}' 屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SourceInterfaceMustBeInterface">
<source>Interface '{0}' has an invalid source interface which is required to embed event '{1}'.</source>
<target state="translated">介面 '{0}' 的來源介面無效,但內嵌事件 '{1}' 需要該介面。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventNoPIANoBackingMember">
<source>Source interface '{0}' is missing method '{1}', which is required to embed event '{2}'.</source>
<target state="translated">來源介面 '{0}' 遺漏內嵌事件 '{2}' 所需的方法 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestedInteropType">
<source>Nested type '{0}' cannot be embedded.</source>
<target state="translated">無法內嵌巢狀類型 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LocalTypeNameClash2">
<source>Embedding the interop type '{0}' from assembly '{1}' causes a name clash in the current assembly. Consider disabling the embedding of interop types.</source>
<target state="translated">從組件 '{1}' 內嵌 Interop 類型 '{0}',會造成目前組件中的名稱衝突。請考慮停用內嵌 Interop 類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InteropMethodWithBody1">
<source>Embedded interop method '{0}' contains a body.</source>
<target state="translated">內嵌 Interop 方法 '{0}' 包含主體。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncInQuery">
<source>'Await' may only be used in a query expression within the first collection expression of the initial 'From' clause or within the collection expression of a 'Join' clause.</source>
<target state="translated">'Await' 只能使用於初始 'From' 子句第一個集合運算式內的查詢運算式,或 'Join' 子句集合運算式內的查詢運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadGetAwaiterMethod1">
<source>'Await' requires that the type '{0}' have a suitable GetAwaiter method.</source>
<target state="translated">'Await' 要求類型 '{0}' 必須具有合適的 GetAwaiter 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIsCompletedOnCompletedGetResult2">
<source>'Await' requires that the return type '{0}' of '{1}.GetAwaiter()' have suitable IsCompleted, OnCompleted and GetResult members, and implement INotifyCompletion or ICriticalNotifyCompletion.</source>
<target state="translated">'Await' 要求 '{1}.GetAwaiter()' 的傳回類型 '{0}',必須具有合適的 IsCompleted、OnCompleted 和 GetResult 成員,且實作 INotifyCompletion 或 ICriticalNotifyCompletion。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DoesntImplementAwaitInterface2">
<source>'{0}' does not implement '{1}'.</source>
<target state="translated">'{0}' 未實作 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitNothing">
<source>Cannot await Nothing. Consider awaiting 'Task.Yield()' instead.</source>
<target state="translated">無法等候 Nothing。請考慮改為等候 'Task.Yield()'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncByRefParam">
<source>Async methods cannot have ByRef parameters.</source>
<target state="translated">Async 方法不可以有 ByRef 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAsyncIteratorModifiers">
<source>'Async' and 'Iterator' modifiers cannot be used together.</source>
<target state="translated">'Async' 和 'Iterator' 修飾元不可以同時使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadResumableAccessReturnVariable">
<source>The implicit return variable of an Iterator or Async method cannot be accessed.</source>
<target state="translated">無法存取 Iterator 或 Async 方法的隱含傳回變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReturnFromNonGenericTaskAsync">
<source>'Return' statements in this Async method cannot return a value since the return type of the function is 'Task'. Consider changing the function's return type to 'Task(Of T)'.</source>
<target state="translated">'這個 Async 方法中的 'Return' 陳述式無法傳回值,因為函式的傳回類型為 'Task'。請考慮將函式的傳回類型變更為 'Task(Of T)'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncReturnOperand1">
<source>Since this is an async method, the return expression must be of type '{0}' rather than 'Task(Of {0})'.</source>
<target state="translated">因為此為 Async 方法,所以傳回運算式必須是 '{0}' 類型,而非 'Task(Of {0})'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAsyncReturn">
<source>The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T).</source>
<target state="translated">Async' 修飾元只能用在傳回 Task 或 Task(Of T) 的子函數或函式上。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantAwaitAsyncSub1">
<source>'{0}' does not return a Task and cannot be awaited. Consider changing it to an Async Function.</source>
<target state="translated">'{0}' 不會傳回 Task 且無法等候。請考慮將其變更為 Async 函式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidLambdaModifier">
<source>'Only the 'Async' or 'Iterator' modifier is valid on a lambda.</source>
<target state="translated">'Lambda 上只有 'Async' 或 'Iterator' 修飾元有效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInNonAsyncMethod">
<source>'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task(Of {0})'.</source>
<target state="translated">'Await' 只可用於 Async 方法中。請考慮以 'Async' 修飾元標記此方法,並將其傳回類型變更為 'Task(Of {0})'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInNonAsyncVoidMethod">
<source>'Await' can only be used within an Async method. Consider marking this method with the 'Async' modifier and changing its return type to 'Task'.</source>
<target state="translated">'Await' 只能在非同步方法使用。請考慮以 'Async' 修飾元標記此方法,並將它的傳回類型變更為 'Task'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInNonAsyncLambda">
<source>'Await' can only be used within an Async lambda expression. Consider marking this lambda expression with the 'Async' modifier.</source>
<target state="translated">'Await' 只能在非同步 Lambda 運算式使用。請考慮以 'Async' 修飾元標記此 Lambda 運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitNotInAsyncMethodOrLambda">
<source>'Await' can only be used when contained within a method or lambda expression marked with the 'Async' modifier.</source>
<target state="translated">'Await' 只有在包含於以 'Async' 修飾元標記的方法或 Lambda 運算式時才能使用。</target>
<note />
</trans-unit>
<trans-unit id="ERR_StatementLambdaInExpressionTree">
<source>Statement lambdas cannot be converted to expression trees.</source>
<target state="translated">陳述式 Lambda 無法轉換成運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableExpression">
<source>Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the Await operator to the result of the call.</source>
<target state="translated">因為未等候此呼叫,所以在呼叫完成之前會繼續執行目前方法。請考慮將 Await 運算子套用至呼叫的結果。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableExpression_Title">
<source>Because this call is not awaited, execution of the current method continues before the call is completed</source>
<target state="translated">因為未等待此呼叫,所以在完成呼叫之前會繼續執行目前方法</target>
<note />
</trans-unit>
<trans-unit id="ERR_LoopControlMustNotAwait">
<source>Loop control variable cannot include an 'Await'.</source>
<target state="translated">迴圈控制變數不可包含 'Await'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadStaticInitializerInResumable">
<source>Static variables cannot appear inside Async or Iterator methods.</source>
<target state="translated">靜態變數不可出現在 Async 或 Iterator 方法中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RestrictedResumableType1">
<source>'{0}' cannot be used as a parameter type for an Iterator or Async method.</source>
<target state="translated">'{0}' 不能用做為 Iterator 或 Async 方法的參數類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstructorAsync">
<source>Constructor must not have the 'Async' modifier.</source>
<target state="translated">建構函式不可以有 'Async' 修飾元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodsMustNotBeAsync1">
<source>'{0}' cannot be declared 'Partial' because it has the 'Async' modifier.</source>
<target state="translated">'{0}' 不可宣告為 'Partial',因為其具有 'Async' 修飾元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ResumablesCannotContainOnError">
<source>'On Error' and 'Resume' cannot appear inside async or iterator methods.</source>
<target state="translated">'On Error' 和 'Resume' 不可以出現在 async 或 iterator 方法內。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ResumableLambdaInExpressionTree">
<source>Lambdas with the 'Async' or 'Iterator' modifiers cannot be converted to expression trees.</source>
<target state="translated">具有 'Async' 或 'Iterator' 修飾元的 Lambda,無法轉換為運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotLiftRestrictedTypeResumable1">
<source>Variable of restricted type '{0}' cannot be declared in an Async or Iterator method.</source>
<target state="translated">無法在 Async 或 Iterator 方法中宣告受限制之類型 '{0}' 的變數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAwaitInTryHandler">
<source>'Await' cannot be used inside a 'Catch' statement, a 'Finally' statement, or a 'SyncLock' statement.</source>
<target state="translated">'Await' 不能用在 'Catch' 陳述式、'Finally' 陳述式或 'SyncLock' 陳述式內。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncLacksAwaits">
<source>This async method lacks 'Await' operators and so will run synchronously. Consider using the 'Await' operator to await non-blocking API calls, or 'Await Task.Run(...)' to do CPU-bound work on a background thread.</source>
<target state="translated">這個 async 方法缺少 'Await' 運算子,因此將以同步方式執行。請考慮使用 'Await' 運算子等候未封鎖的應用程式開發介面呼叫,或使用 'Await Task.Run(...)' 在背景執行緒上執行 CPU-bound 工作。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncLacksAwaits_Title">
<source>This async method lacks 'Await' operators and so will run synchronously</source>
<target state="translated">這個 async 方法缺少 'Await' 運算子,因此將以同步方式執行</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableDelegate">
<source>The Task returned from this Async Function will be dropped, and any exceptions in it ignored. Consider changing it to an Async Sub so its exceptions are propagated.</source>
<target state="translated">將刪除從這個 Async 函式傳回的 Task,並且忽略其中的任何例外狀況。請考慮將它變更為 Async 子函數,以便傳播例外狀況。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnobservedAwaitableDelegate_Title">
<source>The Task returned from this Async Function will be dropped, and any exceptions in it ignored</source>
<target state="translated">將會卸除從這個 Async 函式傳回的 Task,且會忽略其中的所有例外狀況</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityCriticalAsyncInClassOrStruct">
<source>Async and Iterator methods are not allowed in a [Class|Structure|Interface|Module] that has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.</source>
<target state="translated">具有 'SecurityCritical' 或 'SecuritySafeCritical' 屬性的 [Class|Structure|Interface|Module] 中,不可使用 Async 和 Iterator 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SecurityCriticalAsync">
<source>Security attribute '{0}' cannot be applied to an Async or Iterator method.</source>
<target state="translated">安全屬性 '{0}' 無法套用至 Async 或 Iterator 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_DllImportOnResumableMethod">
<source>'System.Runtime.InteropServices.DllImportAttribute' cannot be applied to an Async or Iterator method.</source>
<target state="translated">'System.Runtime.InteropServices.DllImportAttribute' 無法套用至 Async 或 Iterator 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SynchronizedAsyncMethod">
<source>'MethodImplOptions.Synchronized' cannot be applied to an Async method.</source>
<target state="translated">'MethodImplOptions.Synchronized' 無法套用至 Async 方法。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AsyncSubMain">
<source>The 'Main' method cannot be marked 'Async'.</source>
<target state="translated">Main' 方法不能標記為 'Async。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncSubCouldBeFunction">
<source>Some overloads here take an Async Function rather than an Async Sub. Consider either using an Async Function, or casting this Async Sub explicitly to the desired type.</source>
<target state="translated">這裡的有些多載會接受 Async 函式,而非 Async 子函數。請考慮使用 Async 函式,或者將這個 Async 子函數明確地轉型為想要的類型。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AsyncSubCouldBeFunction_Title">
<source>Some overloads here take an Async Function rather than an Async Sub</source>
<target state="translated">有些此處的多載接受 Async 函式但不接受 Async 子函式</target>
<note />
</trans-unit>
<trans-unit id="ERR_MyGroupCollectionAttributeCycle">
<source>MyGroupCollectionAttribute cannot be applied to itself.</source>
<target state="translated">MyGroupCollectionAttribute 無法套用至本身。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LiteralExpected">
<source>Literal expected.</source>
<target state="translated">必須是常值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_WinRTEventWithoutDelegate">
<source>Event declarations that target WinMD must specify a delegate type. Add an As clause to the event declaration.</source>
<target state="translated">目標為 WinMD 的事件宣告必須指定委派類型。請將 As 子句加入至事件宣告。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MixingWinRTAndNETEvents">
<source>Event '{0}' cannot implement a Windows Runtime event '{1}' and a regular .NET event '{2}'</source>
<target state="translated">事件 '{0}' 無法實作 Windows 執行階段事件 '{1}' 和一般 .NET 事件 '{2}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_EventImplRemoveHandlerParamWrong">
<source>Event '{0}' cannot implement event '{1}' on interface '{2}' because the parameters of their 'RemoveHandler' methods do not match.</source>
<target state="translated">事件 '{0}' 無法在介面 '{2}' 上實作事件 '{1}',因為其 'RemoveHandler' 方法的參數不相符。</target>
<note />
</trans-unit>
<trans-unit id="ERR_AddParamWrongForWinRT">
<source>The type of the 'AddHandler' method's parameter must be the same as the type of the event.</source>
<target state="translated">AddHandler' 方法參數的類型必須與事件的類型相同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RemoveParamWrongForWinRT">
<source>In a Windows Runtime event, the type of the 'RemoveHandler' method parameter must be 'EventRegistrationToken'</source>
<target state="translated">在 Windows 執行階段事件中,'RemoveHandler' 方法參數的類型必須是 'EventRegistrationToken'</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReImplementingWinRTInterface5">
<source>'{0}.{1}' from 'implements {2}' is already implemented by the base class '{3}'. Re-implementation of Windows Runtime Interface '{4}' is not allowed</source>
<target state="translated">'基底類別 '{3}' 已實作 'implements {2}' 中的 '{0}.{1}'。不允許重新實作 Windows 執行階段介面 '{4}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_ReImplementingWinRTInterface4">
<source>'{0}.{1}' is already implemented by the base class '{2}'. Re-implementation of Windows Runtime Interface '{3}' is not allowed</source>
<target state="translated">'基底類別 '{2}' 已實作 '{0}.{1}'。不允許重新實作 Windows 執行階段介面 '{3}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIteratorByRefParam">
<source>Iterator methods cannot have ByRef parameters.</source>
<target state="translated">Iterator 方法不可有 ByRef 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIteratorExpressionLambda">
<source>Single-line lambdas cannot have the 'Iterator' modifier. Use a multiline lambda instead.</source>
<target state="translated">單行 Lambda 不能有 'Iterator' 修飾元。請改用多行 Lambda。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadIteratorReturn">
<source>Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator.</source>
<target state="translated">Iterator 函式必須傳回 IEnumerable(Of T) 或 IEnumerator(Of T),或是非泛型表單 IEnumerable 或 IEnumerator。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadReturnValueInIterator">
<source>To return a value from an Iterator function, use 'Yield' rather than 'Return'.</source>
<target state="translated">若要從 Iterator 函式傳回值,請使用 'Yield' 而不要使用 'Return'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadYieldInNonIteratorMethod">
<source>'Yield' can only be used in a method marked with the 'Iterator' modifier.</source>
<target state="translated">'Yield' 只能用在標記為 'Iterator' 修飾元的方法中。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadYieldInTryHandler">
<source>'Yield' cannot be used inside a 'Catch' statement or a 'Finally' statement.</source>
<target state="translated">'Yield' 不能用在 'Catch' 陳述式或 'Finally' 陳述式內。</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValWinRtEventVal1">
<source>The AddHandler for Windows Runtime event '{0}' doesn't return a value on all code paths. Are you missing a 'Return' statement?</source>
<target state="translated">Windows 執行階段事件 '{0}' 的 AddHandler,並未傳回有關所有程式碼路徑的值。是否遺漏了 'Return' 陳述式?</target>
<note />
</trans-unit>
<trans-unit id="WRN_DefAsgNoRetValWinRtEventVal1_Title">
<source>The AddHandler for Windows Runtime event doesn't return a value on all code paths</source>
<target state="translated">Windows 執行階段事件的 AddHandler 在所有程式碼路徑上皆不會傳回值</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodDefaultParameterValueMismatch2">
<source>Optional parameter of a method '{0}' does not have the same default value as the corresponding parameter of the partial method '{1}'.</source>
<target state="translated">方法 '{0}' 的選擇性參數,與部分方法 '{1}' 的對應參數沒有相同的預設值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PartialMethodParamArrayMismatch2">
<source>Parameter of a method '{0}' differs by ParamArray modifier from the corresponding parameter of the partial method '{1}'.</source>
<target state="translated">方法 '{0}' 的參數與部分方法 '{1}' 的對應參數間之差異,在於 ParamArray 的修飾元不同。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NetModuleNameMismatch">
<source>Module name '{0}' stored in '{1}' must match its filename.</source>
<target state="translated">儲存在 '{1}' 中的模組名稱 '{0}',必須符合其檔案名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadModuleName">
<source>Invalid module name: {0}</source>
<target state="translated">模組名稱 {0} 無效</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden">
<source>Attribute '{0}' from module '{1}' will be ignored in favor of the instance appearing in source.</source>
<target state="translated">將會忽略模組 '{1}' 中的屬性 '{0}',改用出現在來源中的執行個體。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden_Title">
<source>Attribute from module will be ignored in favor of the instance appearing in source</source>
<target state="translated">將會忽略模組中的屬性,改用出現在來源中的執行個體</target>
<note />
</trans-unit>
<trans-unit id="ERR_CmdOptionConflictsSource">
<source>Attribute '{0}' given in a source file conflicts with option '{1}'.</source>
<target state="translated">原始程式檔中所提供的屬性 '{0}',與選項 '{1}' 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName">
<source>Referenced assembly '{0}' does not have a strong name.</source>
<target state="translated">參考組件 '{0}' 沒有強式名稱。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName_Title">
<source>Referenced assembly does not have a strong name</source>
<target state="translated">參考的組件沒有強式名稱</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidSignaturePublicKey">
<source>Invalid signature public key specified in AssemblySignatureKeyAttribute.</source>
<target state="translated">AssemblySignatureKeyAttribute 中指定的簽章公開金鑰無效。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CollisionWithPublicTypeInModule">
<source>Type '{0}' conflicts with public type defined in added module '{1}'.</source>
<target state="translated">類型 '{0}' 與加入的模組 '{1}' 中所定義的公用類型相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExportedTypeConflictsWithDeclaration">
<source>Type '{0}' exported from module '{1}' conflicts with type declared in primary module of this assembly.</source>
<target state="translated">從模組 '{1}' 匯出的類型 '{0}' 與此組件的主要模組中所宣告之類型相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExportedTypesConflict">
<source>Type '{0}' exported from module '{1}' conflicts with type '{2}' exported from module '{3}'.</source>
<target state="translated">從模組 '{1}' 匯出的類型 '{0}' 與從模組 '{3}' 匯出的類型 '{2}' 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RefCultureMismatch">
<source>Referenced assembly '{0}' has different culture setting of '{1}'.</source>
<target state="translated">參考組件 '{0}' 有不同的文化特性設定 '{1}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_RefCultureMismatch_Title">
<source>Referenced assembly has different culture setting</source>
<target state="translated">參考的組件具有不同文化特性設定</target>
<note />
</trans-unit>
<trans-unit id="ERR_AgnosticToMachineModule">
<source>Agnostic assembly cannot have a processor specific module '{0}'.</source>
<target state="translated">無從驗證的組件不可有處理器專屬的模組 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConflictingMachineModule">
<source>Assembly and module '{0}' cannot target different processors.</source>
<target state="translated">組件與模組 '{0}' 的目標處理器不可不同。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConflictingMachineAssembly">
<source>Referenced assembly '{0}' targets a different processor.</source>
<target state="translated">參考組件 '{0}' 以不同的處理器為目標。</target>
<note />
</trans-unit>
<trans-unit id="WRN_ConflictingMachineAssembly_Title">
<source>Referenced assembly targets a different processor</source>
<target state="translated">參考的組件以不同的處理器為目標</target>
<note />
</trans-unit>
<trans-unit id="ERR_CryptoHashFailed">
<source>Cryptographic failure while creating hashes.</source>
<target state="translated">建立雜湊時密碼編譯失敗。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantHaveWin32ResAndManifest">
<source>Conflicting options specified: Win32 resource file; Win32 manifest.</source>
<target state="translated">指定的選項相衝突: Win32 資源檔; Win32 資訊清單。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypeConflictsWithDeclaration">
<source>Forwarded type '{0}' conflicts with type declared in primary module of this assembly.</source>
<target state="translated">轉送的類型 '{0}' 與此組件主要模組中所宣告的類型相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypesConflict">
<source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' forwarded to assembly '{3}'.</source>
<target state="translated">轉送到組件 '{1}' 的類型 '{0}' 與轉送到組件 '{3}' 的類型 '{2}' 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooLongMetadataName">
<source>Name '{0}' exceeds the maximum length allowed in metadata.</source>
<target state="translated">名稱 '{0}' 超過中繼資料內所允許的長度上限。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MissingNetModuleReference">
<source>Reference to '{0}' netmodule missing.</source>
<target state="translated">遺漏 '{0}' netmodule 的參考。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NetModuleNameMustBeUnique">
<source>Module '{0}' is already defined in this assembly. Each module must have a unique filename.</source>
<target state="translated">模組 '{0}' 已定義在此組件中。每個模組都必須要有不重複的檔案名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ForwardedTypeConflictsWithExportedType">
<source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' exported from module '{3}'.</source>
<target state="translated">轉送到組件 '{1}' 的類型 '{0}' 與從模組 '{3}' 匯出的類型 '{2}' 相衝突。</target>
<note />
</trans-unit>
<trans-unit id="IDS_MSG_ADDREFERENCE">
<source>Adding assembly reference '{0}'</source>
<target state="translated">正在加入組件參考 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="IDS_MSG_ADDLINKREFERENCE">
<source>Adding embedded assembly reference '{0}'</source>
<target state="translated">正在加入內嵌組件參考 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="IDS_MSG_ADDMODULE">
<source>Adding module reference '{0}'</source>
<target state="translated">正在加入模組參考 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_NestingViolatesCLS1">
<source>Type '{0}' does not inherit the generic type parameters of its container.</source>
<target state="translated">類型 '{0}' 沒有繼承其容器的泛型類型參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PDBWritingFailed">
<source>Failure writing debug information: {0}</source>
<target state="translated">寫入偵錯資訊時失敗: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_ParamDefaultValueDiffersFromAttribute">
<source>The parameter has multiple distinct default values.</source>
<target state="translated">此參數有多個相異的預設值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_FieldHasMultipleDistinctConstantValues">
<source>The field has multiple distinct constant values.</source>
<target state="translated">此欄位有多個相異的常數值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncNoPIAReference">
<source>Cannot continue since the edit includes a reference to an embedded type: '{0}'.</source>
<target state="translated">無法繼續,因為編輯包含內嵌類型的參考: '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncReferenceToAddedMember">
<source>Member '{0}' added during the current debug session can only be accessed from within its declaring assembly '{1}'.</source>
<target state="translated">在目前偵錯工作階段期間加入的成員 '{0}',只能從其宣告組件中 '{1}' 存取。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedModule1">
<source>'{0}' is an unsupported .NET module.</source>
<target state="translated">'{0}' 不是支援的 .NET 模組。</target>
<note />
</trans-unit>
<trans-unit id="ERR_UnsupportedEvent1">
<source>'{0}' is an unsupported event.</source>
<target state="translated">'{0}' 是不支援的事件。</target>
<note />
</trans-unit>
<trans-unit id="PropertiesCanNotHaveTypeArguments">
<source>Properties can not have type arguments</source>
<target state="translated">屬性不可有類型引數</target>
<note />
</trans-unit>
<trans-unit id="IdentifierSyntaxNotWithinSyntaxTree">
<source>IdentifierSyntax not within syntax tree</source>
<target state="translated">IdentifierSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="AnonymousObjectCreationExpressionSyntaxNotWithinTree">
<source>AnonymousObjectCreationExpressionSyntax not within syntax tree</source>
<target state="translated">AnonymousObjectCreationExpressionSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="FieldInitializerSyntaxNotWithinSyntaxTree">
<source>FieldInitializerSyntax not within syntax tree</source>
<target state="translated">FieldInitializerSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="IDS_TheSystemCannotFindThePathSpecified">
<source>The system cannot find the path specified</source>
<target state="translated">系統找不到指定的路徑</target>
<note />
</trans-unit>
<trans-unit id="ThereAreNoPointerTypesInVB">
<source>There are no pointer types in VB.</source>
<target state="translated">VB 中沒有指標類型。</target>
<note />
</trans-unit>
<trans-unit id="ThereIsNoDynamicTypeInVB">
<source>There is no dynamic type in VB.</source>
<target state="translated">VB 中沒有動態類型。</target>
<note />
</trans-unit>
<trans-unit id="VariableSyntaxNotWithinSyntaxTree">
<source>variableSyntax not within syntax tree</source>
<target state="translated">variableSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="AggregateSyntaxNotWithinSyntaxTree">
<source>AggregateSyntax not within syntax tree</source>
<target state="translated">AggregateSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="FunctionSyntaxNotWithinSyntaxTree">
<source>FunctionSyntax not within syntax tree</source>
<target state="translated">FunctionSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="PositionIsNotWithinSyntax">
<source>Position is not within syntax tree</source>
<target state="translated">Position 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="RangeVariableSyntaxNotWithinSyntaxTree">
<source>RangeVariableSyntax not within syntax tree</source>
<target state="translated">RangeVariableSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="DeclarationSyntaxNotWithinSyntaxTree">
<source>DeclarationSyntax not within syntax tree</source>
<target state="translated">DeclarationSyntax 不在語法樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="StatementOrExpressionIsNotAValidType">
<source>StatementOrExpression is not an ExecutableStatementSyntax or an ExpressionSyntax</source>
<target state="translated">StatementOrExpression 不是 ExecutableStatementSyntax 或 ExpressionSyntax</target>
<note />
</trans-unit>
<trans-unit id="DeclarationSyntaxNotWithinTree">
<source>DeclarationSyntax not within tree</source>
<target state="translated">DeclarationSyntax 不在樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="TypeParameterNotWithinTree">
<source>TypeParameter not within tree</source>
<target state="translated">TypeParameter 不在樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="NotWithinTree">
<source> not within tree</source>
<target state="translated"> 不在樹狀結構中</target>
<note />
</trans-unit>
<trans-unit id="LocationMustBeProvided">
<source>Location must be provided in order to provide minimal type qualification.</source>
<target state="translated">必須提供位置,才可提供最基本的類型限定性條件。</target>
<note />
</trans-unit>
<trans-unit id="SemanticModelMustBeProvided">
<source>SemanticModel must be provided in order to provide minimal type qualification.</source>
<target state="translated">必須提供 SemanticModel,才可提供最基本的類型限定性條件。</target>
<note />
</trans-unit>
<trans-unit id="NumberOfTypeParametersAndArgumentsMustMatch">
<source>the number of type parameters and arguments should be the same</source>
<target state="translated">類型參數和引數的數目應相同</target>
<note />
</trans-unit>
<trans-unit id="ERR_ResourceInModule">
<source>Cannot link resource files when building a module</source>
<target state="translated">建立模組時無法連結資源檔案</target>
<note />
</trans-unit>
<trans-unit id="NotAVbSymbol">
<source>Not a VB symbol.</source>
<target state="translated">不是 VB 符號。</target>
<note />
</trans-unit>
<trans-unit id="ElementsCannotBeNull">
<source>Elements cannot be null.</source>
<target state="translated">項目不可為 null。</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportClause">
<source>Unused import clause.</source>
<target state="translated">未使用的匯入子句。</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportStatement">
<source>Unused import statement.</source>
<target state="translated">未使用的匯入陳述式。</target>
<note />
</trans-unit>
<trans-unit id="WrongSemanticModelType">
<source>Expected a {0} SemanticModel.</source>
<target state="translated">必須是 {0} SemanticModel。</target>
<note />
</trans-unit>
<trans-unit id="PositionNotWithinTree">
<source>Position must be within span of the syntax tree.</source>
<target state="translated">位置必須在語法樹狀結構的範圍內。</target>
<note />
</trans-unit>
<trans-unit id="SpeculatedSyntaxNodeCannotBelongToCurrentCompilation">
<source>Syntax node to be speculated cannot belong to a syntax tree from the current compilation.</source>
<target state="translated">要推測的語法節點,不可屬於目前編譯的語法樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ChainingSpeculativeModelIsNotSupported">
<source>Chaining speculative semantic model is not supported. You should create a speculative model from the non-speculative ParentModel.</source>
<target state="translated">不支援鏈結理論式語意模型。應從非理論式 ParentModel 建立理論式模型。</target>
<note />
</trans-unit>
<trans-unit id="IDS_ToolName">
<source>Microsoft (R) Visual Basic Compiler</source>
<target state="translated">Microsoft (R) Visual Basic 編譯器</target>
<note />
</trans-unit>
<trans-unit id="IDS_LogoLine1">
<source>{0} version {1}</source>
<target state="translated">{0} 版 {1}</target>
<note />
</trans-unit>
<trans-unit id="IDS_LogoLine2">
<source>Copyright (C) Microsoft Corporation. All rights reserved.</source>
<target state="translated">Copyright (C) Microsoft Corporation. 著作權所有,並保留一切權利。</target>
<note />
</trans-unit>
<trans-unit id="IDS_LangVersions">
<source>Supported language versions:</source>
<target state="translated">支援的語言版本:</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbLocalNameTooLong">
<source>Local name '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source>
<target state="translated">區域變數名稱 '{0}' 對 PDB 而言太長。請考慮將其縮短,或在編譯時不要使用 /debug。</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbLocalNameTooLong_Title">
<source>Local name is too long for PDB</source>
<target state="translated">PDB 的本機名稱太長</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbUsingNameTooLong">
<source>Import string '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source>
<target state="translated">匯入字串 '{0}' 對 PDB 而言太長。請考慮縮短長度或不使用 /debug 進行編譯。</target>
<note />
</trans-unit>
<trans-unit id="WRN_PdbUsingNameTooLong_Title">
<source>Import string is too long for PDB</source>
<target state="translated">Import 字串對於 PDB 而言太長</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefToTypeParameter">
<source>XML comment has a tag with a 'cref' attribute '{0}' that bound to a type parameter. Use the <typeparamref> tag instead.</source>
<target state="translated">XML 註解的標記具有繫結至類型參數的 'cref' 屬性 '{0}'。請改用 <typeparamref> 標記。</target>
<note />
</trans-unit>
<trans-unit id="WRN_XMLDocCrefToTypeParameter_Title">
<source>XML comment has a tag with a 'cref' attribute that bound to a type parameter</source>
<target state="translated">XML 註解的標記具有與類型參數繫結的 'cref' 屬性</target>
<note />
</trans-unit>
<trans-unit id="ERR_LinkedNetmoduleMetadataMustProvideFullPEImage">
<source>Linked netmodule metadata must provide a full PE image: '{0}'.</source>
<target state="translated">連結的 netmodule 中繼資料必須提供完整的 PE 影像: '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AnalyzerCannotBeCreated">
<source>An instance of analyzer {0} cannot be created from {1} : {2}.</source>
<target state="translated">不可從 {1} 建立分析器 {0} 的執行個體: {2}。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AnalyzerCannotBeCreated_Title">
<source>Instance of analyzer cannot be created</source>
<target state="translated">無法建立分析器的執行個體</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoAnalyzerInAssembly">
<source>The assembly {0} does not contain any analyzers.</source>
<target state="translated">組件 {0} 不包含任何分析器。</target>
<note />
</trans-unit>
<trans-unit id="WRN_NoAnalyzerInAssembly_Title">
<source>Assembly does not contain any analyzers</source>
<target state="translated">組件不包含任何分析器</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnableToLoadAnalyzer">
<source>Unable to load analyzer assembly {0} : {1}.</source>
<target state="translated">無法載入分析器組件 {0} : {1}。</target>
<note />
</trans-unit>
<trans-unit id="WRN_UnableToLoadAnalyzer_Title">
<source>Unable to load analyzer assembly</source>
<target state="translated">無法載入分析器組件</target>
<note />
</trans-unit>
<trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer">
<source>Skipping some types in analyzer assembly {0} due to a ReflectionTypeLoadException : {1}.</source>
<target state="translated">因為 ReflectionTypeLoadException 之故,所以略過分析器組件 {0} 中的某些類型: {1}。</target>
<note />
</trans-unit>
<trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer_Title">
<source>Skip loading types in analyzer assembly that fail due to a ReflectionTypeLoadException</source>
<target state="translated">跳過載入分析器組件中因 ReflectionTypeLoadException 而失敗的類型</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantReadRulesetFile">
<source>Error reading ruleset file {0} - {1}</source>
<target state="translated">讀取規則集檔案 {0} 時發生錯誤 - {1}</target>
<note />
</trans-unit>
<trans-unit id="ERR_PlatformDoesntSupport">
<source>{0} is not supported in current project type.</source>
<target state="translated">目前的專案類型不支援 {0}。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CantUseRequiredAttribute">
<source>The RequiredAttribute attribute is not permitted on Visual Basic types.</source>
<target state="translated">Visual Basic 類型上不可出現 RequiredAttribute 屬性。</target>
<note />
</trans-unit>
<trans-unit id="ERR_EncodinglessSyntaxTree">
<source>Cannot emit debug information for a source text without encoding.</source>
<target state="translated">無法在不編碼的情況下,對原始程式文字發出偵錯資訊。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidFormatSpecifier">
<source>'{0}' is not a valid format specifier</source>
<target state="translated">'{0}' 不是有效的格式規範</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidPreprocessorConstantType">
<source>Preprocessor constant '{0}' of type '{1}' is not supported, only primitive types are allowed.</source>
<target state="translated">不支援類型為 '{1}' 的前置處理器常數 '{0}',只可使用基本類型。</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpectedWarningKeyword">
<source>'Warning' expected.</source>
<target state="translated">'必須是 'Warning'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotBeMadeNullable1">
<source>'{0}' cannot be made nullable.</source>
<target state="translated">'{0}' 不可為 Null。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadConditionalWithRef">
<source>Leading '?' can only appear inside a 'With' statement, but not inside an object member initializer.</source>
<target state="translated">前置的 '?' 只可出現在 'With' 陳述式中,但不能出現在物件成員初始設定式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NullPropagatingOpInExpressionTree">
<source>A null propagating operator cannot be converted into an expression tree.</source>
<target state="translated">Null 散佈運算子無法轉換為運算式樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooLongOrComplexExpression">
<source>An expression is too long or complex to compile</source>
<target state="translated">運算式太長或太複雜,造成編譯困難</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExpressionDoesntHaveName">
<source>This expression does not have a name.</source>
<target state="translated">此運算式沒有名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidNameOfSubExpression">
<source>This sub-expression cannot be used inside NameOf argument.</source>
<target state="translated">NameOf 引數中不可使用這個子運算式。</target>
<note />
</trans-unit>
<trans-unit id="ERR_MethodTypeArgsUnexpected">
<source>Method type arguments unexpected.</source>
<target state="translated">未預期的方法類型引數。</target>
<note />
</trans-unit>
<trans-unit id="NoNoneSearchCriteria">
<source>SearchCriteria is expected.</source>
<target state="translated">必須是 SearchCriteria。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidAssemblyCulture">
<source>Assembly culture strings may not contain embedded NUL characters.</source>
<target state="translated">組件文化特性字串可能不包含內嵌的 NUL 字元。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InReferencedAssembly">
<source>There is an error in a referenced assembly '{0}'.</source>
<target state="translated">參考組件 '{0}' 中有錯誤。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterpolationFormatWhitespace">
<source>Format specifier may not contain trailing whitespace.</source>
<target state="translated">格式指定器尾端不得有空格。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterpolationAlignmentOutOfRange">
<source>Alignment value is outside of the supported range.</source>
<target state="translated">對齊值超出支援的範圍。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InterpolatedStringFactoryError">
<source>There were one or more errors emitting a call to {0}.{1}. Method or its return type may be missing or malformed.</source>
<target state="translated">對 {0}.{1} 發出呼叫時發生一或多項錯誤。方法或其傳回類型可能遺漏或格式錯誤。</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportClause_Title">
<source>Unused import clause</source>
<target state="translated">未使用的匯入子句</target>
<note />
</trans-unit>
<trans-unit id="HDN_UnusedImportStatement_Title">
<source>Unused import statement</source>
<target state="translated">未使用的匯入陳述式</target>
<note />
</trans-unit>
<trans-unit id="ERR_ConstantStringTooLong">
<source>Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.</source>
<target state="translated">從串連產生的字串常數長度超過 System.Int32.MaxValue。請嘗試將字串分割為多個常數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_LanguageVersion">
<source>Visual Basic {0} does not support {1}.</source>
<target state="translated">Visual Basic {0} 不支援 {1}。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadPdbData">
<source>Error reading debug information for '{0}'</source>
<target state="translated">讀取 '{0}' 的偵錯資訊時發生錯誤</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_ArrayLiterals">
<source>array literal expressions</source>
<target state="translated">陣列常值運算式</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_AsyncExpressions">
<source>async methods or lambdas</source>
<target state="translated">async 方法或 Lambda</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_AutoProperties">
<source>auto-implemented properties</source>
<target state="translated">自動實作的屬性</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_ReadonlyAutoProperties">
<source>readonly auto-implemented properties</source>
<target state="translated">自動實作的唯讀屬性</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CoContraVariance">
<source>variance</source>
<target state="translated">變異數</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CollectionInitializers">
<source>collection initializers</source>
<target state="translated">集合初始設定式</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_GlobalNamespace">
<source>declaring a Global namespace</source>
<target state="translated">宣告全域命名空間</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_Iterators">
<source>iterators</source>
<target state="translated">迭代器</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_LineContinuation">
<source>implicit line continuation</source>
<target state="translated">隱含行接續符號</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_StatementLambdas">
<source>multi-line lambda expressions</source>
<target state="translated">多行 Lambda 運算式</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_SubLambdas">
<source>'Sub' lambda expressions</source>
<target state="translated">'Sub' Lambda 運算式</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_NullPropagatingOperator">
<source>null conditional operations</source>
<target state="translated">null 條件運算</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_NameOfExpressions">
<source>'nameof' expressions</source>
<target state="translated">'nameof' 運算式</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_RegionsEverywhere">
<source>region directives within method bodies or regions crossing boundaries of declaration blocks</source>
<target state="translated">方法主體內的區域指示詞,或跨宣告區塊界限的區域</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_MultilineStringLiterals">
<source>multiline string literals</source>
<target state="translated">多行字串常值</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_CObjInAttributeArguments">
<source>CObj in attribute arguments</source>
<target state="translated">屬性引數中的 CObj</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_LineContinuationComments">
<source>line continuation comments</source>
<target state="translated">行接續符號註解</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_TypeOfIsNot">
<source>TypeOf IsNot expression</source>
<target state="translated">TypeOf IsNot 運算式</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_YearFirstDateLiterals">
<source>year-first date literals</source>
<target state="translated">以年起始的日期常值</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_WarningDirectives">
<source>warning directives</source>
<target state="translated">警告指示詞</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_PartialModules">
<source>partial modules</source>
<target state="translated">部分模組</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_PartialInterfaces">
<source>partial interfaces</source>
<target state="translated">部分介面</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_ImplementingReadonlyOrWriteonlyPropertyWithReadwrite">
<source>implementing read-only or write-only property with read-write property</source>
<target state="translated">實作唯讀或唯寫屬性以及讀寫屬性</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_DigitSeparators">
<source>digit separators</source>
<target state="translated">數字分隔符號</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_BinaryLiterals">
<source>binary literals</source>
<target state="translated">二進位常值</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_Tuples">
<source>tuples</source>
<target state="translated">元組</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_PrivateProtected">
<source>Private Protected</source>
<target state="translated">Private Protected</target>
<note />
</trans-unit>
<trans-unit id="ERR_DebugEntryPointNotSourceMethodDefinition">
<source>Debug entry point must be a definition of a method declared in the current compilation.</source>
<target state="translated">偵錯進入點必須是目前編譯中所宣告方法的定義。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidPathMap">
<source>The pathmap option was incorrectly formatted.</source>
<target state="translated">pathmap 選項格式不正確。</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTreeIsNotASubmission">
<source>Syntax tree should be created from a submission.</source>
<target state="translated">提交時就應該建立語法樹狀結構。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TooManyUserStrings">
<source>Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string or XML literals.</source>
<target state="translated">程式所使用的使用者字串加起來長度超過允許限制。請嘗試減少使用字串或 XML 常值。</target>
<note />
</trans-unit>
<trans-unit id="ERR_PeWritingFailure">
<source>An error occurred while writing the output file: {0}</source>
<target state="translated">寫入輸出檔案時發生錯誤: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_OptionMustBeAbsolutePath">
<source>Option '{0}' must be an absolute path.</source>
<target state="translated">選項 '{0}' 必須是絕對路徑。</target>
<note />
</trans-unit>
<trans-unit id="ERR_SourceLinkRequiresPdb">
<source>/sourcelink switch is only supported when emitting PDB.</source>
<target state="translated">只有在發出 PDB 時才支援 /sourcelink 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleDuplicateElementName">
<source>Tuple element names must be unique.</source>
<target state="translated">元組元素名稱不得重複。</target>
<note />
</trans-unit>
<trans-unit id="WRN_TupleLiteralNameMismatch">
<source>The tuple element name '{0}' is ignored because a different name or no name is specified by the target type '{1}'.</source>
<target state="translated">因為目標類型 '{1}' 指定了不同的名稱或未指定名稱,所以會忽略元組項目名稱 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_TupleLiteralNameMismatch_Title">
<source>The tuple element name is ignored because a different name or no name is specified by the assignment target.</source>
<target state="translated">因為指派目標指定了不同的名稱或未指定名稱,所以會忽略元組項目名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleReservedElementName">
<source>Tuple element name '{0}' is only allowed at position {1}.</source>
<target state="translated">只有位置 {1} 允許元組元素名稱 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleReservedElementNameAnyPosition">
<source>Tuple element name '{0}' is disallowed at any position.</source>
<target state="translated">任何位置都不允許元組元素名稱 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleTooFewElements">
<source>Tuple must contain at least two elements.</source>
<target state="translated">元組必須包含至少兩個項目。</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleElementNamesAttributeMissing">
<source>Cannot define a class or member that utilizes tuples because the compiler required type '{0}' cannot be found. Are you missing a reference?</source>
<target state="translated">因為找不到編譯器所需的類型 '{0}',所以無法定義利用元組的類別或成員。是否遺漏參考?</target>
<note />
</trans-unit>
<trans-unit id="ERR_ExplicitTupleElementNamesAttribute">
<source>Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names.</source>
<target state="translated">無法明確參考 'System.Runtime.CompilerServices.TupleElementNamesAttribute'。請使用元組語法定義元組名稱。</target>
<note />
</trans-unit>
<trans-unit id="ERR_RefReturningCallInExpressionTree">
<source>An expression tree may not contain a call to a method or property that returns by reference.</source>
<target state="translated">運算式樹狀架構不能包含藉傳址所傳回的方法或屬性呼叫。</target>
<note />
</trans-unit>
<trans-unit id="ERR_CannotEmbedWithoutPdb">
<source>/embed switch is only supported when emitting a PDB.</source>
<target state="translated">只有在發出 PDB 時才支援 /embed 參數。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidInstrumentationKind">
<source>Invalid instrumentation kind: {0}</source>
<target state="translated">檢測設備種類無效: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_DocFileGen">
<source>Error writing to XML documentation file: {0}</source>
<target state="translated">寫入 XML 文件檔案時發生錯誤: {0}</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadAssemblyName">
<source>Invalid assembly name: {0}</source>
<target state="translated">組件名稱 {0} 無效</target>
<note />
</trans-unit>
<trans-unit id="ERR_TypeForwardedToMultipleAssemblies">
<source>Module '{0}' in assembly '{1}' is forwarding the type '{2}' to multiple assemblies: '{3}' and '{4}'.</source>
<target state="translated">組件 '{1}' 中的模組 '{0}' 正在將類型 '{2}' 轉送給多個組件: '{3}' 及 '{4}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_Merge_conflict_marker_encountered">
<source>Merge conflict marker encountered</source>
<target state="translated">偵測到合併衝突標記</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoRefOutWhenRefOnly">
<source>Do not use refout when using refonly.</source>
<target state="translated">使用 refonly 時,請勿使用 refout。</target>
<note />
</trans-unit>
<trans-unit id="ERR_NoNetModuleOutputWhenRefOutOrRefOnly">
<source>Cannot compile net modules when using /refout or /refonly.</source>
<target state="translated">使用 /refout 或 /refonly 時無法編譯網路模組。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadNonTrailingNamedArgument">
<source>Named argument '{0}' is used out-of-position but is followed by an unnamed argument</source>
<target state="translated">具名引數 '{0}' 未用在正確的位置,但後面接著未命名引數</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadDocumentationMode">
<source>Provided documentation mode is unsupported or invalid: '{0}'.</source>
<target state="translated">提供的文件模式不受支援或無效: '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadLanguageVersion">
<source>Provided language version is unsupported or invalid: '{0}'.</source>
<target state="translated">提供的語言版本不受支援或無效: '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="ERR_BadSourceCodeKind">
<source>Provided source code kind is unsupported or invalid: '{0}'</source>
<target state="translated">提供的原始程式碼類型不受支援或無效: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="ERR_TupleInferredNamesNotAvailable">
<source>Tuple element name '{0}' is inferred. Please use language version {1} or greater to access an element by its inferred name.</source>
<target state="translated">元組項目名稱 '{0}' 從推斷而來。請使用語言版本 {1} 或更新版本,依推斷名稱存取項目。</target>
<note />
</trans-unit>
<trans-unit id="WRN_Experimental">
<source>'{0}' is for evaluation purposes only and is subject to change or removal in future updates.</source>
<target state="translated">'{0}' 僅供評估之用。後續更新時可能會有所變更或移除。</target>
<note />
</trans-unit>
<trans-unit id="WRN_Experimental_Title">
<source>Type is for evaluation purposes only and is subject to change or removal in future updates.</source>
<target state="translated">類型僅供評估之用。後續更新時可能會有所變更或移除。</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidDebugInfo">
<source>Unable to read debug information of method '{0}' (token 0x{1}) from assembly '{2}'</source>
<target state="translated">無法從組件 '{2}' 讀取方法 '{0}' 的偵錯資訊 (權杖 0x{1})</target>
<note />
</trans-unit>
<trans-unit id="IConversionExpressionIsNotVisualBasicConversion">
<source>{0} is not a valid Visual Basic conversion expression</source>
<target state="translated">{0} 不是有效的 Visual Basic 轉換運算式</target>
<note />
</trans-unit>
<trans-unit id="IArgumentIsNotVisualBasicArgument">
<source>{0} is not a valid Visual Basic argument</source>
<target state="translated">{0} 不是有效的 Visual Basic 引數</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_LeadingDigitSeparator">
<source>leading digit separator</source>
<target state="translated">前置數字分隔符號</target>
<note />
</trans-unit>
<trans-unit id="ERR_ValueTupleResolutionAmbiguous3">
<source>Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}'</source>
<target state="translated">在多個參考組件中宣告了預先定義的類型 '{0}': '{1}' 與 '{2}'</target>
<note />
</trans-unit>
<trans-unit id="ICompoundAssignmentOperationIsNotVisualBasicCompoundAssignment">
<source>{0} is not a valid Visual Basic compound assignment operation</source>
<target state="translated">{0} 不是有效的 Visual Basic 複合指派作業</target>
<note />
</trans-unit>
<trans-unit id="ERR_InvalidHashAlgorithmName">
<source>Invalid hash algorithm name: '{0}'</source>
<target state="translated">雜湊演算法名稱無效: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="FEATURE_InterpolatedStrings">
<source>interpolated strings</source>
<target state="translated">內插字串</target>
<note />
</trans-unit>
<trans-unit id="FTL_InvalidInputFileName">
<source>File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long</source>
<target state="translated">檔案名稱 '{0}' 是空的、包含了無效字元、指定了磁碟機但不是絕對路徑,或太長了</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeNotSupportedInVB">
<source>'{0}' is not supported in VB.</source>
<target state="translated">VB 中不支援 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="WRN_AttributeNotSupportedInVB_Title">
<source>Attribute is not supported in VB</source>
<target state="translated">VB 中不支援屬性</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/Core/Impl/CodeModel/ExternalElements/ExternalCodeEvent.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE80.CodeEvent))]
public sealed class ExternalCodeEvent : AbstractExternalCodeMember, EnvDTE80.CodeEvent
{
internal static EnvDTE80.CodeEvent Create(CodeModelState state, ProjectId projectId, IEventSymbol symbol)
{
var element = new ExternalCodeEvent(state, projectId, symbol);
return (EnvDTE80.CodeEvent)ComAggregate.CreateAggregatedObject(element);
}
private ExternalCodeEvent(CodeModelState state, ProjectId projectId, IEventSymbol symbol)
: base(state, projectId, symbol)
{
}
private IEventSymbol EventSymbol
{
get { return (IEventSymbol)LookupSymbol(); }
}
protected override EnvDTE.CodeElements GetParameters()
=> throw new NotImplementedException();
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementEvent; }
}
public EnvDTE.CodeFunction Adder
{
get
{
var symbol = EventSymbol;
if (symbol.AddMethod == null)
{
throw Exceptions.ThrowEFail();
}
return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.AddMethod, this);
}
set
{
throw Exceptions.ThrowEFail();
}
}
// TODO: Verify VB implementation
public bool IsPropertyStyleEvent
{
get { return true; }
}
// TODO: Verify VB implementation
public EnvDTE80.vsCMOverrideKind OverrideKind
{
get
{
throw Exceptions.ThrowENotImpl();
}
set
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeFunction Remover
{
get
{
var symbol = EventSymbol;
if (symbol.RemoveMethod == null)
{
throw Exceptions.ThrowEFail();
}
return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.RemoveMethod, this);
}
set
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeFunction Thrower
{
get
{
// TODO: Verify this with VB implementation
var symbol = EventSymbol;
if (symbol.RaiseMethod == null)
{
throw Exceptions.ThrowEFail();
}
return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.RaiseMethod, this);
}
set
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeTypeRef Type
{
get
{
return CodeTypeRef.Create(this.State, this, this.ProjectId, EventSymbol.Type);
}
set
{
throw Exceptions.ThrowEFail();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE80.CodeEvent))]
public sealed class ExternalCodeEvent : AbstractExternalCodeMember, EnvDTE80.CodeEvent
{
internal static EnvDTE80.CodeEvent Create(CodeModelState state, ProjectId projectId, IEventSymbol symbol)
{
var element = new ExternalCodeEvent(state, projectId, symbol);
return (EnvDTE80.CodeEvent)ComAggregate.CreateAggregatedObject(element);
}
private ExternalCodeEvent(CodeModelState state, ProjectId projectId, IEventSymbol symbol)
: base(state, projectId, symbol)
{
}
private IEventSymbol EventSymbol
{
get { return (IEventSymbol)LookupSymbol(); }
}
protected override EnvDTE.CodeElements GetParameters()
=> throw new NotImplementedException();
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementEvent; }
}
public EnvDTE.CodeFunction Adder
{
get
{
var symbol = EventSymbol;
if (symbol.AddMethod == null)
{
throw Exceptions.ThrowEFail();
}
return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.AddMethod, this);
}
set
{
throw Exceptions.ThrowEFail();
}
}
// TODO: Verify VB implementation
public bool IsPropertyStyleEvent
{
get { return true; }
}
// TODO: Verify VB implementation
public EnvDTE80.vsCMOverrideKind OverrideKind
{
get
{
throw Exceptions.ThrowENotImpl();
}
set
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeFunction Remover
{
get
{
var symbol = EventSymbol;
if (symbol.RemoveMethod == null)
{
throw Exceptions.ThrowEFail();
}
return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.RemoveMethod, this);
}
set
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeFunction Thrower
{
get
{
// TODO: Verify this with VB implementation
var symbol = EventSymbol;
if (symbol.RaiseMethod == null)
{
throw Exceptions.ThrowEFail();
}
return ExternalCodeAccessorFunction.Create(this.State, this.ProjectId, symbol.RaiseMethod, this);
}
set
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeTypeRef Type
{
get
{
return CodeTypeRef.Create(this.State, this, this.ProjectId, EventSymbol.Type);
}
set
{
throw Exceptions.ThrowEFail();
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.GenerateFromMembers;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.GenerateEqualsAndGetHashCodeFromMembers), Shared]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.GenerateConstructorFromMembers,
Before = PredefinedCodeRefactoringProviderNames.AddConstructorParametersFromMembers)]
internal partial class GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider : AbstractGenerateFromMembersCodeRefactoringProvider
{
public const string GenerateOperatorsId = nameof(GenerateOperatorsId);
public const string ImplementIEquatableId = nameof(ImplementIEquatableId);
private const string EqualsName = nameof(object.Equals);
private const string GetHashCodeName = nameof(object.GetHashCode);
private readonly IPickMembersService? _pickMembersService_forTestingPurposes;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider()
: this(pickMembersService: null)
{
}
[SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")]
public GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider(IPickMembersService? pickMembersService)
=> _pickMembersService_forTestingPurposes = pickMembersService;
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var actions = await GenerateEqualsAndGetHashCodeFromMembersAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
if (actions.IsDefaultOrEmpty && textSpan.IsEmpty)
{
await HandleNonSelectionAsync(context).ConfigureAwait(false);
}
}
private async Task HandleNonSelectionAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// We offer the refactoring when the user is either on the header of a class/struct,
// or if they're between any members of a class/struct and are on a blank line.
if (!syntaxFacts.IsOnTypeHeader(root, textSpan.Start, out var typeDeclaration) &&
!syntaxFacts.IsBetweenTypeMembers(sourceText, root, textSpan.Start, out typeDeclaration))
{
return;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// Only supported on classes/structs.
var containingType = semanticModel.GetDeclaredSymbol(typeDeclaration) as INamedTypeSymbol;
if (containingType?.TypeKind is not TypeKind.Class and not TypeKind.Struct)
{
return;
}
// No overrides in static classes.
if (containingType.IsStatic)
{
return;
}
// Find all the possible instance fields/properties. If there are any, then
// show a dialog to the user to select the ones they want.
var viableMembers = containingType
.GetBaseTypesAndThis()
.Reverse()
.SelectAccessibleMembers<ISymbol>(containingType)
.Where(IsReadableInstanceFieldOrProperty)
.ToImmutableArray();
if (viableMembers.Length == 0)
{
return;
}
GetExistingMemberInfo(
containingType, out var hasEquals, out var hasGetHashCode);
var actions = await CreateActionsAsync(
document, typeDeclaration, containingType, viableMembers,
hasEquals, hasGetHashCode, withDialog: true, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
}
private static bool HasOperators(INamedTypeSymbol containingType)
=> HasOperator(containingType, WellKnownMemberNames.EqualityOperatorName) ||
HasOperator(containingType, WellKnownMemberNames.InequalityOperatorName);
private static bool HasOperator(INamedTypeSymbol containingType, string operatorName)
=> containingType.GetMembers(operatorName)
.OfType<IMethodSymbol>()
.Any(m => m.MethodKind == MethodKind.UserDefinedOperator &&
m.Parameters.Length == 2 &&
containingType.Equals(m.Parameters[0].Type) &&
containingType.Equals(m.Parameters[1].Type));
private static bool CanImplementIEquatable(
SemanticModel semanticModel, INamedTypeSymbol containingType,
[NotNullWhen(true)] out INamedTypeSymbol? constructedType)
{
// A ref struct can never implement an interface, therefore never add IEquatable to the selection
// options if the type is a ref struct.
if (!containingType.IsRefLikeType)
{
var equatableTypeOpt = semanticModel.Compilation.GetTypeByMetadataName(typeof(IEquatable<>).FullName!);
if (equatableTypeOpt != null)
{
constructedType = equatableTypeOpt.Construct(containingType);
// A ref struct can never implement an interface, therefore never add IEquatable to the selection
// options if the type is a ref struct.
return !containingType.AllInterfaces.Contains(constructedType);
}
}
constructedType = null;
return false;
}
private static void GetExistingMemberInfo(INamedTypeSymbol containingType, out bool hasEquals, out bool hasGetHashCode)
{
hasEquals = containingType.GetMembers(EqualsName)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Length == 1 && !m.IsStatic);
hasGetHashCode = containingType.GetMembers(GetHashCodeName)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Length == 0 && !m.IsStatic);
}
public async Task<ImmutableArray<CodeAction>> GenerateEqualsAndGetHashCodeFromMembersAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_GenerateFromMembers_GenerateEqualsAndGetHashCode, cancellationToken))
{
var info = await GetSelectedMemberInfoAsync(document, textSpan, allowPartialSelection: false, cancellationToken).ConfigureAwait(false);
if (info != null &&
info.SelectedMembers.All(IsReadableInstanceFieldOrProperty))
{
if (info.ContainingType != null && info.ContainingType.TypeKind != TypeKind.Interface)
{
GetExistingMemberInfo(
info.ContainingType, out var hasEquals, out var hasGetHashCode);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var typeDeclaration = syntaxFacts.GetContainingTypeDeclaration(root, textSpan.Start);
RoslynDebug.AssertNotNull(typeDeclaration);
return await CreateActionsAsync(
document, typeDeclaration, info.ContainingType, info.SelectedMembers,
hasEquals, hasGetHashCode, withDialog: false, cancellationToken).ConfigureAwait(false);
}
}
return default;
}
}
private async Task<ImmutableArray<CodeAction>> CreateActionsAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers,
bool hasEquals, bool hasGetHashCode, bool withDialog, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Task<CodeAction>>.GetInstance(out var tasks);
if (!hasEquals && !hasGetHashCode)
{
// if we don't have either Equals or GetHashCode then offer:
// "Generate Equals" and
// "Generate Equals and GethashCode"
//
// Don't bother offering to just "Generate GetHashCode" as it's very unlikely
// the user would need to bother just generating that member without also
// generating 'Equals' as well.
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: false, withDialog, cancellationToken));
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: true, withDialog, cancellationToken));
}
else if (!hasEquals)
{
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: false, withDialog, cancellationToken));
}
else if (!hasGetHashCode)
{
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: false, generateGetHashCode: true, withDialog, cancellationToken));
}
var codeActions = await Task.WhenAll(tasks).ConfigureAwait(false);
return codeActions.ToImmutableArray();
}
private Task<CodeAction> CreateCodeActionAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, bool withDialog, CancellationToken cancellationToken)
{
return withDialog
? CreateCodeActionWithDialogAsync(document, typeDeclaration, containingType, members, generateEquals, generateGetHashCode, cancellationToken)
: CreateCodeActionWithoutDialogAsync(document, typeDeclaration, containingType, members, generateEquals, generateGetHashCode, cancellationToken);
}
private async Task<CodeAction> CreateCodeActionWithDialogAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, CancellationToken cancellationToken)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<PickMembersOption>.GetInstance(out var pickMembersOptions);
if (CanImplementIEquatable(semanticModel, containingType, out var equatableTypeOpt))
{
var value = options.GetOption(GenerateEqualsAndGetHashCodeFromMembersOptions.ImplementIEquatable);
var displayName = equatableTypeOpt.ToDisplayString(new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters));
pickMembersOptions.Add(new PickMembersOption(
ImplementIEquatableId,
string.Format(FeaturesResources.Implement_0, displayName),
value));
}
if (!HasOperators(containingType))
{
var value = options.GetOption(GenerateEqualsAndGetHashCodeFromMembersOptions.GenerateOperators);
pickMembersOptions.Add(new PickMembersOption(
GenerateOperatorsId,
FeaturesResources.Generate_operators,
value));
}
return new GenerateEqualsAndGetHashCodeWithDialogCodeAction(
this, document, typeDeclaration, containingType, members,
pickMembersOptions.ToImmutable(), generateEquals, generateGetHashCode);
}
private static async Task<CodeAction> CreateCodeActionWithoutDialogAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, CancellationToken cancellationToken)
{
var implementIEquatable = false;
var generateOperators = false;
if (generateEquals && containingType.TypeKind == TypeKind.Struct)
{
// if we're generating equals for a struct, then also add IEquatable<S> support as
// well as operators (as long as the struct does not already have them).
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
implementIEquatable = CanImplementIEquatable(semanticModel, containingType, out _);
generateOperators = !HasOperators(containingType);
}
return new GenerateEqualsAndGetHashCodeAction(
document, typeDeclaration, containingType, members,
generateEquals, generateGetHashCode, implementIEquatable, generateOperators);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.GenerateFromMembers;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.GenerateEqualsAndGetHashCodeFromMembers), Shared]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.GenerateConstructorFromMembers,
Before = PredefinedCodeRefactoringProviderNames.AddConstructorParametersFromMembers)]
internal partial class GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider : AbstractGenerateFromMembersCodeRefactoringProvider
{
public const string GenerateOperatorsId = nameof(GenerateOperatorsId);
public const string ImplementIEquatableId = nameof(ImplementIEquatableId);
private const string EqualsName = nameof(object.Equals);
private const string GetHashCodeName = nameof(object.GetHashCode);
private readonly IPickMembersService? _pickMembersService_forTestingPurposes;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider()
: this(pickMembersService: null)
{
}
[SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")]
public GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider(IPickMembersService? pickMembersService)
=> _pickMembersService_forTestingPurposes = pickMembersService;
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var actions = await GenerateEqualsAndGetHashCodeFromMembersAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
if (actions.IsDefaultOrEmpty && textSpan.IsEmpty)
{
await HandleNonSelectionAsync(context).ConfigureAwait(false);
}
}
private async Task HandleNonSelectionAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// We offer the refactoring when the user is either on the header of a class/struct,
// or if they're between any members of a class/struct and are on a blank line.
if (!syntaxFacts.IsOnTypeHeader(root, textSpan.Start, out var typeDeclaration) &&
!syntaxFacts.IsBetweenTypeMembers(sourceText, root, textSpan.Start, out typeDeclaration))
{
return;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// Only supported on classes/structs.
var containingType = semanticModel.GetDeclaredSymbol(typeDeclaration) as INamedTypeSymbol;
if (containingType?.TypeKind is not TypeKind.Class and not TypeKind.Struct)
{
return;
}
// No overrides in static classes.
if (containingType.IsStatic)
{
return;
}
// Find all the possible instance fields/properties. If there are any, then
// show a dialog to the user to select the ones they want.
var viableMembers = containingType
.GetBaseTypesAndThis()
.Reverse()
.SelectAccessibleMembers<ISymbol>(containingType)
.Where(IsReadableInstanceFieldOrProperty)
.ToImmutableArray();
if (viableMembers.Length == 0)
{
return;
}
GetExistingMemberInfo(
containingType, out var hasEquals, out var hasGetHashCode);
var actions = await CreateActionsAsync(
document, typeDeclaration, containingType, viableMembers,
hasEquals, hasGetHashCode, withDialog: true, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
}
private static bool HasOperators(INamedTypeSymbol containingType)
=> HasOperator(containingType, WellKnownMemberNames.EqualityOperatorName) ||
HasOperator(containingType, WellKnownMemberNames.InequalityOperatorName);
private static bool HasOperator(INamedTypeSymbol containingType, string operatorName)
=> containingType.GetMembers(operatorName)
.OfType<IMethodSymbol>()
.Any(m => m.MethodKind == MethodKind.UserDefinedOperator &&
m.Parameters.Length == 2 &&
containingType.Equals(m.Parameters[0].Type) &&
containingType.Equals(m.Parameters[1].Type));
private static bool CanImplementIEquatable(
SemanticModel semanticModel, INamedTypeSymbol containingType,
[NotNullWhen(true)] out INamedTypeSymbol? constructedType)
{
// A ref struct can never implement an interface, therefore never add IEquatable to the selection
// options if the type is a ref struct.
if (!containingType.IsRefLikeType)
{
var equatableTypeOpt = semanticModel.Compilation.GetTypeByMetadataName(typeof(IEquatable<>).FullName!);
if (equatableTypeOpt != null)
{
constructedType = equatableTypeOpt.Construct(containingType);
// A ref struct can never implement an interface, therefore never add IEquatable to the selection
// options if the type is a ref struct.
return !containingType.AllInterfaces.Contains(constructedType);
}
}
constructedType = null;
return false;
}
private static void GetExistingMemberInfo(INamedTypeSymbol containingType, out bool hasEquals, out bool hasGetHashCode)
{
hasEquals = containingType.GetMembers(EqualsName)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Length == 1 && !m.IsStatic);
hasGetHashCode = containingType.GetMembers(GetHashCodeName)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Length == 0 && !m.IsStatic);
}
public async Task<ImmutableArray<CodeAction>> GenerateEqualsAndGetHashCodeFromMembersAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_GenerateFromMembers_GenerateEqualsAndGetHashCode, cancellationToken))
{
var info = await GetSelectedMemberInfoAsync(document, textSpan, allowPartialSelection: false, cancellationToken).ConfigureAwait(false);
if (info != null &&
info.SelectedMembers.All(IsReadableInstanceFieldOrProperty))
{
if (info.ContainingType != null && info.ContainingType.TypeKind != TypeKind.Interface)
{
GetExistingMemberInfo(
info.ContainingType, out var hasEquals, out var hasGetHashCode);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var typeDeclaration = syntaxFacts.GetContainingTypeDeclaration(root, textSpan.Start);
RoslynDebug.AssertNotNull(typeDeclaration);
return await CreateActionsAsync(
document, typeDeclaration, info.ContainingType, info.SelectedMembers,
hasEquals, hasGetHashCode, withDialog: false, cancellationToken).ConfigureAwait(false);
}
}
return default;
}
}
private async Task<ImmutableArray<CodeAction>> CreateActionsAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers,
bool hasEquals, bool hasGetHashCode, bool withDialog, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Task<CodeAction>>.GetInstance(out var tasks);
if (!hasEquals && !hasGetHashCode)
{
// if we don't have either Equals or GetHashCode then offer:
// "Generate Equals" and
// "Generate Equals and GethashCode"
//
// Don't bother offering to just "Generate GetHashCode" as it's very unlikely
// the user would need to bother just generating that member without also
// generating 'Equals' as well.
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: false, withDialog, cancellationToken));
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: true, withDialog, cancellationToken));
}
else if (!hasEquals)
{
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: false, withDialog, cancellationToken));
}
else if (!hasGetHashCode)
{
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: false, generateGetHashCode: true, withDialog, cancellationToken));
}
var codeActions = await Task.WhenAll(tasks).ConfigureAwait(false);
return codeActions.ToImmutableArray();
}
private Task<CodeAction> CreateCodeActionAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, bool withDialog, CancellationToken cancellationToken)
{
return withDialog
? CreateCodeActionWithDialogAsync(document, typeDeclaration, containingType, members, generateEquals, generateGetHashCode, cancellationToken)
: CreateCodeActionWithoutDialogAsync(document, typeDeclaration, containingType, members, generateEquals, generateGetHashCode, cancellationToken);
}
private async Task<CodeAction> CreateCodeActionWithDialogAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, CancellationToken cancellationToken)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<PickMembersOption>.GetInstance(out var pickMembersOptions);
if (CanImplementIEquatable(semanticModel, containingType, out var equatableTypeOpt))
{
var value = options.GetOption(GenerateEqualsAndGetHashCodeFromMembersOptions.ImplementIEquatable);
var displayName = equatableTypeOpt.ToDisplayString(new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters));
pickMembersOptions.Add(new PickMembersOption(
ImplementIEquatableId,
string.Format(FeaturesResources.Implement_0, displayName),
value));
}
if (!HasOperators(containingType))
{
var value = options.GetOption(GenerateEqualsAndGetHashCodeFromMembersOptions.GenerateOperators);
pickMembersOptions.Add(new PickMembersOption(
GenerateOperatorsId,
FeaturesResources.Generate_operators,
value));
}
return new GenerateEqualsAndGetHashCodeWithDialogCodeAction(
this, document, typeDeclaration, containingType, members,
pickMembersOptions.ToImmutable(), generateEquals, generateGetHashCode);
}
private static async Task<CodeAction> CreateCodeActionWithoutDialogAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, CancellationToken cancellationToken)
{
var implementIEquatable = false;
var generateOperators = false;
if (generateEquals && containingType.TypeKind == TypeKind.Struct)
{
// if we're generating equals for a struct, then also add IEquatable<S> support as
// well as operators (as long as the struct does not already have them).
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
implementIEquatable = CanImplementIEquatable(semanticModel, containingType, out _);
generateOperators = !HasOperators(containingType);
}
return new GenerateEqualsAndGetHashCodeAction(
document, typeDeclaration, containingType, members,
generateEquals, generateGetHashCode, implementIEquatable, generateOperators);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/Formatting/ExportNewDocumentFormattingProviderAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis.Formatting
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
internal class ExportNewDocumentFormattingProviderAttribute : ExportAttribute
{
public ExportNewDocumentFormattingProviderAttribute(string languageName)
: base(typeof(INewDocumentFormattingProvider))
{
Language = languageName;
}
public string Language { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis.Formatting
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class)]
internal class ExportNewDocumentFormattingProviderAttribute : ExportAttribute
{
public ExportNewDocumentFormattingProviderAttribute(string languageName)
: base(typeof(INewDocumentFormattingProvider))
{
Language = languageName;
}
public string Language { get; }
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/Core/Test.Next/Services/LspDiagnosticsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient;
using Microsoft.VisualStudio.Threading;
using Moq;
using Nerdbank.Streams;
using Newtonsoft.Json.Linq;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using StreamJsonRpc;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Roslyn.VisualStudio.Next.UnitTests.Services
{
[UseExportProvider]
public class LspDiagnosticsTests : AbstractLanguageServerProtocolTests
{
[Fact]
public async Task AddDiagnosticTestAsync()
{
using var workspace = CreateTestLspServer("", out _).TestWorkspace;
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Create a mock that returns a diagnostic for the document.
SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false));
// Publish one document change diagnostic notification ->
// 1. doc1 with id.
//
// We expect one publish diagnostic notification ->
// 1. from doc1 with id.
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 1, document).ConfigureAwait(false);
var result = Assert.Single(results);
Assert.Equal(new Uri(document.FilePath), result.Uri);
Assert.Equal("id", result.Diagnostics.Single().Code);
}
[Fact]
public async Task NoDiagnosticsWhenInPullMode()
{
using var workspace = CreateTestLspServer("", out _).TestWorkspace;
workspace.SetOptions(workspace.Options.WithChangedOption(
InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull));
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Create a mock that returns a diagnostic for the document.
SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false));
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 0, document).ConfigureAwait(false);
Assert.Empty(results);
}
[Fact]
public async Task AddDiagnosticWithMappedFilesTestAsync()
{
using var workspace = CreateTestLspServer("", out _).TestWorkspace;
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Create two mapped diagnostics for the document.
SetupMockWithDiagnostics(diagnosticsMock, document.Id,
await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", document.FilePath + "m1"), ("id2", document.FilePath + "m2")).ConfigureAwait(false));
// Publish one document change diagnostic notification ->
// 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2.
//
// We expect two publish diagnostic notifications ->
// 1. from m1 with id1 (from 1 above).
// 2. from m2 with id2 (from 1 above).
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, expectedNumberOfCallbacks: 2, document).ConfigureAwait(false);
Assert.Equal(2, results.Count);
Assert.Equal(new Uri(document.FilePath + "m1"), results[0].Uri);
Assert.Equal("id1", results[0].Diagnostics.Single().Code);
Assert.Equal(new Uri(document.FilePath + "m2"), results[1].Uri);
Assert.Equal("id2", results[1].Diagnostics.Single().Code);
}
[Fact]
public async Task AddDiagnosticWithMappedFileToManyDocumentsTestAsync()
{
using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace;
var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Create diagnostic for the first document that has a mapped location.
var mappedFilePath = documents[0].FilePath + "m1";
var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false);
// Create diagnostic for the second document that maps to the same location as the first document diagnostic.
var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false);
SetupMockWithDiagnostics(diagnosticsMock, documents[0].Id, documentOneDiagnostic);
SetupMockWithDiagnostics(diagnosticsMock, documents[1].Id, documentTwoDiagnostic);
// Publish two document change diagnostic notifications ->
// 1. doc1 with doc1Diagnostic = mapped file m1.
// 2. doc2 with doc2Diagnostic = mapped file m1.
//
// We expect two publish diagnostic notifications ->
// 1. from m1 with doc1Diagnostic (from 1 above).
// 2. from m1 with doc1Diagnostic and doc2Diagnostic (from 2 above adding doc2Diagnostic to m1).
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 2, documents[0], documents[1]).ConfigureAwait(false);
Assert.Equal(2, results.Count);
var expectedUri = new Uri(mappedFilePath);
Assert.Equal(expectedUri, results[0].Uri);
Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code);
Assert.Equal(expectedUri, results[1].Uri);
Assert.Equal(2, results[1].Diagnostics.Length);
Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic");
Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic");
}
[Fact]
public async Task RemoveDiagnosticTestAsync()
{
using var workspace = CreateTestLspServer("", out _).TestWorkspace;
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Setup the mock so the first call for a document returns a diagnostic, but the second returns empty.
SetupMockDiagnosticSequence(diagnosticsMock, document.Id,
await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false),
ImmutableArray<DiagnosticData>.Empty);
// Publish two document change diagnostic notifications ->
// 1. doc1 with id.
// 2. doc1 with empty.
//
// We expect two publish diagnostic notifications ->
// 1. from doc1 with id.
// 2. from doc1 with empty (from 2 above clearing out diagnostics from doc1).
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 2, document, document).ConfigureAwait(false);
Assert.Equal(2, results.Count);
Assert.Equal(new Uri(document.FilePath), results[0].Uri);
Assert.Equal("id", results[0].Diagnostics.Single().Code);
Assert.Equal(new Uri(document.FilePath), results[1].Uri);
Assert.True(results[1].Diagnostics.IsEmpty());
Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris());
Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics());
}
[Fact]
public async Task RemoveDiagnosticForMappedFilesTestAsync()
{
using var workspace = CreateTestLspServer("", out _).TestWorkspace;
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
var mappedFilePathM1 = document.FilePath + "m1";
var mappedFilePathM2 = document.FilePath + "m2";
// Create two mapped diagnostics for the document on first call.
// On the second call, return only the second mapped diagnostic for the document.
SetupMockDiagnosticSequence(diagnosticsMock, document.Id,
await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", mappedFilePathM1), ("id2", mappedFilePathM2)).ConfigureAwait(false),
await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id2", mappedFilePathM2)).ConfigureAwait(false));
// Publish three document change diagnostic notifications ->
// 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2.
// 2. doc1 with just id2 = mapped file m2.
//
// We expect four publish diagnostic notifications ->
// 1. from m1 with id1 (from 1 above).
// 2. from m2 with id2 (from 1 above).
// 3. from m1 with empty (from 2 above clearing out diagnostics for m1).
// 4. from m2 with id2 (from 2 above clearing out diagnostics for m1).
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, document, document).ConfigureAwait(false);
var mappedFileURIM1 = new Uri(mappedFilePathM1);
var mappedFileURIM2 = new Uri(mappedFilePathM2);
Assert.Equal(4, results.Count);
// First document update.
Assert.Equal(mappedFileURIM1, results[0].Uri);
Assert.Equal("id1", results[0].Diagnostics.Single().Code);
Assert.Equal(mappedFileURIM2, results[1].Uri);
Assert.Equal("id2", results[1].Diagnostics.Single().Code);
// Second document update.
Assert.Equal(mappedFileURIM1, results[2].Uri);
Assert.True(results[2].Diagnostics.IsEmpty());
Assert.Equal(mappedFileURIM2, results[3].Uri);
Assert.Equal("id2", results[3].Diagnostics.Single().Code);
Assert.Single(testAccessor.GetFileUrisForDocument(document.Id), mappedFileURIM2);
Assert.Equal("id2", testAccessor.GetDiagnosticsForUriAndDocument(document.Id, mappedFileURIM2).Single().Code);
Assert.Empty(testAccessor.GetDiagnosticsForUriAndDocument(document.Id, mappedFileURIM1));
}
[Fact]
public async Task RemoveDiagnosticForMappedFileToManyDocumentsTestAsync()
{
using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace;
var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Create diagnostic for the first document that has a mapped location.
var mappedFilePath = documents[0].FilePath + "m1";
var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false);
// Create diagnostic for the second document that maps to the same location as the first document diagnostic.
var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false);
// On the first call for this document, return the mapped diagnostic. On the second, return nothing.
SetupMockDiagnosticSequence(diagnosticsMock, documents[0].Id, documentOneDiagnostic, ImmutableArray<DiagnosticData>.Empty);
// Always return the mapped diagnostic for this document.
SetupMockWithDiagnostics(diagnosticsMock, documents[1].Id, documentTwoDiagnostic);
// Publish three document change diagnostic notifications ->
// 1. doc1 with doc1Diagnostic = mapped file path m1
// 2. doc2 with doc2Diagnostic = mapped file path m1
// 3. doc1 with empty.
//
// We expect three publish diagnostics ->
// 1. from m1 with doc1Diagnostic (triggered by 1 above to add doc1Diagnostic).
// 2. from m1 with doc1Diagnostic and doc2Diagnostic (triggered by 2 above to add doc2Diagnostic).
// 3. from m1 with just doc2Diagnostic (triggered by 3 above to remove doc1Diagnostic).
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 3, documents[0], documents[1], documents[0]).ConfigureAwait(false);
Assert.Equal(3, results.Count);
var expectedUri = new Uri(mappedFilePath);
Assert.Equal(expectedUri, results[0].Uri);
Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code);
Assert.Equal(expectedUri, results[1].Uri);
Assert.Equal(2, results[1].Diagnostics.Length);
Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic");
Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic");
Assert.Equal(expectedUri, results[2].Uri);
Assert.Equal(1, results[2].Diagnostics.Length);
Assert.Contains(results[2].Diagnostics, d => d.Code == "doc2Diagnostic");
Assert.Single(testAccessor.GetFileUrisForDocument(documents[1].Id), expectedUri);
Assert.Equal("doc2Diagnostic", testAccessor.GetDiagnosticsForUriAndDocument(documents[1].Id, expectedUri).Single().Code);
Assert.Empty(testAccessor.GetDiagnosticsForUriAndDocument(documents[0].Id, expectedUri));
}
[Fact]
public async Task ClearAllDiagnosticsForMappedFilesTestAsync()
{
using var workspace = CreateTestLspServer("", out _).TestWorkspace;
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
var mappedFilePathM1 = document.FilePath + "m1";
var mappedFilePathM2 = document.FilePath + "m2";
// Create two mapped diagnostics for the document on first call.
// On the second call, return only empty diagnostics.
SetupMockDiagnosticSequence(diagnosticsMock, document.Id,
await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", mappedFilePathM1), ("id2", mappedFilePathM2)).ConfigureAwait(false),
ImmutableArray<DiagnosticData>.Empty);
// Publish two document change diagnostic notifications ->
// 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2.
// 2. doc1 with empty.
//
// We expect four publish diagnostic notifications - the first two are the two mapped files from 1.
// The second two are the two mapped files being cleared by 2.
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, document, document).ConfigureAwait(false);
var mappedFileURIM1 = new Uri(document.FilePath + "m1");
var mappedFileURIM2 = new Uri(document.FilePath + "m2");
Assert.Equal(4, results.Count);
// Document's first update.
Assert.Equal(mappedFileURIM1, results[0].Uri);
Assert.Equal("id1", results[0].Diagnostics.Single().Code);
Assert.Equal(mappedFileURIM2, results[1].Uri);
Assert.Equal("id2", results[1].Diagnostics.Single().Code);
// Document's second update.
Assert.Equal(mappedFileURIM1, results[2].Uri);
Assert.True(results[2].Diagnostics.IsEmpty());
Assert.Equal(mappedFileURIM2, results[3].Uri);
Assert.True(results[3].Diagnostics.IsEmpty());
Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris());
Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics());
}
[Fact]
public async Task ClearAllDiagnosticsForMappedFileToManyDocumentsTestAsync()
{
using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace;
var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Create diagnostic for the first document that has a mapped location.
var mappedFilePath = documents[0].FilePath + "m1";
var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false);
// Create diagnostic for the second document that maps to the same location as the first document diagnostic.
var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false);
// On the first call for the documents, return the mapped diagnostic. On the second, return nothing.
SetupMockDiagnosticSequence(diagnosticsMock, documents[0].Id, documentOneDiagnostic, ImmutableArray<DiagnosticData>.Empty);
SetupMockDiagnosticSequence(diagnosticsMock, documents[1].Id, documentTwoDiagnostic, ImmutableArray<DiagnosticData>.Empty);
// Publish four document change diagnostic notifications ->
// 1. doc1 with doc1Diagnostic = mapped file m1.
// 2. doc2 with doc2Diagnostic = mapped file m1.
// 3. doc1 with empty diagnostics.
// 4. doc2 with empty diagnostics.
//
// We expect four publish diagnostics ->
// 1. from URI m1 with doc1Diagnostic (triggered by 1 above to add doc1Diagnostic).
// 2. from URI m1 with doc1Diagnostic and doc2Diagnostic (triggered by 2 above to add doc2Diagnostic).
// 3. from URI m1 with just doc2Diagnostic (triggered by 3 above to clear doc1 diagnostic).
// 4. from URI m1 with empty (triggered by 4 above to also clear doc2 diagnostic).
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, documents[0], documents[1], documents[0], documents[1]).ConfigureAwait(false);
Assert.Equal(4, results.Count);
var expectedUri = new Uri(mappedFilePath);
Assert.Equal(expectedUri, results[0].Uri);
Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code);
Assert.Equal(expectedUri, results[1].Uri);
Assert.Equal(2, results[1].Diagnostics.Length);
Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic");
Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic");
Assert.Equal(expectedUri, results[2].Uri);
Assert.Equal(1, results[2].Diagnostics.Length);
Assert.Contains(results[2].Diagnostics, d => d.Code == "doc2Diagnostic");
Assert.Equal(expectedUri, results[3].Uri);
Assert.True(results[3].Diagnostics.IsEmpty());
Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris());
Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics());
}
private async Task<(VisualStudioInProcLanguageServer.TestAccessor, List<LSP.PublishDiagnosticParams>)> RunPublishDiagnosticsAsync(
TestWorkspace workspace,
IDiagnosticService diagnosticService,
int expectedNumberOfCallbacks,
params Document[] documentsToPublish)
{
var (clientStream, serverStream) = FullDuplexStream.CreatePair();
var languageServer = CreateLanguageServer(serverStream, serverStream, workspace, diagnosticService);
// Notification target for tests to receive the notification details
var callback = new Callback(expectedNumberOfCallbacks);
using var jsonRpc = new JsonRpc(clientStream, clientStream, callback)
{
ExceptionStrategy = ExceptionProcessing.ISerializable,
};
// The json rpc messages won't necessarily come back in order by default.
// So use a synchronization context to preserve the original ordering.
// https://github.com/microsoft/vs-streamjsonrpc/blob/bc970c61b90db5db135a1b3d1c72ef355c2112af/doc/resiliency.md#when-message-order-is-important
jsonRpc.SynchronizationContext = new RpcOrderPreservingSynchronizationContext();
jsonRpc.StartListening();
// Triggers language server to send notifications.
await languageServer.ProcessDiagnosticUpdatedBatchAsync(
diagnosticService, documentsToPublish.SelectAsArray(d => d.Id), CancellationToken.None);
// Waits for all notifications to be received.
await callback.CallbackCompletedTask.ConfigureAwait(false);
return (languageServer.GetTestAccessor(), callback.Results);
static VisualStudioInProcLanguageServer CreateLanguageServer(Stream inputStream, Stream outputStream, TestWorkspace workspace, IDiagnosticService mockDiagnosticService)
{
var dispatcherFactory = workspace.ExportProvider.GetExportedValue<RequestDispatcherFactory>();
var listenerProvider = workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>();
var lspWorkspaceRegistrationService = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>();
var capabilitiesProvider = workspace.ExportProvider.GetExportedValue<DefaultCapabilitiesProvider>();
var jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream))
{
ExceptionStrategy = ExceptionProcessing.ISerializable,
};
var languageServer = new VisualStudioInProcLanguageServer(
dispatcherFactory,
jsonRpc,
capabilitiesProvider,
lspWorkspaceRegistrationService,
listenerProvider,
NoOpLspLogger.Instance,
mockDiagnosticService,
ProtocolConstants.RoslynLspLanguages,
clientName: null,
userVisibleServerName: string.Empty,
telemetryServerTypeName: string.Empty);
jsonRpc.StartListening();
return languageServer;
}
}
private void SetupMockWithDiagnostics(Mock<IDiagnosticService> diagnosticServiceMock, DocumentId documentId, ImmutableArray<DiagnosticData> diagnostics)
{
diagnosticServiceMock.Setup(d => d.GetPushDiagnosticsAsync(
It.IsAny<Workspace>(),
It.IsAny<ProjectId>(),
documentId,
It.IsAny<object>(),
It.IsAny<bool>(),
It.IsAny<Option2<DiagnosticMode>>(),
It.IsAny<CancellationToken>())).Returns(new ValueTask<ImmutableArray<DiagnosticData>>(diagnostics));
}
private void SetupMockDiagnosticSequence(Mock<IDiagnosticService> diagnosticServiceMock, DocumentId documentId,
ImmutableArray<DiagnosticData> firstDiagnostics, ImmutableArray<DiagnosticData> secondDiagnostics)
{
diagnosticServiceMock.SetupSequence(d => d.GetPushDiagnosticsAsync(
It.IsAny<Workspace>(),
It.IsAny<ProjectId>(),
documentId,
It.IsAny<object>(),
It.IsAny<bool>(),
It.IsAny<Option2<DiagnosticMode>>(),
It.IsAny<CancellationToken>()))
.Returns(new ValueTask<ImmutableArray<DiagnosticData>>(firstDiagnostics))
.Returns(new ValueTask<ImmutableArray<DiagnosticData>>(secondDiagnostics));
}
private async Task<ImmutableArray<DiagnosticData>> CreateMockDiagnosticDataAsync(Document document, string id)
{
var descriptor = new DiagnosticDescriptor(id, "", "", "", DiagnosticSeverity.Error, true);
var location = Location.Create(await document.GetRequiredSyntaxTreeAsync(CancellationToken.None).ConfigureAwait(false), new TextSpan());
return ImmutableArray.Create(DiagnosticData.Create(Diagnostic.Create(descriptor, location), document));
}
private async Task<ImmutableArray<DiagnosticData>> CreateMockDiagnosticDatasWithMappedLocationAsync(Document document, params (string diagnosticId, string mappedFilePath)[] diagnostics)
{
var tree = await document.GetRequiredSyntaxTreeAsync(CancellationToken.None).ConfigureAwait(false);
return diagnostics.Select(d => CreateMockDiagnosticDataWithMappedLocation(document, tree, d.diagnosticId, d.mappedFilePath)).ToImmutableArray();
static DiagnosticData CreateMockDiagnosticDataWithMappedLocation(Document document, SyntaxTree tree, string id, string mappedFilePath)
{
var descriptor = new DiagnosticDescriptor(id, "", "", "", DiagnosticSeverity.Error, true);
var location = Location.Create(tree, new TextSpan());
var diagnostic = Diagnostic.Create(descriptor, location);
return new DiagnosticData(diagnostic.Id,
diagnostic.Descriptor.Category,
null,
null,
diagnostic.Severity,
diagnostic.DefaultSeverity,
diagnostic.Descriptor.IsEnabledByDefault,
diagnostic.WarningLevel,
diagnostic.Descriptor.ImmutableCustomTags(),
diagnostic.Properties,
document.Project.Id,
GetDataLocation(document, mappedFilePath),
additionalLocations: default,
document.Project.Language,
diagnostic.Descriptor.Title.ToString(),
diagnostic.Descriptor.Description.ToString(),
null,
diagnostic.IsSuppressed);
}
static DiagnosticDataLocation GetDataLocation(Document document, string mappedFilePath)
=> new DiagnosticDataLocation(document.Id, originalFilePath: document.FilePath, mappedFilePath: mappedFilePath);
}
/// <summary>
/// Synchronization context to preserve ordering of the RPC messages
/// Adapted from https://dev.azure.com/devdiv/DevDiv/VS%20Cloud%20Kernel/_git/DevCore?path=%2Fsrc%2Fclr%2FMicrosoft.ServiceHub.Framework%2FServiceRpcDescriptor%2BRpcOrderPreservingSynchronizationContext.cs
/// https://github.com/microsoft/vs-streamjsonrpc/issues/440 tracks exposing functionality so we don't need to copy this.
/// </summary>
private class RpcOrderPreservingSynchronizationContext : SynchronizationContext, IDisposable
{
/// <summary>
/// The queue of work to execute.
/// </summary>
private readonly AsyncQueue<(SendOrPostCallback, object?)> _queue = new AsyncQueue<(SendOrPostCallback, object?)>();
public RpcOrderPreservingSynchronizationContext()
{
// Process the work in the background.
this.ProcessQueueAsync().Forget();
}
public override void Post(SendOrPostCallback d, object? state) => this._queue.Enqueue((d, state));
public override void Send(SendOrPostCallback d, object? state) => throw new NotSupportedException();
public override SynchronizationContext CreateCopy() => throw new NotSupportedException();
/// <summary>
/// Causes this <see cref="SynchronizationContext"/> to reject all future posted work and
/// releases the queue processor when it is empty.
/// </summary>
public void Dispose() => this._queue.Complete();
/// <summary>
/// Executes queued work on the thread-pool, one at a time.
/// Don't catch exceptions - let them bubble up to fail the test.
/// </summary>
private async Task ProcessQueueAsync()
{
while (!this._queue.IsCompleted)
{
var work = await this._queue.DequeueAsync().ConfigureAwait(false);
work.Item1(work.Item2);
}
}
}
private class Callback
{
private readonly TaskCompletionSource<object?> _callbackCompletedTaskSource = new();
/// <summary>
/// Task that can be awaited for the all callbacks to complete.
/// </summary>
public Task CallbackCompletedTask => _callbackCompletedTaskSource.Task;
/// <summary>
/// Serialized results of all publish diagnostic notifications received by this callback.
/// </summary>
public List<LSP.PublishDiagnosticParams> Results { get; }
/// <summary>
/// Lock to guard concurrent callbacks.
/// </summary>
private readonly object _lock = new();
/// <summary>
/// The expected number of times this callback should be hit.
/// Used in conjunction with <see cref="_currentNumberOfCallbacks"/>
/// to determine if the callbacks are complete.
/// </summary>
private readonly int _expectedNumberOfCallbacks;
/// <summary>
/// The current number of callbacks that this callback has been hit.
/// </summary>
private int _currentNumberOfCallbacks;
public Callback(int expectedNumberOfCallbacks)
{
Results = new List<LSP.PublishDiagnosticParams>();
_expectedNumberOfCallbacks = expectedNumberOfCallbacks;
_currentNumberOfCallbacks = 0;
if (expectedNumberOfCallbacks == 0)
_callbackCompletedTaskSource.SetResult(null);
}
[JsonRpcMethod(LSP.Methods.TextDocumentPublishDiagnosticsName)]
public Task OnDiagnosticsPublished(JToken input)
{
lock (_lock)
{
_currentNumberOfCallbacks++;
Contract.ThrowIfTrue(_currentNumberOfCallbacks > _expectedNumberOfCallbacks, "received too many callbacks");
var diagnosticParams = input.ToObject<LSP.PublishDiagnosticParams>();
Results.Add(diagnosticParams);
if (_currentNumberOfCallbacks == _expectedNumberOfCallbacks)
_callbackCompletedTaskSource.SetResult(null);
return Task.CompletedTask;
}
}
}
private class TestLanguageClient : AbstractInProcLanguageClient
{
public TestLanguageClient()
: base(null!, null!, null, null!, null!, null!, null!, null)
{
}
protected override ImmutableArray<string> SupportedLanguages => ProtocolConstants.RoslynLspLanguages;
public override string Name => nameof(LspDiagnosticsTests);
public override bool ShowNotificationOnInitializeFailed => false;
public override LSP.ServerCapabilities GetCapabilities(LSP.ClientCapabilities clientCapabilities) => new();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServer;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageClient;
using Microsoft.VisualStudio.Threading;
using Moq;
using Nerdbank.Streams;
using Newtonsoft.Json.Linq;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using StreamJsonRpc;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Roslyn.VisualStudio.Next.UnitTests.Services
{
[UseExportProvider]
public class LspDiagnosticsTests : AbstractLanguageServerProtocolTests
{
[Fact]
public async Task AddDiagnosticTestAsync()
{
using var workspace = CreateTestLspServer("", out _).TestWorkspace;
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Create a mock that returns a diagnostic for the document.
SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false));
// Publish one document change diagnostic notification ->
// 1. doc1 with id.
//
// We expect one publish diagnostic notification ->
// 1. from doc1 with id.
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 1, document).ConfigureAwait(false);
var result = Assert.Single(results);
Assert.Equal(new Uri(document.FilePath), result.Uri);
Assert.Equal("id", result.Diagnostics.Single().Code);
}
[Fact]
public async Task NoDiagnosticsWhenInPullMode()
{
using var workspace = CreateTestLspServer("", out _).TestWorkspace;
workspace.SetOptions(workspace.Options.WithChangedOption(
InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull));
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Create a mock that returns a diagnostic for the document.
SetupMockWithDiagnostics(diagnosticsMock, document.Id, await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false));
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 0, document).ConfigureAwait(false);
Assert.Empty(results);
}
[Fact]
public async Task AddDiagnosticWithMappedFilesTestAsync()
{
using var workspace = CreateTestLspServer("", out _).TestWorkspace;
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Create two mapped diagnostics for the document.
SetupMockWithDiagnostics(diagnosticsMock, document.Id,
await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", document.FilePath + "m1"), ("id2", document.FilePath + "m2")).ConfigureAwait(false));
// Publish one document change diagnostic notification ->
// 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2.
//
// We expect two publish diagnostic notifications ->
// 1. from m1 with id1 (from 1 above).
// 2. from m2 with id2 (from 1 above).
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, expectedNumberOfCallbacks: 2, document).ConfigureAwait(false);
Assert.Equal(2, results.Count);
Assert.Equal(new Uri(document.FilePath + "m1"), results[0].Uri);
Assert.Equal("id1", results[0].Diagnostics.Single().Code);
Assert.Equal(new Uri(document.FilePath + "m2"), results[1].Uri);
Assert.Equal("id2", results[1].Diagnostics.Single().Code);
}
[Fact]
public async Task AddDiagnosticWithMappedFileToManyDocumentsTestAsync()
{
using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace;
var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Create diagnostic for the first document that has a mapped location.
var mappedFilePath = documents[0].FilePath + "m1";
var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false);
// Create diagnostic for the second document that maps to the same location as the first document diagnostic.
var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false);
SetupMockWithDiagnostics(diagnosticsMock, documents[0].Id, documentOneDiagnostic);
SetupMockWithDiagnostics(diagnosticsMock, documents[1].Id, documentTwoDiagnostic);
// Publish two document change diagnostic notifications ->
// 1. doc1 with doc1Diagnostic = mapped file m1.
// 2. doc2 with doc2Diagnostic = mapped file m1.
//
// We expect two publish diagnostic notifications ->
// 1. from m1 with doc1Diagnostic (from 1 above).
// 2. from m1 with doc1Diagnostic and doc2Diagnostic (from 2 above adding doc2Diagnostic to m1).
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 2, documents[0], documents[1]).ConfigureAwait(false);
Assert.Equal(2, results.Count);
var expectedUri = new Uri(mappedFilePath);
Assert.Equal(expectedUri, results[0].Uri);
Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code);
Assert.Equal(expectedUri, results[1].Uri);
Assert.Equal(2, results[1].Diagnostics.Length);
Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic");
Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic");
}
[Fact]
public async Task RemoveDiagnosticTestAsync()
{
using var workspace = CreateTestLspServer("", out _).TestWorkspace;
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Setup the mock so the first call for a document returns a diagnostic, but the second returns empty.
SetupMockDiagnosticSequence(diagnosticsMock, document.Id,
await CreateMockDiagnosticDataAsync(document, "id").ConfigureAwait(false),
ImmutableArray<DiagnosticData>.Empty);
// Publish two document change diagnostic notifications ->
// 1. doc1 with id.
// 2. doc1 with empty.
//
// We expect two publish diagnostic notifications ->
// 1. from doc1 with id.
// 2. from doc1 with empty (from 2 above clearing out diagnostics from doc1).
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 2, document, document).ConfigureAwait(false);
Assert.Equal(2, results.Count);
Assert.Equal(new Uri(document.FilePath), results[0].Uri);
Assert.Equal("id", results[0].Diagnostics.Single().Code);
Assert.Equal(new Uri(document.FilePath), results[1].Uri);
Assert.True(results[1].Diagnostics.IsEmpty());
Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris());
Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics());
}
[Fact]
public async Task RemoveDiagnosticForMappedFilesTestAsync()
{
using var workspace = CreateTestLspServer("", out _).TestWorkspace;
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
var mappedFilePathM1 = document.FilePath + "m1";
var mappedFilePathM2 = document.FilePath + "m2";
// Create two mapped diagnostics for the document on first call.
// On the second call, return only the second mapped diagnostic for the document.
SetupMockDiagnosticSequence(diagnosticsMock, document.Id,
await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", mappedFilePathM1), ("id2", mappedFilePathM2)).ConfigureAwait(false),
await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id2", mappedFilePathM2)).ConfigureAwait(false));
// Publish three document change diagnostic notifications ->
// 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2.
// 2. doc1 with just id2 = mapped file m2.
//
// We expect four publish diagnostic notifications ->
// 1. from m1 with id1 (from 1 above).
// 2. from m2 with id2 (from 1 above).
// 3. from m1 with empty (from 2 above clearing out diagnostics for m1).
// 4. from m2 with id2 (from 2 above clearing out diagnostics for m1).
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, document, document).ConfigureAwait(false);
var mappedFileURIM1 = new Uri(mappedFilePathM1);
var mappedFileURIM2 = new Uri(mappedFilePathM2);
Assert.Equal(4, results.Count);
// First document update.
Assert.Equal(mappedFileURIM1, results[0].Uri);
Assert.Equal("id1", results[0].Diagnostics.Single().Code);
Assert.Equal(mappedFileURIM2, results[1].Uri);
Assert.Equal("id2", results[1].Diagnostics.Single().Code);
// Second document update.
Assert.Equal(mappedFileURIM1, results[2].Uri);
Assert.True(results[2].Diagnostics.IsEmpty());
Assert.Equal(mappedFileURIM2, results[3].Uri);
Assert.Equal("id2", results[3].Diagnostics.Single().Code);
Assert.Single(testAccessor.GetFileUrisForDocument(document.Id), mappedFileURIM2);
Assert.Equal("id2", testAccessor.GetDiagnosticsForUriAndDocument(document.Id, mappedFileURIM2).Single().Code);
Assert.Empty(testAccessor.GetDiagnosticsForUriAndDocument(document.Id, mappedFileURIM1));
}
[Fact]
public async Task RemoveDiagnosticForMappedFileToManyDocumentsTestAsync()
{
using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace;
var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Create diagnostic for the first document that has a mapped location.
var mappedFilePath = documents[0].FilePath + "m1";
var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false);
// Create diagnostic for the second document that maps to the same location as the first document diagnostic.
var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false);
// On the first call for this document, return the mapped diagnostic. On the second, return nothing.
SetupMockDiagnosticSequence(diagnosticsMock, documents[0].Id, documentOneDiagnostic, ImmutableArray<DiagnosticData>.Empty);
// Always return the mapped diagnostic for this document.
SetupMockWithDiagnostics(diagnosticsMock, documents[1].Id, documentTwoDiagnostic);
// Publish three document change diagnostic notifications ->
// 1. doc1 with doc1Diagnostic = mapped file path m1
// 2. doc2 with doc2Diagnostic = mapped file path m1
// 3. doc1 with empty.
//
// We expect three publish diagnostics ->
// 1. from m1 with doc1Diagnostic (triggered by 1 above to add doc1Diagnostic).
// 2. from m1 with doc1Diagnostic and doc2Diagnostic (triggered by 2 above to add doc2Diagnostic).
// 3. from m1 with just doc2Diagnostic (triggered by 3 above to remove doc1Diagnostic).
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 3, documents[0], documents[1], documents[0]).ConfigureAwait(false);
Assert.Equal(3, results.Count);
var expectedUri = new Uri(mappedFilePath);
Assert.Equal(expectedUri, results[0].Uri);
Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code);
Assert.Equal(expectedUri, results[1].Uri);
Assert.Equal(2, results[1].Diagnostics.Length);
Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic");
Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic");
Assert.Equal(expectedUri, results[2].Uri);
Assert.Equal(1, results[2].Diagnostics.Length);
Assert.Contains(results[2].Diagnostics, d => d.Code == "doc2Diagnostic");
Assert.Single(testAccessor.GetFileUrisForDocument(documents[1].Id), expectedUri);
Assert.Equal("doc2Diagnostic", testAccessor.GetDiagnosticsForUriAndDocument(documents[1].Id, expectedUri).Single().Code);
Assert.Empty(testAccessor.GetDiagnosticsForUriAndDocument(documents[0].Id, expectedUri));
}
[Fact]
public async Task ClearAllDiagnosticsForMappedFilesTestAsync()
{
using var workspace = CreateTestLspServer("", out _).TestWorkspace;
var document = workspace.CurrentSolution.Projects.First().Documents.First();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
var mappedFilePathM1 = document.FilePath + "m1";
var mappedFilePathM2 = document.FilePath + "m2";
// Create two mapped diagnostics for the document on first call.
// On the second call, return only empty diagnostics.
SetupMockDiagnosticSequence(diagnosticsMock, document.Id,
await CreateMockDiagnosticDatasWithMappedLocationAsync(document, ("id1", mappedFilePathM1), ("id2", mappedFilePathM2)).ConfigureAwait(false),
ImmutableArray<DiagnosticData>.Empty);
// Publish two document change diagnostic notifications ->
// 1. doc1 with id1 = mapped file m1 and id2 = mapped file m2.
// 2. doc1 with empty.
//
// We expect four publish diagnostic notifications - the first two are the two mapped files from 1.
// The second two are the two mapped files being cleared by 2.
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, document, document).ConfigureAwait(false);
var mappedFileURIM1 = new Uri(document.FilePath + "m1");
var mappedFileURIM2 = new Uri(document.FilePath + "m2");
Assert.Equal(4, results.Count);
// Document's first update.
Assert.Equal(mappedFileURIM1, results[0].Uri);
Assert.Equal("id1", results[0].Diagnostics.Single().Code);
Assert.Equal(mappedFileURIM2, results[1].Uri);
Assert.Equal("id2", results[1].Diagnostics.Single().Code);
// Document's second update.
Assert.Equal(mappedFileURIM1, results[2].Uri);
Assert.True(results[2].Diagnostics.IsEmpty());
Assert.Equal(mappedFileURIM2, results[3].Uri);
Assert.True(results[3].Diagnostics.IsEmpty());
Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris());
Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics());
}
[Fact]
public async Task ClearAllDiagnosticsForMappedFileToManyDocumentsTestAsync()
{
using var workspace = CreateTestLspServer(new string[] { "", "" }, out _).TestWorkspace;
var documents = workspace.CurrentSolution.Projects.First().Documents.ToImmutableArray();
var diagnosticsMock = new Mock<IDiagnosticService>(MockBehavior.Strict);
// Create diagnostic for the first document that has a mapped location.
var mappedFilePath = documents[0].FilePath + "m1";
var documentOneDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[0], ("doc1Diagnostic", mappedFilePath)).ConfigureAwait(false);
// Create diagnostic for the second document that maps to the same location as the first document diagnostic.
var documentTwoDiagnostic = await CreateMockDiagnosticDatasWithMappedLocationAsync(documents[1], ("doc2Diagnostic", mappedFilePath)).ConfigureAwait(false);
// On the first call for the documents, return the mapped diagnostic. On the second, return nothing.
SetupMockDiagnosticSequence(diagnosticsMock, documents[0].Id, documentOneDiagnostic, ImmutableArray<DiagnosticData>.Empty);
SetupMockDiagnosticSequence(diagnosticsMock, documents[1].Id, documentTwoDiagnostic, ImmutableArray<DiagnosticData>.Empty);
// Publish four document change diagnostic notifications ->
// 1. doc1 with doc1Diagnostic = mapped file m1.
// 2. doc2 with doc2Diagnostic = mapped file m1.
// 3. doc1 with empty diagnostics.
// 4. doc2 with empty diagnostics.
//
// We expect four publish diagnostics ->
// 1. from URI m1 with doc1Diagnostic (triggered by 1 above to add doc1Diagnostic).
// 2. from URI m1 with doc1Diagnostic and doc2Diagnostic (triggered by 2 above to add doc2Diagnostic).
// 3. from URI m1 with just doc2Diagnostic (triggered by 3 above to clear doc1 diagnostic).
// 4. from URI m1 with empty (triggered by 4 above to also clear doc2 diagnostic).
var (testAccessor, results) = await RunPublishDiagnosticsAsync(workspace, diagnosticsMock.Object, 4, documents[0], documents[1], documents[0], documents[1]).ConfigureAwait(false);
Assert.Equal(4, results.Count);
var expectedUri = new Uri(mappedFilePath);
Assert.Equal(expectedUri, results[0].Uri);
Assert.Equal("doc1Diagnostic", results[0].Diagnostics.Single().Code);
Assert.Equal(expectedUri, results[1].Uri);
Assert.Equal(2, results[1].Diagnostics.Length);
Assert.Contains(results[1].Diagnostics, d => d.Code == "doc1Diagnostic");
Assert.Contains(results[1].Diagnostics, d => d.Code == "doc2Diagnostic");
Assert.Equal(expectedUri, results[2].Uri);
Assert.Equal(1, results[2].Diagnostics.Length);
Assert.Contains(results[2].Diagnostics, d => d.Code == "doc2Diagnostic");
Assert.Equal(expectedUri, results[3].Uri);
Assert.True(results[3].Diagnostics.IsEmpty());
Assert.Empty(testAccessor.GetDocumentIdsInPublishedUris());
Assert.Empty(testAccessor.GetFileUrisInPublishDiagnostics());
}
private async Task<(VisualStudioInProcLanguageServer.TestAccessor, List<LSP.PublishDiagnosticParams>)> RunPublishDiagnosticsAsync(
TestWorkspace workspace,
IDiagnosticService diagnosticService,
int expectedNumberOfCallbacks,
params Document[] documentsToPublish)
{
var (clientStream, serverStream) = FullDuplexStream.CreatePair();
var languageServer = CreateLanguageServer(serverStream, serverStream, workspace, diagnosticService);
// Notification target for tests to receive the notification details
var callback = new Callback(expectedNumberOfCallbacks);
using var jsonRpc = new JsonRpc(clientStream, clientStream, callback)
{
ExceptionStrategy = ExceptionProcessing.ISerializable,
};
// The json rpc messages won't necessarily come back in order by default.
// So use a synchronization context to preserve the original ordering.
// https://github.com/microsoft/vs-streamjsonrpc/blob/bc970c61b90db5db135a1b3d1c72ef355c2112af/doc/resiliency.md#when-message-order-is-important
jsonRpc.SynchronizationContext = new RpcOrderPreservingSynchronizationContext();
jsonRpc.StartListening();
// Triggers language server to send notifications.
await languageServer.ProcessDiagnosticUpdatedBatchAsync(
diagnosticService, documentsToPublish.SelectAsArray(d => d.Id), CancellationToken.None);
// Waits for all notifications to be received.
await callback.CallbackCompletedTask.ConfigureAwait(false);
return (languageServer.GetTestAccessor(), callback.Results);
static VisualStudioInProcLanguageServer CreateLanguageServer(Stream inputStream, Stream outputStream, TestWorkspace workspace, IDiagnosticService mockDiagnosticService)
{
var dispatcherFactory = workspace.ExportProvider.GetExportedValue<RequestDispatcherFactory>();
var listenerProvider = workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>();
var lspWorkspaceRegistrationService = workspace.ExportProvider.GetExportedValue<ILspWorkspaceRegistrationService>();
var capabilitiesProvider = workspace.ExportProvider.GetExportedValue<DefaultCapabilitiesProvider>();
var jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(outputStream, inputStream))
{
ExceptionStrategy = ExceptionProcessing.ISerializable,
};
var languageServer = new VisualStudioInProcLanguageServer(
dispatcherFactory,
jsonRpc,
capabilitiesProvider,
lspWorkspaceRegistrationService,
listenerProvider,
NoOpLspLogger.Instance,
mockDiagnosticService,
ProtocolConstants.RoslynLspLanguages,
clientName: null,
userVisibleServerName: string.Empty,
telemetryServerTypeName: string.Empty);
jsonRpc.StartListening();
return languageServer;
}
}
private void SetupMockWithDiagnostics(Mock<IDiagnosticService> diagnosticServiceMock, DocumentId documentId, ImmutableArray<DiagnosticData> diagnostics)
{
diagnosticServiceMock.Setup(d => d.GetPushDiagnosticsAsync(
It.IsAny<Workspace>(),
It.IsAny<ProjectId>(),
documentId,
It.IsAny<object>(),
It.IsAny<bool>(),
It.IsAny<Option2<DiagnosticMode>>(),
It.IsAny<CancellationToken>())).Returns(new ValueTask<ImmutableArray<DiagnosticData>>(diagnostics));
}
private void SetupMockDiagnosticSequence(Mock<IDiagnosticService> diagnosticServiceMock, DocumentId documentId,
ImmutableArray<DiagnosticData> firstDiagnostics, ImmutableArray<DiagnosticData> secondDiagnostics)
{
diagnosticServiceMock.SetupSequence(d => d.GetPushDiagnosticsAsync(
It.IsAny<Workspace>(),
It.IsAny<ProjectId>(),
documentId,
It.IsAny<object>(),
It.IsAny<bool>(),
It.IsAny<Option2<DiagnosticMode>>(),
It.IsAny<CancellationToken>()))
.Returns(new ValueTask<ImmutableArray<DiagnosticData>>(firstDiagnostics))
.Returns(new ValueTask<ImmutableArray<DiagnosticData>>(secondDiagnostics));
}
private async Task<ImmutableArray<DiagnosticData>> CreateMockDiagnosticDataAsync(Document document, string id)
{
var descriptor = new DiagnosticDescriptor(id, "", "", "", DiagnosticSeverity.Error, true);
var location = Location.Create(await document.GetRequiredSyntaxTreeAsync(CancellationToken.None).ConfigureAwait(false), new TextSpan());
return ImmutableArray.Create(DiagnosticData.Create(Diagnostic.Create(descriptor, location), document));
}
private async Task<ImmutableArray<DiagnosticData>> CreateMockDiagnosticDatasWithMappedLocationAsync(Document document, params (string diagnosticId, string mappedFilePath)[] diagnostics)
{
var tree = await document.GetRequiredSyntaxTreeAsync(CancellationToken.None).ConfigureAwait(false);
return diagnostics.Select(d => CreateMockDiagnosticDataWithMappedLocation(document, tree, d.diagnosticId, d.mappedFilePath)).ToImmutableArray();
static DiagnosticData CreateMockDiagnosticDataWithMappedLocation(Document document, SyntaxTree tree, string id, string mappedFilePath)
{
var descriptor = new DiagnosticDescriptor(id, "", "", "", DiagnosticSeverity.Error, true);
var location = Location.Create(tree, new TextSpan());
var diagnostic = Diagnostic.Create(descriptor, location);
return new DiagnosticData(diagnostic.Id,
diagnostic.Descriptor.Category,
null,
null,
diagnostic.Severity,
diagnostic.DefaultSeverity,
diagnostic.Descriptor.IsEnabledByDefault,
diagnostic.WarningLevel,
diagnostic.Descriptor.ImmutableCustomTags(),
diagnostic.Properties,
document.Project.Id,
GetDataLocation(document, mappedFilePath),
additionalLocations: default,
document.Project.Language,
diagnostic.Descriptor.Title.ToString(),
diagnostic.Descriptor.Description.ToString(),
null,
diagnostic.IsSuppressed);
}
static DiagnosticDataLocation GetDataLocation(Document document, string mappedFilePath)
=> new DiagnosticDataLocation(document.Id, originalFilePath: document.FilePath, mappedFilePath: mappedFilePath);
}
/// <summary>
/// Synchronization context to preserve ordering of the RPC messages
/// Adapted from https://dev.azure.com/devdiv/DevDiv/VS%20Cloud%20Kernel/_git/DevCore?path=%2Fsrc%2Fclr%2FMicrosoft.ServiceHub.Framework%2FServiceRpcDescriptor%2BRpcOrderPreservingSynchronizationContext.cs
/// https://github.com/microsoft/vs-streamjsonrpc/issues/440 tracks exposing functionality so we don't need to copy this.
/// </summary>
private class RpcOrderPreservingSynchronizationContext : SynchronizationContext, IDisposable
{
/// <summary>
/// The queue of work to execute.
/// </summary>
private readonly AsyncQueue<(SendOrPostCallback, object?)> _queue = new AsyncQueue<(SendOrPostCallback, object?)>();
public RpcOrderPreservingSynchronizationContext()
{
// Process the work in the background.
this.ProcessQueueAsync().Forget();
}
public override void Post(SendOrPostCallback d, object? state) => this._queue.Enqueue((d, state));
public override void Send(SendOrPostCallback d, object? state) => throw new NotSupportedException();
public override SynchronizationContext CreateCopy() => throw new NotSupportedException();
/// <summary>
/// Causes this <see cref="SynchronizationContext"/> to reject all future posted work and
/// releases the queue processor when it is empty.
/// </summary>
public void Dispose() => this._queue.Complete();
/// <summary>
/// Executes queued work on the thread-pool, one at a time.
/// Don't catch exceptions - let them bubble up to fail the test.
/// </summary>
private async Task ProcessQueueAsync()
{
while (!this._queue.IsCompleted)
{
var work = await this._queue.DequeueAsync().ConfigureAwait(false);
work.Item1(work.Item2);
}
}
}
private class Callback
{
private readonly TaskCompletionSource<object?> _callbackCompletedTaskSource = new();
/// <summary>
/// Task that can be awaited for the all callbacks to complete.
/// </summary>
public Task CallbackCompletedTask => _callbackCompletedTaskSource.Task;
/// <summary>
/// Serialized results of all publish diagnostic notifications received by this callback.
/// </summary>
public List<LSP.PublishDiagnosticParams> Results { get; }
/// <summary>
/// Lock to guard concurrent callbacks.
/// </summary>
private readonly object _lock = new();
/// <summary>
/// The expected number of times this callback should be hit.
/// Used in conjunction with <see cref="_currentNumberOfCallbacks"/>
/// to determine if the callbacks are complete.
/// </summary>
private readonly int _expectedNumberOfCallbacks;
/// <summary>
/// The current number of callbacks that this callback has been hit.
/// </summary>
private int _currentNumberOfCallbacks;
public Callback(int expectedNumberOfCallbacks)
{
Results = new List<LSP.PublishDiagnosticParams>();
_expectedNumberOfCallbacks = expectedNumberOfCallbacks;
_currentNumberOfCallbacks = 0;
if (expectedNumberOfCallbacks == 0)
_callbackCompletedTaskSource.SetResult(null);
}
[JsonRpcMethod(LSP.Methods.TextDocumentPublishDiagnosticsName)]
public Task OnDiagnosticsPublished(JToken input)
{
lock (_lock)
{
_currentNumberOfCallbacks++;
Contract.ThrowIfTrue(_currentNumberOfCallbacks > _expectedNumberOfCallbacks, "received too many callbacks");
var diagnosticParams = input.ToObject<LSP.PublishDiagnosticParams>();
Results.Add(diagnosticParams);
if (_currentNumberOfCallbacks == _expectedNumberOfCallbacks)
_callbackCompletedTaskSource.SetResult(null);
return Task.CompletedTask;
}
}
}
private class TestLanguageClient : AbstractInProcLanguageClient
{
public TestLanguageClient()
: base(null!, null!, null, null!, null!, null!, null!, null)
{
}
protected override ImmutableArray<string> SupportedLanguages => ProtocolConstants.RoslynLspLanguages;
public override string Name => nameof(LspDiagnosticsTests);
public override bool ShowNotificationOnInitializeFailed => false;
public override LSP.ServerCapabilities GetCapabilities(LSP.ClientCapabilities clientCapabilities) => new();
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.State.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
using MetadataOrDiagnostic = System.Object;
internal abstract class CommonReferenceManager
{
/// <summary>
/// Must be acquired whenever the following data are about to be modified:
/// - Compilation.lazyAssemblySymbol
/// - Compilation.referenceManager
/// - ReferenceManager state
/// - <see cref="AssemblyMetadata.CachedSymbols"/>
/// - <see cref="Compilation.RetargetingAssemblySymbols"/>
///
/// All the above data should be updated at once while holding this lock.
/// Once lazyAssemblySymbol is set the Compilation.referenceManager field and ReferenceManager
/// state should not change.
/// </summary>
internal static object SymbolCacheAndReferenceManagerStateGuard = new object();
/// <summary>
/// Enumerates all referenced assemblies.
/// </summary>
internal abstract IEnumerable<KeyValuePair<MetadataReference, IAssemblySymbolInternal>> GetReferencedAssemblies();
/// <summary>
/// Enumerates all referenced assemblies and their aliases.
/// </summary>
internal abstract IEnumerable<(IAssemblySymbolInternal AssemblySymbol, ImmutableArray<string> Aliases)> GetReferencedAssemblyAliases();
internal abstract MetadataReference? GetMetadataReference(IAssemblySymbolInternal? assemblySymbol);
internal abstract ImmutableArray<MetadataReference> ExplicitReferences { get; }
internal abstract ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?> ImplicitReferenceResolutions { get; }
}
internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol> : CommonReferenceManager
{
/// <summary>
/// If the compilation being built represents an assembly its assembly name.
/// If the compilation being built represents a module, the name of the
/// containing assembly or <see cref="Compilation.UnspecifiedModuleAssemblyName"/>
/// if not specified (/moduleassemblyname command line option).
/// </summary>
internal readonly string SimpleAssemblyName;
/// <summary>
/// Used to compares assembly identities.
/// May implement unification and portability policies specific to the target platform.
/// </summary>
internal readonly AssemblyIdentityComparer IdentityComparer;
/// <summary>
/// Metadata observed by the compiler.
/// May be shared across multiple Reference Managers.
/// Access only under lock(<see cref="ObservedMetadata"/>).
/// </summary>
internal readonly Dictionary<MetadataReference, MetadataOrDiagnostic> ObservedMetadata;
/// <summary>
/// Once this is non-zero the state of the manager is fully initialized and immutable.
/// </summary>
private int _isBound;
/// <summary>
/// True if the compilation has a reference that refers back to the assembly being compiled.
/// </summary>
/// <remarks>
/// If we have a circular reference the bound references can't be shared with other compilations.
/// </remarks>
private ThreeState _lazyHasCircularReference;
/// <summary>
/// A map from a metadata reference to an index to <see cref="_lazyReferencedAssemblies"/> array. Do not access
/// directly, use <see cref="_lazyReferencedAssembliesMap"/> property instead.
/// </summary>
private Dictionary<MetadataReference, int>? _lazyReferencedAssembliesMap;
/// <summary>
/// A map from a net-module metadata reference to the index of the corresponding module
/// symbol in the source assembly symbol for the current compilation.
/// </summary>
/// <remarks>
/// Subtract one from the index (for the manifest module) to find the corresponding elements
/// of <see cref="_lazyReferencedModules"/> and <see cref="_lazyReferencedModulesReferences"/>.
/// </remarks>
private Dictionary<MetadataReference, int>? _lazyReferencedModuleIndexMap;
/// <summary>
/// Maps (containing syntax tree file name, reference string) of #r directive to a resolved metadata reference.
/// If multiple #r's in the same tree use the same value as a reference the resolved metadata reference is the same as well.
/// </summary>
private IDictionary<(string, string), MetadataReference>? _lazyReferenceDirectiveMap;
/// <summary>
/// Array of unique bound #r references.
/// </summary>
/// <remarks>
/// The references are in the order they appear in syntax trees. This order is currently preserved
/// as syntax trees are added or removed, but we might decide to share reference manager between compilations
/// with different order of #r's. It doesn't seem this would be an issue since all #r's within the compilation
/// have the same "priority" with respect to each other.
/// </remarks>
private ImmutableArray<MetadataReference> _lazyDirectiveReferences;
private ImmutableArray<MetadataReference> _lazyExplicitReferences;
/// <summary>
/// Stores the results of implicit reference resolutions.
/// If <see cref="MetadataReferenceResolver.ResolveMissingAssemblies"/> is true the reference manager attempts to resolve assembly identities,
/// that do not match any explicit metadata references passed to the compilation (or specified via #r directive).
/// For each such assembly identity <see cref="MetadataReferenceResolver.ResolveMissingAssembly(MetadataReference, AssemblyIdentity)"/> is called
/// and its result is captured in this map.
/// The map also stores failures - the reference is null if the assembly of the given identity is not found by the resolver.
/// This is important to maintain consistency, especially across multiple submissions (e.g. the reference is not found during compilation of the first submission
/// but then it is available when the second submission is compiled).
/// </summary>
private ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?>? _lazyImplicitReferenceResolutions;
/// <summary>
/// Diagnostics produced during reference resolution and binding.
/// </summary>
/// <remarks>
/// When reporting diagnostics be sure not to include any information that can't be shared among
/// compilations that share the same reference manager (such as full identity of the compilation,
/// simple assembly name is ok).
/// </remarks>
private ImmutableArray<Diagnostic> _lazyDiagnostics;
/// <summary>
/// COR library symbol, or null if the compilation itself is the COR library.
/// </summary>
/// <remarks>
/// If the compilation being built is the COR library we don't want to store its source assembly symbol
/// here since we wouldn't be able to share the state among subsequent compilations that are derived from it
/// (each of them has its own source assembly symbol).
/// </remarks>
private TAssemblySymbol? _lazyCorLibraryOpt;
/// <summary>
/// Standalone modules referenced by the compilation (doesn't include the manifest module of the compilation).
/// </summary>
/// <remarks>
/// <see cref="_lazyReferencedModules"/>[i] corresponds to <see cref="_lazyReferencedModulesReferences"/>[i].
/// </remarks>
private ImmutableArray<PEModule> _lazyReferencedModules;
/// <summary>
/// References of standalone modules referenced by the compilation (doesn't include the manifest module of the compilation).
/// </summary>
/// <remarks>
/// <see cref="_lazyReferencedModules"/>[i] corresponds to <see cref="_lazyReferencedModulesReferences"/>[i].
/// </remarks>
private ImmutableArray<ModuleReferences<TAssemblySymbol>> _lazyReferencedModulesReferences;
/// <summary>
/// Assemblies referenced directly by the source module of the compilation.
/// </summary>
private ImmutableArray<TAssemblySymbol> _lazyReferencedAssemblies;
/// <summary>
/// Aliases used by assemblies referenced directly by the source module of the compilation.
/// </summary>
/// <remarks>
/// Aliases <see cref="_lazyAliasesOfReferencedAssemblies"/>[i] are of an assembly <see cref="_lazyReferencedAssemblies"/>[i].
/// </remarks>
private ImmutableArray<ImmutableArray<string>> _lazyAliasesOfReferencedAssemblies;
/// <summary>
/// A map capturing <see cref="MetadataReference"/>s that were "merged" to a single referenced assembly
/// associated with a key in the map.
/// The keys are a subset of keys from <see cref="_lazyReferencedAssembliesMap"/>.
/// </summary>
private ImmutableDictionary<MetadataReference, ImmutableArray<MetadataReference>>? _lazyMergedAssemblyReferencesMap;
/// <summary>
/// Unified assemblies referenced directly by the source module of the compilation.
/// </summary>
private ImmutableArray<UnifiedAssembly<TAssemblySymbol>> _lazyUnifiedAssemblies;
public CommonReferenceManager(string simpleAssemblyName, AssemblyIdentityComparer identityComparer, Dictionary<MetadataReference, MetadataOrDiagnostic>? observedMetadata)
{
Debug.Assert(simpleAssemblyName != null);
Debug.Assert(identityComparer != null);
this.SimpleAssemblyName = simpleAssemblyName;
this.IdentityComparer = identityComparer;
this.ObservedMetadata = observedMetadata ?? new Dictionary<MetadataReference, MetadataOrDiagnostic>();
}
internal ImmutableArray<Diagnostic> Diagnostics
{
get
{
AssertBound();
return _lazyDiagnostics;
}
}
internal bool HasCircularReference
{
get
{
AssertBound();
return _lazyHasCircularReference == ThreeState.True;
}
}
internal Dictionary<MetadataReference, int> ReferencedAssembliesMap
{
get
{
AssertBound();
return _lazyReferencedAssembliesMap;
}
}
internal Dictionary<MetadataReference, int> ReferencedModuleIndexMap
{
get
{
AssertBound();
return _lazyReferencedModuleIndexMap;
}
}
internal IDictionary<(string, string), MetadataReference> ReferenceDirectiveMap
{
get
{
AssertBound();
return _lazyReferenceDirectiveMap;
}
}
internal ImmutableArray<MetadataReference> DirectiveReferences
{
get
{
AssertBound();
return _lazyDirectiveReferences;
}
}
internal override ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?> ImplicitReferenceResolutions
{
get
{
AssertBound();
return _lazyImplicitReferenceResolutions;
}
}
internal override ImmutableArray<MetadataReference> ExplicitReferences
{
get
{
AssertBound();
return _lazyExplicitReferences;
}
}
#region Symbols necessary to set up source assembly and module
internal TAssemblySymbol? CorLibraryOpt
{
get
{
AssertBound();
return _lazyCorLibraryOpt;
}
}
internal ImmutableArray<PEModule> ReferencedModules
{
get
{
AssertBound();
return _lazyReferencedModules;
}
}
internal ImmutableArray<ModuleReferences<TAssemblySymbol>> ReferencedModulesReferences
{
get
{
AssertBound();
return _lazyReferencedModulesReferences;
}
}
internal ImmutableArray<TAssemblySymbol> ReferencedAssemblies
{
get
{
AssertBound();
return _lazyReferencedAssemblies;
}
}
internal ImmutableArray<ImmutableArray<string>> AliasesOfReferencedAssemblies
{
get
{
AssertBound();
return _lazyAliasesOfReferencedAssemblies;
}
}
internal ImmutableDictionary<MetadataReference, ImmutableArray<MetadataReference>> MergedAssemblyReferencesMap
{
get
{
AssertBound();
Debug.Assert(_lazyMergedAssemblyReferencesMap != null);
return _lazyMergedAssemblyReferencesMap;
}
}
internal ImmutableArray<UnifiedAssembly<TAssemblySymbol>> UnifiedAssemblies
{
get
{
AssertBound();
return _lazyUnifiedAssemblies;
}
}
#endregion
/// <summary>
/// Call only while holding <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/>.
/// </summary>
[Conditional("DEBUG")]
internal void AssertUnbound()
{
Debug.Assert(_isBound == 0);
Debug.Assert(_lazyHasCircularReference == ThreeState.Unknown);
Debug.Assert(_lazyReferencedAssembliesMap == null);
Debug.Assert(_lazyReferencedModuleIndexMap == null);
Debug.Assert(_lazyReferenceDirectiveMap == null);
Debug.Assert(_lazyDirectiveReferences.IsDefault);
Debug.Assert(_lazyImplicitReferenceResolutions == null);
Debug.Assert(_lazyExplicitReferences.IsDefault);
Debug.Assert(_lazyReferencedModules.IsDefault);
Debug.Assert(_lazyReferencedModulesReferences.IsDefault);
Debug.Assert(_lazyReferencedAssemblies.IsDefault);
Debug.Assert(_lazyAliasesOfReferencedAssemblies.IsDefault);
Debug.Assert(_lazyMergedAssemblyReferencesMap == null);
Debug.Assert(_lazyUnifiedAssemblies.IsDefault);
Debug.Assert(_lazyCorLibraryOpt == null);
}
[Conditional("DEBUG")]
[MemberNotNull(nameof(_lazyReferencedAssembliesMap), nameof(_lazyReferencedModuleIndexMap), nameof(_lazyReferenceDirectiveMap), nameof(_lazyImplicitReferenceResolutions))]
internal void AssertBound()
{
Debug.Assert(_isBound != 0);
Debug.Assert(_lazyHasCircularReference != ThreeState.Unknown);
Debug.Assert(_lazyReferencedAssembliesMap != null);
Debug.Assert(_lazyReferencedModuleIndexMap != null);
Debug.Assert(_lazyReferenceDirectiveMap != null);
Debug.Assert(!_lazyDirectiveReferences.IsDefault);
Debug.Assert(_lazyImplicitReferenceResolutions != null);
Debug.Assert(!_lazyExplicitReferences.IsDefault);
Debug.Assert(!_lazyReferencedModules.IsDefault);
Debug.Assert(!_lazyReferencedModulesReferences.IsDefault);
Debug.Assert(!_lazyReferencedAssemblies.IsDefault);
Debug.Assert(!_lazyAliasesOfReferencedAssemblies.IsDefault);
Debug.Assert(_lazyMergedAssemblyReferencesMap != null);
Debug.Assert(!_lazyUnifiedAssemblies.IsDefault);
// lazyCorLibrary is null if the compilation is corlib
Debug.Assert(_lazyReferencedAssemblies.Length == 0 || _lazyCorLibraryOpt != null);
}
[Conditional("DEBUG")]
internal void AssertCanReuseForCompilation(TCompilation compilation)
{
Debug.Assert(compilation.MakeSourceAssemblySimpleName() == this.SimpleAssemblyName);
}
internal bool IsBound
{
get
{
return _isBound != 0;
}
}
/// <summary>
/// Call only while holding <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/>.
/// </summary>
internal void InitializeNoLock(
Dictionary<MetadataReference, int> referencedAssembliesMap,
Dictionary<MetadataReference, int> referencedModulesMap,
IDictionary<(string, string), MetadataReference> boundReferenceDirectiveMap,
ImmutableArray<MetadataReference> directiveReferences,
ImmutableArray<MetadataReference> explicitReferences,
ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?> implicitReferenceResolutions,
bool containsCircularReferences,
ImmutableArray<Diagnostic> diagnostics,
TAssemblySymbol? corLibraryOpt,
ImmutableArray<PEModule> referencedModules,
ImmutableArray<ModuleReferences<TAssemblySymbol>> referencedModulesReferences,
ImmutableArray<TAssemblySymbol> referencedAssemblies,
ImmutableArray<ImmutableArray<string>> aliasesOfReferencedAssemblies,
ImmutableArray<UnifiedAssembly<TAssemblySymbol>> unifiedAssemblies,
Dictionary<MetadataReference, ImmutableArray<MetadataReference>>? mergedAssemblyReferencesMapOpt)
{
AssertUnbound();
Debug.Assert(referencedModules.Length == referencedModulesReferences.Length);
Debug.Assert(referencedModules.Length == referencedModulesMap.Count);
Debug.Assert(referencedAssemblies.Length == aliasesOfReferencedAssemblies.Length);
_lazyReferencedAssembliesMap = referencedAssembliesMap;
_lazyReferencedModuleIndexMap = referencedModulesMap;
_lazyDiagnostics = diagnostics;
_lazyReferenceDirectiveMap = boundReferenceDirectiveMap;
_lazyDirectiveReferences = directiveReferences;
_lazyExplicitReferences = explicitReferences;
_lazyImplicitReferenceResolutions = implicitReferenceResolutions;
_lazyCorLibraryOpt = corLibraryOpt;
_lazyReferencedModules = referencedModules;
_lazyReferencedModulesReferences = referencedModulesReferences;
_lazyReferencedAssemblies = referencedAssemblies;
_lazyAliasesOfReferencedAssemblies = aliasesOfReferencedAssemblies;
_lazyMergedAssemblyReferencesMap = mergedAssemblyReferencesMapOpt?.ToImmutableDictionary() ?? ImmutableDictionary<MetadataReference, ImmutableArray<MetadataReference>>.Empty;
_lazyUnifiedAssemblies = unifiedAssemblies;
_lazyHasCircularReference = containsCircularReferences.ToThreeState();
// once we flip this bit the state of the manager is immutable and available to any readers:
Interlocked.Exchange(ref _isBound, 1);
}
/// <summary>
/// Global namespaces of assembly references that have been superseded by an assembly reference with a higher version are
/// hidden behind <see cref="s_supersededAlias"/> to avoid ambiguity when they are accessed from source.
/// All existing aliases of a superseded assembly are discarded.
/// </summary>
private static readonly ImmutableArray<string> s_supersededAlias = ImmutableArray.Create("<superseded>");
protected static void BuildReferencedAssembliesAndModulesMaps(
BoundInputAssembly[] bindingResult,
ImmutableArray<MetadataReference> references,
ImmutableArray<ResolvedReference> referenceMap,
int referencedModuleCount,
int explicitlyReferencedAssemblyCount,
IReadOnlyDictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName,
bool supersedeLowerVersions,
out Dictionary<MetadataReference, int> referencedAssembliesMap,
out Dictionary<MetadataReference, int> referencedModulesMap,
out ImmutableArray<ImmutableArray<string>> aliasesOfReferencedAssemblies,
out Dictionary<MetadataReference, ImmutableArray<MetadataReference>>? mergedAssemblyReferencesMapOpt)
{
referencedAssembliesMap = new Dictionary<MetadataReference, int>(referenceMap.Length);
referencedModulesMap = new Dictionary<MetadataReference, int>(referencedModuleCount);
var aliasesOfReferencedAssembliesBuilder = ArrayBuilder<ImmutableArray<string>>.GetInstance(referenceMap.Length - referencedModuleCount);
bool hasRecursiveAliases = false;
mergedAssemblyReferencesMapOpt = null;
for (int i = 0; i < referenceMap.Length; i++)
{
if (referenceMap[i].IsSkipped)
{
continue;
}
if (referenceMap[i].Kind == MetadataImageKind.Module)
{
// add 1 for the manifest module:
int moduleIndex = 1 + referenceMap[i].Index;
referencedModulesMap.Add(references[i], moduleIndex);
}
else
{
// index into assembly data array
int assemblyIndex = referenceMap[i].Index;
Debug.Assert(aliasesOfReferencedAssembliesBuilder.Count == assemblyIndex);
MetadataReference reference = references[i];
referencedAssembliesMap.Add(reference, assemblyIndex);
aliasesOfReferencedAssembliesBuilder.Add(referenceMap[i].AliasesOpt);
if (!referenceMap[i].MergedReferences.IsEmpty)
{
(mergedAssemblyReferencesMapOpt ??= new Dictionary<MetadataReference, ImmutableArray<MetadataReference>>()).Add(reference, referenceMap[i].MergedReferences);
}
hasRecursiveAliases |= !referenceMap[i].RecursiveAliasesOpt.IsDefault;
}
}
if (hasRecursiveAliases)
{
PropagateRecursiveAliases(bindingResult, referenceMap, aliasesOfReferencedAssembliesBuilder);
}
Debug.Assert(!aliasesOfReferencedAssembliesBuilder.Any(a => a.IsDefault));
if (supersedeLowerVersions)
{
foreach (var assemblyReference in assemblyReferencesBySimpleName)
{
// the item in the list is the highest version, by construction
for (int i = 1; i < assemblyReference.Value.Count; i++)
{
int assemblyIndex = assemblyReference.Value[i].GetAssemblyIndex(explicitlyReferencedAssemblyCount);
aliasesOfReferencedAssembliesBuilder[assemblyIndex] = s_supersededAlias;
}
}
}
aliasesOfReferencedAssemblies = aliasesOfReferencedAssembliesBuilder.ToImmutableAndFree();
}
/// <summary>
/// Calculates map from the identities of specified symbols to the corresponding identities in the original EnC baseline metadata.
/// The map only includes an entry for identities that differ, i.e. for symbols representing assembly references of the current compilation that have different identities
/// than the corresponding identity in baseline metadata AssemblyRef table. The key comparer of the map ignores build and revision parts of the version number,
/// since these might change if the original version included wildcard.
/// </summary>
/// <param name="symbols">Assembly symbols for references of the current compilation.</param>
/// <param name="originalIdentities">Identities in the baseline. <paramref name="originalIdentities"/>[i] corresponds to <paramref name="symbols"/>[i].</param>
internal static ImmutableDictionary<AssemblyIdentity, AssemblyIdentity> GetAssemblyReferenceIdentityBaselineMap(ImmutableArray<TAssemblySymbol> symbols, ImmutableArray<AssemblyIdentity> originalIdentities)
{
Debug.Assert(originalIdentities.Length == symbols.Length);
ImmutableDictionary<AssemblyIdentity, AssemblyIdentity>.Builder? lazyBuilder = null;
for (int i = 0; i < originalIdentities.Length; i++)
{
var symbolIdentity = symbols[i].Identity;
var versionPattern = symbols[i].AssemblyVersionPattern;
var originalIdentity = originalIdentities[i];
if (versionPattern is object)
{
Debug.Assert(versionPattern.Build == ushort.MaxValue || versionPattern.Revision == ushort.MaxValue);
lazyBuilder = lazyBuilder ?? ImmutableDictionary.CreateBuilder<AssemblyIdentity, AssemblyIdentity>();
var sourceIdentity = symbolIdentity.WithVersion(versionPattern);
if (lazyBuilder.ContainsKey(sourceIdentity))
{
// The compilation references multiple assemblies whose versions only differ in auto-generated build and/or revision numbers.
throw new NotSupportedException(CodeAnalysisResources.CompilationReferencesAssembliesWithDifferentAutoGeneratedVersion);
}
lazyBuilder.Add(sourceIdentity, originalIdentity);
}
else
{
// by construction of the arguments:
Debug.Assert(originalIdentity == symbolIdentity);
}
}
return lazyBuilder?.ToImmutable() ?? ImmutableDictionary<AssemblyIdentity, AssemblyIdentity>.Empty;
}
internal static bool CompareVersionPartsSpecifiedInSource(Version version, Version candidateVersion, TAssemblySymbol candidateSymbol)
{
// major and minor parts must match exactly
if (version.Major != candidateVersion.Major || version.Minor != candidateVersion.Minor)
{
return false;
}
// build and revision parts can differ only if the corresponding source versions were auto-generated:
var versionPattern = candidateSymbol.AssemblyVersionPattern;
Debug.Assert(versionPattern is null || versionPattern.Build == ushort.MaxValue || versionPattern.Revision == ushort.MaxValue);
if ((versionPattern is null || versionPattern.Build < ushort.MaxValue) && version.Build != candidateVersion.Build)
{
return false;
}
if (versionPattern is null && version.Revision != candidateVersion.Revision)
{
return false;
}
return true;
}
// #r references are recursive, their aliases should be merged into all their dependencies.
//
// For example, if a compilation has a reference to LibA with alias A and the user #r's LibB with alias B,
// which references LibA, LibA should be available under both aliases A and B. B is usually "global",
// which means LibA namespaces should become available to the compilation without any qualification when #r LibB
// is encountered.
//
// Pairs: (assembly index -- index into bindingResult array; index of the #r reference in referenceMap array).
private static void PropagateRecursiveAliases(
BoundInputAssembly[] bindingResult,
ImmutableArray<ResolvedReference> referenceMap,
ArrayBuilder<ImmutableArray<string>> aliasesOfReferencedAssembliesBuilder)
{
var assemblyIndicesToProcess = ArrayBuilder<int>.GetInstance();
var visitedAssemblies = BitVector.Create(bindingResult.Length);
// +1 for assembly being built
Debug.Assert(bindingResult.Length == aliasesOfReferencedAssembliesBuilder.Count + 1);
foreach (ResolvedReference reference in referenceMap)
{
if (!reference.IsSkipped && !reference.RecursiveAliasesOpt.IsDefault)
{
var recursiveAliases = reference.RecursiveAliasesOpt;
Debug.Assert(reference.Kind == MetadataImageKind.Assembly);
visitedAssemblies.Clear();
Debug.Assert(assemblyIndicesToProcess.Count == 0);
assemblyIndicesToProcess.Add(reference.Index);
while (assemblyIndicesToProcess.Count > 0)
{
int assemblyIndex = assemblyIndicesToProcess.Pop();
visitedAssemblies[assemblyIndex] = true;
// merge aliases:
aliasesOfReferencedAssembliesBuilder[assemblyIndex] = MergedAliases.Merge(aliasesOfReferencedAssembliesBuilder[assemblyIndex], recursiveAliases);
// push dependencies onto the stack:
// +1 for the assembly being built:
var referenceBinding = bindingResult[assemblyIndex + 1].ReferenceBinding;
Debug.Assert(referenceBinding is object);
foreach (var binding in referenceBinding)
{
if (binding.IsBound)
{
// -1 for the assembly being built:
int dependentAssemblyIndex = binding.DefinitionIndex - 1;
if (!visitedAssemblies[dependentAssemblyIndex])
{
assemblyIndicesToProcess.Add(dependentAssemblyIndex);
}
}
}
}
}
}
for (int i = 0; i < aliasesOfReferencedAssembliesBuilder.Count; i++)
{
if (aliasesOfReferencedAssembliesBuilder[i].IsDefault)
{
aliasesOfReferencedAssembliesBuilder[i] = ImmutableArray<string>.Empty;
}
}
assemblyIndicesToProcess.Free();
}
#region Compilation APIs Implementation
// for testing purposes
internal IEnumerable<string> ExternAliases => AliasesOfReferencedAssemblies.SelectMany(aliases => aliases);
internal sealed override IEnumerable<KeyValuePair<MetadataReference, IAssemblySymbolInternal>> GetReferencedAssemblies()
{
return ReferencedAssembliesMap.Select(ra => KeyValuePairUtil.Create(ra.Key, (IAssemblySymbolInternal)ReferencedAssemblies[ra.Value]));
}
internal TAssemblySymbol? GetReferencedAssemblySymbol(MetadataReference reference)
{
int index;
return ReferencedAssembliesMap.TryGetValue(reference, out index) ? ReferencedAssemblies[index] : null;
}
internal int GetReferencedModuleIndex(MetadataReference reference)
{
int index;
return ReferencedModuleIndexMap.TryGetValue(reference, out index) ? index : -1;
}
/// <summary>
/// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol.
/// </summary>
internal override MetadataReference? GetMetadataReference(IAssemblySymbolInternal? assemblySymbol)
{
foreach (var entry in ReferencedAssembliesMap)
{
if ((object)ReferencedAssemblies[entry.Value] == assemblySymbol)
{
return entry.Key;
}
}
return null;
}
internal override IEnumerable<(IAssemblySymbolInternal AssemblySymbol, ImmutableArray<string> Aliases)> GetReferencedAssemblyAliases()
{
for (int i = 0; i < ReferencedAssemblies.Length; i++)
{
yield return (ReferencedAssemblies[i], AliasesOfReferencedAssemblies[i]);
}
}
public bool DeclarationsAccessibleWithoutAlias(int referencedAssemblyIndex)
{
var aliases = AliasesOfReferencedAssemblies[referencedAssemblyIndex];
return aliases.Length == 0 || aliases.IndexOf(MetadataReferenceProperties.GlobalAlias, StringComparer.Ordinal) >= 0;
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
using MetadataOrDiagnostic = System.Object;
internal abstract class CommonReferenceManager
{
/// <summary>
/// Must be acquired whenever the following data are about to be modified:
/// - Compilation.lazyAssemblySymbol
/// - Compilation.referenceManager
/// - ReferenceManager state
/// - <see cref="AssemblyMetadata.CachedSymbols"/>
/// - <see cref="Compilation.RetargetingAssemblySymbols"/>
///
/// All the above data should be updated at once while holding this lock.
/// Once lazyAssemblySymbol is set the Compilation.referenceManager field and ReferenceManager
/// state should not change.
/// </summary>
internal static object SymbolCacheAndReferenceManagerStateGuard = new object();
/// <summary>
/// Enumerates all referenced assemblies.
/// </summary>
internal abstract IEnumerable<KeyValuePair<MetadataReference, IAssemblySymbolInternal>> GetReferencedAssemblies();
/// <summary>
/// Enumerates all referenced assemblies and their aliases.
/// </summary>
internal abstract IEnumerable<(IAssemblySymbolInternal AssemblySymbol, ImmutableArray<string> Aliases)> GetReferencedAssemblyAliases();
internal abstract MetadataReference? GetMetadataReference(IAssemblySymbolInternal? assemblySymbol);
internal abstract ImmutableArray<MetadataReference> ExplicitReferences { get; }
internal abstract ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?> ImplicitReferenceResolutions { get; }
}
internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol> : CommonReferenceManager
{
/// <summary>
/// If the compilation being built represents an assembly its assembly name.
/// If the compilation being built represents a module, the name of the
/// containing assembly or <see cref="Compilation.UnspecifiedModuleAssemblyName"/>
/// if not specified (/moduleassemblyname command line option).
/// </summary>
internal readonly string SimpleAssemblyName;
/// <summary>
/// Used to compares assembly identities.
/// May implement unification and portability policies specific to the target platform.
/// </summary>
internal readonly AssemblyIdentityComparer IdentityComparer;
/// <summary>
/// Metadata observed by the compiler.
/// May be shared across multiple Reference Managers.
/// Access only under lock(<see cref="ObservedMetadata"/>).
/// </summary>
internal readonly Dictionary<MetadataReference, MetadataOrDiagnostic> ObservedMetadata;
/// <summary>
/// Once this is non-zero the state of the manager is fully initialized and immutable.
/// </summary>
private int _isBound;
/// <summary>
/// True if the compilation has a reference that refers back to the assembly being compiled.
/// </summary>
/// <remarks>
/// If we have a circular reference the bound references can't be shared with other compilations.
/// </remarks>
private ThreeState _lazyHasCircularReference;
/// <summary>
/// A map from a metadata reference to an index to <see cref="_lazyReferencedAssemblies"/> array. Do not access
/// directly, use <see cref="_lazyReferencedAssembliesMap"/> property instead.
/// </summary>
private Dictionary<MetadataReference, int>? _lazyReferencedAssembliesMap;
/// <summary>
/// A map from a net-module metadata reference to the index of the corresponding module
/// symbol in the source assembly symbol for the current compilation.
/// </summary>
/// <remarks>
/// Subtract one from the index (for the manifest module) to find the corresponding elements
/// of <see cref="_lazyReferencedModules"/> and <see cref="_lazyReferencedModulesReferences"/>.
/// </remarks>
private Dictionary<MetadataReference, int>? _lazyReferencedModuleIndexMap;
/// <summary>
/// Maps (containing syntax tree file name, reference string) of #r directive to a resolved metadata reference.
/// If multiple #r's in the same tree use the same value as a reference the resolved metadata reference is the same as well.
/// </summary>
private IDictionary<(string, string), MetadataReference>? _lazyReferenceDirectiveMap;
/// <summary>
/// Array of unique bound #r references.
/// </summary>
/// <remarks>
/// The references are in the order they appear in syntax trees. This order is currently preserved
/// as syntax trees are added or removed, but we might decide to share reference manager between compilations
/// with different order of #r's. It doesn't seem this would be an issue since all #r's within the compilation
/// have the same "priority" with respect to each other.
/// </remarks>
private ImmutableArray<MetadataReference> _lazyDirectiveReferences;
private ImmutableArray<MetadataReference> _lazyExplicitReferences;
/// <summary>
/// Stores the results of implicit reference resolutions.
/// If <see cref="MetadataReferenceResolver.ResolveMissingAssemblies"/> is true the reference manager attempts to resolve assembly identities,
/// that do not match any explicit metadata references passed to the compilation (or specified via #r directive).
/// For each such assembly identity <see cref="MetadataReferenceResolver.ResolveMissingAssembly(MetadataReference, AssemblyIdentity)"/> is called
/// and its result is captured in this map.
/// The map also stores failures - the reference is null if the assembly of the given identity is not found by the resolver.
/// This is important to maintain consistency, especially across multiple submissions (e.g. the reference is not found during compilation of the first submission
/// but then it is available when the second submission is compiled).
/// </summary>
private ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?>? _lazyImplicitReferenceResolutions;
/// <summary>
/// Diagnostics produced during reference resolution and binding.
/// </summary>
/// <remarks>
/// When reporting diagnostics be sure not to include any information that can't be shared among
/// compilations that share the same reference manager (such as full identity of the compilation,
/// simple assembly name is ok).
/// </remarks>
private ImmutableArray<Diagnostic> _lazyDiagnostics;
/// <summary>
/// COR library symbol, or null if the compilation itself is the COR library.
/// </summary>
/// <remarks>
/// If the compilation being built is the COR library we don't want to store its source assembly symbol
/// here since we wouldn't be able to share the state among subsequent compilations that are derived from it
/// (each of them has its own source assembly symbol).
/// </remarks>
private TAssemblySymbol? _lazyCorLibraryOpt;
/// <summary>
/// Standalone modules referenced by the compilation (doesn't include the manifest module of the compilation).
/// </summary>
/// <remarks>
/// <see cref="_lazyReferencedModules"/>[i] corresponds to <see cref="_lazyReferencedModulesReferences"/>[i].
/// </remarks>
private ImmutableArray<PEModule> _lazyReferencedModules;
/// <summary>
/// References of standalone modules referenced by the compilation (doesn't include the manifest module of the compilation).
/// </summary>
/// <remarks>
/// <see cref="_lazyReferencedModules"/>[i] corresponds to <see cref="_lazyReferencedModulesReferences"/>[i].
/// </remarks>
private ImmutableArray<ModuleReferences<TAssemblySymbol>> _lazyReferencedModulesReferences;
/// <summary>
/// Assemblies referenced directly by the source module of the compilation.
/// </summary>
private ImmutableArray<TAssemblySymbol> _lazyReferencedAssemblies;
/// <summary>
/// Aliases used by assemblies referenced directly by the source module of the compilation.
/// </summary>
/// <remarks>
/// Aliases <see cref="_lazyAliasesOfReferencedAssemblies"/>[i] are of an assembly <see cref="_lazyReferencedAssemblies"/>[i].
/// </remarks>
private ImmutableArray<ImmutableArray<string>> _lazyAliasesOfReferencedAssemblies;
/// <summary>
/// A map capturing <see cref="MetadataReference"/>s that were "merged" to a single referenced assembly
/// associated with a key in the map.
/// The keys are a subset of keys from <see cref="_lazyReferencedAssembliesMap"/>.
/// </summary>
private ImmutableDictionary<MetadataReference, ImmutableArray<MetadataReference>>? _lazyMergedAssemblyReferencesMap;
/// <summary>
/// Unified assemblies referenced directly by the source module of the compilation.
/// </summary>
private ImmutableArray<UnifiedAssembly<TAssemblySymbol>> _lazyUnifiedAssemblies;
public CommonReferenceManager(string simpleAssemblyName, AssemblyIdentityComparer identityComparer, Dictionary<MetadataReference, MetadataOrDiagnostic>? observedMetadata)
{
Debug.Assert(simpleAssemblyName != null);
Debug.Assert(identityComparer != null);
this.SimpleAssemblyName = simpleAssemblyName;
this.IdentityComparer = identityComparer;
this.ObservedMetadata = observedMetadata ?? new Dictionary<MetadataReference, MetadataOrDiagnostic>();
}
internal ImmutableArray<Diagnostic> Diagnostics
{
get
{
AssertBound();
return _lazyDiagnostics;
}
}
internal bool HasCircularReference
{
get
{
AssertBound();
return _lazyHasCircularReference == ThreeState.True;
}
}
internal Dictionary<MetadataReference, int> ReferencedAssembliesMap
{
get
{
AssertBound();
return _lazyReferencedAssembliesMap;
}
}
internal Dictionary<MetadataReference, int> ReferencedModuleIndexMap
{
get
{
AssertBound();
return _lazyReferencedModuleIndexMap;
}
}
internal IDictionary<(string, string), MetadataReference> ReferenceDirectiveMap
{
get
{
AssertBound();
return _lazyReferenceDirectiveMap;
}
}
internal ImmutableArray<MetadataReference> DirectiveReferences
{
get
{
AssertBound();
return _lazyDirectiveReferences;
}
}
internal override ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?> ImplicitReferenceResolutions
{
get
{
AssertBound();
return _lazyImplicitReferenceResolutions;
}
}
internal override ImmutableArray<MetadataReference> ExplicitReferences
{
get
{
AssertBound();
return _lazyExplicitReferences;
}
}
#region Symbols necessary to set up source assembly and module
internal TAssemblySymbol? CorLibraryOpt
{
get
{
AssertBound();
return _lazyCorLibraryOpt;
}
}
internal ImmutableArray<PEModule> ReferencedModules
{
get
{
AssertBound();
return _lazyReferencedModules;
}
}
internal ImmutableArray<ModuleReferences<TAssemblySymbol>> ReferencedModulesReferences
{
get
{
AssertBound();
return _lazyReferencedModulesReferences;
}
}
internal ImmutableArray<TAssemblySymbol> ReferencedAssemblies
{
get
{
AssertBound();
return _lazyReferencedAssemblies;
}
}
internal ImmutableArray<ImmutableArray<string>> AliasesOfReferencedAssemblies
{
get
{
AssertBound();
return _lazyAliasesOfReferencedAssemblies;
}
}
internal ImmutableDictionary<MetadataReference, ImmutableArray<MetadataReference>> MergedAssemblyReferencesMap
{
get
{
AssertBound();
Debug.Assert(_lazyMergedAssemblyReferencesMap != null);
return _lazyMergedAssemblyReferencesMap;
}
}
internal ImmutableArray<UnifiedAssembly<TAssemblySymbol>> UnifiedAssemblies
{
get
{
AssertBound();
return _lazyUnifiedAssemblies;
}
}
#endregion
/// <summary>
/// Call only while holding <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/>.
/// </summary>
[Conditional("DEBUG")]
internal void AssertUnbound()
{
Debug.Assert(_isBound == 0);
Debug.Assert(_lazyHasCircularReference == ThreeState.Unknown);
Debug.Assert(_lazyReferencedAssembliesMap == null);
Debug.Assert(_lazyReferencedModuleIndexMap == null);
Debug.Assert(_lazyReferenceDirectiveMap == null);
Debug.Assert(_lazyDirectiveReferences.IsDefault);
Debug.Assert(_lazyImplicitReferenceResolutions == null);
Debug.Assert(_lazyExplicitReferences.IsDefault);
Debug.Assert(_lazyReferencedModules.IsDefault);
Debug.Assert(_lazyReferencedModulesReferences.IsDefault);
Debug.Assert(_lazyReferencedAssemblies.IsDefault);
Debug.Assert(_lazyAliasesOfReferencedAssemblies.IsDefault);
Debug.Assert(_lazyMergedAssemblyReferencesMap == null);
Debug.Assert(_lazyUnifiedAssemblies.IsDefault);
Debug.Assert(_lazyCorLibraryOpt == null);
}
[Conditional("DEBUG")]
[MemberNotNull(nameof(_lazyReferencedAssembliesMap), nameof(_lazyReferencedModuleIndexMap), nameof(_lazyReferenceDirectiveMap), nameof(_lazyImplicitReferenceResolutions))]
internal void AssertBound()
{
Debug.Assert(_isBound != 0);
Debug.Assert(_lazyHasCircularReference != ThreeState.Unknown);
Debug.Assert(_lazyReferencedAssembliesMap != null);
Debug.Assert(_lazyReferencedModuleIndexMap != null);
Debug.Assert(_lazyReferenceDirectiveMap != null);
Debug.Assert(!_lazyDirectiveReferences.IsDefault);
Debug.Assert(_lazyImplicitReferenceResolutions != null);
Debug.Assert(!_lazyExplicitReferences.IsDefault);
Debug.Assert(!_lazyReferencedModules.IsDefault);
Debug.Assert(!_lazyReferencedModulesReferences.IsDefault);
Debug.Assert(!_lazyReferencedAssemblies.IsDefault);
Debug.Assert(!_lazyAliasesOfReferencedAssemblies.IsDefault);
Debug.Assert(_lazyMergedAssemblyReferencesMap != null);
Debug.Assert(!_lazyUnifiedAssemblies.IsDefault);
// lazyCorLibrary is null if the compilation is corlib
Debug.Assert(_lazyReferencedAssemblies.Length == 0 || _lazyCorLibraryOpt != null);
}
[Conditional("DEBUG")]
internal void AssertCanReuseForCompilation(TCompilation compilation)
{
Debug.Assert(compilation.MakeSourceAssemblySimpleName() == this.SimpleAssemblyName);
}
internal bool IsBound
{
get
{
return _isBound != 0;
}
}
/// <summary>
/// Call only while holding <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/>.
/// </summary>
internal void InitializeNoLock(
Dictionary<MetadataReference, int> referencedAssembliesMap,
Dictionary<MetadataReference, int> referencedModulesMap,
IDictionary<(string, string), MetadataReference> boundReferenceDirectiveMap,
ImmutableArray<MetadataReference> directiveReferences,
ImmutableArray<MetadataReference> explicitReferences,
ImmutableDictionary<AssemblyIdentity, PortableExecutableReference?> implicitReferenceResolutions,
bool containsCircularReferences,
ImmutableArray<Diagnostic> diagnostics,
TAssemblySymbol? corLibraryOpt,
ImmutableArray<PEModule> referencedModules,
ImmutableArray<ModuleReferences<TAssemblySymbol>> referencedModulesReferences,
ImmutableArray<TAssemblySymbol> referencedAssemblies,
ImmutableArray<ImmutableArray<string>> aliasesOfReferencedAssemblies,
ImmutableArray<UnifiedAssembly<TAssemblySymbol>> unifiedAssemblies,
Dictionary<MetadataReference, ImmutableArray<MetadataReference>>? mergedAssemblyReferencesMapOpt)
{
AssertUnbound();
Debug.Assert(referencedModules.Length == referencedModulesReferences.Length);
Debug.Assert(referencedModules.Length == referencedModulesMap.Count);
Debug.Assert(referencedAssemblies.Length == aliasesOfReferencedAssemblies.Length);
_lazyReferencedAssembliesMap = referencedAssembliesMap;
_lazyReferencedModuleIndexMap = referencedModulesMap;
_lazyDiagnostics = diagnostics;
_lazyReferenceDirectiveMap = boundReferenceDirectiveMap;
_lazyDirectiveReferences = directiveReferences;
_lazyExplicitReferences = explicitReferences;
_lazyImplicitReferenceResolutions = implicitReferenceResolutions;
_lazyCorLibraryOpt = corLibraryOpt;
_lazyReferencedModules = referencedModules;
_lazyReferencedModulesReferences = referencedModulesReferences;
_lazyReferencedAssemblies = referencedAssemblies;
_lazyAliasesOfReferencedAssemblies = aliasesOfReferencedAssemblies;
_lazyMergedAssemblyReferencesMap = mergedAssemblyReferencesMapOpt?.ToImmutableDictionary() ?? ImmutableDictionary<MetadataReference, ImmutableArray<MetadataReference>>.Empty;
_lazyUnifiedAssemblies = unifiedAssemblies;
_lazyHasCircularReference = containsCircularReferences.ToThreeState();
// once we flip this bit the state of the manager is immutable and available to any readers:
Interlocked.Exchange(ref _isBound, 1);
}
/// <summary>
/// Global namespaces of assembly references that have been superseded by an assembly reference with a higher version are
/// hidden behind <see cref="s_supersededAlias"/> to avoid ambiguity when they are accessed from source.
/// All existing aliases of a superseded assembly are discarded.
/// </summary>
private static readonly ImmutableArray<string> s_supersededAlias = ImmutableArray.Create("<superseded>");
protected static void BuildReferencedAssembliesAndModulesMaps(
BoundInputAssembly[] bindingResult,
ImmutableArray<MetadataReference> references,
ImmutableArray<ResolvedReference> referenceMap,
int referencedModuleCount,
int explicitlyReferencedAssemblyCount,
IReadOnlyDictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName,
bool supersedeLowerVersions,
out Dictionary<MetadataReference, int> referencedAssembliesMap,
out Dictionary<MetadataReference, int> referencedModulesMap,
out ImmutableArray<ImmutableArray<string>> aliasesOfReferencedAssemblies,
out Dictionary<MetadataReference, ImmutableArray<MetadataReference>>? mergedAssemblyReferencesMapOpt)
{
referencedAssembliesMap = new Dictionary<MetadataReference, int>(referenceMap.Length);
referencedModulesMap = new Dictionary<MetadataReference, int>(referencedModuleCount);
var aliasesOfReferencedAssembliesBuilder = ArrayBuilder<ImmutableArray<string>>.GetInstance(referenceMap.Length - referencedModuleCount);
bool hasRecursiveAliases = false;
mergedAssemblyReferencesMapOpt = null;
for (int i = 0; i < referenceMap.Length; i++)
{
if (referenceMap[i].IsSkipped)
{
continue;
}
if (referenceMap[i].Kind == MetadataImageKind.Module)
{
// add 1 for the manifest module:
int moduleIndex = 1 + referenceMap[i].Index;
referencedModulesMap.Add(references[i], moduleIndex);
}
else
{
// index into assembly data array
int assemblyIndex = referenceMap[i].Index;
Debug.Assert(aliasesOfReferencedAssembliesBuilder.Count == assemblyIndex);
MetadataReference reference = references[i];
referencedAssembliesMap.Add(reference, assemblyIndex);
aliasesOfReferencedAssembliesBuilder.Add(referenceMap[i].AliasesOpt);
if (!referenceMap[i].MergedReferences.IsEmpty)
{
(mergedAssemblyReferencesMapOpt ??= new Dictionary<MetadataReference, ImmutableArray<MetadataReference>>()).Add(reference, referenceMap[i].MergedReferences);
}
hasRecursiveAliases |= !referenceMap[i].RecursiveAliasesOpt.IsDefault;
}
}
if (hasRecursiveAliases)
{
PropagateRecursiveAliases(bindingResult, referenceMap, aliasesOfReferencedAssembliesBuilder);
}
Debug.Assert(!aliasesOfReferencedAssembliesBuilder.Any(a => a.IsDefault));
if (supersedeLowerVersions)
{
foreach (var assemblyReference in assemblyReferencesBySimpleName)
{
// the item in the list is the highest version, by construction
for (int i = 1; i < assemblyReference.Value.Count; i++)
{
int assemblyIndex = assemblyReference.Value[i].GetAssemblyIndex(explicitlyReferencedAssemblyCount);
aliasesOfReferencedAssembliesBuilder[assemblyIndex] = s_supersededAlias;
}
}
}
aliasesOfReferencedAssemblies = aliasesOfReferencedAssembliesBuilder.ToImmutableAndFree();
}
/// <summary>
/// Calculates map from the identities of specified symbols to the corresponding identities in the original EnC baseline metadata.
/// The map only includes an entry for identities that differ, i.e. for symbols representing assembly references of the current compilation that have different identities
/// than the corresponding identity in baseline metadata AssemblyRef table. The key comparer of the map ignores build and revision parts of the version number,
/// since these might change if the original version included wildcard.
/// </summary>
/// <param name="symbols">Assembly symbols for references of the current compilation.</param>
/// <param name="originalIdentities">Identities in the baseline. <paramref name="originalIdentities"/>[i] corresponds to <paramref name="symbols"/>[i].</param>
internal static ImmutableDictionary<AssemblyIdentity, AssemblyIdentity> GetAssemblyReferenceIdentityBaselineMap(ImmutableArray<TAssemblySymbol> symbols, ImmutableArray<AssemblyIdentity> originalIdentities)
{
Debug.Assert(originalIdentities.Length == symbols.Length);
ImmutableDictionary<AssemblyIdentity, AssemblyIdentity>.Builder? lazyBuilder = null;
for (int i = 0; i < originalIdentities.Length; i++)
{
var symbolIdentity = symbols[i].Identity;
var versionPattern = symbols[i].AssemblyVersionPattern;
var originalIdentity = originalIdentities[i];
if (versionPattern is object)
{
Debug.Assert(versionPattern.Build == ushort.MaxValue || versionPattern.Revision == ushort.MaxValue);
lazyBuilder = lazyBuilder ?? ImmutableDictionary.CreateBuilder<AssemblyIdentity, AssemblyIdentity>();
var sourceIdentity = symbolIdentity.WithVersion(versionPattern);
if (lazyBuilder.ContainsKey(sourceIdentity))
{
// The compilation references multiple assemblies whose versions only differ in auto-generated build and/or revision numbers.
throw new NotSupportedException(CodeAnalysisResources.CompilationReferencesAssembliesWithDifferentAutoGeneratedVersion);
}
lazyBuilder.Add(sourceIdentity, originalIdentity);
}
else
{
// by construction of the arguments:
Debug.Assert(originalIdentity == symbolIdentity);
}
}
return lazyBuilder?.ToImmutable() ?? ImmutableDictionary<AssemblyIdentity, AssemblyIdentity>.Empty;
}
internal static bool CompareVersionPartsSpecifiedInSource(Version version, Version candidateVersion, TAssemblySymbol candidateSymbol)
{
// major and minor parts must match exactly
if (version.Major != candidateVersion.Major || version.Minor != candidateVersion.Minor)
{
return false;
}
// build and revision parts can differ only if the corresponding source versions were auto-generated:
var versionPattern = candidateSymbol.AssemblyVersionPattern;
Debug.Assert(versionPattern is null || versionPattern.Build == ushort.MaxValue || versionPattern.Revision == ushort.MaxValue);
if ((versionPattern is null || versionPattern.Build < ushort.MaxValue) && version.Build != candidateVersion.Build)
{
return false;
}
if (versionPattern is null && version.Revision != candidateVersion.Revision)
{
return false;
}
return true;
}
// #r references are recursive, their aliases should be merged into all their dependencies.
//
// For example, if a compilation has a reference to LibA with alias A and the user #r's LibB with alias B,
// which references LibA, LibA should be available under both aliases A and B. B is usually "global",
// which means LibA namespaces should become available to the compilation without any qualification when #r LibB
// is encountered.
//
// Pairs: (assembly index -- index into bindingResult array; index of the #r reference in referenceMap array).
private static void PropagateRecursiveAliases(
BoundInputAssembly[] bindingResult,
ImmutableArray<ResolvedReference> referenceMap,
ArrayBuilder<ImmutableArray<string>> aliasesOfReferencedAssembliesBuilder)
{
var assemblyIndicesToProcess = ArrayBuilder<int>.GetInstance();
var visitedAssemblies = BitVector.Create(bindingResult.Length);
// +1 for assembly being built
Debug.Assert(bindingResult.Length == aliasesOfReferencedAssembliesBuilder.Count + 1);
foreach (ResolvedReference reference in referenceMap)
{
if (!reference.IsSkipped && !reference.RecursiveAliasesOpt.IsDefault)
{
var recursiveAliases = reference.RecursiveAliasesOpt;
Debug.Assert(reference.Kind == MetadataImageKind.Assembly);
visitedAssemblies.Clear();
Debug.Assert(assemblyIndicesToProcess.Count == 0);
assemblyIndicesToProcess.Add(reference.Index);
while (assemblyIndicesToProcess.Count > 0)
{
int assemblyIndex = assemblyIndicesToProcess.Pop();
visitedAssemblies[assemblyIndex] = true;
// merge aliases:
aliasesOfReferencedAssembliesBuilder[assemblyIndex] = MergedAliases.Merge(aliasesOfReferencedAssembliesBuilder[assemblyIndex], recursiveAliases);
// push dependencies onto the stack:
// +1 for the assembly being built:
var referenceBinding = bindingResult[assemblyIndex + 1].ReferenceBinding;
Debug.Assert(referenceBinding is object);
foreach (var binding in referenceBinding)
{
if (binding.IsBound)
{
// -1 for the assembly being built:
int dependentAssemblyIndex = binding.DefinitionIndex - 1;
if (!visitedAssemblies[dependentAssemblyIndex])
{
assemblyIndicesToProcess.Add(dependentAssemblyIndex);
}
}
}
}
}
}
for (int i = 0; i < aliasesOfReferencedAssembliesBuilder.Count; i++)
{
if (aliasesOfReferencedAssembliesBuilder[i].IsDefault)
{
aliasesOfReferencedAssembliesBuilder[i] = ImmutableArray<string>.Empty;
}
}
assemblyIndicesToProcess.Free();
}
#region Compilation APIs Implementation
// for testing purposes
internal IEnumerable<string> ExternAliases => AliasesOfReferencedAssemblies.SelectMany(aliases => aliases);
internal sealed override IEnumerable<KeyValuePair<MetadataReference, IAssemblySymbolInternal>> GetReferencedAssemblies()
{
return ReferencedAssembliesMap.Select(ra => KeyValuePairUtil.Create(ra.Key, (IAssemblySymbolInternal)ReferencedAssemblies[ra.Value]));
}
internal TAssemblySymbol? GetReferencedAssemblySymbol(MetadataReference reference)
{
int index;
return ReferencedAssembliesMap.TryGetValue(reference, out index) ? ReferencedAssemblies[index] : null;
}
internal int GetReferencedModuleIndex(MetadataReference reference)
{
int index;
return ReferencedModuleIndexMap.TryGetValue(reference, out index) ? index : -1;
}
/// <summary>
/// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol.
/// </summary>
internal override MetadataReference? GetMetadataReference(IAssemblySymbolInternal? assemblySymbol)
{
foreach (var entry in ReferencedAssembliesMap)
{
if ((object)ReferencedAssemblies[entry.Value] == assemblySymbol)
{
return entry.Key;
}
}
return null;
}
internal override IEnumerable<(IAssemblySymbolInternal AssemblySymbol, ImmutableArray<string> Aliases)> GetReferencedAssemblyAliases()
{
for (int i = 0; i < ReferencedAssemblies.Length; i++)
{
yield return (ReferencedAssemblies[i], AliasesOfReferencedAssemblies[i]);
}
}
public bool DeclarationsAccessibleWithoutAlias(int referencedAssemblyIndex)
{
var aliases = AliasesOfReferencedAssemblies[referencedAssemblyIndex];
return aliases.Length == 0 || aliases.IndexOf(MetadataReferenceProperties.GlobalAlias, StringComparer.Ordinal) >= 0;
}
#endregion
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/ExtractInterface/ExtractInterfaceCodeAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractInterface
{
internal class ExtractInterfaceCodeAction : CodeActionWithOptions
{
private readonly ExtractInterfaceTypeAnalysisResult _typeAnalysisResult;
private readonly AbstractExtractInterfaceService _extractInterfaceService;
public ExtractInterfaceCodeAction(AbstractExtractInterfaceService extractInterfaceService, ExtractInterfaceTypeAnalysisResult typeAnalysisResult)
{
_extractInterfaceService = extractInterfaceService;
_typeAnalysisResult = typeAnalysisResult;
}
public override object GetOptions(CancellationToken cancellationToken)
{
var containingNamespaceDisplay = _typeAnalysisResult.TypeToExtractFrom.ContainingNamespace.IsGlobalNamespace
? string.Empty
: _typeAnalysisResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString();
return AbstractExtractInterfaceService.GetExtractInterfaceOptionsAsync(
_typeAnalysisResult.DocumentToExtractFrom,
_typeAnalysisResult.TypeToExtractFrom,
_typeAnalysisResult.ExtractableMembers,
containingNamespaceDisplay,
cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
}
protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken)
{
var operations = SpecializedCollections.EmptyEnumerable<CodeActionOperation>();
if (options is ExtractInterfaceOptionsResult extractInterfaceOptions && !extractInterfaceOptions.IsCancelled)
{
var extractInterfaceResult = await _extractInterfaceService
.ExtractInterfaceFromAnalyzedTypeAsync(_typeAnalysisResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false);
if (extractInterfaceResult.Succeeded)
{
operations = new CodeActionOperation[]
{
new ApplyChangesOperation(extractInterfaceResult.UpdatedSolution),
new DocumentNavigationOperation(extractInterfaceResult.NavigationDocumentId, position: 0)
};
}
}
return operations;
}
public override string Title => FeaturesResources.Extract_interface;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExtractInterface
{
internal class ExtractInterfaceCodeAction : CodeActionWithOptions
{
private readonly ExtractInterfaceTypeAnalysisResult _typeAnalysisResult;
private readonly AbstractExtractInterfaceService _extractInterfaceService;
public ExtractInterfaceCodeAction(AbstractExtractInterfaceService extractInterfaceService, ExtractInterfaceTypeAnalysisResult typeAnalysisResult)
{
_extractInterfaceService = extractInterfaceService;
_typeAnalysisResult = typeAnalysisResult;
}
public override object GetOptions(CancellationToken cancellationToken)
{
var containingNamespaceDisplay = _typeAnalysisResult.TypeToExtractFrom.ContainingNamespace.IsGlobalNamespace
? string.Empty
: _typeAnalysisResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString();
return AbstractExtractInterfaceService.GetExtractInterfaceOptionsAsync(
_typeAnalysisResult.DocumentToExtractFrom,
_typeAnalysisResult.TypeToExtractFrom,
_typeAnalysisResult.ExtractableMembers,
containingNamespaceDisplay,
cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
}
protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken)
{
var operations = SpecializedCollections.EmptyEnumerable<CodeActionOperation>();
if (options is ExtractInterfaceOptionsResult extractInterfaceOptions && !extractInterfaceOptions.IsCancelled)
{
var extractInterfaceResult = await _extractInterfaceService
.ExtractInterfaceFromAnalyzedTypeAsync(_typeAnalysisResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false);
if (extractInterfaceResult.Succeeded)
{
operations = new CodeActionOperation[]
{
new ApplyChangesOperation(extractInterfaceResult.UpdatedSolution),
new DocumentNavigationOperation(extractInterfaceResult.NavigationDocumentId, position: 0)
};
}
}
return operations;
}
public override string Title => FeaturesResources.Extract_interface;
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeAccessorFunction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE80.CodeFunction2))]
public sealed partial class CodeAccessorFunction : AbstractCodeElement, EnvDTE.CodeFunction, EnvDTE80.CodeFunction2
{
internal static EnvDTE.CodeFunction Create(CodeModelState state, AbstractCodeMember parent, MethodKind kind)
{
var newElement = new CodeAccessorFunction(state, parent, kind);
return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(newElement);
}
private readonly ParentHandle<AbstractCodeMember> _parentHandle;
private readonly MethodKind _kind;
private CodeAccessorFunction(CodeModelState state, AbstractCodeMember parent, MethodKind kind)
: base(state, parent.FileCodeModel)
{
Debug.Assert(kind == MethodKind.EventAdd ||
kind == MethodKind.EventRaise ||
kind == MethodKind.EventRemove ||
kind == MethodKind.PropertyGet ||
kind == MethodKind.PropertySet);
_parentHandle = new ParentHandle<AbstractCodeMember>(parent);
_kind = kind;
}
private AbstractCodeMember ParentMember => _parentHandle.Value;
private bool IsPropertyAccessor()
=> _kind == MethodKind.PropertyGet || _kind == MethodKind.PropertySet;
internal override bool TryLookupNode(out SyntaxNode node)
{
node = null;
var parentNode = _parentHandle.Value.LookupNode();
if (parentNode == null)
{
return false;
}
return CodeModelService.TryGetAutoPropertyExpressionBody(parentNode, out node) ||
CodeModelService.TryGetAccessorNode(parentNode, _kind, out node);
}
public override EnvDTE.vsCMElement Kind
=> EnvDTE.vsCMElement.vsCMElementFunction;
public override object Parent => _parentHandle.Value;
public override EnvDTE.CodeElements Children
=> EmptyCollection.Create(this.State, this);
protected override string GetName()
=> this.ParentMember.Name;
protected override void SetName(string value)
=> this.ParentMember.Name = value;
protected override string GetFullName()
=> this.ParentMember.FullName;
public EnvDTE.CodeElements Attributes
=> AttributeCollection.Create(this.State, this);
public EnvDTE.vsCMAccess Access
{
get
{
var node = LookupNode();
return CodeModelService.GetAccess(node);
}
set
{
UpdateNode(FileCodeModel.UpdateAccess, value);
}
}
public bool CanOverride
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
public string Comment
{
get
{
throw Exceptions.ThrowEFail();
}
set
{
throw Exceptions.ThrowEFail();
}
}
public string DocComment
{
get
{
return string.Empty;
}
set
{
throw Exceptions.ThrowENotImpl();
}
}
public EnvDTE.vsCMFunction FunctionKind
{
get
{
if (!(LookupSymbol() is IMethodSymbol methodSymbol))
{
throw Exceptions.ThrowEUnexpected();
}
return CodeModelService.GetFunctionKind(methodSymbol);
}
}
public bool IsGeneric
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).IsGeneric;
}
else
{
return ((CodeEvent)this.ParentMember).IsGeneric;
}
}
}
public EnvDTE80.vsCMOverrideKind OverrideKind
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).OverrideKind;
}
else
{
return ((CodeEvent)this.ParentMember).OverrideKind;
}
}
set
{
if (IsPropertyAccessor())
{
((CodeProperty)this.ParentMember).OverrideKind = value;
}
else
{
((CodeEvent)this.ParentMember).OverrideKind = value;
}
}
}
public bool IsOverloaded => false;
public bool IsShared
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).IsShared;
}
else
{
return ((CodeEvent)this.ParentMember).IsShared;
}
}
set
{
if (IsPropertyAccessor())
{
((CodeProperty)this.ParentMember).IsShared = value;
}
else
{
((CodeEvent)this.ParentMember).IsShared = value;
}
}
}
public bool MustImplement
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).MustImplement;
}
else
{
return ((CodeEvent)this.ParentMember).MustImplement;
}
}
set
{
if (IsPropertyAccessor())
{
((CodeProperty)this.ParentMember).MustImplement = value;
}
else
{
((CodeEvent)this.ParentMember).MustImplement = value;
}
}
}
public EnvDTE.CodeElements Overloads
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeElements Parameters
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).Parameters;
}
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeTypeRef Type
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).Type;
}
throw Exceptions.ThrowEFail();
}
set
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position)
{
// TODO(DustinCa): Check VB
throw Exceptions.ThrowEFail();
}
public EnvDTE.CodeParameter AddParameter(string name, object type, object position)
{
// TODO(DustinCa): Check VB
throw Exceptions.ThrowEFail();
}
public void RemoveParameter(object element)
{
// TODO(DustinCa): Check VB
throw Exceptions.ThrowEFail();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE80.CodeFunction2))]
public sealed partial class CodeAccessorFunction : AbstractCodeElement, EnvDTE.CodeFunction, EnvDTE80.CodeFunction2
{
internal static EnvDTE.CodeFunction Create(CodeModelState state, AbstractCodeMember parent, MethodKind kind)
{
var newElement = new CodeAccessorFunction(state, parent, kind);
return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(newElement);
}
private readonly ParentHandle<AbstractCodeMember> _parentHandle;
private readonly MethodKind _kind;
private CodeAccessorFunction(CodeModelState state, AbstractCodeMember parent, MethodKind kind)
: base(state, parent.FileCodeModel)
{
Debug.Assert(kind == MethodKind.EventAdd ||
kind == MethodKind.EventRaise ||
kind == MethodKind.EventRemove ||
kind == MethodKind.PropertyGet ||
kind == MethodKind.PropertySet);
_parentHandle = new ParentHandle<AbstractCodeMember>(parent);
_kind = kind;
}
private AbstractCodeMember ParentMember => _parentHandle.Value;
private bool IsPropertyAccessor()
=> _kind == MethodKind.PropertyGet || _kind == MethodKind.PropertySet;
internal override bool TryLookupNode(out SyntaxNode node)
{
node = null;
var parentNode = _parentHandle.Value.LookupNode();
if (parentNode == null)
{
return false;
}
return CodeModelService.TryGetAutoPropertyExpressionBody(parentNode, out node) ||
CodeModelService.TryGetAccessorNode(parentNode, _kind, out node);
}
public override EnvDTE.vsCMElement Kind
=> EnvDTE.vsCMElement.vsCMElementFunction;
public override object Parent => _parentHandle.Value;
public override EnvDTE.CodeElements Children
=> EmptyCollection.Create(this.State, this);
protected override string GetName()
=> this.ParentMember.Name;
protected override void SetName(string value)
=> this.ParentMember.Name = value;
protected override string GetFullName()
=> this.ParentMember.FullName;
public EnvDTE.CodeElements Attributes
=> AttributeCollection.Create(this.State, this);
public EnvDTE.vsCMAccess Access
{
get
{
var node = LookupNode();
return CodeModelService.GetAccess(node);
}
set
{
UpdateNode(FileCodeModel.UpdateAccess, value);
}
}
public bool CanOverride
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
public string Comment
{
get
{
throw Exceptions.ThrowEFail();
}
set
{
throw Exceptions.ThrowEFail();
}
}
public string DocComment
{
get
{
return string.Empty;
}
set
{
throw Exceptions.ThrowENotImpl();
}
}
public EnvDTE.vsCMFunction FunctionKind
{
get
{
if (!(LookupSymbol() is IMethodSymbol methodSymbol))
{
throw Exceptions.ThrowEUnexpected();
}
return CodeModelService.GetFunctionKind(methodSymbol);
}
}
public bool IsGeneric
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).IsGeneric;
}
else
{
return ((CodeEvent)this.ParentMember).IsGeneric;
}
}
}
public EnvDTE80.vsCMOverrideKind OverrideKind
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).OverrideKind;
}
else
{
return ((CodeEvent)this.ParentMember).OverrideKind;
}
}
set
{
if (IsPropertyAccessor())
{
((CodeProperty)this.ParentMember).OverrideKind = value;
}
else
{
((CodeEvent)this.ParentMember).OverrideKind = value;
}
}
}
public bool IsOverloaded => false;
public bool IsShared
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).IsShared;
}
else
{
return ((CodeEvent)this.ParentMember).IsShared;
}
}
set
{
if (IsPropertyAccessor())
{
((CodeProperty)this.ParentMember).IsShared = value;
}
else
{
((CodeEvent)this.ParentMember).IsShared = value;
}
}
}
public bool MustImplement
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).MustImplement;
}
else
{
return ((CodeEvent)this.ParentMember).MustImplement;
}
}
set
{
if (IsPropertyAccessor())
{
((CodeProperty)this.ParentMember).MustImplement = value;
}
else
{
((CodeEvent)this.ParentMember).MustImplement = value;
}
}
}
public EnvDTE.CodeElements Overloads
=> throw Exceptions.ThrowEFail();
public EnvDTE.CodeElements Parameters
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).Parameters;
}
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeTypeRef Type
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).Type;
}
throw Exceptions.ThrowEFail();
}
set
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position)
{
// TODO(DustinCa): Check VB
throw Exceptions.ThrowEFail();
}
public EnvDTE.CodeParameter AddParameter(string name, object type, object position)
{
// TODO(DustinCa): Check VB
throw Exceptions.ThrowEFail();
}
public void RemoveParameter(object element)
{
// TODO(DustinCa): Check VB
throw Exceptions.ThrowEFail();
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/CSharp/Portable/Syntax/LookupPosition.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
/// <summary>
/// This class contains a variety of helper methods for determining whether a
/// position is within the scope (and not just the span) of a node. In general,
/// general, the scope extends from the first token up to, but not including,
/// the last token. For example, the open brace of a block is within the scope
/// of the block, but the close brace is not.
/// </summary>
internal static class LookupPosition
{
/// <summary>
/// A position is considered to be inside a block if it is on or after
/// the open brace and strictly before the close brace.
/// </summary>
internal static bool IsInBlock(int position, BlockSyntax? blockOpt)
{
return blockOpt != null && IsBeforeToken(position, blockOpt, blockOpt.CloseBraceToken);
}
internal static bool IsInExpressionBody(
int position,
ArrowExpressionClauseSyntax? expressionBodyOpt,
SyntaxToken semicolonToken)
{
return expressionBodyOpt != null
&& IsBeforeToken(position, expressionBodyOpt, semicolonToken);
}
private static bool IsInBody(int position, BlockSyntax? blockOpt, ArrowExpressionClauseSyntax? exprOpt, SyntaxToken semiOpt)
{
return IsInExpressionBody(position, exprOpt, semiOpt)
|| IsInBlock(position, blockOpt);
}
/// <summary>
/// A position is inside a property body only if it is inside an expression body.
/// All block bodies for properties are part of the accessor declaration (a type
/// of BaseMethodDeclaration), not the property declaration.
/// </summary>
internal static bool IsInBody(int position,
PropertyDeclarationSyntax property)
=> IsInBody(position, blockOpt: null, property.GetExpressionBodySyntax(), property.SemicolonToken);
/// <summary>
/// A position is inside a property body only if it is inside an expression body.
/// All block bodies for properties are part of the accessor declaration (a type
/// of BaseMethodDeclaration), not the property declaration.
/// </summary>
internal static bool IsInBody(int position,
IndexerDeclarationSyntax indexer)
=> IsInBody(position, blockOpt: null, indexer.GetExpressionBodySyntax(), indexer.SemicolonToken);
/// <summary>
/// A position is inside an accessor body if it is inside the block or expression
/// body.
/// </summary>
internal static bool IsInBody(int position, AccessorDeclarationSyntax method)
=> IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken);
/// <summary>
/// A position is inside a body if it is inside the block or expression
/// body.
///
/// A position is considered to be inside a block if it is on or after
/// the open brace and strictly before the close brace. A position is
/// considered to be inside an expression body if it is on or after
/// the '=>' and strictly before the semicolon.
/// </summary>
internal static bool IsInBody(int position, BaseMethodDeclarationSyntax method)
=> IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken);
internal static bool IsBetweenTokens(int position, SyntaxToken firstIncluded, SyntaxToken firstExcluded)
{
return position >= firstIncluded.SpanStart && IsBeforeToken(position, firstExcluded);
}
/// <summary>
/// Returns true if position is within the given node and before the first excluded token.
/// </summary>
private static bool IsBeforeToken(int position, CSharpSyntaxNode node, SyntaxToken firstExcluded)
{
return IsBeforeToken(position, firstExcluded) && position >= node.SpanStart;
}
private static bool IsBeforeToken(int position, SyntaxToken firstExcluded)
{
return firstExcluded.Kind() == SyntaxKind.None || position < firstExcluded.SpanStart;
}
internal static bool IsInAttributeSpecification(int position, SyntaxList<AttributeListSyntax> attributesSyntaxList)
{
int count = attributesSyntaxList.Count;
if (count == 0)
{
return false;
}
var startToken = attributesSyntaxList[0].OpenBracketToken;
var endToken = attributesSyntaxList[count - 1].CloseBracketToken;
return IsBetweenTokens(position, startToken, endToken);
}
internal static bool IsInTypeParameterList(int position, TypeDeclarationSyntax typeDecl)
{
var typeParameterListOpt = typeDecl.TypeParameterList;
return typeParameterListOpt != null && IsBeforeToken(position, typeParameterListOpt, typeParameterListOpt.GreaterThanToken);
}
internal static bool IsInParameterList(int position, BaseMethodDeclarationSyntax methodDecl)
{
var parameterList = methodDecl.ParameterList;
return IsBeforeToken(position, parameterList, parameterList.CloseParenToken);
}
internal static bool IsInParameterList(int position, ParameterListSyntax parameterList)
=> parameterList != null && IsBeforeToken(position, parameterList, parameterList.CloseParenToken);
internal static bool IsInMethodDeclaration(int position, BaseMethodDeclarationSyntax methodDecl)
{
Debug.Assert(methodDecl != null);
var body = methodDecl.Body;
if (body == null)
{
return IsBeforeToken(position, methodDecl, methodDecl.SemicolonToken);
}
return IsBeforeToken(position, methodDecl, body.CloseBraceToken) ||
IsInExpressionBody(position, methodDecl.GetExpressionBodySyntax(), methodDecl.SemicolonToken);
}
internal static bool IsInMethodDeclaration(int position, AccessorDeclarationSyntax accessorDecl)
{
Debug.Assert(accessorDecl != null);
var body = accessorDecl.Body;
SyntaxToken lastToken = body == null ? accessorDecl.SemicolonToken : body.CloseBraceToken;
return IsBeforeToken(position, accessorDecl, lastToken);
}
internal static bool IsInDelegateDeclaration(int position, DelegateDeclarationSyntax delegateDecl)
{
Debug.Assert(delegateDecl != null);
return IsBeforeToken(position, delegateDecl, delegateDecl.SemicolonToken);
}
internal static bool IsInTypeDeclaration(int position, BaseTypeDeclarationSyntax typeDecl)
{
Debug.Assert(typeDecl != null);
return IsBeforeToken(position, typeDecl, typeDecl.CloseBraceToken);
}
internal static bool IsInNamespaceDeclaration(int position, NamespaceDeclarationSyntax namespaceDecl)
{
Debug.Assert(namespaceDecl != null);
return IsBetweenTokens(position, namespaceDecl.NamespaceKeyword, namespaceDecl.CloseBraceToken);
}
internal static bool IsInNamespaceDeclaration(int position, FileScopedNamespaceDeclarationSyntax namespaceDecl)
{
Debug.Assert(namespaceDecl != null);
return position >= namespaceDecl.SpanStart;
}
internal static bool IsInConstructorParameterScope(int position, ConstructorDeclarationSyntax constructorDecl)
{
Debug.Assert(constructorDecl != null);
var initializerOpt = constructorDecl.Initializer;
var hasBody = constructorDecl.Body != null || constructorDecl.ExpressionBody != null;
if (!hasBody)
{
var nextToken = (SyntaxToken)SyntaxNavigator.Instance.GetNextToken(constructorDecl, predicate: null, stepInto: null);
return initializerOpt == null ?
position >= constructorDecl.ParameterList.CloseParenToken.Span.End && IsBeforeToken(position, nextToken) :
IsBetweenTokens(position, initializerOpt.ColonToken, nextToken);
}
return initializerOpt == null ?
IsInBody(position, constructorDecl) :
IsBetweenTokens(position, initializerOpt.ColonToken,
constructorDecl.SemicolonToken.Kind() == SyntaxKind.None ? constructorDecl.Body!.CloseBraceToken : constructorDecl.SemicolonToken);
}
internal static bool IsInMethodTypeParameterScope(int position, MethodDeclarationSyntax methodDecl)
{
Debug.Assert(methodDecl != null);
Debug.Assert(IsInMethodDeclaration(position, methodDecl));
if (methodDecl.TypeParameterList == null)
{
// no type parameters => nothing can be in their scope
return false;
}
// optimization for a common case - when position is in the ReturnType, we can see type parameters
if (methodDecl.ReturnType.FullSpan.Contains(position))
{
return true;
}
// Must be in the method, but not in an attribute on the method.
if (IsInAttributeSpecification(position, methodDecl.AttributeLists))
{
return false;
}
var explicitInterfaceSpecifier = methodDecl.ExplicitInterfaceSpecifier;
var firstNameToken = explicitInterfaceSpecifier == null ? methodDecl.Identifier : explicitInterfaceSpecifier.GetFirstToken();
var typeParams = methodDecl.TypeParameterList;
var firstPostNameToken = typeParams == null ? methodDecl.ParameterList.OpenParenToken : typeParams.LessThanToken;
// Scope does not include method name.
return !IsBetweenTokens(position, firstNameToken, firstPostNameToken);
}
/// <remarks>
/// Used to determine whether it would be appropriate to use the binder for the statement (if any).
/// Not used to determine whether the position is syntactically within the statement.
/// </remarks>
internal static bool IsInStatementScope(int position, StatementSyntax statement)
{
Debug.Assert(statement != null);
if (statement.Kind() == SyntaxKind.EmptyStatement)
{
return false;
}
// CONSIDER: the check for default(SyntaxToken) could go in IsBetweenTokens,
// but this is where it has special meaning.
SyntaxToken firstIncludedToken = GetFirstIncludedToken(statement);
return firstIncludedToken != default(SyntaxToken) &&
IsBetweenTokens(position, firstIncludedToken, GetFirstExcludedToken(statement));
}
/// <remarks>
/// Used to determine whether it would be appropriate to use the binder for the switch section (if any).
/// Not used to determine whether the position is syntactically within the statement.
/// </remarks>
internal static bool IsInSwitchSectionScope(int position, SwitchSectionSyntax section)
{
Debug.Assert(section != null);
return section.Span.Contains(position);
}
/// <remarks>
/// Used to determine whether it would be appropriate to use the binder for the statement (if any).
/// Not used to determine whether the position is syntactically within the statement.
/// </remarks>
internal static bool IsInCatchBlockScope(int position, CatchClauseSyntax catchClause)
{
Debug.Assert(catchClause != null);
return IsBetweenTokens(position, catchClause.Block.OpenBraceToken, catchClause.Block.CloseBraceToken);
}
/// <remarks>
/// Used to determine whether it would be appropriate to use the binder for the statement (if any).
/// Not used to determine whether the position is syntactically within the statement.
/// </remarks>
internal static bool IsInCatchFilterScope(int position, CatchFilterClauseSyntax filterClause)
{
Debug.Assert(filterClause != null);
return IsBetweenTokens(position, filterClause.OpenParenToken, filterClause.CloseParenToken);
}
private static SyntaxToken GetFirstIncludedToken(StatementSyntax statement)
{
Debug.Assert(statement != null);
switch (statement.Kind())
{
case SyntaxKind.Block:
return ((BlockSyntax)statement).OpenBraceToken;
case SyntaxKind.BreakStatement:
return ((BreakStatementSyntax)statement).BreakKeyword;
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
return ((CheckedStatementSyntax)statement).Keyword;
case SyntaxKind.ContinueStatement:
return ((ContinueStatementSyntax)statement).ContinueKeyword;
case SyntaxKind.ExpressionStatement:
case SyntaxKind.LocalDeclarationStatement:
return statement.GetFirstToken();
case SyntaxKind.DoStatement:
return ((DoStatementSyntax)statement).DoKeyword;
case SyntaxKind.EmptyStatement:
return default(SyntaxToken); //The caller will have to check for this.
case SyntaxKind.FixedStatement:
return ((FixedStatementSyntax)statement).FixedKeyword;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return ((CommonForEachStatementSyntax)statement).OpenParenToken.GetNextToken();
case SyntaxKind.ForStatement:
return ((ForStatementSyntax)statement).OpenParenToken.GetNextToken();
case SyntaxKind.GotoDefaultStatement:
case SyntaxKind.GotoCaseStatement:
case SyntaxKind.GotoStatement:
return ((GotoStatementSyntax)statement).GotoKeyword;
case SyntaxKind.IfStatement:
return ((IfStatementSyntax)statement).IfKeyword;
case SyntaxKind.LabeledStatement:
return ((LabeledStatementSyntax)statement).Identifier;
case SyntaxKind.LockStatement:
return ((LockStatementSyntax)statement).LockKeyword;
case SyntaxKind.ReturnStatement:
return ((ReturnStatementSyntax)statement).ReturnKeyword;
case SyntaxKind.SwitchStatement:
return ((SwitchStatementSyntax)statement).Expression.GetFirstToken();
case SyntaxKind.ThrowStatement:
return ((ThrowStatementSyntax)statement).ThrowKeyword;
case SyntaxKind.TryStatement:
return ((TryStatementSyntax)statement).TryKeyword;
case SyntaxKind.UnsafeStatement:
return ((UnsafeStatementSyntax)statement).UnsafeKeyword;
case SyntaxKind.UsingStatement:
return ((UsingStatementSyntax)statement).UsingKeyword;
case SyntaxKind.WhileStatement:
return ((WhileStatementSyntax)statement).WhileKeyword;
case SyntaxKind.YieldReturnStatement:
case SyntaxKind.YieldBreakStatement:
return ((YieldStatementSyntax)statement).YieldKeyword;
case SyntaxKind.LocalFunctionStatement:
return statement.GetFirstToken();
default:
throw ExceptionUtilities.UnexpectedValue(statement.Kind());
}
}
internal static SyntaxToken GetFirstExcludedToken(StatementSyntax statement)
{
Debug.Assert(statement != null);
switch (statement.Kind())
{
case SyntaxKind.Block:
return ((BlockSyntax)statement).CloseBraceToken;
case SyntaxKind.BreakStatement:
return ((BreakStatementSyntax)statement).SemicolonToken;
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
return ((CheckedStatementSyntax)statement).Block.CloseBraceToken;
case SyntaxKind.ContinueStatement:
return ((ContinueStatementSyntax)statement).SemicolonToken;
case SyntaxKind.LocalDeclarationStatement:
return ((LocalDeclarationStatementSyntax)statement).SemicolonToken;
case SyntaxKind.DoStatement:
return ((DoStatementSyntax)statement).SemicolonToken;
case SyntaxKind.EmptyStatement:
return ((EmptyStatementSyntax)statement).SemicolonToken;
case SyntaxKind.ExpressionStatement:
return ((ExpressionStatementSyntax)statement).SemicolonToken;
case SyntaxKind.FixedStatement:
return GetFirstExcludedToken(((FixedStatementSyntax)statement).Statement);
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return GetFirstExcludedToken(((CommonForEachStatementSyntax)statement).Statement);
case SyntaxKind.ForStatement:
return GetFirstExcludedToken(((ForStatementSyntax)statement).Statement);
case SyntaxKind.GotoDefaultStatement:
case SyntaxKind.GotoCaseStatement:
case SyntaxKind.GotoStatement:
return ((GotoStatementSyntax)statement).SemicolonToken;
case SyntaxKind.IfStatement:
IfStatementSyntax ifStmt = (IfStatementSyntax)statement;
ElseClauseSyntax? elseOpt = ifStmt.Else;
return GetFirstExcludedToken(elseOpt == null ? ifStmt.Statement : elseOpt.Statement);
case SyntaxKind.LabeledStatement:
return GetFirstExcludedToken(((LabeledStatementSyntax)statement).Statement);
case SyntaxKind.LockStatement:
return GetFirstExcludedToken(((LockStatementSyntax)statement).Statement);
case SyntaxKind.ReturnStatement:
return ((ReturnStatementSyntax)statement).SemicolonToken;
case SyntaxKind.SwitchStatement:
return ((SwitchStatementSyntax)statement).CloseBraceToken;
case SyntaxKind.ThrowStatement:
return ((ThrowStatementSyntax)statement).SemicolonToken;
case SyntaxKind.TryStatement:
TryStatementSyntax tryStmt = (TryStatementSyntax)statement;
FinallyClauseSyntax? finallyClause = tryStmt.Finally;
if (finallyClause != null)
{
return finallyClause.Block.CloseBraceToken;
}
CatchClauseSyntax? lastCatch = tryStmt.Catches.LastOrDefault();
if (lastCatch != null)
{
return lastCatch.Block.CloseBraceToken;
}
return tryStmt.Block.CloseBraceToken;
case SyntaxKind.UnsafeStatement:
return ((UnsafeStatementSyntax)statement).Block.CloseBraceToken;
case SyntaxKind.UsingStatement:
return GetFirstExcludedToken(((UsingStatementSyntax)statement).Statement);
case SyntaxKind.WhileStatement:
return GetFirstExcludedToken(((WhileStatementSyntax)statement).Statement);
case SyntaxKind.YieldReturnStatement:
case SyntaxKind.YieldBreakStatement:
return ((YieldStatementSyntax)statement).SemicolonToken;
case SyntaxKind.LocalFunctionStatement:
LocalFunctionStatementSyntax localFunctionStmt = (LocalFunctionStatementSyntax)statement;
if (localFunctionStmt.Body != null)
return GetFirstExcludedToken(localFunctionStmt.Body);
if (localFunctionStmt.SemicolonToken != default(SyntaxToken))
return localFunctionStmt.SemicolonToken;
return localFunctionStmt.ParameterList.GetLastToken();
default:
throw ExceptionUtilities.UnexpectedValue(statement.Kind());
}
}
internal static bool IsInAnonymousFunctionOrQuery(int position, SyntaxNode lambdaExpressionOrQueryNode)
{
Debug.Assert(lambdaExpressionOrQueryNode.IsAnonymousFunction() || lambdaExpressionOrQueryNode.IsQuery());
SyntaxToken firstIncluded;
CSharpSyntaxNode body;
switch (lambdaExpressionOrQueryNode.Kind())
{
case SyntaxKind.SimpleLambdaExpression:
SimpleLambdaExpressionSyntax simple = (SimpleLambdaExpressionSyntax)lambdaExpressionOrQueryNode;
firstIncluded = simple.ArrowToken;
body = simple.Body;
break;
case SyntaxKind.ParenthesizedLambdaExpression:
ParenthesizedLambdaExpressionSyntax parenthesized = (ParenthesizedLambdaExpressionSyntax)lambdaExpressionOrQueryNode;
firstIncluded = parenthesized.ArrowToken;
body = parenthesized.Body;
break;
case SyntaxKind.AnonymousMethodExpression:
AnonymousMethodExpressionSyntax anon = (AnonymousMethodExpressionSyntax)lambdaExpressionOrQueryNode;
body = anon.Block;
firstIncluded = body.GetFirstToken(includeZeroWidth: true);
break;
default:
// OK, so we have some kind of query clause. They all start with a keyword token, so we'll skip that.
firstIncluded = lambdaExpressionOrQueryNode.GetFirstToken().GetNextToken();
return IsBetweenTokens(position, firstIncluded, lambdaExpressionOrQueryNode.GetLastToken().GetNextToken());
}
var bodyStatement = body as StatementSyntax;
var firstExcluded = bodyStatement != null ?
GetFirstExcludedToken(bodyStatement) :
(SyntaxToken)SyntaxNavigator.Instance.GetNextToken(body, predicate: null, stepInto: null);
return IsBetweenTokens(position, firstIncluded, firstExcluded);
}
internal static bool IsInXmlAttributeValue(int position, XmlAttributeSyntax attribute)
{
return IsBetweenTokens(position, attribute.StartQuoteToken, attribute.EndQuoteToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
/// <summary>
/// This class contains a variety of helper methods for determining whether a
/// position is within the scope (and not just the span) of a node. In general,
/// general, the scope extends from the first token up to, but not including,
/// the last token. For example, the open brace of a block is within the scope
/// of the block, but the close brace is not.
/// </summary>
internal static class LookupPosition
{
/// <summary>
/// A position is considered to be inside a block if it is on or after
/// the open brace and strictly before the close brace.
/// </summary>
internal static bool IsInBlock(int position, BlockSyntax? blockOpt)
{
return blockOpt != null && IsBeforeToken(position, blockOpt, blockOpt.CloseBraceToken);
}
internal static bool IsInExpressionBody(
int position,
ArrowExpressionClauseSyntax? expressionBodyOpt,
SyntaxToken semicolonToken)
{
return expressionBodyOpt != null
&& IsBeforeToken(position, expressionBodyOpt, semicolonToken);
}
private static bool IsInBody(int position, BlockSyntax? blockOpt, ArrowExpressionClauseSyntax? exprOpt, SyntaxToken semiOpt)
{
return IsInExpressionBody(position, exprOpt, semiOpt)
|| IsInBlock(position, blockOpt);
}
/// <summary>
/// A position is inside a property body only if it is inside an expression body.
/// All block bodies for properties are part of the accessor declaration (a type
/// of BaseMethodDeclaration), not the property declaration.
/// </summary>
internal static bool IsInBody(int position,
PropertyDeclarationSyntax property)
=> IsInBody(position, blockOpt: null, property.GetExpressionBodySyntax(), property.SemicolonToken);
/// <summary>
/// A position is inside a property body only if it is inside an expression body.
/// All block bodies for properties are part of the accessor declaration (a type
/// of BaseMethodDeclaration), not the property declaration.
/// </summary>
internal static bool IsInBody(int position,
IndexerDeclarationSyntax indexer)
=> IsInBody(position, blockOpt: null, indexer.GetExpressionBodySyntax(), indexer.SemicolonToken);
/// <summary>
/// A position is inside an accessor body if it is inside the block or expression
/// body.
/// </summary>
internal static bool IsInBody(int position, AccessorDeclarationSyntax method)
=> IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken);
/// <summary>
/// A position is inside a body if it is inside the block or expression
/// body.
///
/// A position is considered to be inside a block if it is on or after
/// the open brace and strictly before the close brace. A position is
/// considered to be inside an expression body if it is on or after
/// the '=>' and strictly before the semicolon.
/// </summary>
internal static bool IsInBody(int position, BaseMethodDeclarationSyntax method)
=> IsInBody(position, method.Body, method.GetExpressionBodySyntax(), method.SemicolonToken);
internal static bool IsBetweenTokens(int position, SyntaxToken firstIncluded, SyntaxToken firstExcluded)
{
return position >= firstIncluded.SpanStart && IsBeforeToken(position, firstExcluded);
}
/// <summary>
/// Returns true if position is within the given node and before the first excluded token.
/// </summary>
private static bool IsBeforeToken(int position, CSharpSyntaxNode node, SyntaxToken firstExcluded)
{
return IsBeforeToken(position, firstExcluded) && position >= node.SpanStart;
}
private static bool IsBeforeToken(int position, SyntaxToken firstExcluded)
{
return firstExcluded.Kind() == SyntaxKind.None || position < firstExcluded.SpanStart;
}
internal static bool IsInAttributeSpecification(int position, SyntaxList<AttributeListSyntax> attributesSyntaxList)
{
int count = attributesSyntaxList.Count;
if (count == 0)
{
return false;
}
var startToken = attributesSyntaxList[0].OpenBracketToken;
var endToken = attributesSyntaxList[count - 1].CloseBracketToken;
return IsBetweenTokens(position, startToken, endToken);
}
internal static bool IsInTypeParameterList(int position, TypeDeclarationSyntax typeDecl)
{
var typeParameterListOpt = typeDecl.TypeParameterList;
return typeParameterListOpt != null && IsBeforeToken(position, typeParameterListOpt, typeParameterListOpt.GreaterThanToken);
}
internal static bool IsInParameterList(int position, BaseMethodDeclarationSyntax methodDecl)
{
var parameterList = methodDecl.ParameterList;
return IsBeforeToken(position, parameterList, parameterList.CloseParenToken);
}
internal static bool IsInParameterList(int position, ParameterListSyntax parameterList)
=> parameterList != null && IsBeforeToken(position, parameterList, parameterList.CloseParenToken);
internal static bool IsInMethodDeclaration(int position, BaseMethodDeclarationSyntax methodDecl)
{
Debug.Assert(methodDecl != null);
var body = methodDecl.Body;
if (body == null)
{
return IsBeforeToken(position, methodDecl, methodDecl.SemicolonToken);
}
return IsBeforeToken(position, methodDecl, body.CloseBraceToken) ||
IsInExpressionBody(position, methodDecl.GetExpressionBodySyntax(), methodDecl.SemicolonToken);
}
internal static bool IsInMethodDeclaration(int position, AccessorDeclarationSyntax accessorDecl)
{
Debug.Assert(accessorDecl != null);
var body = accessorDecl.Body;
SyntaxToken lastToken = body == null ? accessorDecl.SemicolonToken : body.CloseBraceToken;
return IsBeforeToken(position, accessorDecl, lastToken);
}
internal static bool IsInDelegateDeclaration(int position, DelegateDeclarationSyntax delegateDecl)
{
Debug.Assert(delegateDecl != null);
return IsBeforeToken(position, delegateDecl, delegateDecl.SemicolonToken);
}
internal static bool IsInTypeDeclaration(int position, BaseTypeDeclarationSyntax typeDecl)
{
Debug.Assert(typeDecl != null);
return IsBeforeToken(position, typeDecl, typeDecl.CloseBraceToken);
}
internal static bool IsInNamespaceDeclaration(int position, NamespaceDeclarationSyntax namespaceDecl)
{
Debug.Assert(namespaceDecl != null);
return IsBetweenTokens(position, namespaceDecl.NamespaceKeyword, namespaceDecl.CloseBraceToken);
}
internal static bool IsInNamespaceDeclaration(int position, FileScopedNamespaceDeclarationSyntax namespaceDecl)
{
Debug.Assert(namespaceDecl != null);
return position >= namespaceDecl.SpanStart;
}
internal static bool IsInConstructorParameterScope(int position, ConstructorDeclarationSyntax constructorDecl)
{
Debug.Assert(constructorDecl != null);
var initializerOpt = constructorDecl.Initializer;
var hasBody = constructorDecl.Body != null || constructorDecl.ExpressionBody != null;
if (!hasBody)
{
var nextToken = (SyntaxToken)SyntaxNavigator.Instance.GetNextToken(constructorDecl, predicate: null, stepInto: null);
return initializerOpt == null ?
position >= constructorDecl.ParameterList.CloseParenToken.Span.End && IsBeforeToken(position, nextToken) :
IsBetweenTokens(position, initializerOpt.ColonToken, nextToken);
}
return initializerOpt == null ?
IsInBody(position, constructorDecl) :
IsBetweenTokens(position, initializerOpt.ColonToken,
constructorDecl.SemicolonToken.Kind() == SyntaxKind.None ? constructorDecl.Body!.CloseBraceToken : constructorDecl.SemicolonToken);
}
internal static bool IsInMethodTypeParameterScope(int position, MethodDeclarationSyntax methodDecl)
{
Debug.Assert(methodDecl != null);
Debug.Assert(IsInMethodDeclaration(position, methodDecl));
if (methodDecl.TypeParameterList == null)
{
// no type parameters => nothing can be in their scope
return false;
}
// optimization for a common case - when position is in the ReturnType, we can see type parameters
if (methodDecl.ReturnType.FullSpan.Contains(position))
{
return true;
}
// Must be in the method, but not in an attribute on the method.
if (IsInAttributeSpecification(position, methodDecl.AttributeLists))
{
return false;
}
var explicitInterfaceSpecifier = methodDecl.ExplicitInterfaceSpecifier;
var firstNameToken = explicitInterfaceSpecifier == null ? methodDecl.Identifier : explicitInterfaceSpecifier.GetFirstToken();
var typeParams = methodDecl.TypeParameterList;
var firstPostNameToken = typeParams == null ? methodDecl.ParameterList.OpenParenToken : typeParams.LessThanToken;
// Scope does not include method name.
return !IsBetweenTokens(position, firstNameToken, firstPostNameToken);
}
/// <remarks>
/// Used to determine whether it would be appropriate to use the binder for the statement (if any).
/// Not used to determine whether the position is syntactically within the statement.
/// </remarks>
internal static bool IsInStatementScope(int position, StatementSyntax statement)
{
Debug.Assert(statement != null);
if (statement.Kind() == SyntaxKind.EmptyStatement)
{
return false;
}
// CONSIDER: the check for default(SyntaxToken) could go in IsBetweenTokens,
// but this is where it has special meaning.
SyntaxToken firstIncludedToken = GetFirstIncludedToken(statement);
return firstIncludedToken != default(SyntaxToken) &&
IsBetweenTokens(position, firstIncludedToken, GetFirstExcludedToken(statement));
}
/// <remarks>
/// Used to determine whether it would be appropriate to use the binder for the switch section (if any).
/// Not used to determine whether the position is syntactically within the statement.
/// </remarks>
internal static bool IsInSwitchSectionScope(int position, SwitchSectionSyntax section)
{
Debug.Assert(section != null);
return section.Span.Contains(position);
}
/// <remarks>
/// Used to determine whether it would be appropriate to use the binder for the statement (if any).
/// Not used to determine whether the position is syntactically within the statement.
/// </remarks>
internal static bool IsInCatchBlockScope(int position, CatchClauseSyntax catchClause)
{
Debug.Assert(catchClause != null);
return IsBetweenTokens(position, catchClause.Block.OpenBraceToken, catchClause.Block.CloseBraceToken);
}
/// <remarks>
/// Used to determine whether it would be appropriate to use the binder for the statement (if any).
/// Not used to determine whether the position is syntactically within the statement.
/// </remarks>
internal static bool IsInCatchFilterScope(int position, CatchFilterClauseSyntax filterClause)
{
Debug.Assert(filterClause != null);
return IsBetweenTokens(position, filterClause.OpenParenToken, filterClause.CloseParenToken);
}
private static SyntaxToken GetFirstIncludedToken(StatementSyntax statement)
{
Debug.Assert(statement != null);
switch (statement.Kind())
{
case SyntaxKind.Block:
return ((BlockSyntax)statement).OpenBraceToken;
case SyntaxKind.BreakStatement:
return ((BreakStatementSyntax)statement).BreakKeyword;
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
return ((CheckedStatementSyntax)statement).Keyword;
case SyntaxKind.ContinueStatement:
return ((ContinueStatementSyntax)statement).ContinueKeyword;
case SyntaxKind.ExpressionStatement:
case SyntaxKind.LocalDeclarationStatement:
return statement.GetFirstToken();
case SyntaxKind.DoStatement:
return ((DoStatementSyntax)statement).DoKeyword;
case SyntaxKind.EmptyStatement:
return default(SyntaxToken); //The caller will have to check for this.
case SyntaxKind.FixedStatement:
return ((FixedStatementSyntax)statement).FixedKeyword;
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return ((CommonForEachStatementSyntax)statement).OpenParenToken.GetNextToken();
case SyntaxKind.ForStatement:
return ((ForStatementSyntax)statement).OpenParenToken.GetNextToken();
case SyntaxKind.GotoDefaultStatement:
case SyntaxKind.GotoCaseStatement:
case SyntaxKind.GotoStatement:
return ((GotoStatementSyntax)statement).GotoKeyword;
case SyntaxKind.IfStatement:
return ((IfStatementSyntax)statement).IfKeyword;
case SyntaxKind.LabeledStatement:
return ((LabeledStatementSyntax)statement).Identifier;
case SyntaxKind.LockStatement:
return ((LockStatementSyntax)statement).LockKeyword;
case SyntaxKind.ReturnStatement:
return ((ReturnStatementSyntax)statement).ReturnKeyword;
case SyntaxKind.SwitchStatement:
return ((SwitchStatementSyntax)statement).Expression.GetFirstToken();
case SyntaxKind.ThrowStatement:
return ((ThrowStatementSyntax)statement).ThrowKeyword;
case SyntaxKind.TryStatement:
return ((TryStatementSyntax)statement).TryKeyword;
case SyntaxKind.UnsafeStatement:
return ((UnsafeStatementSyntax)statement).UnsafeKeyword;
case SyntaxKind.UsingStatement:
return ((UsingStatementSyntax)statement).UsingKeyword;
case SyntaxKind.WhileStatement:
return ((WhileStatementSyntax)statement).WhileKeyword;
case SyntaxKind.YieldReturnStatement:
case SyntaxKind.YieldBreakStatement:
return ((YieldStatementSyntax)statement).YieldKeyword;
case SyntaxKind.LocalFunctionStatement:
return statement.GetFirstToken();
default:
throw ExceptionUtilities.UnexpectedValue(statement.Kind());
}
}
internal static SyntaxToken GetFirstExcludedToken(StatementSyntax statement)
{
Debug.Assert(statement != null);
switch (statement.Kind())
{
case SyntaxKind.Block:
return ((BlockSyntax)statement).CloseBraceToken;
case SyntaxKind.BreakStatement:
return ((BreakStatementSyntax)statement).SemicolonToken;
case SyntaxKind.CheckedStatement:
case SyntaxKind.UncheckedStatement:
return ((CheckedStatementSyntax)statement).Block.CloseBraceToken;
case SyntaxKind.ContinueStatement:
return ((ContinueStatementSyntax)statement).SemicolonToken;
case SyntaxKind.LocalDeclarationStatement:
return ((LocalDeclarationStatementSyntax)statement).SemicolonToken;
case SyntaxKind.DoStatement:
return ((DoStatementSyntax)statement).SemicolonToken;
case SyntaxKind.EmptyStatement:
return ((EmptyStatementSyntax)statement).SemicolonToken;
case SyntaxKind.ExpressionStatement:
return ((ExpressionStatementSyntax)statement).SemicolonToken;
case SyntaxKind.FixedStatement:
return GetFirstExcludedToken(((FixedStatementSyntax)statement).Statement);
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return GetFirstExcludedToken(((CommonForEachStatementSyntax)statement).Statement);
case SyntaxKind.ForStatement:
return GetFirstExcludedToken(((ForStatementSyntax)statement).Statement);
case SyntaxKind.GotoDefaultStatement:
case SyntaxKind.GotoCaseStatement:
case SyntaxKind.GotoStatement:
return ((GotoStatementSyntax)statement).SemicolonToken;
case SyntaxKind.IfStatement:
IfStatementSyntax ifStmt = (IfStatementSyntax)statement;
ElseClauseSyntax? elseOpt = ifStmt.Else;
return GetFirstExcludedToken(elseOpt == null ? ifStmt.Statement : elseOpt.Statement);
case SyntaxKind.LabeledStatement:
return GetFirstExcludedToken(((LabeledStatementSyntax)statement).Statement);
case SyntaxKind.LockStatement:
return GetFirstExcludedToken(((LockStatementSyntax)statement).Statement);
case SyntaxKind.ReturnStatement:
return ((ReturnStatementSyntax)statement).SemicolonToken;
case SyntaxKind.SwitchStatement:
return ((SwitchStatementSyntax)statement).CloseBraceToken;
case SyntaxKind.ThrowStatement:
return ((ThrowStatementSyntax)statement).SemicolonToken;
case SyntaxKind.TryStatement:
TryStatementSyntax tryStmt = (TryStatementSyntax)statement;
FinallyClauseSyntax? finallyClause = tryStmt.Finally;
if (finallyClause != null)
{
return finallyClause.Block.CloseBraceToken;
}
CatchClauseSyntax? lastCatch = tryStmt.Catches.LastOrDefault();
if (lastCatch != null)
{
return lastCatch.Block.CloseBraceToken;
}
return tryStmt.Block.CloseBraceToken;
case SyntaxKind.UnsafeStatement:
return ((UnsafeStatementSyntax)statement).Block.CloseBraceToken;
case SyntaxKind.UsingStatement:
return GetFirstExcludedToken(((UsingStatementSyntax)statement).Statement);
case SyntaxKind.WhileStatement:
return GetFirstExcludedToken(((WhileStatementSyntax)statement).Statement);
case SyntaxKind.YieldReturnStatement:
case SyntaxKind.YieldBreakStatement:
return ((YieldStatementSyntax)statement).SemicolonToken;
case SyntaxKind.LocalFunctionStatement:
LocalFunctionStatementSyntax localFunctionStmt = (LocalFunctionStatementSyntax)statement;
if (localFunctionStmt.Body != null)
return GetFirstExcludedToken(localFunctionStmt.Body);
if (localFunctionStmt.SemicolonToken != default(SyntaxToken))
return localFunctionStmt.SemicolonToken;
return localFunctionStmt.ParameterList.GetLastToken();
default:
throw ExceptionUtilities.UnexpectedValue(statement.Kind());
}
}
internal static bool IsInAnonymousFunctionOrQuery(int position, SyntaxNode lambdaExpressionOrQueryNode)
{
Debug.Assert(lambdaExpressionOrQueryNode.IsAnonymousFunction() || lambdaExpressionOrQueryNode.IsQuery());
SyntaxToken firstIncluded;
CSharpSyntaxNode body;
switch (lambdaExpressionOrQueryNode.Kind())
{
case SyntaxKind.SimpleLambdaExpression:
SimpleLambdaExpressionSyntax simple = (SimpleLambdaExpressionSyntax)lambdaExpressionOrQueryNode;
firstIncluded = simple.ArrowToken;
body = simple.Body;
break;
case SyntaxKind.ParenthesizedLambdaExpression:
ParenthesizedLambdaExpressionSyntax parenthesized = (ParenthesizedLambdaExpressionSyntax)lambdaExpressionOrQueryNode;
firstIncluded = parenthesized.ArrowToken;
body = parenthesized.Body;
break;
case SyntaxKind.AnonymousMethodExpression:
AnonymousMethodExpressionSyntax anon = (AnonymousMethodExpressionSyntax)lambdaExpressionOrQueryNode;
body = anon.Block;
firstIncluded = body.GetFirstToken(includeZeroWidth: true);
break;
default:
// OK, so we have some kind of query clause. They all start with a keyword token, so we'll skip that.
firstIncluded = lambdaExpressionOrQueryNode.GetFirstToken().GetNextToken();
return IsBetweenTokens(position, firstIncluded, lambdaExpressionOrQueryNode.GetLastToken().GetNextToken());
}
var bodyStatement = body as StatementSyntax;
var firstExcluded = bodyStatement != null ?
GetFirstExcludedToken(bodyStatement) :
(SyntaxToken)SyntaxNavigator.Instance.GetNextToken(body, predicate: null, stepInto: null);
return IsBetweenTokens(position, firstIncluded, firstExcluded);
}
internal static bool IsInXmlAttributeValue(int position, XmlAttributeSyntax attribute)
{
return IsBetweenTokens(position, attribute.StartQuoteToken, attribute.EndQuoteToken);
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Core/Portable/Symbols/Attributes/CommonAssemblyWellKnownAttributeData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Reflection;
using Microsoft.CodeAnalysis.Text;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Information decoded from well-known custom attributes applied on an assembly.
/// </summary>
internal class CommonAssemblyWellKnownAttributeData<TNamedTypeSymbol> : WellKnownAttributeData, ISecurityAttributeTarget
{
#region AssemblySignatureKeyAttributeSetting
private string _assemblySignatureKeyAttributeSetting;
public string AssemblySignatureKeyAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblySignatureKeyAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblySignatureKeyAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyDelaySignAttributeSetting
private ThreeState _assemblyDelaySignAttributeSetting;
public ThreeState AssemblyDelaySignAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyDelaySignAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyDelaySignAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyKeyFileAttributeSetting
private string _assemblyKeyFileAttributeSetting = StringMissingValue;
public string AssemblyKeyFileAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyKeyFileAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyKeyFileAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyKeyContainerAttributeSetting
private string _assemblyKeyContainerAttributeSetting = StringMissingValue;
public string AssemblyKeyContainerAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyKeyContainerAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyKeyContainerAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyVersionAttributeSetting
private Version _assemblyVersionAttributeSetting;
/// <summary>
/// Raw assembly version as specified in the AssemblyVersionAttribute, or Nothing if none specified.
/// If the string passed to AssemblyVersionAttribute contains * the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>.
/// </summary>
public Version AssemblyVersionAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyVersionAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyVersionAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyFileVersionAttributeSetting
private string _assemblyFileVersionAttributeSetting;
public string AssemblyFileVersionAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyFileVersionAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyFileVersionAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyTitleAttributeSetting
private string _assemblyTitleAttributeSetting;
public string AssemblyTitleAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyTitleAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyTitleAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyDescriptionAttributeSetting
private string _assemblyDescriptionAttributeSetting;
public string AssemblyDescriptionAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyDescriptionAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyDescriptionAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyCultureAttributeSetting
private string _assemblyCultureAttributeSetting;
public string AssemblyCultureAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyCultureAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyCultureAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyCompanyAttributeSetting
private string _assemblyCompanyAttributeSetting;
public string AssemblyCompanyAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyCompanyAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyCompanyAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyProductAttributeSetting
private string _assemblyProductAttributeSetting;
public string AssemblyProductAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyProductAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyProductAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyInformationalVersionAttributeSetting
private string _assemblyInformationalVersionAttributeSetting;
public string AssemblyInformationalVersionAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyInformationalVersionAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyInformationalVersionAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyCopyrightAttributeSetting
private string _assemblyCopyrightAttributeSetting;
public string AssemblyCopyrightAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyCopyrightAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyCopyrightAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyTrademarkAttributeSetting
private string _assemblyTrademarkAttributeSetting;
public string AssemblyTrademarkAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyTrademarkAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyTrademarkAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyFlagsAttributeSetting
private AssemblyFlags _assemblyFlagsAttributeSetting;
public AssemblyFlags AssemblyFlagsAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyFlagsAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyFlagsAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyAlgorithmIdAttribute
private AssemblyHashAlgorithm? _assemblyAlgorithmIdAttributeSetting;
public AssemblyHashAlgorithm? AssemblyAlgorithmIdAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyAlgorithmIdAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyAlgorithmIdAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region CompilationRelaxationsAttribute
private bool _hasCompilationRelaxationsAttribute;
public bool HasCompilationRelaxationsAttribute
{
get
{
VerifySealed(expected: true);
return _hasCompilationRelaxationsAttribute;
}
set
{
VerifySealed(expected: false);
_hasCompilationRelaxationsAttribute = value;
SetDataStored();
}
}
#endregion
#region ReferenceAssemblyAttribute
private bool _hasReferenceAssemblyAttribute;
public bool HasReferenceAssemblyAttribute
{
get
{
VerifySealed(expected: true);
return _hasReferenceAssemblyAttribute;
}
set
{
VerifySealed(expected: false);
_hasReferenceAssemblyAttribute = value;
SetDataStored();
}
}
#endregion
#region RuntimeCompatibilityAttribute
private bool? _runtimeCompatibilityWrapNonExceptionThrows;
// By default WrapNonExceptionThrows is considered to be true.
internal const bool WrapNonExceptionThrowsDefault = true;
public bool HasRuntimeCompatibilityAttribute
{
get
{
VerifySealed(expected: true);
return _runtimeCompatibilityWrapNonExceptionThrows.HasValue;
}
}
public bool RuntimeCompatibilityWrapNonExceptionThrows
{
get
{
VerifySealed(expected: true);
return _runtimeCompatibilityWrapNonExceptionThrows ?? WrapNonExceptionThrowsDefault;
}
set
{
VerifySealed(expected: false);
_runtimeCompatibilityWrapNonExceptionThrows = value;
SetDataStored();
}
}
#endregion
#region DebuggableAttribute
private bool _hasDebuggableAttribute;
public bool HasDebuggableAttribute
{
get
{
VerifySealed(expected: true);
return _hasDebuggableAttribute;
}
set
{
VerifySealed(expected: false);
_hasDebuggableAttribute = value;
SetDataStored();
}
}
#endregion
#region Security Attributes
private SecurityWellKnownAttributeData _lazySecurityAttributeData;
SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData()
{
VerifySealed(expected: false);
if (_lazySecurityAttributeData == null)
{
_lazySecurityAttributeData = new SecurityWellKnownAttributeData();
SetDataStored();
}
return _lazySecurityAttributeData;
}
/// <summary>
/// Returns data decoded from security attributes or null if there are no security attributes.
/// </summary>
public SecurityWellKnownAttributeData SecurityInformation
{
get
{
VerifySealed(expected: true);
return _lazySecurityAttributeData;
}
}
#endregion
#region ForwardedTypes
private HashSet<TNamedTypeSymbol> _forwardedTypes;
public HashSet<TNamedTypeSymbol> ForwardedTypes
{
get
{
return _forwardedTypes;
}
set
{
VerifySealed(expected: false);
_forwardedTypes = value;
SetDataStored();
}
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Reflection;
using Microsoft.CodeAnalysis.Text;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Information decoded from well-known custom attributes applied on an assembly.
/// </summary>
internal class CommonAssemblyWellKnownAttributeData<TNamedTypeSymbol> : WellKnownAttributeData, ISecurityAttributeTarget
{
#region AssemblySignatureKeyAttributeSetting
private string _assemblySignatureKeyAttributeSetting;
public string AssemblySignatureKeyAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblySignatureKeyAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblySignatureKeyAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyDelaySignAttributeSetting
private ThreeState _assemblyDelaySignAttributeSetting;
public ThreeState AssemblyDelaySignAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyDelaySignAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyDelaySignAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyKeyFileAttributeSetting
private string _assemblyKeyFileAttributeSetting = StringMissingValue;
public string AssemblyKeyFileAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyKeyFileAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyKeyFileAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyKeyContainerAttributeSetting
private string _assemblyKeyContainerAttributeSetting = StringMissingValue;
public string AssemblyKeyContainerAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyKeyContainerAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyKeyContainerAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyVersionAttributeSetting
private Version _assemblyVersionAttributeSetting;
/// <summary>
/// Raw assembly version as specified in the AssemblyVersionAttribute, or Nothing if none specified.
/// If the string passed to AssemblyVersionAttribute contains * the version build and/or revision numbers are set to <see cref="ushort.MaxValue"/>.
/// </summary>
public Version AssemblyVersionAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyVersionAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyVersionAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyFileVersionAttributeSetting
private string _assemblyFileVersionAttributeSetting;
public string AssemblyFileVersionAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyFileVersionAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyFileVersionAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyTitleAttributeSetting
private string _assemblyTitleAttributeSetting;
public string AssemblyTitleAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyTitleAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyTitleAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyDescriptionAttributeSetting
private string _assemblyDescriptionAttributeSetting;
public string AssemblyDescriptionAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyDescriptionAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyDescriptionAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyCultureAttributeSetting
private string _assemblyCultureAttributeSetting;
public string AssemblyCultureAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyCultureAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyCultureAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyCompanyAttributeSetting
private string _assemblyCompanyAttributeSetting;
public string AssemblyCompanyAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyCompanyAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyCompanyAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyProductAttributeSetting
private string _assemblyProductAttributeSetting;
public string AssemblyProductAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyProductAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyProductAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyInformationalVersionAttributeSetting
private string _assemblyInformationalVersionAttributeSetting;
public string AssemblyInformationalVersionAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyInformationalVersionAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyInformationalVersionAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyCopyrightAttributeSetting
private string _assemblyCopyrightAttributeSetting;
public string AssemblyCopyrightAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyCopyrightAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyCopyrightAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyTrademarkAttributeSetting
private string _assemblyTrademarkAttributeSetting;
public string AssemblyTrademarkAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyTrademarkAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyTrademarkAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyFlagsAttributeSetting
private AssemblyFlags _assemblyFlagsAttributeSetting;
public AssemblyFlags AssemblyFlagsAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyFlagsAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyFlagsAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region AssemblyAlgorithmIdAttribute
private AssemblyHashAlgorithm? _assemblyAlgorithmIdAttributeSetting;
public AssemblyHashAlgorithm? AssemblyAlgorithmIdAttributeSetting
{
get
{
VerifySealed(expected: true);
return _assemblyAlgorithmIdAttributeSetting;
}
set
{
VerifySealed(expected: false);
_assemblyAlgorithmIdAttributeSetting = value;
SetDataStored();
}
}
#endregion
#region CompilationRelaxationsAttribute
private bool _hasCompilationRelaxationsAttribute;
public bool HasCompilationRelaxationsAttribute
{
get
{
VerifySealed(expected: true);
return _hasCompilationRelaxationsAttribute;
}
set
{
VerifySealed(expected: false);
_hasCompilationRelaxationsAttribute = value;
SetDataStored();
}
}
#endregion
#region ReferenceAssemblyAttribute
private bool _hasReferenceAssemblyAttribute;
public bool HasReferenceAssemblyAttribute
{
get
{
VerifySealed(expected: true);
return _hasReferenceAssemblyAttribute;
}
set
{
VerifySealed(expected: false);
_hasReferenceAssemblyAttribute = value;
SetDataStored();
}
}
#endregion
#region RuntimeCompatibilityAttribute
private bool? _runtimeCompatibilityWrapNonExceptionThrows;
// By default WrapNonExceptionThrows is considered to be true.
internal const bool WrapNonExceptionThrowsDefault = true;
public bool HasRuntimeCompatibilityAttribute
{
get
{
VerifySealed(expected: true);
return _runtimeCompatibilityWrapNonExceptionThrows.HasValue;
}
}
public bool RuntimeCompatibilityWrapNonExceptionThrows
{
get
{
VerifySealed(expected: true);
return _runtimeCompatibilityWrapNonExceptionThrows ?? WrapNonExceptionThrowsDefault;
}
set
{
VerifySealed(expected: false);
_runtimeCompatibilityWrapNonExceptionThrows = value;
SetDataStored();
}
}
#endregion
#region DebuggableAttribute
private bool _hasDebuggableAttribute;
public bool HasDebuggableAttribute
{
get
{
VerifySealed(expected: true);
return _hasDebuggableAttribute;
}
set
{
VerifySealed(expected: false);
_hasDebuggableAttribute = value;
SetDataStored();
}
}
#endregion
#region Security Attributes
private SecurityWellKnownAttributeData _lazySecurityAttributeData;
SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData()
{
VerifySealed(expected: false);
if (_lazySecurityAttributeData == null)
{
_lazySecurityAttributeData = new SecurityWellKnownAttributeData();
SetDataStored();
}
return _lazySecurityAttributeData;
}
/// <summary>
/// Returns data decoded from security attributes or null if there are no security attributes.
/// </summary>
public SecurityWellKnownAttributeData SecurityInformation
{
get
{
VerifySealed(expected: true);
return _lazySecurityAttributeData;
}
}
#endregion
#region ForwardedTypes
private HashSet<TNamedTypeSymbol> _forwardedTypes;
public HashSet<TNamedTypeSymbol> ForwardedTypes
{
get
{
return _forwardedTypes;
}
set
{
VerifySealed(expected: false);
_forwardedTypes = value;
SetDataStored();
}
}
#endregion
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Dependencies/Collections/Internal/xlf/Strings.ko.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ko" original="../Strings.resx">
<body>
<trans-unit id="Arg_ArrayPlusOffTooSmall">
<source>Destination array is not long enough to copy all the items in the collection. Check array index and length.</source>
<target state="translated">대상 배열이 컬렉션의 모든 항목을 복사하기에 충분히 길지 않습니다. 배열 인덱스와 길이를 확인하세요.</target>
<note />
</trans-unit>
<trans-unit id="Arg_BogusIComparer">
<source>Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.</source>
<target state="translated">IComparer.Compare() 메서드가 일관성 없는 결과를 반환하므로 정렬할 수 없습니다. 값이 자신과 같은지 비교하지 않거나 한 값이 다른 값과 반복해서 비교되어 다른 결과를 생성합니다. IComparer: '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Arg_HTCapacityOverflow">
<source>Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.</source>
<target state="translated">해시 테이블 용량에 오버플로가 발생하여 음수가 되었습니다. 로드 비율, 용량 및 테이블의 현재 크기를 확인하십시오.</target>
<note />
</trans-unit>
<trans-unit id="Arg_KeyNotFoundWithKey">
<source>The given key '{0}' was not present in the dictionary.</source>
<target state="translated">지정된 키 '{0}'이(가) 사전에 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="Arg_LongerThanDestArray">
<source>Destination array was not long enough. Check the destination index, length, and the array's lower bounds.</source>
<target state="translated">대상 배열의 길이가 짧습니다. 대상 인덱스, 길이, 배열의 하한을 확인하세요.</target>
<note />
</trans-unit>
<trans-unit id="Arg_LongerThanSrcArray">
<source>Source array was not long enough. Check the source index, length, and the array's lower bounds.</source>
<target state="translated">소스 배열의 길이가 짧습니다. 소스 인덱스, 길이, 배열의 하한을 확인하세요.</target>
<note />
</trans-unit>
<trans-unit id="Arg_NonZeroLowerBound">
<source>The lower bound of target array must be zero.</source>
<target state="translated">대상 배열의 하한은 0이어야 합니다.</target>
<note />
</trans-unit>
<trans-unit id="Arg_RankMultiDimNotSupported">
<source>Only single dimensional arrays are supported for the requested action.</source>
<target state="translated">요청한 동작에 대해 1차원 배열만 지원됩니다.</target>
<note />
</trans-unit>
<trans-unit id="Arg_WrongType">
<source>The value "{0}" is not of type "{1}" and cannot be used in this generic collection.</source>
<target state="translated">"{0}" 값은 "{1}" 형식이 아니므로 이 제네릭 컬렉션에 사용할 수 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentException_OtherNotArrayOfCorrectLength">
<source>Object is not a array with the same number of elements as the array to compare it to.</source>
<target state="translated">개체가 비교할 배열과 요소 수가 같은 배열이 아닙니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_ArrayLB">
<source>Number was less than the array's lower bound in the first dimension.</source>
<target state="translated">숫자가 첫째 차원에서 배열의 하한보다 작습니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_BiggerThanCollection">
<source>Larger than collection size.</source>
<target state="translated">컬렉션 크기보다 큽니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_Count">
<source>Count must be positive and count must refer to a location within the string/array/collection.</source>
<target state="translated">개수는 양수여야 하고 문자열/배열/컬렉션 내의 위치를 참조해야 합니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_Index">
<source>Index was out of range. Must be non-negative and less than the size of the collection.</source>
<target state="translated">인덱스가 범위를 벗어났습니다. 인덱스는 음수가 아니어야 하며 컬렉션의 크기보다 작아야 합니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_ListInsert">
<source>Index must be within the bounds of the List.</source>
<target state="translated">인덱스는 목록의 범위 내에 있어야 합니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_NeedNonNegNum">
<source>Non-negative number required.</source>
<target state="translated">음수가 아닌 수가 필요합니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_SmallCapacity">
<source>capacity was less than the current size.</source>
<target state="translated">용량이 현재 크기보다 작습니다.</target>
<note />
</trans-unit>
<trans-unit id="Argument_AddingDuplicateWithKey">
<source>An item with the same key has already been added. Key: {0}</source>
<target state="translated">동일한 키를 사용하는 항목이 이미 추가되었습니다. 키: {0}</target>
<note />
</trans-unit>
<trans-unit id="Argument_InvalidArrayType">
<source>Target array type is not compatible with the type of items in the collection.</source>
<target state="translated">대상 배열 형식이 컬렉션의 항목 형식과 호환되지 않습니다.</target>
<note />
</trans-unit>
<trans-unit id="Argument_InvalidOffLen">
<source>Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.</source>
<target state="translated">오프셋 및 길이가 배열의 범위를 벗어났거나 카운트가 인덱스부터 소스 컬렉션 끝까지의 요소 수보다 큽니다.</target>
<note />
</trans-unit>
<trans-unit id="CannotFindOldValue">
<source>Cannot find the old value</source>
<target state="new">Cannot find the old value</target>
<note />
</trans-unit>
<trans-unit id="InvalidOperation_ConcurrentOperationsNotSupported">
<source>Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.</source>
<target state="translated">비동시 컬렉션을 변경하는 작업에는 단독 액세스 권한이 있어야 합니다. 이 컬렉션에 대해 동시 업데이트가 수행되어 해당 상태가 손상되었습니다. 컬렉션의 상태가 더 이상 올바르지 않습니다.</target>
<note />
</trans-unit>
<trans-unit id="InvalidOperation_EnumFailedVersion">
<source>Collection was modified; enumeration operation may not execute.</source>
<target state="translated">컬렉션이 수정되었습니다. 열거 작업이 실행되지 않을 수도 있습니다.</target>
<note />
</trans-unit>
<trans-unit id="InvalidOperation_EnumOpCantHappen">
<source>Enumeration has either not started or has already finished.</source>
<target state="translated">열거가 시작되지 않았거나 이미 완료되었습니다.</target>
<note />
</trans-unit>
<trans-unit id="InvalidOperation_IComparerFailed">
<source>Failed to compare two elements in the array.</source>
<target state="translated">배열의 두 요소를 비교하지 못했습니다.</target>
<note />
</trans-unit>
<trans-unit id="NotSupported_FixedSizeCollection">
<source>Collection was of a fixed size.</source>
<target state="translated">컬렉션이 고정 크기입니다.</target>
<note />
</trans-unit>
<trans-unit id="NotSupported_KeyCollectionSet">
<source>Mutating a key collection derived from a dictionary is not allowed.</source>
<target state="translated">사전에서 파생된 키 컬렉션은 변경할 수 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="NotSupported_ValueCollectionSet">
<source>Mutating a value collection derived from a dictionary is not allowed.</source>
<target state="translated">사전에서 파생된 값 컬렉션은 변경할 수 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="Rank_MustMatch">
<source>The specified arrays must have the same number of dimensions.</source>
<target state="translated">지정한 배열의 차수가 같아야 합니다.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ko" original="../Strings.resx">
<body>
<trans-unit id="Arg_ArrayPlusOffTooSmall">
<source>Destination array is not long enough to copy all the items in the collection. Check array index and length.</source>
<target state="translated">대상 배열이 컬렉션의 모든 항목을 복사하기에 충분히 길지 않습니다. 배열 인덱스와 길이를 확인하세요.</target>
<note />
</trans-unit>
<trans-unit id="Arg_BogusIComparer">
<source>Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.</source>
<target state="translated">IComparer.Compare() 메서드가 일관성 없는 결과를 반환하므로 정렬할 수 없습니다. 값이 자신과 같은지 비교하지 않거나 한 값이 다른 값과 반복해서 비교되어 다른 결과를 생성합니다. IComparer: '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Arg_HTCapacityOverflow">
<source>Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.</source>
<target state="translated">해시 테이블 용량에 오버플로가 발생하여 음수가 되었습니다. 로드 비율, 용량 및 테이블의 현재 크기를 확인하십시오.</target>
<note />
</trans-unit>
<trans-unit id="Arg_KeyNotFoundWithKey">
<source>The given key '{0}' was not present in the dictionary.</source>
<target state="translated">지정된 키 '{0}'이(가) 사전에 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="Arg_LongerThanDestArray">
<source>Destination array was not long enough. Check the destination index, length, and the array's lower bounds.</source>
<target state="translated">대상 배열의 길이가 짧습니다. 대상 인덱스, 길이, 배열의 하한을 확인하세요.</target>
<note />
</trans-unit>
<trans-unit id="Arg_LongerThanSrcArray">
<source>Source array was not long enough. Check the source index, length, and the array's lower bounds.</source>
<target state="translated">소스 배열의 길이가 짧습니다. 소스 인덱스, 길이, 배열의 하한을 확인하세요.</target>
<note />
</trans-unit>
<trans-unit id="Arg_NonZeroLowerBound">
<source>The lower bound of target array must be zero.</source>
<target state="translated">대상 배열의 하한은 0이어야 합니다.</target>
<note />
</trans-unit>
<trans-unit id="Arg_RankMultiDimNotSupported">
<source>Only single dimensional arrays are supported for the requested action.</source>
<target state="translated">요청한 동작에 대해 1차원 배열만 지원됩니다.</target>
<note />
</trans-unit>
<trans-unit id="Arg_WrongType">
<source>The value "{0}" is not of type "{1}" and cannot be used in this generic collection.</source>
<target state="translated">"{0}" 값은 "{1}" 형식이 아니므로 이 제네릭 컬렉션에 사용할 수 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentException_OtherNotArrayOfCorrectLength">
<source>Object is not a array with the same number of elements as the array to compare it to.</source>
<target state="translated">개체가 비교할 배열과 요소 수가 같은 배열이 아닙니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_ArrayLB">
<source>Number was less than the array's lower bound in the first dimension.</source>
<target state="translated">숫자가 첫째 차원에서 배열의 하한보다 작습니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_BiggerThanCollection">
<source>Larger than collection size.</source>
<target state="translated">컬렉션 크기보다 큽니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_Count">
<source>Count must be positive and count must refer to a location within the string/array/collection.</source>
<target state="translated">개수는 양수여야 하고 문자열/배열/컬렉션 내의 위치를 참조해야 합니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_Index">
<source>Index was out of range. Must be non-negative and less than the size of the collection.</source>
<target state="translated">인덱스가 범위를 벗어났습니다. 인덱스는 음수가 아니어야 하며 컬렉션의 크기보다 작아야 합니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_ListInsert">
<source>Index must be within the bounds of the List.</source>
<target state="translated">인덱스는 목록의 범위 내에 있어야 합니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_NeedNonNegNum">
<source>Non-negative number required.</source>
<target state="translated">음수가 아닌 수가 필요합니다.</target>
<note />
</trans-unit>
<trans-unit id="ArgumentOutOfRange_SmallCapacity">
<source>capacity was less than the current size.</source>
<target state="translated">용량이 현재 크기보다 작습니다.</target>
<note />
</trans-unit>
<trans-unit id="Argument_AddingDuplicateWithKey">
<source>An item with the same key has already been added. Key: {0}</source>
<target state="translated">동일한 키를 사용하는 항목이 이미 추가되었습니다. 키: {0}</target>
<note />
</trans-unit>
<trans-unit id="Argument_InvalidArrayType">
<source>Target array type is not compatible with the type of items in the collection.</source>
<target state="translated">대상 배열 형식이 컬렉션의 항목 형식과 호환되지 않습니다.</target>
<note />
</trans-unit>
<trans-unit id="Argument_InvalidOffLen">
<source>Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.</source>
<target state="translated">오프셋 및 길이가 배열의 범위를 벗어났거나 카운트가 인덱스부터 소스 컬렉션 끝까지의 요소 수보다 큽니다.</target>
<note />
</trans-unit>
<trans-unit id="CannotFindOldValue">
<source>Cannot find the old value</source>
<target state="new">Cannot find the old value</target>
<note />
</trans-unit>
<trans-unit id="InvalidOperation_ConcurrentOperationsNotSupported">
<source>Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.</source>
<target state="translated">비동시 컬렉션을 변경하는 작업에는 단독 액세스 권한이 있어야 합니다. 이 컬렉션에 대해 동시 업데이트가 수행되어 해당 상태가 손상되었습니다. 컬렉션의 상태가 더 이상 올바르지 않습니다.</target>
<note />
</trans-unit>
<trans-unit id="InvalidOperation_EnumFailedVersion">
<source>Collection was modified; enumeration operation may not execute.</source>
<target state="translated">컬렉션이 수정되었습니다. 열거 작업이 실행되지 않을 수도 있습니다.</target>
<note />
</trans-unit>
<trans-unit id="InvalidOperation_EnumOpCantHappen">
<source>Enumeration has either not started or has already finished.</source>
<target state="translated">열거가 시작되지 않았거나 이미 완료되었습니다.</target>
<note />
</trans-unit>
<trans-unit id="InvalidOperation_IComparerFailed">
<source>Failed to compare two elements in the array.</source>
<target state="translated">배열의 두 요소를 비교하지 못했습니다.</target>
<note />
</trans-unit>
<trans-unit id="NotSupported_FixedSizeCollection">
<source>Collection was of a fixed size.</source>
<target state="translated">컬렉션이 고정 크기입니다.</target>
<note />
</trans-unit>
<trans-unit id="NotSupported_KeyCollectionSet">
<source>Mutating a key collection derived from a dictionary is not allowed.</source>
<target state="translated">사전에서 파생된 키 컬렉션은 변경할 수 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="NotSupported_ValueCollectionSet">
<source>Mutating a value collection derived from a dictionary is not allowed.</source>
<target state="translated">사전에서 파생된 값 컬렉션은 변경할 수 없습니다.</target>
<note />
</trans-unit>
<trans-unit id="Rank_MustMatch">
<source>The specified arrays must have the same number of dimensions.</source>
<target state="translated">지정한 배열의 차수가 같아야 합니다.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/VisualBasic/Portable/PublicAPI.Unshipped.txt | Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic16_9 = 1609 -> Microsoft.CodeAnalysis.VisualBasic.LanguageVersion
Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver
Overrides Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.GetLineMappings(cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Collections.Generic.IEnumerable(Of Microsoft.CodeAnalysis.LineMapping)
Overrides Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.GetUsedAssemblyReferences(cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.MetadataReference)
*REMOVED*Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText) = Nothing, parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions = Nothing, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider = Nothing) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver
Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText) = Nothing, parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions = Nothing, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider = Nothing, driverOptions As Microsoft.CodeAnalysis.GeneratorDriverOptions = Nothing) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver
Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText), parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver | Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.VisualBasic16_9 = 1609 -> Microsoft.CodeAnalysis.VisualBasic.LanguageVersion
Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver
Overrides Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.GetLineMappings(cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Collections.Generic.IEnumerable(Of Microsoft.CodeAnalysis.LineMapping)
Overrides Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.GetUsedAssemblyReferences(cancellationToken As System.Threading.CancellationToken = Nothing) -> System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.MetadataReference)
*REMOVED*Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText) = Nothing, parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions = Nothing, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider = Nothing) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver
Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText) = Nothing, parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions = Nothing, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider = Nothing, driverOptions As Microsoft.CodeAnalysis.GeneratorDriverOptions = Nothing) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver
Shared Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver.Create(generators As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.ISourceGenerator), additionalTexts As System.Collections.Immutable.ImmutableArray(Of Microsoft.CodeAnalysis.AdditionalText), parseOptions As Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions, analyzerConfigOptionsProvider As Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider) -> Microsoft.CodeAnalysis.VisualBasic.VisualBasicGeneratorDriver | -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/Core/Def/Implementation/Venus/VenusCommandFilter`2.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus
{
[Obsolete("This is a compatibility shim for LiveShare and TypeScript; please do not use it.")]
internal class VenusCommandFilter<TPackage, TLanguageService> : VenusCommandFilter
where TPackage : AbstractPackage<TPackage, TLanguageService>
where TLanguageService : AbstractLanguageService<TPackage, TLanguageService>
{
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
public VenusCommandFilter(
TLanguageService languageService,
IWpfTextView wpfTextView,
ICommandHandlerServiceFactory commandHandlerServiceFactory,
ITextBuffer subjectBuffer,
IOleCommandTarget nextCommandTarget,
IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
: base(wpfTextView, subjectBuffer, nextCommandTarget, languageService.Package.ComponentModel)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus
{
[Obsolete("This is a compatibility shim for LiveShare and TypeScript; please do not use it.")]
internal class VenusCommandFilter<TPackage, TLanguageService> : VenusCommandFilter
where TPackage : AbstractPackage<TPackage, TLanguageService>
where TLanguageService : AbstractLanguageService<TPackage, TLanguageService>
{
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
public VenusCommandFilter(
TLanguageService languageService,
IWpfTextView wpfTextView,
ICommandHandlerServiceFactory commandHandlerServiceFactory,
ITextBuffer subjectBuffer,
IOleCommandTarget nextCommandTarget,
IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
: base(wpfTextView, subjectBuffer, nextCommandTarget, languageService.Package.ComponentModel)
{
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/VisualBasic/Portable/CodeRefactorings/AddMissingImports/VisualBasicAddMissingImportsRefactoringProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.AddMissingImports
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.PasteTracking
Imports Microsoft.CodeAnalysis.VisualBasic
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.AddMissingImports), [Shared]>
Friend Class VisualBasicAddMissingImportsRefactoringProvider
Inherits AbstractAddMissingImportsRefactoringProvider
Protected Overrides ReadOnly Property CodeActionTitle As String = VBFeaturesResources.Add_missing_Imports
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New(pasteTrackingService As IPasteTrackingService)
MyBase.New(pasteTrackingService)
End Sub
End Class
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.AddMissingImports
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.PasteTracking
Imports Microsoft.CodeAnalysis.VisualBasic
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.AddMissingImports), [Shared]>
Friend Class VisualBasicAddMissingImportsRefactoringProvider
Inherits AbstractAddMissingImportsRefactoringProvider
Protected Overrides ReadOnly Property CodeActionTitle As String = VBFeaturesResources.Add_missing_Imports
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New(pasteTrackingService As IPasteTrackingService)
MyBase.New(pasteTrackingService)
End Sub
End Class
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/Library2.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
' vbc /t:library /vbruntime- /r:Pia1.dll,Pia5.dll Library2.vb
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58260")>
<Assembly: ImportedFromTypeLib("Library2.dll")>
<ComImport(), Guid("27e3e649-994b-4f58-b3c6-f8089a5f2002"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _
Public Interface I7
Function Goo() As List(Of I5)
Function Bar() As List(Of I1)
End Interface
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
' vbc /t:library /vbruntime- /r:Pia1.dll,Pia5.dll Library2.vb
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58260")>
<Assembly: ImportedFromTypeLib("Library2.dll")>
<ComImport(), Guid("27e3e649-994b-4f58-b3c6-f8089a5f2002"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _
Public Interface I7
Function Goo() As List(Of I5)
Function Bar() As List(Of I1)
End Interface
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/EditorFeatures/VisualBasic/LanguageServices/VisualBasicContentTypeLanguageService.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LanguageServices
<ExportContentTypeLanguageService(ContentTypeNames.VisualBasicContentType, LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicContentTypeLanguageService
Implements IContentTypeLanguageService
Private ReadOnly _contentTypeRegistry As IContentTypeRegistryService
<ImportingConstructor()>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(contentTypeRegistry As IContentTypeRegistryService)
Me._contentTypeRegistry = contentTypeRegistry
End Sub
Public Function GetDefaultContentType() As IContentType Implements IContentTypeLanguageService.GetDefaultContentType
Return Me._contentTypeRegistry.GetContentType(ContentTypeNames.VisualBasicContentType)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LanguageServices
<ExportContentTypeLanguageService(ContentTypeNames.VisualBasicContentType, LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicContentTypeLanguageService
Implements IContentTypeLanguageService
Private ReadOnly _contentTypeRegistry As IContentTypeRegistryService
<ImportingConstructor()>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(contentTypeRegistry As IContentTypeRegistryService)
Me._contentTypeRegistry = contentTypeRegistry
End Sub
Public Function GetDefaultContentType() As IContentType Implements IContentTypeLanguageService.GetDefaultContentType
Return Me._contentTypeRegistry.GetContentType(ContentTypeNames.VisualBasicContentType)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.NormalPriorityProcessor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
#if DEBUG
using System.Diagnostics;
#endif
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
internal sealed partial class WorkCoordinator
{
private sealed partial class IncrementalAnalyzerProcessor
{
private sealed class NormalPriorityProcessor : AbstractPriorityProcessor
{
private const int MaxHighPriorityQueueCache = 29;
private readonly AsyncDocumentWorkItemQueue _workItemQueue;
private readonly ConcurrentDictionary<DocumentId, IDisposable?> _higherPriorityDocumentsNotProcessed;
private ProjectId? _currentProjectProcessing;
private IDisposable? _projectCache;
// this is only used in ResetState to find out solution has changed
// and reset some states such as logging some telemetry or
// priorities active,visible, opened files and etc
private Solution? _lastSolution = null;
// whether this processor is running or not
private Task _running;
public NormalPriorityProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers,
IGlobalOperationNotificationService globalOperationNotificationService,
TimeSpan backOffTimeSpan,
CancellationToken shutdownToken)
: base(listener, processor, lazyAnalyzers, globalOperationNotificationService, backOffTimeSpan, shutdownToken)
{
_running = Task.CompletedTask;
_workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter, processor._registration.Workspace);
_higherPriorityDocumentsNotProcessed = new ConcurrentDictionary<DocumentId, IDisposable?>(concurrencyLevel: 2, capacity: 20);
_currentProjectProcessing = null;
Start();
}
public void Enqueue(WorkItem item)
{
Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item");
UpdateLastAccessTime();
var added = _workItemQueue.AddOrReplace(item);
Logger.Log(FunctionId.WorkCoordinator_DocumentWorker_Enqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added);
CheckHigherPriorityDocument(item);
SolutionCrawlerLogger.LogWorkItemEnqueue(
Processor._logAggregator, item.Language, item.DocumentId, item.InvocationReasons, item.IsLowPriority, item.ActiveMember, added);
}
private void CheckHigherPriorityDocument(WorkItem item)
{
Contract.ThrowIfFalse(item.DocumentId != null);
if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.HighPriority))
{
return;
}
AddHigherPriorityDocument(item.DocumentId);
}
private void AddHigherPriorityDocument(DocumentId id)
{
var cache = GetHighPriorityQueueProjectCache(id);
if (!_higherPriorityDocumentsNotProcessed.TryAdd(id, cache))
{
// we already have the document in the queue.
cache?.Dispose();
}
SolutionCrawlerLogger.LogHigherPriority(Processor._logAggregator, id.Id);
}
private IDisposable? GetHighPriorityQueueProjectCache(DocumentId id)
{
// NOTE: we have one potential issue where we can cache a lot of stuff in memory
// since we will cache all high prioirty work's projects in memory until they are processed.
//
// To mitigate that, we will turn off cache if we have too many items in high priority queue
// this shouldn't affect active file since we always enable active file cache from background compiler.
return _higherPriorityDocumentsNotProcessed.Count <= MaxHighPriorityQueueCache ? Processor.EnableCaching(id.ProjectId) : null;
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
if (!_workItemQueue.HasAnyWork)
{
_projectCache?.Dispose();
_projectCache = null;
}
return _workItemQueue.WaitAsync(cancellationToken);
}
public Task Running => _running;
public int WorkItemCount => _workItemQueue.WorkItemCount;
public bool HasAnyWork => _workItemQueue.HasAnyWork;
protected override async Task ExecuteAsync()
{
if (CancellationToken.IsCancellationRequested)
{
return;
}
var source = new TaskCompletionSource<object?>();
try
{
// mark it as running
_running = source.Task;
await WaitForHigherPriorityOperationsAsync().ConfigureAwait(false);
// okay, there must be at least one item in the map
await ResetStatesAsync().ConfigureAwait(false);
if (await TryProcessOneHigherPriorityDocumentAsync().ConfigureAwait(false))
{
// successfully processed a high priority document.
return;
}
// process one of documents remaining
if (!_workItemQueue.TryTakeAnyWork(
_currentProjectProcessing, Processor.DependencyGraph, Processor.DiagnosticAnalyzerService,
out var workItem, out var documentCancellation))
{
return;
}
// check whether we have been shutdown
if (CancellationToken.IsCancellationRequested)
{
return;
}
// check whether we have moved to new project
SetProjectProcessing(workItem.ProjectId);
// process the new document
await ProcessDocumentAsync(Analyzers, workItem, documentCancellation).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// mark it as done running
source.SetResult(null);
}
}
protected override Task HigherQueueOperationTask
{
get
{
return Processor._highPriorityProcessor.Running;
}
}
protected override bool HigherQueueHasWorkItem
{
get
{
return Processor._highPriorityProcessor.HasAnyWork;
}
}
protected override void PauseOnGlobalOperation()
{
base.PauseOnGlobalOperation();
_workItemQueue.RequestCancellationOnRunningTasks();
}
private void SetProjectProcessing(ProjectId currentProject)
{
EnableProjectCacheIfNecessary(currentProject);
_currentProjectProcessing = currentProject;
}
private void EnableProjectCacheIfNecessary(ProjectId currentProject)
{
if (_projectCache != null && currentProject == _currentProjectProcessing)
{
return;
}
_projectCache?.Dispose();
_projectCache = Processor.EnableCaching(currentProject);
}
private IEnumerable<DocumentId> GetPrioritizedPendingDocuments()
{
// First the active document
var activeDocumentId = Processor._documentTracker.TryGetActiveDocument();
if (activeDocumentId != null)
{
yield return activeDocumentId;
}
// Now any visible documents
foreach (var visibleDocumentId in Processor._documentTracker.GetVisibleDocuments())
{
yield return visibleDocumentId;
}
// Any other high priority documents
foreach (var documentId in _higherPriorityDocumentsNotProcessed.Keys)
{
yield return documentId;
}
}
private async Task<bool> TryProcessOneHigherPriorityDocumentAsync()
{
try
{
if (!Processor._documentTracker.SupportsDocumentTracking)
{
return false;
}
foreach (var documentId in GetPrioritizedPendingDocuments())
{
if (CancellationToken.IsCancellationRequested)
{
return true;
}
// this is a best effort algorithm with some shortcomings.
//
// the most obvious issue is if there is a new work item (without a solution change - but very unlikely)
// for a opened document we already processed, the work item will be treated as a regular one rather than higher priority one
// (opened document)
// see whether we have work item for the document
if (!_workItemQueue.TryTake(documentId, out var workItem, out var documentCancellation))
{
RemoveHigherPriorityDocument(documentId);
continue;
}
// okay now we have work to do
await ProcessDocumentAsync(Analyzers, workItem, documentCancellation).ConfigureAwait(false);
RemoveHigherPriorityDocument(documentId);
return true;
}
return false;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void RemoveHigherPriorityDocument(DocumentId documentId)
{
// remove opened document processed
if (_higherPriorityDocumentsNotProcessed.TryRemove(documentId, out var projectCache))
{
projectCache?.Dispose();
}
}
private async Task ProcessDocumentAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(workItem.DocumentId);
if (CancellationToken.IsCancellationRequested)
{
return;
}
var processedEverything = false;
var documentId = workItem.DocumentId;
// we should always use solution snapshot after workitem is removed from the queue.
// otherwise, we can have a race such as below.
//
// 1.solution crawler picked up a solution
// 2.before processing the solution, an workitem got changed
// 3.and then the work item got picked up from the queue
// 4.and use the work item with the solution that got picked up in step 1
//
// step 2 is happening because solution has changed, but step 4 used old solution from step 1
// that doesn't have effects of the solution changes.
//
// solution crawler must remove the work item from the queue first and then pick up the soluton,
// so that the queue gets new work item if there is any solution changes after the work item is removed
// from the queue
//
// using later version of solution is always fine since, as long as there is new work item in the queue,
// solution crawler will eventually call the last workitem with the lastest solution
// making everything to catch up
var solution = Processor._registration.GetSolutionToAnalyze();
try
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, w => w.ToString(), workItem, cancellationToken))
{
var textDocument = solution.GetTextDocument(documentId);
if (textDocument != null)
{
// if we are called because a document is opened, we invalidate the document so that
// it can be re-analyzed. otherwise, since newly opened document has same version as before
// analyzer will simply return same data back
if (workItem.MustRefresh && !workItem.IsRetry)
{
var isOpen = textDocument.IsOpen();
await ProcessOpenDocumentIfNeededAsync(analyzers, workItem, textDocument, isOpen, cancellationToken).ConfigureAwait(false);
await ProcessCloseDocumentIfNeededAsync(analyzers, workItem, textDocument, isOpen, cancellationToken).ConfigureAwait(false);
}
// check whether we are having special reanalyze request
await ProcessReanalyzeDocumentAsync(workItem, textDocument, cancellationToken).ConfigureAwait(false);
await Processor.ProcessDocumentAnalyzersAsync(textDocument, analyzers, workItem, cancellationToken).ConfigureAwait(false);
}
else
{
SolutionCrawlerLogger.LogProcessDocumentNotExist(Processor._logAggregator);
await RemoveDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
}
if (!cancellationToken.IsCancellationRequested)
{
processedEverything = true;
}
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// we got cancelled in the middle of processing the document.
// let's make sure newly enqueued work item has all the flag needed.
// Avoid retry attempts after cancellation is requested, since work will not be processed
// after that point.
if (!processedEverything && !CancellationToken.IsCancellationRequested)
{
_workItemQueue.AddOrReplace(workItem.Retry(Listener.BeginAsyncOperation("ReenqueueWorkItem")));
}
SolutionCrawlerLogger.LogProcessDocument(Processor._logAggregator, documentId.Id, processedEverything);
// remove one that is finished running
_workItemQueue.MarkWorkItemDoneFor(workItem.DocumentId);
}
}
private async Task ProcessOpenDocumentIfNeededAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, TextDocument textDocument, bool isOpen, CancellationToken cancellationToken)
{
if (!isOpen || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentOpened))
{
return;
}
SolutionCrawlerLogger.LogProcessOpenDocument(Processor._logAggregator, textDocument.Id.Id);
await Processor.RunAnalyzersAsync(analyzers, textDocument, workItem, DocumentOpenAsync, cancellationToken).ConfigureAwait(false);
return;
static async Task DocumentOpenAsync(IIncrementalAnalyzer analyzer, TextDocument textDocument, CancellationToken cancellationToken)
{
if (textDocument is Document document)
{
await analyzer.DocumentOpenAsync(document, cancellationToken).ConfigureAwait(false);
}
else if (analyzer is IIncrementalAnalyzer2 analyzer2)
{
await analyzer2.NonSourceDocumentOpenAsync(textDocument, cancellationToken).ConfigureAwait(false);
}
}
}
private async Task ProcessCloseDocumentIfNeededAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, TextDocument textDocument, bool isOpen, CancellationToken cancellationToken)
{
if (isOpen || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentClosed))
{
return;
}
SolutionCrawlerLogger.LogProcessCloseDocument(Processor._logAggregator, textDocument.Id.Id);
await Processor.RunAnalyzersAsync(analyzers, textDocument, workItem, DocumentCloseAsync, cancellationToken).ConfigureAwait(false);
return;
static async Task DocumentCloseAsync(IIncrementalAnalyzer analyzer, TextDocument textDocument, CancellationToken cancellationToken)
{
if (textDocument is Document document)
{
await analyzer.DocumentCloseAsync(document, cancellationToken).ConfigureAwait(false);
}
else if (analyzer is IIncrementalAnalyzer2 analyzer2)
{
await analyzer2.NonSourceDocumentCloseAsync(textDocument, cancellationToken).ConfigureAwait(false);
}
}
}
private async Task ProcessReanalyzeDocumentAsync(WorkItem workItem, TextDocument document, CancellationToken cancellationToken)
{
try
{
#if DEBUG
Debug.Assert(!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.Reanalyze) || workItem.SpecificAnalyzers.Count > 0);
#endif
// No-reanalyze request or we already have a request to re-analyze every thing
if (workItem.MustRefresh || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.Reanalyze))
{
return;
}
// First reset the document state in analyzers.
var reanalyzers = workItem.SpecificAnalyzers.ToImmutableArray();
await Processor.RunAnalyzersAsync(reanalyzers, document, workItem, DocumentResetAsync, cancellationToken).ConfigureAwait(false);
// No request to re-run syntax change analysis. run it here
var reasons = workItem.InvocationReasons;
if (!reasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
await Processor.RunAnalyzersAsync(reanalyzers, document, workItem, (a, d, c) => AnalyzeSyntaxAsync(a, d, reasons, c), cancellationToken).ConfigureAwait(false);
}
// No request to re-run semantic change analysis. run it here
// Note: Semantic analysis is not supported for non-source documents.
if (document is Document sourceDocument &&
!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged))
{
await Processor.RunAnalyzersAsync(reanalyzers, sourceDocument, workItem, (a, d, c) => a.AnalyzeDocumentAsync(d, null, reasons, c), cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
return;
static async Task DocumentResetAsync(IIncrementalAnalyzer analyzer, TextDocument textDocument, CancellationToken cancellationToken)
{
if (textDocument is Document document)
{
await analyzer.DocumentResetAsync(document, cancellationToken).ConfigureAwait(false);
}
else if (analyzer is IIncrementalAnalyzer2 analyzer2)
{
await analyzer2.NonSourceDocumentResetAsync(textDocument, cancellationToken).ConfigureAwait(false);
}
}
static async Task AnalyzeSyntaxAsync(IIncrementalAnalyzer analyzer, TextDocument textDocument, InvocationReasons reasons, CancellationToken cancellationToken)
{
if (textDocument is Document document)
{
await analyzer.AnalyzeSyntaxAsync((Document)document, reasons, cancellationToken).ConfigureAwait(false);
}
else if (analyzer is IIncrementalAnalyzer2 analyzer2)
{
await analyzer2.AnalyzeNonSourceDocumentAsync(textDocument, reasons, cancellationToken).ConfigureAwait(false);
}
}
}
private Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken)
=> RemoveDocumentAsync(Analyzers, documentId, cancellationToken);
private static async Task RemoveDocumentAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, DocumentId documentId, CancellationToken cancellationToken)
{
foreach (var analyzer in analyzers)
{
await analyzer.RemoveDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
}
}
private async Task ResetStatesAsync()
{
try
{
if (!IsSolutionChanged())
{
return;
}
await Processor.RunAnalyzersAsync(
Analyzers,
Processor._registration.GetSolutionToAnalyze(),
workItem: new WorkItem(), (a, s, c) => a.NewSolutionSnapshotAsync(s, c), CancellationToken).ConfigureAwait(false);
foreach (var id in Processor.GetOpenDocumentIds())
{
AddHigherPriorityDocument(id);
}
SolutionCrawlerLogger.LogResetStates(Processor._logAggregator);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
bool IsSolutionChanged()
{
var currentSolution = Processor._registration.GetSolutionToAnalyze();
var oldSolution = _lastSolution;
if (currentSolution == oldSolution)
{
return false;
}
_lastSolution = currentSolution;
ResetLogAggregatorIfNeeded(currentSolution, oldSolution);
return true;
}
void ResetLogAggregatorIfNeeded(Solution currentSolution, Solution? oldSolution)
{
if (oldSolution == null || currentSolution.Id == oldSolution.Id)
{
// we log aggregated info when solution is changed such as
// new solution is opened or solution is closed
return;
}
// this log things like how many time we analyzed active files, how many times other files are analyzed,
// avg time to analyze files, how many solution snapshot got analyzed and etc.
// all accumultation is done in VS side and we only send statistics to VS telemetry otherwise, it is too much
// data to send
SolutionCrawlerLogger.LogIncrementalAnalyzerProcessorStatistics(
Processor._registration.CorrelationId, oldSolution, Processor._logAggregator, Analyzers);
Processor.ResetLogAggregator();
}
}
public override void Shutdown()
{
base.Shutdown();
_workItemQueue.Dispose();
_projectCache?.Dispose();
_projectCache = null;
}
internal TestAccessor GetTestAccessor()
{
return new TestAccessor(this);
}
internal readonly struct TestAccessor
{
private readonly NormalPriorityProcessor _normalPriorityProcessor;
internal TestAccessor(NormalPriorityProcessor normalPriorityProcessor)
{
_normalPriorityProcessor = normalPriorityProcessor;
}
internal void WaitUntilCompletion(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items)
{
foreach (var item in items)
{
_normalPriorityProcessor.ProcessDocumentAsync(analyzers, item, CancellationToken.None).Wait();
}
}
internal void WaitUntilCompletion()
{
// this shouldn't happen. would like to get some diagnostic
while (_normalPriorityProcessor._workItemQueue.HasAnyWork)
{
FailFast.Fail("How?");
}
}
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
#if DEBUG
using System.Diagnostics;
#endif
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
internal sealed partial class WorkCoordinator
{
private sealed partial class IncrementalAnalyzerProcessor
{
private sealed class NormalPriorityProcessor : AbstractPriorityProcessor
{
private const int MaxHighPriorityQueueCache = 29;
private readonly AsyncDocumentWorkItemQueue _workItemQueue;
private readonly ConcurrentDictionary<DocumentId, IDisposable?> _higherPriorityDocumentsNotProcessed;
private ProjectId? _currentProjectProcessing;
private IDisposable? _projectCache;
// this is only used in ResetState to find out solution has changed
// and reset some states such as logging some telemetry or
// priorities active,visible, opened files and etc
private Solution? _lastSolution = null;
// whether this processor is running or not
private Task _running;
public NormalPriorityProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers,
IGlobalOperationNotificationService globalOperationNotificationService,
TimeSpan backOffTimeSpan,
CancellationToken shutdownToken)
: base(listener, processor, lazyAnalyzers, globalOperationNotificationService, backOffTimeSpan, shutdownToken)
{
_running = Task.CompletedTask;
_workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter, processor._registration.Workspace);
_higherPriorityDocumentsNotProcessed = new ConcurrentDictionary<DocumentId, IDisposable?>(concurrencyLevel: 2, capacity: 20);
_currentProjectProcessing = null;
Start();
}
public void Enqueue(WorkItem item)
{
Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item");
UpdateLastAccessTime();
var added = _workItemQueue.AddOrReplace(item);
Logger.Log(FunctionId.WorkCoordinator_DocumentWorker_Enqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added);
CheckHigherPriorityDocument(item);
SolutionCrawlerLogger.LogWorkItemEnqueue(
Processor._logAggregator, item.Language, item.DocumentId, item.InvocationReasons, item.IsLowPriority, item.ActiveMember, added);
}
private void CheckHigherPriorityDocument(WorkItem item)
{
Contract.ThrowIfFalse(item.DocumentId != null);
if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.HighPriority))
{
return;
}
AddHigherPriorityDocument(item.DocumentId);
}
private void AddHigherPriorityDocument(DocumentId id)
{
var cache = GetHighPriorityQueueProjectCache(id);
if (!_higherPriorityDocumentsNotProcessed.TryAdd(id, cache))
{
// we already have the document in the queue.
cache?.Dispose();
}
SolutionCrawlerLogger.LogHigherPriority(Processor._logAggregator, id.Id);
}
private IDisposable? GetHighPriorityQueueProjectCache(DocumentId id)
{
// NOTE: we have one potential issue where we can cache a lot of stuff in memory
// since we will cache all high prioirty work's projects in memory until they are processed.
//
// To mitigate that, we will turn off cache if we have too many items in high priority queue
// this shouldn't affect active file since we always enable active file cache from background compiler.
return _higherPriorityDocumentsNotProcessed.Count <= MaxHighPriorityQueueCache ? Processor.EnableCaching(id.ProjectId) : null;
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
if (!_workItemQueue.HasAnyWork)
{
_projectCache?.Dispose();
_projectCache = null;
}
return _workItemQueue.WaitAsync(cancellationToken);
}
public Task Running => _running;
public int WorkItemCount => _workItemQueue.WorkItemCount;
public bool HasAnyWork => _workItemQueue.HasAnyWork;
protected override async Task ExecuteAsync()
{
if (CancellationToken.IsCancellationRequested)
{
return;
}
var source = new TaskCompletionSource<object?>();
try
{
// mark it as running
_running = source.Task;
await WaitForHigherPriorityOperationsAsync().ConfigureAwait(false);
// okay, there must be at least one item in the map
await ResetStatesAsync().ConfigureAwait(false);
if (await TryProcessOneHigherPriorityDocumentAsync().ConfigureAwait(false))
{
// successfully processed a high priority document.
return;
}
// process one of documents remaining
if (!_workItemQueue.TryTakeAnyWork(
_currentProjectProcessing, Processor.DependencyGraph, Processor.DiagnosticAnalyzerService,
out var workItem, out var documentCancellation))
{
return;
}
// check whether we have been shutdown
if (CancellationToken.IsCancellationRequested)
{
return;
}
// check whether we have moved to new project
SetProjectProcessing(workItem.ProjectId);
// process the new document
await ProcessDocumentAsync(Analyzers, workItem, documentCancellation).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// mark it as done running
source.SetResult(null);
}
}
protected override Task HigherQueueOperationTask
{
get
{
return Processor._highPriorityProcessor.Running;
}
}
protected override bool HigherQueueHasWorkItem
{
get
{
return Processor._highPriorityProcessor.HasAnyWork;
}
}
protected override void PauseOnGlobalOperation()
{
base.PauseOnGlobalOperation();
_workItemQueue.RequestCancellationOnRunningTasks();
}
private void SetProjectProcessing(ProjectId currentProject)
{
EnableProjectCacheIfNecessary(currentProject);
_currentProjectProcessing = currentProject;
}
private void EnableProjectCacheIfNecessary(ProjectId currentProject)
{
if (_projectCache != null && currentProject == _currentProjectProcessing)
{
return;
}
_projectCache?.Dispose();
_projectCache = Processor.EnableCaching(currentProject);
}
private IEnumerable<DocumentId> GetPrioritizedPendingDocuments()
{
// First the active document
var activeDocumentId = Processor._documentTracker.TryGetActiveDocument();
if (activeDocumentId != null)
{
yield return activeDocumentId;
}
// Now any visible documents
foreach (var visibleDocumentId in Processor._documentTracker.GetVisibleDocuments())
{
yield return visibleDocumentId;
}
// Any other high priority documents
foreach (var documentId in _higherPriorityDocumentsNotProcessed.Keys)
{
yield return documentId;
}
}
private async Task<bool> TryProcessOneHigherPriorityDocumentAsync()
{
try
{
if (!Processor._documentTracker.SupportsDocumentTracking)
{
return false;
}
foreach (var documentId in GetPrioritizedPendingDocuments())
{
if (CancellationToken.IsCancellationRequested)
{
return true;
}
// this is a best effort algorithm with some shortcomings.
//
// the most obvious issue is if there is a new work item (without a solution change - but very unlikely)
// for a opened document we already processed, the work item will be treated as a regular one rather than higher priority one
// (opened document)
// see whether we have work item for the document
if (!_workItemQueue.TryTake(documentId, out var workItem, out var documentCancellation))
{
RemoveHigherPriorityDocument(documentId);
continue;
}
// okay now we have work to do
await ProcessDocumentAsync(Analyzers, workItem, documentCancellation).ConfigureAwait(false);
RemoveHigherPriorityDocument(documentId);
return true;
}
return false;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void RemoveHigherPriorityDocument(DocumentId documentId)
{
// remove opened document processed
if (_higherPriorityDocumentsNotProcessed.TryRemove(documentId, out var projectCache))
{
projectCache?.Dispose();
}
}
private async Task ProcessDocumentAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationToken cancellationToken)
{
Contract.ThrowIfNull(workItem.DocumentId);
if (CancellationToken.IsCancellationRequested)
{
return;
}
var processedEverything = false;
var documentId = workItem.DocumentId;
// we should always use solution snapshot after workitem is removed from the queue.
// otherwise, we can have a race such as below.
//
// 1.solution crawler picked up a solution
// 2.before processing the solution, an workitem got changed
// 3.and then the work item got picked up from the queue
// 4.and use the work item with the solution that got picked up in step 1
//
// step 2 is happening because solution has changed, but step 4 used old solution from step 1
// that doesn't have effects of the solution changes.
//
// solution crawler must remove the work item from the queue first and then pick up the soluton,
// so that the queue gets new work item if there is any solution changes after the work item is removed
// from the queue
//
// using later version of solution is always fine since, as long as there is new work item in the queue,
// solution crawler will eventually call the last workitem with the lastest solution
// making everything to catch up
var solution = Processor._registration.GetSolutionToAnalyze();
try
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, w => w.ToString(), workItem, cancellationToken))
{
var textDocument = solution.GetTextDocument(documentId);
if (textDocument != null)
{
// if we are called because a document is opened, we invalidate the document so that
// it can be re-analyzed. otherwise, since newly opened document has same version as before
// analyzer will simply return same data back
if (workItem.MustRefresh && !workItem.IsRetry)
{
var isOpen = textDocument.IsOpen();
await ProcessOpenDocumentIfNeededAsync(analyzers, workItem, textDocument, isOpen, cancellationToken).ConfigureAwait(false);
await ProcessCloseDocumentIfNeededAsync(analyzers, workItem, textDocument, isOpen, cancellationToken).ConfigureAwait(false);
}
// check whether we are having special reanalyze request
await ProcessReanalyzeDocumentAsync(workItem, textDocument, cancellationToken).ConfigureAwait(false);
await Processor.ProcessDocumentAnalyzersAsync(textDocument, analyzers, workItem, cancellationToken).ConfigureAwait(false);
}
else
{
SolutionCrawlerLogger.LogProcessDocumentNotExist(Processor._logAggregator);
await RemoveDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
}
if (!cancellationToken.IsCancellationRequested)
{
processedEverything = true;
}
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// we got cancelled in the middle of processing the document.
// let's make sure newly enqueued work item has all the flag needed.
// Avoid retry attempts after cancellation is requested, since work will not be processed
// after that point.
if (!processedEverything && !CancellationToken.IsCancellationRequested)
{
_workItemQueue.AddOrReplace(workItem.Retry(Listener.BeginAsyncOperation("ReenqueueWorkItem")));
}
SolutionCrawlerLogger.LogProcessDocument(Processor._logAggregator, documentId.Id, processedEverything);
// remove one that is finished running
_workItemQueue.MarkWorkItemDoneFor(workItem.DocumentId);
}
}
private async Task ProcessOpenDocumentIfNeededAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, TextDocument textDocument, bool isOpen, CancellationToken cancellationToken)
{
if (!isOpen || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentOpened))
{
return;
}
SolutionCrawlerLogger.LogProcessOpenDocument(Processor._logAggregator, textDocument.Id.Id);
await Processor.RunAnalyzersAsync(analyzers, textDocument, workItem, DocumentOpenAsync, cancellationToken).ConfigureAwait(false);
return;
static async Task DocumentOpenAsync(IIncrementalAnalyzer analyzer, TextDocument textDocument, CancellationToken cancellationToken)
{
if (textDocument is Document document)
{
await analyzer.DocumentOpenAsync(document, cancellationToken).ConfigureAwait(false);
}
else if (analyzer is IIncrementalAnalyzer2 analyzer2)
{
await analyzer2.NonSourceDocumentOpenAsync(textDocument, cancellationToken).ConfigureAwait(false);
}
}
}
private async Task ProcessCloseDocumentIfNeededAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, TextDocument textDocument, bool isOpen, CancellationToken cancellationToken)
{
if (isOpen || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.DocumentClosed))
{
return;
}
SolutionCrawlerLogger.LogProcessCloseDocument(Processor._logAggregator, textDocument.Id.Id);
await Processor.RunAnalyzersAsync(analyzers, textDocument, workItem, DocumentCloseAsync, cancellationToken).ConfigureAwait(false);
return;
static async Task DocumentCloseAsync(IIncrementalAnalyzer analyzer, TextDocument textDocument, CancellationToken cancellationToken)
{
if (textDocument is Document document)
{
await analyzer.DocumentCloseAsync(document, cancellationToken).ConfigureAwait(false);
}
else if (analyzer is IIncrementalAnalyzer2 analyzer2)
{
await analyzer2.NonSourceDocumentCloseAsync(textDocument, cancellationToken).ConfigureAwait(false);
}
}
}
private async Task ProcessReanalyzeDocumentAsync(WorkItem workItem, TextDocument document, CancellationToken cancellationToken)
{
try
{
#if DEBUG
Debug.Assert(!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.Reanalyze) || workItem.SpecificAnalyzers.Count > 0);
#endif
// No-reanalyze request or we already have a request to re-analyze every thing
if (workItem.MustRefresh || !workItem.InvocationReasons.Contains(PredefinedInvocationReasons.Reanalyze))
{
return;
}
// First reset the document state in analyzers.
var reanalyzers = workItem.SpecificAnalyzers.ToImmutableArray();
await Processor.RunAnalyzersAsync(reanalyzers, document, workItem, DocumentResetAsync, cancellationToken).ConfigureAwait(false);
// No request to re-run syntax change analysis. run it here
var reasons = workItem.InvocationReasons;
if (!reasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
await Processor.RunAnalyzersAsync(reanalyzers, document, workItem, (a, d, c) => AnalyzeSyntaxAsync(a, d, reasons, c), cancellationToken).ConfigureAwait(false);
}
// No request to re-run semantic change analysis. run it here
// Note: Semantic analysis is not supported for non-source documents.
if (document is Document sourceDocument &&
!workItem.InvocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged))
{
await Processor.RunAnalyzersAsync(reanalyzers, sourceDocument, workItem, (a, d, c) => a.AnalyzeDocumentAsync(d, null, reasons, c), cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
return;
static async Task DocumentResetAsync(IIncrementalAnalyzer analyzer, TextDocument textDocument, CancellationToken cancellationToken)
{
if (textDocument is Document document)
{
await analyzer.DocumentResetAsync(document, cancellationToken).ConfigureAwait(false);
}
else if (analyzer is IIncrementalAnalyzer2 analyzer2)
{
await analyzer2.NonSourceDocumentResetAsync(textDocument, cancellationToken).ConfigureAwait(false);
}
}
static async Task AnalyzeSyntaxAsync(IIncrementalAnalyzer analyzer, TextDocument textDocument, InvocationReasons reasons, CancellationToken cancellationToken)
{
if (textDocument is Document document)
{
await analyzer.AnalyzeSyntaxAsync((Document)document, reasons, cancellationToken).ConfigureAwait(false);
}
else if (analyzer is IIncrementalAnalyzer2 analyzer2)
{
await analyzer2.AnalyzeNonSourceDocumentAsync(textDocument, reasons, cancellationToken).ConfigureAwait(false);
}
}
}
private Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken)
=> RemoveDocumentAsync(Analyzers, documentId, cancellationToken);
private static async Task RemoveDocumentAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, DocumentId documentId, CancellationToken cancellationToken)
{
foreach (var analyzer in analyzers)
{
await analyzer.RemoveDocumentAsync(documentId, cancellationToken).ConfigureAwait(false);
}
}
private async Task ResetStatesAsync()
{
try
{
if (!IsSolutionChanged())
{
return;
}
await Processor.RunAnalyzersAsync(
Analyzers,
Processor._registration.GetSolutionToAnalyze(),
workItem: new WorkItem(), (a, s, c) => a.NewSolutionSnapshotAsync(s, c), CancellationToken).ConfigureAwait(false);
foreach (var id in Processor.GetOpenDocumentIds())
{
AddHigherPriorityDocument(id);
}
SolutionCrawlerLogger.LogResetStates(Processor._logAggregator);
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
bool IsSolutionChanged()
{
var currentSolution = Processor._registration.GetSolutionToAnalyze();
var oldSolution = _lastSolution;
if (currentSolution == oldSolution)
{
return false;
}
_lastSolution = currentSolution;
ResetLogAggregatorIfNeeded(currentSolution, oldSolution);
return true;
}
void ResetLogAggregatorIfNeeded(Solution currentSolution, Solution? oldSolution)
{
if (oldSolution == null || currentSolution.Id == oldSolution.Id)
{
// we log aggregated info when solution is changed such as
// new solution is opened or solution is closed
return;
}
// this log things like how many time we analyzed active files, how many times other files are analyzed,
// avg time to analyze files, how many solution snapshot got analyzed and etc.
// all accumultation is done in VS side and we only send statistics to VS telemetry otherwise, it is too much
// data to send
SolutionCrawlerLogger.LogIncrementalAnalyzerProcessorStatistics(
Processor._registration.CorrelationId, oldSolution, Processor._logAggregator, Analyzers);
Processor.ResetLogAggregator();
}
}
public override void Shutdown()
{
base.Shutdown();
_workItemQueue.Dispose();
_projectCache?.Dispose();
_projectCache = null;
}
internal TestAccessor GetTestAccessor()
{
return new TestAccessor(this);
}
internal readonly struct TestAccessor
{
private readonly NormalPriorityProcessor _normalPriorityProcessor;
internal TestAccessor(NormalPriorityProcessor normalPriorityProcessor)
{
_normalPriorityProcessor = normalPriorityProcessor;
}
internal void WaitUntilCompletion(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items)
{
foreach (var item in items)
{
_normalPriorityProcessor.ProcessDocumentAsync(analyzers, item, CancellationToken.None).Wait();
}
}
internal void WaitUntilCompletion()
{
// this shouldn't happen. would like to get some diagnostic
while (_normalPriorityProcessor._workItemQueue.HasAnyWork)
{
FailFast.Fail("How?");
}
}
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Features/Core/Portable/UnusedReferences/ReferenceUpdate.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.UnusedReferences
{
internal sealed class ReferenceUpdate
{
/// <summary>
/// Indicates action to perform on the reference.
/// </summary>
public UpdateAction Action { get; set; }
/// <summary>
/// Gets the reference to be updated.
/// </summary>
public ReferenceInfo ReferenceInfo { get; }
public ReferenceUpdate(UpdateAction action, ReferenceInfo referenceInfo)
{
Action = action;
ReferenceInfo = referenceInfo;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.UnusedReferences
{
internal sealed class ReferenceUpdate
{
/// <summary>
/// Indicates action to perform on the reference.
/// </summary>
public UpdateAction Action { get; set; }
/// <summary>
/// Gets the reference to be updated.
/// </summary>
public ReferenceInfo ReferenceInfo { get; }
public ReferenceUpdate(UpdateAction action, ReferenceInfo referenceInfo)
{
Action = action;
ReferenceInfo = referenceInfo;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/VisualStudio/CSharp/Impl/LanguageService/CSharpEditorFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.FileHeaders;
using Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.FileHeaders;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService
{
[ExcludeFromCodeCoverage]
[Guid(Guids.CSharpEditorFactoryIdString)]
internal class CSharpEditorFactory : AbstractEditorFactory
{
public CSharpEditorFactory(IComponentModel componentModel)
: base(componentModel)
{
}
protected override string ContentTypeName => ContentTypeNames.CSharpContentType;
protected override string LanguageName => LanguageNames.CSharp;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.FileHeaders;
using Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.FileHeaders;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService
{
[ExcludeFromCodeCoverage]
[Guid(Guids.CSharpEditorFactoryIdString)]
internal class CSharpEditorFactory : AbstractEditorFactory
{
public CSharpEditorFactory(IComponentModel componentModel)
: base(componentModel)
{
}
protected override string ContentTypeName => ContentTypeNames.CSharpContentType;
protected override string LanguageName => LanguageNames.CSharp;
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Compilers/Core/Portable/RuleSet/RuleSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a set of rules as specified in a ruleset file.
/// </summary>
public class RuleSet
{
private readonly string _filePath;
/// <summary>
/// The file path of the ruleset file.
/// </summary>
public string FilePath
{
get { return _filePath; }
}
private readonly ReportDiagnostic _generalDiagnosticOption;
/// <summary>
/// The global option specified by the IncludeAll tag.
/// </summary>
public ReportDiagnostic GeneralDiagnosticOption
{
get { return _generalDiagnosticOption; }
}
private readonly ImmutableDictionary<string, ReportDiagnostic> _specificDiagnosticOptions;
/// <summary>
/// Individual rule ids and their associated actions.
/// </summary>
public ImmutableDictionary<string, ReportDiagnostic> SpecificDiagnosticOptions
{
get { return _specificDiagnosticOptions; }
}
private readonly ImmutableArray<RuleSetInclude> _includes;
/// <summary>
/// List of rulesets included by this ruleset.
/// </summary>
public ImmutableArray<RuleSetInclude> Includes
{
get { return _includes; }
}
/// <summary>
/// Create a RuleSet.
/// </summary>
public RuleSet(string filePath, ReportDiagnostic generalOption, ImmutableDictionary<string, ReportDiagnostic> specificOptions, ImmutableArray<RuleSetInclude> includes)
{
_filePath = filePath;
_generalDiagnosticOption = generalOption;
_specificDiagnosticOptions = specificOptions == null ? ImmutableDictionary<string, ReportDiagnostic>.Empty : specificOptions;
_includes = includes.NullToEmpty();
}
/// <summary>
/// Create a RuleSet with a global effective action applied on it.
/// </summary>
public RuleSet? WithEffectiveAction(ReportDiagnostic action)
{
if (!_includes.IsEmpty)
{
throw new ArgumentException("Effective action cannot be applied to rulesets with Includes");
}
switch (action)
{
case ReportDiagnostic.Default:
return this;
case ReportDiagnostic.Suppress:
return null;
case ReportDiagnostic.Error:
case ReportDiagnostic.Warn:
case ReportDiagnostic.Info:
case ReportDiagnostic.Hidden:
var generalOption = _generalDiagnosticOption == ReportDiagnostic.Default ? ReportDiagnostic.Default : action;
var specificOptions = _specificDiagnosticOptions.ToBuilder();
foreach (var item in _specificDiagnosticOptions)
{
if (item.Value != ReportDiagnostic.Suppress && item.Value != ReportDiagnostic.Default)
{
specificOptions[item.Key] = action;
}
}
return new RuleSet(FilePath, generalOption, specificOptions.ToImmutable(), _includes);
default:
return null;
}
}
/// <summary>
/// Get the effective ruleset after resolving all the included rulesets.
/// </summary>
private RuleSet GetEffectiveRuleSet(HashSet<string> includedRulesetPaths)
{
var effectiveGeneralOption = _generalDiagnosticOption;
var effectiveSpecificOptions = new Dictionary<string, ReportDiagnostic>();
// If we don't have any include then there's nothing to resolve.
if (_includes.IsEmpty)
{
return this;
}
foreach (var ruleSetInclude in _includes)
{
// If the include has been suppressed then there's nothing to do.
if (ruleSetInclude.Action == ReportDiagnostic.Suppress)
{
continue;
}
var ruleSet = ruleSetInclude.LoadRuleSet(this);
// If we couldn't load the ruleset file, then there's nothing to do.
if (ruleSet == null)
{
continue;
}
// If the ruleset has already been included then just ignore it.
if (includedRulesetPaths.Contains(ruleSet.FilePath.ToLowerInvariant()))
{
continue;
}
includedRulesetPaths.Add(ruleSet.FilePath.ToLowerInvariant());
// Recursively get the effective ruleset of the included file, in case they in turn
// contain includes.
RuleSet? effectiveRuleset = ruleSet.GetEffectiveRuleSet(includedRulesetPaths);
// Apply the includeAction on this ruleset.
effectiveRuleset = effectiveRuleset.WithEffectiveAction(ruleSetInclude.Action);
Debug.Assert(effectiveRuleset is object);
// If the included ruleset's global option is stricter, then make that the effective option.
if (IsStricterThan(effectiveRuleset.GeneralDiagnosticOption, effectiveGeneralOption))
{
effectiveGeneralOption = effectiveRuleset.GeneralDiagnosticOption;
}
// Copy every rule in the ruleset and change the action if there's a stricter one.
foreach (var item in effectiveRuleset.SpecificDiagnosticOptions)
{
if (effectiveSpecificOptions.TryGetValue(item.Key, out var value))
{
if (IsStricterThan(item.Value, value))
{
effectiveSpecificOptions[item.Key] = item.Value;
}
}
else
{
effectiveSpecificOptions.Add(item.Key, item.Value);
}
}
}
// Finally, copy all the rules in the current ruleset. This overrides the actions
// of any included ruleset - therefore, no strictness check.
foreach (var item in _specificDiagnosticOptions)
{
if (effectiveSpecificOptions.ContainsKey(item.Key))
{
effectiveSpecificOptions[item.Key] = item.Value;
}
else
{
effectiveSpecificOptions.Add(item.Key, item.Value);
}
}
return new RuleSet(_filePath, effectiveGeneralOption, effectiveSpecificOptions.ToImmutableDictionary(), ImmutableArray<RuleSetInclude>.Empty);
}
/// <summary>
/// Get all the files involved in resolving this ruleset.
/// </summary>
private ImmutableArray<string> GetEffectiveIncludes()
{
var arrayBuilder = ImmutableArray.CreateBuilder<string>();
GetEffectiveIncludesCore(arrayBuilder);
return arrayBuilder.ToImmutable();
}
private void GetEffectiveIncludesCore(ImmutableArray<string>.Builder arrayBuilder)
{
arrayBuilder.Add(this.FilePath);
foreach (var ruleSetInclude in _includes)
{
var ruleSet = ruleSetInclude.LoadRuleSet(this);
// If we couldn't load the ruleset file, then there's nothing to do.
if (ruleSet == null)
{
continue;
}
// If this file has already been included don't recurse into it.
if (!arrayBuilder.Contains(ruleSet.FilePath, StringComparer.OrdinalIgnoreCase))
{
ruleSet.GetEffectiveIncludesCore(arrayBuilder);
}
}
}
/// <summary>
/// Returns true if the action1 is stricter than action2.
/// </summary>
private static bool IsStricterThan(ReportDiagnostic action1, ReportDiagnostic action2)
{
switch (action2)
{
case ReportDiagnostic.Suppress:
return true;
case ReportDiagnostic.Default:
return action1 == ReportDiagnostic.Warn || action1 == ReportDiagnostic.Error || action1 == ReportDiagnostic.Info || action1 == ReportDiagnostic.Hidden;
case ReportDiagnostic.Hidden:
return action1 == ReportDiagnostic.Warn || action1 == ReportDiagnostic.Error || action1 == ReportDiagnostic.Info;
case ReportDiagnostic.Info:
return action1 == ReportDiagnostic.Warn || action1 == ReportDiagnostic.Error;
case ReportDiagnostic.Warn:
return action1 == ReportDiagnostic.Error;
case ReportDiagnostic.Error:
return false;
default:
return false;
}
}
/// <summary>
/// Load the ruleset from the specified file. This ruleset will contain
/// all the rules resolved from the includes specified in the ruleset file
/// as well. See also: <seealso cref="GetEffectiveIncludesFromFile(string)" />.
/// </summary>
/// <returns>
/// A ruleset that contains resolved rules or null if there were errors.
/// </returns>
public static RuleSet LoadEffectiveRuleSetFromFile(string filePath)
{
var ruleSet = RuleSetProcessor.LoadFromFile(filePath);
return ruleSet.GetEffectiveRuleSet(new HashSet<string>());
}
/// <summary>
/// Get the paths to all files contributing rules to the ruleset from the specified file.
/// See also: <seealso cref="LoadEffectiveRuleSetFromFile(string)" />.
/// </summary>
/// <returns>
/// The full paths to included files, or an empty array if there were errors.
/// </returns>
public static ImmutableArray<string> GetEffectiveIncludesFromFile(string filePath)
{
var ruleSet = RuleSetProcessor.LoadFromFile(filePath);
if (ruleSet != null)
{
return ruleSet.GetEffectiveIncludes();
}
return ImmutableArray<string>.Empty;
}
#nullable enable
/// <summary>
/// Parses the ruleset file at the given <paramref name="rulesetFileFullPath"/> and returns the following diagnostic options from the parsed file:
/// 1) A map of <paramref name="specificDiagnosticOptions"/> from rule ID to <see cref="ReportDiagnostic"/> option.
/// 2) A global <see cref="ReportDiagnostic"/> option for all rules in the ruleset file.
/// </summary>
public static ReportDiagnostic GetDiagnosticOptionsFromRulesetFile(string? rulesetFileFullPath, out Dictionary<string, ReportDiagnostic> specificDiagnosticOptions)
{
return GetDiagnosticOptionsFromRulesetFile(rulesetFileFullPath, out specificDiagnosticOptions, null, null);
}
internal static ReportDiagnostic GetDiagnosticOptionsFromRulesetFile(string? rulesetFileFullPath, out Dictionary<string, ReportDiagnostic> diagnosticOptions, IList<Diagnostic>? diagnosticsOpt, CommonMessageProvider? messageProviderOpt)
{
diagnosticOptions = new Dictionary<string, ReportDiagnostic>();
if (rulesetFileFullPath == null)
{
return ReportDiagnostic.Default;
}
return GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, rulesetFileFullPath, diagnosticsOpt, messageProviderOpt);
}
private static ReportDiagnostic GetDiagnosticOptionsFromRulesetFile(Dictionary<string, ReportDiagnostic> diagnosticOptions, string resolvedPath, IList<Diagnostic>? diagnosticsOpt, CommonMessageProvider? messageProviderOpt)
{
Debug.Assert(resolvedPath != null);
var generalDiagnosticOption = ReportDiagnostic.Default;
try
{
var ruleSet = RuleSet.LoadEffectiveRuleSetFromFile(resolvedPath);
generalDiagnosticOption = ruleSet.GeneralDiagnosticOption;
foreach (var rule in ruleSet.SpecificDiagnosticOptions)
{
diagnosticOptions.Add(rule.Key, rule.Value);
}
}
catch (InvalidRuleSetException e)
{
if (diagnosticsOpt != null && messageProviderOpt != null)
{
diagnosticsOpt.Add(Diagnostic.Create(messageProviderOpt, messageProviderOpt.ERR_CantReadRulesetFile, resolvedPath, e.Message));
}
}
catch (IOException e)
{
if (e is FileNotFoundException || e.GetType().Name == "DirectoryNotFoundException")
{
if (diagnosticsOpt != null && messageProviderOpt != null)
{
diagnosticsOpt.Add(Diagnostic.Create(messageProviderOpt, messageProviderOpt.ERR_CantReadRulesetFile, resolvedPath, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.FileNotFound))));
}
}
else
{
if (diagnosticsOpt != null && messageProviderOpt != null)
{
diagnosticsOpt.Add(Diagnostic.Create(messageProviderOpt, messageProviderOpt.ERR_CantReadRulesetFile, resolvedPath, e.Message));
}
}
}
return generalDiagnosticOption;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a set of rules as specified in a ruleset file.
/// </summary>
public class RuleSet
{
private readonly string _filePath;
/// <summary>
/// The file path of the ruleset file.
/// </summary>
public string FilePath
{
get { return _filePath; }
}
private readonly ReportDiagnostic _generalDiagnosticOption;
/// <summary>
/// The global option specified by the IncludeAll tag.
/// </summary>
public ReportDiagnostic GeneralDiagnosticOption
{
get { return _generalDiagnosticOption; }
}
private readonly ImmutableDictionary<string, ReportDiagnostic> _specificDiagnosticOptions;
/// <summary>
/// Individual rule ids and their associated actions.
/// </summary>
public ImmutableDictionary<string, ReportDiagnostic> SpecificDiagnosticOptions
{
get { return _specificDiagnosticOptions; }
}
private readonly ImmutableArray<RuleSetInclude> _includes;
/// <summary>
/// List of rulesets included by this ruleset.
/// </summary>
public ImmutableArray<RuleSetInclude> Includes
{
get { return _includes; }
}
/// <summary>
/// Create a RuleSet.
/// </summary>
public RuleSet(string filePath, ReportDiagnostic generalOption, ImmutableDictionary<string, ReportDiagnostic> specificOptions, ImmutableArray<RuleSetInclude> includes)
{
_filePath = filePath;
_generalDiagnosticOption = generalOption;
_specificDiagnosticOptions = specificOptions == null ? ImmutableDictionary<string, ReportDiagnostic>.Empty : specificOptions;
_includes = includes.NullToEmpty();
}
/// <summary>
/// Create a RuleSet with a global effective action applied on it.
/// </summary>
public RuleSet? WithEffectiveAction(ReportDiagnostic action)
{
if (!_includes.IsEmpty)
{
throw new ArgumentException("Effective action cannot be applied to rulesets with Includes");
}
switch (action)
{
case ReportDiagnostic.Default:
return this;
case ReportDiagnostic.Suppress:
return null;
case ReportDiagnostic.Error:
case ReportDiagnostic.Warn:
case ReportDiagnostic.Info:
case ReportDiagnostic.Hidden:
var generalOption = _generalDiagnosticOption == ReportDiagnostic.Default ? ReportDiagnostic.Default : action;
var specificOptions = _specificDiagnosticOptions.ToBuilder();
foreach (var item in _specificDiagnosticOptions)
{
if (item.Value != ReportDiagnostic.Suppress && item.Value != ReportDiagnostic.Default)
{
specificOptions[item.Key] = action;
}
}
return new RuleSet(FilePath, generalOption, specificOptions.ToImmutable(), _includes);
default:
return null;
}
}
/// <summary>
/// Get the effective ruleset after resolving all the included rulesets.
/// </summary>
private RuleSet GetEffectiveRuleSet(HashSet<string> includedRulesetPaths)
{
var effectiveGeneralOption = _generalDiagnosticOption;
var effectiveSpecificOptions = new Dictionary<string, ReportDiagnostic>();
// If we don't have any include then there's nothing to resolve.
if (_includes.IsEmpty)
{
return this;
}
foreach (var ruleSetInclude in _includes)
{
// If the include has been suppressed then there's nothing to do.
if (ruleSetInclude.Action == ReportDiagnostic.Suppress)
{
continue;
}
var ruleSet = ruleSetInclude.LoadRuleSet(this);
// If we couldn't load the ruleset file, then there's nothing to do.
if (ruleSet == null)
{
continue;
}
// If the ruleset has already been included then just ignore it.
if (includedRulesetPaths.Contains(ruleSet.FilePath.ToLowerInvariant()))
{
continue;
}
includedRulesetPaths.Add(ruleSet.FilePath.ToLowerInvariant());
// Recursively get the effective ruleset of the included file, in case they in turn
// contain includes.
RuleSet? effectiveRuleset = ruleSet.GetEffectiveRuleSet(includedRulesetPaths);
// Apply the includeAction on this ruleset.
effectiveRuleset = effectiveRuleset.WithEffectiveAction(ruleSetInclude.Action);
Debug.Assert(effectiveRuleset is object);
// If the included ruleset's global option is stricter, then make that the effective option.
if (IsStricterThan(effectiveRuleset.GeneralDiagnosticOption, effectiveGeneralOption))
{
effectiveGeneralOption = effectiveRuleset.GeneralDiagnosticOption;
}
// Copy every rule in the ruleset and change the action if there's a stricter one.
foreach (var item in effectiveRuleset.SpecificDiagnosticOptions)
{
if (effectiveSpecificOptions.TryGetValue(item.Key, out var value))
{
if (IsStricterThan(item.Value, value))
{
effectiveSpecificOptions[item.Key] = item.Value;
}
}
else
{
effectiveSpecificOptions.Add(item.Key, item.Value);
}
}
}
// Finally, copy all the rules in the current ruleset. This overrides the actions
// of any included ruleset - therefore, no strictness check.
foreach (var item in _specificDiagnosticOptions)
{
if (effectiveSpecificOptions.ContainsKey(item.Key))
{
effectiveSpecificOptions[item.Key] = item.Value;
}
else
{
effectiveSpecificOptions.Add(item.Key, item.Value);
}
}
return new RuleSet(_filePath, effectiveGeneralOption, effectiveSpecificOptions.ToImmutableDictionary(), ImmutableArray<RuleSetInclude>.Empty);
}
/// <summary>
/// Get all the files involved in resolving this ruleset.
/// </summary>
private ImmutableArray<string> GetEffectiveIncludes()
{
var arrayBuilder = ImmutableArray.CreateBuilder<string>();
GetEffectiveIncludesCore(arrayBuilder);
return arrayBuilder.ToImmutable();
}
private void GetEffectiveIncludesCore(ImmutableArray<string>.Builder arrayBuilder)
{
arrayBuilder.Add(this.FilePath);
foreach (var ruleSetInclude in _includes)
{
var ruleSet = ruleSetInclude.LoadRuleSet(this);
// If we couldn't load the ruleset file, then there's nothing to do.
if (ruleSet == null)
{
continue;
}
// If this file has already been included don't recurse into it.
if (!arrayBuilder.Contains(ruleSet.FilePath, StringComparer.OrdinalIgnoreCase))
{
ruleSet.GetEffectiveIncludesCore(arrayBuilder);
}
}
}
/// <summary>
/// Returns true if the action1 is stricter than action2.
/// </summary>
private static bool IsStricterThan(ReportDiagnostic action1, ReportDiagnostic action2)
{
switch (action2)
{
case ReportDiagnostic.Suppress:
return true;
case ReportDiagnostic.Default:
return action1 == ReportDiagnostic.Warn || action1 == ReportDiagnostic.Error || action1 == ReportDiagnostic.Info || action1 == ReportDiagnostic.Hidden;
case ReportDiagnostic.Hidden:
return action1 == ReportDiagnostic.Warn || action1 == ReportDiagnostic.Error || action1 == ReportDiagnostic.Info;
case ReportDiagnostic.Info:
return action1 == ReportDiagnostic.Warn || action1 == ReportDiagnostic.Error;
case ReportDiagnostic.Warn:
return action1 == ReportDiagnostic.Error;
case ReportDiagnostic.Error:
return false;
default:
return false;
}
}
/// <summary>
/// Load the ruleset from the specified file. This ruleset will contain
/// all the rules resolved from the includes specified in the ruleset file
/// as well. See also: <seealso cref="GetEffectiveIncludesFromFile(string)" />.
/// </summary>
/// <returns>
/// A ruleset that contains resolved rules or null if there were errors.
/// </returns>
public static RuleSet LoadEffectiveRuleSetFromFile(string filePath)
{
var ruleSet = RuleSetProcessor.LoadFromFile(filePath);
return ruleSet.GetEffectiveRuleSet(new HashSet<string>());
}
/// <summary>
/// Get the paths to all files contributing rules to the ruleset from the specified file.
/// See also: <seealso cref="LoadEffectiveRuleSetFromFile(string)" />.
/// </summary>
/// <returns>
/// The full paths to included files, or an empty array if there were errors.
/// </returns>
public static ImmutableArray<string> GetEffectiveIncludesFromFile(string filePath)
{
var ruleSet = RuleSetProcessor.LoadFromFile(filePath);
if (ruleSet != null)
{
return ruleSet.GetEffectiveIncludes();
}
return ImmutableArray<string>.Empty;
}
#nullable enable
/// <summary>
/// Parses the ruleset file at the given <paramref name="rulesetFileFullPath"/> and returns the following diagnostic options from the parsed file:
/// 1) A map of <paramref name="specificDiagnosticOptions"/> from rule ID to <see cref="ReportDiagnostic"/> option.
/// 2) A global <see cref="ReportDiagnostic"/> option for all rules in the ruleset file.
/// </summary>
public static ReportDiagnostic GetDiagnosticOptionsFromRulesetFile(string? rulesetFileFullPath, out Dictionary<string, ReportDiagnostic> specificDiagnosticOptions)
{
return GetDiagnosticOptionsFromRulesetFile(rulesetFileFullPath, out specificDiagnosticOptions, null, null);
}
internal static ReportDiagnostic GetDiagnosticOptionsFromRulesetFile(string? rulesetFileFullPath, out Dictionary<string, ReportDiagnostic> diagnosticOptions, IList<Diagnostic>? diagnosticsOpt, CommonMessageProvider? messageProviderOpt)
{
diagnosticOptions = new Dictionary<string, ReportDiagnostic>();
if (rulesetFileFullPath == null)
{
return ReportDiagnostic.Default;
}
return GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, rulesetFileFullPath, diagnosticsOpt, messageProviderOpt);
}
private static ReportDiagnostic GetDiagnosticOptionsFromRulesetFile(Dictionary<string, ReportDiagnostic> diagnosticOptions, string resolvedPath, IList<Diagnostic>? diagnosticsOpt, CommonMessageProvider? messageProviderOpt)
{
Debug.Assert(resolvedPath != null);
var generalDiagnosticOption = ReportDiagnostic.Default;
try
{
var ruleSet = RuleSet.LoadEffectiveRuleSetFromFile(resolvedPath);
generalDiagnosticOption = ruleSet.GeneralDiagnosticOption;
foreach (var rule in ruleSet.SpecificDiagnosticOptions)
{
diagnosticOptions.Add(rule.Key, rule.Value);
}
}
catch (InvalidRuleSetException e)
{
if (diagnosticsOpt != null && messageProviderOpt != null)
{
diagnosticsOpt.Add(Diagnostic.Create(messageProviderOpt, messageProviderOpt.ERR_CantReadRulesetFile, resolvedPath, e.Message));
}
}
catch (IOException e)
{
if (e is FileNotFoundException || e.GetType().Name == "DirectoryNotFoundException")
{
if (diagnosticsOpt != null && messageProviderOpt != null)
{
diagnosticsOpt.Add(Diagnostic.Create(messageProviderOpt, messageProviderOpt.ERR_CantReadRulesetFile, resolvedPath, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.FileNotFound))));
}
}
else
{
if (diagnosticsOpt != null && messageProviderOpt != null)
{
diagnosticsOpt.Add(Diagnostic.Create(messageProviderOpt, messageProviderOpt.ERR_CantReadRulesetFile, resolvedPath, e.Message));
}
}
}
return generalDiagnosticOption;
}
}
}
| -1 |
dotnet/roslyn | 56,135 | Merge release/dev17.0 to main |
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| dotnet-bot | "2021-09-02T21:01:14Z" | "2021-09-02T21:01:27Z" | 99014d0615bf706b51c9e0aa325fc431a7d68711 | 7d328caf396488de8fc8a0ea4e39ae2e5824a48a | Merge release/dev17.0 to main.
This is an automatically generated pull request from release/dev17.0 into main.
Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯
## Troubleshooting conflicts
### Identify authors of changes which introduced merge conflicts
Scroll to the bottom, then for each file containing conflicts copy its path into the following searches:
- https://github.com/dotnet/roslyn/find/release/dev17.0
- https://github.com/dotnet/roslyn/find/main
Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts.
### Resolve merge conflicts using your local repo
Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub.
``` bash
git fetch --all
git checkout merges/release/dev17.0-to-main
git reset --hard upstream/main
git merge upstream/release/dev17.0
# Fix merge conflicts
git commit
git push upstream merges/release/dev17.0-to-main --force
```
| ./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingSymbolExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal static class UnitTestingSymbolExtensions
{
public static string GetSymbolKeyString(this ISymbol symbol, CancellationToken cancellationToken)
=> SymbolKey.Create(symbol, cancellationToken).ToString();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal static class UnitTestingSymbolExtensions
{
public static string GetSymbolKeyString(this ISymbol symbol, CancellationToken cancellationToken)
=> SymbolKey.Create(symbol, cancellationToken).ToString();
}
}
| -1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.