Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
11d15c9
Add blank 'Roslyn4110' project
Sergio0694 Oct 23, 2024
e27359f
Fix naming conventions for all Roslyn projects
Sergio0694 Oct 23, 2024
a67a31d
Add 'global.json' file
Sergio0694 Oct 23, 2024
9c9061d
Update .targets for Roslyn setup
Sergio0694 Oct 23, 2024
f4fdb27
Pack new source generator in MVVM Toolkit
Sergio0694 Oct 23, 2024
c8e794b
Add logic to match partial properties
Sergio0694 Oct 23, 2024
76264f7
Update the generator to also work on properties
Sergio0694 Oct 23, 2024
3df53f3
Add 'RequiresCSharpLanguageVersionPreviewAnalyzer'
Sergio0694 Oct 23, 2024
fff5f91
Suppress warnings about removed rules
Sergio0694 Oct 23, 2024
41dc834
Add blank test project for new generator
Sergio0694 Oct 23, 2024
34a7c6f
Update '[ObservableProperty]' attribute
Sergio0694 Oct 23, 2024
bbd59ec
Add unit tests for new analyzer
Sergio0694 Oct 23, 2024
f970ba6
Move forwarded attributes gathering to helper
Sergio0694 Oct 24, 2024
e5b2802
Gather accessibility information from nodes
Sergio0694 Oct 24, 2024
17263fe
Generalizing the generated accessibility modifiers
Sergio0694 Oct 24, 2024
5f2ffcf
Don't emit an error for collisions for properties
Sergio0694 Oct 24, 2024
46d03e8
Update generation to account for properties
Sergio0694 Oct 24, 2024
52ad254
Fix a generator crash when used on properties
Sergio0694 Oct 24, 2024
8ca2f3c
Omit implicit accessibility modifiers
Sergio0694 Oct 24, 2024
db221ed
Update the targets of additional attributes
Sergio0694 Oct 24, 2024
f9f7771
Fix handling notify data error info
Sergio0694 Oct 24, 2024
5d37b73
Fix nullability for generated partial properties
Sergio0694 Oct 24, 2024
aabcd15
Add initial codegen tests for partial properties
Sergio0694 Oct 24, 2024
62c06f1
Add 'UseObservablePropertyOnPartialPropertyAnalyzer'
Sergio0694 Oct 24, 2024
6342b83
Add unit tests for new analyzer
Sergio0694 Oct 24, 2024
efa90a3
Add 'InvalidPropertyLevelObservablePropertyAttributeAnalyzer'
Sergio0694 Oct 24, 2024
767c05b
Add 'UnsupportedRoslynVersionForPartialPropertyAnalyzer'
Sergio0694 Oct 24, 2024
eea59fd
Fix handling of 'private protected' accessors
Sergio0694 Oct 24, 2024
162bab5
Add unit tests for invalid property declarations
Sergio0694 Oct 24, 2024
5e02b9a
Add 'UsePartialPropertyForObservablePropertyCodeFixer'
Sergio0694 Oct 25, 2024
9ba8f27
Add new helper for testing code fixers
Sergio0694 Oct 25, 2024
b98a658
Add unit test for new code fixer
Sergio0694 Oct 25, 2024
8cdebe0
Fix attributes handling, add unit tests
Sergio0694 Oct 25, 2024
e6a5c09
Add unit tests for comments in code fixer
Sergio0694 Oct 25, 2024
00ebe42
Support updating field references as well
Sergio0694 Oct 25, 2024
3453824
Improve messages in diagnostics when emitted on properties
Sergio0694 Oct 25, 2024
7b402b6
Add workaround for older Roslyn versions
Sergio0694 Oct 25, 2024
ca5d9dd
Fix a unit test on .NET Framework
Sergio0694 Oct 25, 2024
648788c
Fix last remaining unit test, and test regex
Sergio0694 Oct 25, 2024
9c9ff44
Set version.json to 8.4.0
Sergio0694 Oct 25, 2024
f75edab
Don't suggest partial properties for static fields
Sergio0694 Oct 25, 2024
0a81f27
Support field initializers in code fixer
Sergio0694 Oct 25, 2024
a7840b2
Don't run analyzers on generated code
Sergio0694 Oct 26, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add logic to match partial properties
  • Loading branch information
