Skip subtree in Listener ANTLR4 - listener

Is there any Way to skip the parsing of specific block while using Listener in ANTLR4 using enter or exit method.
I have read link here but unable to make it work.
Thank You!

By the time you're using the Listener pattern with your own Listener class, the input is already correctly lexed and parsed. Therefore, the answer to your question is no. When you're using the listener you're typically just walking the tree post-parse.
Does that mean all is lost though? Of course not. All you have to do is simply not code the Enter or Exit events for those constructs you want to "ignore." It's that easy.
As to if-else statements, I've always implemented them using the visitor pattern like this:
As to how to program an if statement, I'll give you a peek at they way I implement them:
public override MuValue VisitIfstmt(LISBASICParser.IfstmtContext context)
{
LISBASICParser.Condition_blockContext[] conditions = context.condition_block();
bool evaluatedBlock = false;
foreach (LISBASICParser.Condition_blockContext condition in conditions)
{
MuValue evaluated = Visit(condition.expr());
if (evaluated.AsBoolean())
{
evaluatedBlock = true;
Visit(condition.stmt_block());
break;
}
}
if (!evaluatedBlock && context.stmt_block() != null)
{
Visit(context.stmt_block());
}
return MuValue.Void;
}
Granted, this probably doesn't make much sense out of context, but rest assured it works. To see this in its full context, please visit Bart Kiers for an excellent example of grammar and implementation .

Related

How to implement custom Tcl event loop?

I saw a few other posts, but they were all in TCL and I'm looking to do this in my embedded interpreter using C++. The problem I'm having is that I need my own event loop so that I can read off the network, some where's where I can check a socket. I saw Tcl_SetMainLoop() but not sure how it works.
My app is structured like the following.
int Tcl_AppInit(Tcl_Interp *interp)
{
if (Tcl_Init(interp) == TCL_ERROR)
return TCL_ERROR;
if (MyTcl_Init(interp) == TCL_ERROR)
return TCL_ERROR;
return TCL_OK;
}
int main(int argc, char* argv[])
{
//...
Tcl_Main(argc, argv, Tcl_AppInit);
/* Replaced Tcl_Main for this, didn't work.
Tcl_SetMainLoop([]() {
Tcl_DoOneEvent(0);
});
*/
}
I do not use Tk. Any thoughts on how to set a custom event loop?
The classic example of how to an event loop in Tcl is the vwait command. The core of that is this code:
done = 0;
foundEvent = 1;
while (!done && foundEvent) {
foundEvent = Tcl_DoOneEvent(TCL_ALL_EVENTS);
if (Tcl_Canceled(interp, TCL_LEAVE_ERR_MSG) == TCL_ERROR) {
break;
}
if (Tcl_LimitExceeded(interp)) {
Tcl_ResetResult(interp);
Tcl_SetObjResult(interp, Tcl_NewStringObj("limit exceeded", -1));
break;
}
}
The done variable is set by a callback when the end-loop-triggering event happens (a write on a variable), and the clauses with cancellation and limit management can probably be omitted in your own code. The cut-down bare-bones version is:
done = 0;
foundEvent = 1;
while (!done && foundEvent) {
foundEvent = Tcl_DoOneEvent(TCL_ALL_EVENTS);
}
Yes, it delegates most of its work to Tcl_DoOneEvent (which is part of the notifier layer). If you want to plug your fancy socket into that, the easiest way is to write your own event handler and install it with Tcl_CreateFileHandler or Tcl_CreateChannelHandler; probably the former, assuming you're not on Windows (as it relies on the POSIX concept of a file descriptor) and on Windows you need to do the work to make a channel type (because the underlying notifier system works a little differently on that platform under the hood). Once you do that, you can use the standard event loop; your custom handler (in C or C++) will be called at the right time. (The ClientData arguments are really just an arbitrary pointer that will be passed uninterpreted through Tcl to your callback; you'll probably cast that back to a pointer to the real object type as the first thing you do in the callback; that's what everyone else does.)
It's possible to install your own low-level event handling engine with Tcl_SetNotifier — call it very early if you want to do that — but it is usually a bad idea. In particular, you don't need a custom event loop to just handle a custom socket type. A better use for a custom event loop is integrating Tk with some other GUI toolkit, but that's a far more complex use case!

Junit testing in java for void methods

How to write test case for this function in a binary search tree ?
void insert(String key){
root=insertRec(root,key);
}
Your method does something. It obviously changes the state of the object by inserting a rec(ord?) and somehow re-evaluating what the root is. So, to test it, you should somehow be able to determine the new state, for example...
public void insert_should_create_new_record_and_set_root() {
assertThat( myObject.getRec( originalRoot) ).isNull();
Object originalRoot = myObject.getRoot();
myObject.insert("xyz");
assertThat( myObject.getRec( originalRoot) ).isEqualTo( "xyz"); // using AssertJ style here
assertThat( myObject.getRoot().value() ).isNotEqualTo( originalRoot );
}
If, on the other hand, you have no way to check the state from the outside, then you'll have a problem. But somehow your class has to communicate to the outside, hasn't it? If you really think that you cannot check the new state, then you'll have to provide more code of this class, as this answer is, of course, very general (which means "guessing", here).

How to use the result of this method?

