what does getType do in antlr4? - antlr4

This question is with reference to the Cymbol code from the book (~ page 143) :
int t = ctx.type().start.getType(); // in DefPhase.enterFunctionDecl()
Symbol.Type type = CheckSymbols.getType(t);
What does each component return: "ctx.type()", "start", "getType()" ? The book does not contain any explanation about these names.
I can "kind of" understand that "ctx.type()" refers to the "type" rule, and "getType()" returns the number associated with it. But what exactly does the "start" do?
Also, to generalize this question: what is the mechanism to get the value/structure returned by a rule - especially in the context of usage in a listener?
I can see that for an ID, it is:
String name = ctx.ID().getText();
And as in above, for an enumeration of keywords it is via "start.getType()". Any other special kinds of access that I should be aware of?

Lets disassemble problem step by step. Obviously, ctx is instance of CymbolParser.FunctionDeclContext. On page 98-99 you can see how grammar and ParseTree are implemented (at least the feeling - for real implementation please see th .g4 file).
Take a look at the figure of AST on page 99 - you can see that node FunctionDeclContext has a several children, one labeled type. Intuitively you see that it somehow correspond with function return-type. This is the node you retrieve when calling CymbolParser.FunctionDeclContext::type. The return type is probably sth like TypeContext.
Note that methods without 'get' at the beginning are usually children-getters - e.g. you can access the block by calling CymbolParser.FunctionDeclContext::block.
So you got the type context of the method you got passed. You can call either begin or end on any context to get first of last Token defining the context. Simply start gets you "the first word". In this case, the first Token is of course the function return-type itsef, e.g. int.
And the last call - Token::getType returns integral representation of Token.
You can find more information at API reference webpages - Context, Token. But the best way of understanding the behavior is reading through the generated ANTLR classes such as <GrammarName>Parser etc. And to be complete, I attach a link to the book.

Related

How to read visual studio code intellisense syntax hint, any document for operators?

