This is part of a series of posts documenting Sprache:

This post covers CommentParser and Commented, which are helpers for parsing single and multi-line comments.

CommentParser

The CommentParser class is a helper for parsing comments with members SingleLineComment, MultiLineComment and AnyComment for parsing different comment types, for example to parse XML comments

1
2
3
4
5
6
var comment = new CommentParser("<!--", "-->", "\r\n");

Assert.Equal(" Commented text ", comment.AnyComment.Parse("<!-- Commented text -->"));

// No single-line comment header was defined, so this throws an exception
Assert.Throws<ParseException>(() => comment.SingleLineComment);

The default constructor creates a comment parser for parsing C style comments, and is equivalent to new CommentParser("//", "/*", "*/", "\n")

1
2
3
4
var comment = new CommentParser();

Assert.Equal("single-line comment", comment.SingleLineComment.Parse("//single-line comment"));
Assert.Equal("multi-line comment", comment.MultiLineComment.Parse("/*multi-line comment*/"));

Commented

Constructs a parser that consumes a whitespace and all comments parsed by the commentParser.AnyComment parser, but parses only one trailing comment that starts exactly on the last line of the parsed value.

  • Parser<ICommented<T>> Commented<T>(this Parser<T> parser, IComment commentParser = null)

If a comment parser is not supplied then the default comment parser (which parses C style comments) is used. The return ICommented type has properties for accessing the leading and trailing comments, as well as the element parsed by parser.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var commented = Parse.Identifier(Parse.Letter, Parse.LetterOrDigit)
    .Token().Commented(new CommentParser {NewLine = Environment.NewLine});

var parsed = commented.Parse(@"
/* Test comment */
// B
foo // C
// D
");

Assert.Equal(new[] {" Test comment ", " B"}, parsed.LeadingComments);
Assert.Equal("foo", parsed.Value);
Assert.Equal(new[] {" C"}, parsed.TrailingComments.ToArray());

This parser is used extensively by the ApexSharp parser.