Distinguish normal field access from compiler generated fields

Topics: Metadata Model
Aug 10, 2011 at 7:59 AM

Hi!

I'm trying to detect field usages inside of method bodies using CCI. For this I am currently using the

 Visit (IOperation operation)

method to get all "Ldfld", "Ldsfld", "Stfld", ... Operations that operate on Fields.

Unfortunately, when using Events and Properties, the compiler generates a lot of backing fields, etc like

<Property>k__BackingField
or
_event
or
CS$<>9__CachedAnonymousMethodDelegate1

and of course the Visit method is called each and every time one of these compiler generated fields are accessed.

 

Is there a way to distinguish these fields from normal fields?

I can get to the FieldDefinition from the Operation, but I can't seem to find something like the IsCompilerGenerated in the object tree.

 

Thanks for your help,

Martin

Coordinator
Aug 10, 2011 at 5:39 PM

Compilers are not very consistent about how they decorate compiler generated metadata. Fortunately the C# compiler seems reasonably sane: if the metadata definition can have custom attributes, such as the fields you mention above, then you can look for System.Runtime.CompilerServices.CompilerGeneratedAttribute in their Attributes collection.

In other cases, such as compiler generated locals, you can either just rely on the naming pattern "CS$..." or you can use the PDB information (via the Source Model method, ISourceLocationProvider.GetSourceNameFor).