[antlr-interest] Lua long brackets

Don Reba don_reba at inbox.ru
Mon Jul 7 09:09:58 PDT 2008


Alright. I did the following:

-------------
ANTLR grammar
-------------

LONGSTRING
        : LONG_BRACKET
        ;

COMMENT
        : '--' LONG_BRACKET {Skip();}
        ;

fragment
LONG_BRACKET
@init {int n = 0;}
        : ('['('=' {++n;})*'[') ({IsLongBracketOpen(n)}? => .)* {MatchLongBracketClose(n);}
        ;


-------
C# code
-------

public override bool IsLongBracketOpen(int length)
{
	if (input.LA(1) != ']')
		return true;
	for (int i = 0; i != length; ++i)
	{
		if (input.LA(i + 2) != '=')
			return true;
	}
	if (input.LA(length + 2) != ']')
		return true;
	return false;
}

public override void MatchLongBracketClose(int length)
{
	var builder = new StringBuilder();
	builder.Append(']');
	for (int i = 0; i != length; ++i)
		builder.Append('=');
	builder.Append(']');
	Match(builder.ToString());
}


-----Original Message-----

> 
> What would be a good approach to implementation of long brackets in Lua? Here is the definition:
> 
> Literal strings can also be defined using a long format enclosed by long brackets. We define an opening long bracket of level n as an opening square bracket followed by n equal signs followed by another opening square bracket. So, an opening long bracket of level 0 is written as [[, an opening long bracket of level 1 is written as [=[, and so on. A closing long bracket is defined similarly; for instance, a closing long bracket of level 4 is written as ]====]. A long string starts with an opening long bracket of any level and ends at the first closing long bracket of the same level. Literals in this bracketed form may run for several lines, do not interpret any escape sequences, and ignore long brackets of any other level. They may contain anything except a closing bracket of the proper level.
> 


More information about the antlr-interest mailing list