[antlr-interest] dynamically scoped attribute syntax

Terence Parr parrt at cs.usfca.edu
Wed Nov 23 10:15:57 PST 2005


I've changed my mind on this syntax too (yet more changes in my tests/ 
examples).  John Mitchell and others warned me that access to  
dynamically scoped stuff vs parameters etc... should be syntactically  
different.  I agreed but was loath to use an extra valuable char like  
@, which I note is now very useful for actions.

Anyway, imagine how things currently work:

function returns [String funcName]
scope {
	String name;
}
	: "function" ID {$name=$ID.text; $funcName=$name;} args body ;

body : ... {System.out.println("fname="+$function.name);} ;

Since function calls body, body can access the dynamic scope of  
function.  You must explicitly say was is visible with the scope  
notation.  Setting the dynamic value $name looks exactly like the  
parameter $funcName.  In the body rule, you must specifically  
reference the scope with the attribute as $function.name, but this  
still doesn't scream "the value is in another rule, dude!"

I am proposing to avoid use of a special '@' symbol or whatever in  
favor of the C++ style scope override "::".  THat said, I think the  
distinction should be sort of "local" vs "global" so that you can say  
$name inside the rule that defines the scope, but you must use  
$scope::name in an invoked rule like body:

function returns [String funcName]
scope {
	String name;
}
	: "function" ID {$name=$ID.text; $funcName=$name;} args body ;

body : ... {System.out.println("fname="+$function::name);} ;

What about shared global scopes?  I propose that we always have to  
use the fully-qualified scope in this case.

scope Symbols {
	List names;
}

classDef
scope Symbols;
init {
	$Symbols::names = new ArrayList();
}
	:	... {$Symbols::names.add("foo");} ;

body
scope Symbols;
init {
	$Symbols::names = new ArrayList();
}
	:	... {$Symbols::names.add("foo");} ;

Speaking of which, we need to be able to specify some init code in  
the global scope so we can avoid code duplication and do avoid  
forgetting.  I shied away from it originally because I didn't know  
what the syntax would look like and whether it would be useful.  This  
bit me hard yesterday when building an ANTLR+ST example.  How about  
just adding the init action into the scope?

scope Symbols {
	List names;
	init {
		$Symbols::names = new ArrayList();
	}
}

Actually I'll be using probably @init {...} (yet another tweak to the  
syntax...sorry! It's rapidly converging though I'm letting actual  
experience show me my faulty syntax).

That's a lot to think about but does anybody wanna comment?  I added  
to blog:

http://www.antlr.org/blog/antlr3/rewrite.tml

Ter


More information about the antlr-interest mailing list