Sergio0694 committed Oct 23, 2024
commit c8e794beeefdf89c95770727f149da6a588d4f5d
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,66 @@ partial class ObservablePropertyGenerator
/// </summary>
internal static class Execute
{
/// <summary>
/// Checks whether an input syntax node is a candidate property declaration for the generator.
/// </summary>
/// <param name="node">The input syntax node to check.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <returns>Whether <paramref name="node"/> is a candidate property declaration.</returns>
public static bool IsCandidatePropertyDeclaration(SyntaxNode node, CancellationToken token)
{
// Matches a valid field declaration, for legacy support
static bool IsCandidateField(SyntaxNode node)
{
return node is VariableDeclaratorSyntax {
Parent: VariableDeclarationSyntax {
Parent: FieldDeclarationSyntax {
Parent: ClassDeclarationSyntax or RecordDeclarationSyntax, AttributeLists.Count: > 0 } } };
}

#if ROSLYN_4_11_0_OR_GREATER
// Matches a valid partial property declaration
static bool IsCandidateProperty(SyntaxNode node)
{
// The node must be a property declaration with two accessors
if (node is not PropertyDeclarationSyntax { AccessorList.Accessors: { Count: 2 } accessors } property)
{
return false;
}

// The property must be partial (we'll check that it's a declaration from its symbol)
if (!property.Modifiers.Any(SyntaxKind.PartialKeyword))
{
return false;
}

// The accessors must be a get and a set (with any accessibility)
if (accessors[0].Kind() is not (SyntaxKind.GetAccessorDeclaration or SyntaxKind.SetAccessorDeclaration) ||
accessors[1].Kind() is not (SyntaxKind.GetAccessorDeclaration or SyntaxKind.SetAccessorDeclaration))
{
return false;
}

return true;
}

// We only support matching properties on Roslyn 4.11 and greater
if (!IsCandidateField(node) && !IsCandidateProperty(node))
{
return false;
}
#else
// Otherwise, we only support matching fields
if (!IsCandidateField(node))
{
return false;
}
#endif

// The property must be in a type with a base type (as it must derive from ObservableObject)
return node.Parent?.IsTypeDeclarationWithOrPotentiallyWithBaseTypes<ClassDeclarationSyntax>() == true;
}

/// <summary>
/// Processes a given field.
/// </summary>
Expand Down Expand Up @@ -799,6 +859,60 @@ private static void GetNullabilityInfo(
semanticModel.Compilation.HasAccessibleTypeWithMetadataName("System.Diagnostics.CodeAnalysis.MemberNotNullAttribute");
}

/// <summary>
/// Tries to get the accessibility of the property and accessors, if possible.
/// </summary>
/// <param name="node">The input <see cref="PropertyDeclarationSyntax"/> node.</param>
/// <param name="symbol">The input <see cref="IPropertySymbol"/> instance.</param>
/// <param name="declaredAccessibility">The accessibility of the property, if available.</param>
/// <param name="getterAccessibility">The accessibility of the <see langword="get"/> accessor, if available.</param>
/// <param name="setterAccessibility">The accessibility of the <see langword="set"/> accessor, if available.</param>
/// <returns>Whether the property was valid and the accessibilities could be retrieved.</returns>
private static bool TryGetAccessibilityModifiers(
PropertyDeclarationSyntax node,
IPropertySymbol symbol,
out Accessibility declaredAccessibility,
out Accessibility getterAccessibility,
out Accessibility setterAccessibility)
{
declaredAccessibility = Accessibility.NotApplicable;
getterAccessibility = Accessibility.NotApplicable;
setterAccessibility = Accessibility.NotApplicable;

// Ensure that we have a getter and a setter, and that the setter is not init-only
if (symbol is not { GetMethod: { } getMethod, SetMethod: { IsInitOnly: false } setMethod })
{
return false;
}

// Track the property accessibility if explicitly set
if (node.Modifiers.Count > 0)
{
declaredAccessibility = symbol.DeclaredAccessibility;
}

// Track the accessors accessibility, if explicitly set
foreach (AccessorDeclarationSyntax accessor in node.AccessorList?.Accessors ?? [])
{
if (accessor.Modifiers.Count == 0)
{
continue;
}

switch (accessor.Kind())
{
case SyntaxKind.GetAccessorDeclaration:
getterAccessibility = getMethod.DeclaredAccessibility;
break;
case SyntaxKind.SetAccessorDeclaration:
setterAccessibility = setMethod.DeclaredAccessibility;
break;
}
}

return true;
}

/// <summary>
/// Gets a <see cref="CompilationUnitSyntax"/> instance with the cached args for property changing notifications.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result<PropertyInfo?> Info)> propertyInfoWithErrors =
context.ForAttributeWithMetadataNameAndOptions(
"CommunityToolkit.Mvvm.ComponentModel.ObservablePropertyAttribute",
static (node, _) => node is VariableDeclaratorSyntax { Parent: VariableDeclarationSyntax { Parent: FieldDeclarationSyntax { Parent: ClassDeclarationSyntax or RecordDeclarationSyntax, AttributeLists.Count: > 0 } } },
Execute.IsCandidatePropertyDeclaration,
static (context, token) =>
{
if (!context.SemanticModel.Compilation.HasLanguageVersionAtLeastEqualTo(LanguageVersion.CSharp8))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// See the LICENSE file in the project root for more information.

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp;

namespace CommunityToolkit.Mvvm.SourceGenerators.Extensions;

Expand Down Expand Up @@ -30,4 +32,30 @@ public static bool IsFirstSyntaxDeclarationForSymbol(this SyntaxNode syntaxNode,
syntaxReference.SyntaxTree == syntaxNode.SyntaxTree &&
syntaxReference.Span == syntaxNode.Span;
}

/// <summary>
/// Checks whether a given <see cref="SyntaxNode"/> is a given type declaration with or potentially with any base types, using only syntax.
/// </summary>
/// <typeparam name="T">The type of declaration to check for.</typeparam>
/// <param name="node">The input <see cref="SyntaxNode"/> to check.</param>
/// <returns>Whether <paramref name="node"/> is a given type declaration with or potentially with any base types.</returns>
public static bool IsTypeDeclarationWithOrPotentiallyWithBaseTypes<T>(this SyntaxNode node)
where T : TypeDeclarationSyntax
{
// Immediately bail if the node is not a type declaration of the specified type
if (node is not T typeDeclaration)
{
return false;
}

// If the base types list is not empty, the type can definitely has implemented interfaces
if (typeDeclaration.BaseList is { Types.Count: > 0 })
{
return true;
}

// If the base types list is empty, check if the type is partial. If it is, it means
// that there could be another partial declaration with a non-empty base types list.
return typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword);
}
}