Skip to content

Commit

Permalink
Pass the location of the target field
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergio0694 committed Dec 12, 2024
1 parent e481f48 commit ef70aab
Showing 1 changed file with 27 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -392,9 +392,15 @@ void HandleSetAccessor(IPropertySymbol propertySymbol, PropertyFlags propertyFla
return;
}

// Find the parent field for the operation (we're guaranteed to only fine one)
if (context.Operation.Syntax.FirstAncestor<FieldDeclarationSyntax>()?.GetLocation() is not Location fieldLocation)
{
return;
}

fieldFlags.PropertyName = propertyName;
fieldFlags.PropertyType = propertyTypeSymbol;
fieldFlags.IsInitializerValid = true;
fieldFlags.FieldLocation = fieldLocation;
}, OperationKind.FieldInitializer);

// Finally, we can consume this information when we finish processing the symbol
Expand All @@ -421,14 +427,27 @@ void HandleSetAccessor(IPropertySymbol propertySymbol, PropertyFlags propertyFla
continue;
}

// Validate the combination of accessors and target field, and warn if that's the case
if (fieldFlags.PropertyName == pair.Key.Name &&
SymbolEqualityComparer.Default.Equals(fieldFlags.PropertyType, pair.Key.Type) &&
fieldFlags.IsInitializerValid)
// We only support rewriting when the property name matches the field being initialized.
// Note that the property name here is the literal being passed for the 'name' parameter.
if (fieldFlags.PropertyName != pair.Key.Name)
{
continue;
}

// Make sure that the 'propertyType' value matches the actual type of the property.
// We are intentionally not handling combinations of nullable value types here.
if (!SymbolEqualityComparer.Default.Equals(fieldFlags.PropertyType, pair.Key.Type))
{
return;
}

// Finally, check whether the field was valid (if so, we will have a valid location)
if (fieldFlags.FieldLocation is Location fieldLocation)
{
context.ReportDiagnostic(Diagnostic.Create(
UseGeneratedDependencyPropertyForManualProperty,
pair.Key.Locations.FirstOrDefault(),
[fieldLocation],
pair.Key));
}
}
Expand All @@ -448,7 +467,7 @@ void HandleSetAccessor(IPropertySymbol propertySymbol, PropertyFlags propertyFla
{
fieldFlags.PropertyName = null;
fieldFlags.PropertyType = null;
fieldFlags.IsInitializerValid = false;
fieldFlags.FieldLocation = null;

fieldFlagsStack.Push(fieldFlags);
}
Expand Down Expand Up @@ -518,8 +537,8 @@ private sealed class FieldFlags
public ITypeSymbol? PropertyType;

/// <summary>
/// Whether the initializer is valid.
/// The location of the target field being initialized.
/// </summary>
public bool IsInitializerValid;
public Location? FieldLocation;
}
}

0 comments on commit ef70aab

Please sign in to comment.