This project has moved. For the latest updates, please go here.

Force String Literal to be Non-Empty

Oct 27, 2011 at 1:53 PM

We're trying to enforce a rule in our grammar that our string literals can't be empty.  It seems like we'll need to extend StringLiteral to do so, but we're not sure what methods (if any) we'll need to override.

Any advice would be greatly appreciated.  Thanks.

Oct 27, 2011 at 2:12 PM
Edited Oct 27, 2011 at 2:37 PM

After digging around, this seems easy enough.  Not sure if this is the preferred way of getting it done but it seems to work:


public class NonEmptyStringLiteral : StringLiteral {
	public NonEmptyStringLiteral(string name, string startEndSymbol, StringOptions options) : base(name, startEndSymbol, options) { }

	public override Token TryMatch(ParsingContext context, ISourceStream source) {
		var token = base.TryMatch(context, source);
		if (token != null && token.Value.ToString() == String.Empty) {
			return source.CreateErrorToken(string.Format(@"Empty string provided in expression: {0}", source.Text));
		return token;
Oct 27, 2011 at 3:27 PM

It's even easier, you don't have to subclass anything, just hook to ValidateToken on Terminal

Oct 27, 2011 at 4:03 PM

Cool, thanks.  Is there a way we can generate a similar error message from the token, since we won't have access to the source?

Oct 27, 2011 at 5:13 PM

dont' quite understand... source.Text is the entire input source file - I don't think this is the right thing you do in your initial snippet.

You can use methods of ValidateTokenEventArgs to set error message that will translate into error token. The error will refer to the position in the source code (that happens automatically), so when you double-click on error message in grammar Explorer you'll jump to error location.