namespace Sprache
{
///
/// Constructs customizable comment parsers.
///
public class CommentParser : IComment
{
///
///Single-line comment header.
///
public string Single { get; set; }
///
///Newline character preference.
///
public string NewLine { get; set; }
///
///Multi-line comment opener.
///
public string MultiOpen { get; set; }
///
///Multi-line comment closer.
///
public string MultiClose { get; set; }
///
/// Initializes a Comment with C-style headers and Windows newlines.
///
public CommentParser()
{
Single = "//";
MultiOpen = "/*";
MultiClose = "*/";
NewLine = "\n";
}
///
/// Initializes a Comment with custom multi-line headers and newline characters.
/// Single-line headers are made null, it is assumed they would not be used.
///
///
///
///
public CommentParser(string multiOpen, string multiClose, string newLine)
{
Single = null;
MultiOpen = multiOpen;
MultiClose = multiClose;
NewLine = newLine;
}
///
/// Initializes a Comment with custom headers and newline characters.
///
///
///
///
///
public CommentParser(string single, string multiOpen, string multiClose, string newLine)
{
Single = single;
MultiOpen = multiOpen;
MultiClose = multiClose;
NewLine = newLine;
}
///
///Parse a single-line comment.
///
public Parser SingleLineComment
{
get
{
if (Single == null)
throw new ParseException("Field 'Single' is null; single-line comments not allowed.");
return from first in Parse.String(Single)
from rest in Parse.CharExcept(NewLine).Many().Text()
select rest;
}
private set { }
}
///
///Parse a multi-line comment.
///
public Parser MultiLineComment
{
get
{
if (MultiOpen == null)
throw new ParseException("Field 'MultiOpen' is null; multi-line comments not allowed.");
else if (MultiClose == null)
throw new ParseException("Field 'MultiClose' is null; multi-line comments not allowed.");
return from first in Parse.String(MultiOpen)
from rest in Parse.AnyChar
.Until(Parse.String(MultiClose)).Text()
select rest;
}
private set { }
}
///
///Parse a comment.
///
public Parser AnyComment
{
get
{
if (Single != null && MultiOpen != null && MultiClose != null)
return SingleLineComment.Or(MultiLineComment);
else if (Single != null && (MultiOpen == null || MultiClose == null))
return SingleLineComment;
else if (Single == null && (MultiOpen != null && MultiClose != null))
return MultiLineComment;
else throw new ParseException("Unable to parse comment; check values of fields 'MultiOpen' and 'MultiClose'.");
}
private set { }
}
}
}