Reputation: 7429
I have seen Attributes and Reflection and now i know how to create and use reflection to see meta data of attribute but is it possible to make a standalone tool that can analyse a cs
file and extract attributes used ?
What am I trying to do?
Basically I am working on a tool which takes C# code
as input. Next step is to see what Attributes are used in that source code. Extract Intrinsic
and Custom Attributes
.
Probem?
this makes sense if you are using reflection
in same project in which your attributes
are defined, however I do not know in what direction I should move
to write a separate tool that can give you above extracted statics and meta data of attributes.
Some say I should use Regex
to extract the attributes in files where as other say I need to use Irony - .NET Language Implementation Kit
Furthermore
above work will result me to have an application that will be used for attributes(annotation) based Design Pattern Recovery
from Source Code
. I have less idea if Regex
would come to rescue or i need something like Reflection
. As Reflection is deals with runtime. I do not have to deal with run time. just static files analysis
Upvotes: 1
Views: 582
Reputation: 8462
If I properly understood your problem, you really need to parse your code. Regex won't help you, as beside parsing attributes you will need to parse class hierarchy. Reflection might do the trick, but you won't be able to show to the user the results. So, the best idea is to use any parser to get an expression tree from the source, and than investigate it.
If you don't know which parser to choose - I'd recommend Rosalyn, as it should be easiest for parsing C# code (it is designed especially for it). You can find an example for parsing here: http://blog.filipekberg.se/2011/10/20/using-roslyn-to-parse-c-code-files/
I think it should be really powerful and useful for your task
Upvotes: 2
Reputation: 427
Apparently I don't have enough reputation to comment, so I'm gonna have to say this as an answer.
Reflection deals with Runtime Type Information. It is a mechanism for finding out things about a type that you the programmer don't already know about (perhaps someone else is providing you a code library, and forgot to document it). Reflection will give you any information you need about the public contract of a class, including methods, properties, fields, attributes, and interfaces/classes inherited.
What you need however is a parser. A parser is a standard programming concept that processes files and extracts specific information. You are looking for information in code files, which are not runtime types yet, which means reflection has no information on them yet, however you have your eyes, since they're still code files. In the event your eyes are not sufficient (as I suspect their not if you asked the question) you need to write a parser. Extracting specific information from a cs file is pretty simple. And the regex for an attribute is: \[.+\]
Upvotes: 2