0

I have some source code files where I would like to extract all the comments (C-style) and search them for a specific construct that I can then use in my source generator to make some additional code...

Example:

...
var v = something();//comment I just want to skip
//record Car (
//string CarId This is the CarId
//)
var whatever = ()=>{...};
/*record AnotherCar(
  string CarId This is the CarId
)*/
...

I have 2 problems. First, I cannot figure out how to skip all of the things but the comments, and Second how do I make it only return the records encoded therein? Alternatively, just search for the keywords and attempt to parse from there, but cannot figure that out either.

Cine
  • 4,255
  • 26
  • 46
  • You might want to look at existing languageparser to extract comments. In the c# world that might be Roslyn. For an idea how that looks see here https://www.tabsoverspaces.com/233623-checking-for-big-blocks-of-comments-in-code-ndepend-roslyn – Ralf Mar 19 '21 at 11:00
  • I gave up and did it with 2 regex instead. – Cine Mar 22 '21 at 13:30

1 Answers1

0

Old question, but the answer may help someone.

First, I cannot figure out how to skip all of the things but the comments, and Second how do I make it only return the records encoded therein?

You can use Linq query to parse the sequence and select only what you need as given below:

//Extract comments from CSharp code
    public static  IEnumerable<string> GetComments(string text)
        {
            CommentParser comment = new CommentParser();
            var separators = Parse.String("//").Or(Parse.String("/*"));
            Parser<string> comments =
                from _ in Parse.AnyChar.Except(separators).Many().Text()   //ignore
                from c in comment.AnyComment     // select
                select c;
            var result = comments.Many().Parse(text);            
            return result;
        }

Output result

comment I just want to skip
record Car (
string CarId This is the CarId
)
record AnotherCar(
  string CarId This is the CarId
)

Try it

M.Hassan
  • 10,282
  • 5
  • 65
  • 84