I'm developing in AS3 for the Doubleclick platform, though this may be more of a generic programming question.
I am trying to determine whether a video is playing or paused. Doubleclick has the following method:
videoController.getPlayerState()
Which when traced, returns either:
[object PlayingState]
or
[object PausedState]
My question is, how do I do work with that result? I just want to turn it into a boolean that I can use in an if statement to call, or not call, another function.
Like:
if([object PlayingState]){ doSomething(); } else {doNothing(); }
Except that you can't do that, because whenever I try to do anything like that I get an error!! And I can't figure out how you're supposed to do this.
I'm sure this is super-basic. Can anyone enlighten me??
Thanks so much!!
Look at this doc PlayingState
The PlayingState and PausedState class extends AbstractPlayerState,
And AbstractPlayerState get a function getStateType said like this
getStateType() : String
Returns the player state as a string such as "InitialState","BufferingState",
"LoadingState", "PausedState", "PlayingState", or "StoppedState".
It is encouraged to use videoController.getPlayerState() and match against the
relevant class using instanceof or is.
So I think you can do like this
var state:AbstractPlayerState = videoController.getPlayerState();
if (state is PlayingState) {
} else if ( state is PausedState) {
}

Haxe, differentiate anonymous function at runtime

I'm trying to differentiate anonymous functions like:
function() { trace("WOO"); }
from the other ones ('named'?) like
var _FUNC:Dynamic = function() { trace("WOO"); }
The reason I want to do that is because I can't compare between two anonymous functions, because they are two different ones.
To help me make things clearer, consider the following quick example.
var _TEST:Dynamic = function(a:Dynamic):String {
var _TESTA:Dynamic = function() { trace("WOO"); };
var _TESTB:Dynamic = _FUNC;
return (a == _TESTA) + ", " + (a == _TESTB);
}
If I run _TEST(_FUNC);, I'll get back "false, true". Even though they are the same function, they are NOT the same object.
Is there a way to compare those such that functions that they are the same if they perform the same task?
Is there a way to serialize functions? So that maybe I can compare the serialized representations and see if they share the same 'code'.
A few clarifications:
The first two samples you have posted are virtually identical. The only difference is that you have assigned the second to a static var. You could have used a static function directly with the main difference that in that case the function is not changeable If you want to make it so you should add the dynamic modifier.
Starting from the latest version you can have local named functions:
static f() { function a() { trace("hi"); }; a() }
To properly compare methods you should use Reflect.compareMethods(). Sometimes Haxe creates closures around functions and that can break equality.
You can compare function references but not the function bodies. So the answer is no, you can't compare function that are generated in different statements but do the same thing.
You cannot serialize functions.
You can maybe find some platform specific way to deal with this situation or Macro may apply too (to create function signatures) but I think it is easier to redesign your code. Another option is to adopt a lib like hscript for those calls that need to be comparable and serializable.

Can a Flex 3 method detect the calling object?

If I have a method such as:
private function testMethod(param:string):void
{
// Get the object that called this function
}
Inside the testMethod, can I work out what object called us? e.g.
class A
{
doSomething()
{
var b:B = new B();
b.fooBar();
}
}
class B
{
fooBar()
{
// Can I tell that the calling object is type of class A?
}
}
Sorry the answer is no (see edit below). Functions received a special property called arguments and in AS2 it used to have the property caller that would do roughly what you want. Although the arguments object is still available in AS3 the caller property was removed from AS3 (and therefore Flex 3) so there is no direct way you can do what you want. It is also recommeded that you use the [...rest parameter](http://livedocs.adobe.com/flex/3/langref/statements.html#..._(rest)_parameter) language feature instead of arguments.
Here is a reference on the matter (search for callee to find the relevant details).
Edit: Further investigation has shown that it is possible to get a stack trace for the current executing function so if you are lucky you can do something with that. See this blog entry and this forum post for more details.
The basic idea from the blog post is you throw an Error and then catch it immediately and then parse the stack trace. Ugly, but it may work for you.
code from the blog post:
var stackTrace:String;
try { throw new Error(); }
catch (e:Error) { stackTrace = e.getStackTrace(); }
var lines:Array = stackTrace.split("\n");
var isDebug:Boolean = (lines[1] as String).indexOf('[') != -1;
var path:String;
var line:int = -1;
if(isDebug)
{
var regex:RegExp = /at\x20(.+?)\[(.+?)\]/i;
var matches:Array = regex.exec(lines[2]);
path = matches[1];
//file:line = matches[2]
//windows == 2 because of drive:\
line = matches[2].split(':')[2];
}
else
{
path = (lines[2] as String).substring(4);
}
trace(path + (line != -1 ? '[' + line.toString() + ']' : ''));
Is important to know that stackTrace is only available on the debugger version of Flash Player. Sorry! :(
I'd second the idea of explicitly passing a "callingObject" parameter. Unless you're doing really tricky stuff, it should be better for the caller to be able to supply the target object, anyway. (Sorry if this seems obvious, I can't tell what you're trying to accomplish.)
To add to the somewhat ambiguous first paragraph of James: the arguments property is still available inside a Function object, but the caller property has been removed.
Here's a link to the docs: http://livedocs.adobe.com/flex/3/langref/arguments.html
This might help someone, I'm not sure... but if one is using an Event this is possible using the e.currentTarget as follows:
private function button_hover(e:Event):void
{
e.currentTarget.label="Hovering";
}