VSC like VS gives out syntax/signature hint. I understand : means data type
myText: string // : means datatype of myText is string
myStuff: any // any means can be any data type.
sometimes hard to guess what the operators mean, for example the Node's request(),
my understanding is
const request means I can define any variable like const x=request(...) or var x=request(...).
request.RequestAPI means it's an API call.
options: defines this parameter is a typical object-like options in form of {...}
(request.UriOptions & request.CoreOptions) I understand the beginning and end parts, they must be enum of Uri and Core, but what is &? Does it mean I need to supply both Uri AND Core?
| does this pipe mean OR? If it is then it's duplicating the part before the pipe.
callback?: request.RequestCallback, so here I must provide a callback which will be typed (or functioning) as RequestCallback, but what is ?:?
Is there any document for these conventions?
I wanted to comment, because I don't know the complete answer, but here is some helpful information:
You are probably seeing this definition of DefinitelyTyped: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/request/index.d.ts#L29
Have a look at this to understand the definition file syntax: http://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html
And you can interpret the definition like this:
const request: there is a constant named request that implements the interface request.RequestAPI (which is also callable directly and then for that) takes arguments options of type (request.UriOptions & request.CoreOptions) | (request.UrlOptions & request.CoreOptions) and an optional parameter callback (hence the ? of type request.RequestCallback. The function returns a request.Request.
& usually mean and
A pipe | usually means or, there is no duplication URI vs URL
=> "returns"
You see request in front of everything because it's the namespace (my wording may be off here)
The definitions of UriOptions, UrlOptions, CoreOptions are buried a bit. I'm not a node user, so I don't know what you can pass to request.
For example UrlOptions can either be a string argument named "url" or a url (from require('url')). See https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/request/index.d.ts#L162

Erlang: Search through list for matching string

Hopefully this is what my problem is(having problem reading the error log that erlang prints). I'm trying to search through a list to find a matching string(PID from a client converted to a string) but it just results in a crash.
...
#7 ClientPID = pid_to_list(From),
#8 list:member(ClientPID, #server.users), % 'users' being a list in the record 'server'
...
The 'users' list in the 'server' record is just defined to users = [], if it helps.
Crash report:
** Reason for termination ==
** "{undef,[{list,member,[\"<0.568.0>\",2],[]}, {server,loop,2,[{file,\"server.erl\"},{line,8}]},
{genserver,loop,2,[{file,\"c:/Erlang/ServCli/genserver.erl\"}{line,13}]}]}"
Module is called lists not list. It's common mistake :)
And your argument are little off. You are using record, and proper usage look like this: VariableThatStoresRecord#record_name.filed_name. In your case it could be something like State#state.users (or just shorten State parameter in loop function to S if you don't like this double state).
What you are doing is actually a semantic suger, which returns on which element in record/tuple given field is stored (since all records are in fact tuples). In you case #state.users returns 2 (first element is record name, and I guess that users is first defined field in your record).
Regarding the error message. First thing is thing you get undef error. So it means that you are meking call to undefined function (which is quite common, since Erlang is dynamic language). Than you get list of tuples, which represents call-trace, from newest to oldest like this
[ { function call definition }
{ function call definition }
{ function call definition } ]
The first one is most interesting, since it is the call to undefined function. You can see that it is call to module list and function member. Other than that you can expect either actual arguments, or just arrity (those variables could be garbage collected already in erlang), and some information about function definition (like file and line number).
And from {list,member,[\"<0.568.0>\",2],[]} you can see that you are trying to call list:member function, with arguments "<0.568.0>" and 2. If you change your call to lists:member(ClientPID, Server#server.users) it should work.
Since most of the error messages are usually nested tuples/lists, which are hard to read if they are presented in one line. So what I do is copy them to my editor, split the one-liner into multiple lines, and than auto indent (emacs does this really great, and some editor can follow this lisp-like indention for Erlang).

Referencing an instance of a given class in sequence diagrams

I have to model a system where an object of the class Person will invoke the static method getBook(...) : Book on the class Book which will return an instance of a particular book.
How do you reference the book instance obtained by the operation?
As of now, I can think of two approaches, neither of which I have ever seen/used, which is why I am looking for the correct approach.
The first approach is to invoke methods directly on the book instance obtained, e.g. if the reference returned by getBook(...) : Book is named matchingBook, I would use matchingBook.doSomething(...), much like having a local variable.
The second way, which I find more in the line of sequence diagrams is to let the book instance returned by the operation appear with its own lifeline, e.g. next to the Book class, and referencing it with an arrow labeled doSomething(...).
However, with the second approach, it is not that obvious that this object is in fact the one returned by the operation.
The second approach is the correct. To show that you are pointing to the returned object (matchingBook), you can add the variable name to the title of the lifeline, like this:
The second approach is the correct one. Anytime you call operations on an object returned by a first operation, you can't do better than a name match between the result of the first call and the lifeline.
Anyway I don't really understand what you expect of the first way: where would you put matchingBook.doSomething(...)? on a arrow pointing which lifeline?

GroovyCodeVisitor says java method returns Object instead of actual type. No generics involved

I am using a GroovyCodeVisitor to check and complain if banned types are within a script. The visitor sees attempts to new Banned() but when visiting a method that returns Banned it only sees Object. Is this intentional or am i missing something. I just want to confirm the method is a plain vanilla declaration that returns plain old boring Banned and does not included generics in any form which should eliminate erasure as a potential source of the problem.
Before any jumps, I am not using SecureASTCompilationCustsomer because i am using a matcher to ban classes rather than simply adding black and white lists and other stuff which are supported by SecureASTCompilationCustomizer.
GroovyCodeVisitor is for visiting "code". That is for example the body of a Method. The return type of a method is stored in the MethodNode, not the code part you handle with your GroovyCodeVisitor. You could use ClassCodeVisitorSupport and override visitMethod(MethodNode mn) to then get the return type via mn.getReturnType() and give that into your checking code. Of course a method's return type is only for example "Banned" if declared so. If you use "def" for example the return type will be Object.

should it be allowed to change the method signature in a non statically typed language

Hypothetic and academic question.
pseudo-code:
<pre><code>
class Book{
read(theReader)
}
class BookWithMemory extends Book {
read(theReader, aTimestamp = null)
}
</pre></code>
Assuming:
an interface (if supported) would prohibit it
default value for parameters are supported
Notes:
PHP triggers an strict standards error for this.
I'm not surprised that PHP strict mode complains about such an override. It's very easy for a similar situation to arise unintentionally in which part of a class hierarchy was edited to use a new signature and a one or a few classes have fallen out of sync.
To avoid the ambiguity, name the new method something different (for this example, maybe readAt?), and override read to call readAt in the new class. This makes the intent plain to the interpreter as well as anyone reading the code.
The actual behavior in such a case is language-dependent -- more specifically, it depends on how much of the signature makes up the method selector, and how parameters are passed.
If the name alone is the selector (as in PHP or Perl), then it's down to how the language handles mismatched method parameter lists. If default arguments are processed at the call site based on the static type of the receiver instead of at the callee's entry point, when called through a base class reference you'd end up with an undefined argument value instead of your specified default, similarly to what would happen if there was no default specified.
If the number of parameters (with or without their types) are part of the method selector (as in Erlang or E), as is common in dynamic languages that run on JVM or CLR, you have two different methods. Create a new overload taking additional arguments, and override the base method with one that calls the new overload with default argument values.
If I am reading the question correctly, this question seems very language specific (as in it is not applicable to all dynamic languages), as I know you can do this in ruby.
class Book
def read(book)
puts book
end
end
class BookWithMemory < Book
def read(book,aTimeStamp = nil)
super book
puts aTimeStamp
end
end
I am not sure about dynamic languages besides ruby. This seems like a pretty subjective question as well, as at least two languages were designed on either side of the issue (method overloading vs not: ruby vs php).

Resources