I've been playing around with ANTLR4, trying to convert an ANTLR3 project.
I have generated a lexer, a parser and a visitor class from an ANLTR4 grammar coming from the official repository. In the visitor, I am calling one of my classes using the ctx available from the visitor:
myFunction(ctx.getChild(0))
Then, in myFunction, I want to retrieve the first child having a specific type, so I tried doing:
final ParseTree classNameElement =
(ParseTree) ((GrammarAST) node).getFirstChildWithType(MyParser.IDENTIFIER);
where node is the argument of myFunction, thus a ParseTree. getFirstChildWithType seems to be available only in GrammarAST, hence the cast.
I am getting the error: cannot be cast to org.antlr.v4.tool.ast.GrammarAST
So maybe this is not possible as is and I must have missed something, but I want to find the first child having a specific type from a ParseTree.
Thank you!
Notice that GrammarAST is in the ANTLR tool hierarchy. With a generated parse-tree, you should be dealing exclusively with the runtime.
To search a parse-tree node for a child of a given type:
public ParseTree getFirstChildOfType(ParseTree node, int tokentype) {
for (int idx = 0; idx < node.getChildCount(); idx++) {
ParseTree child = node.getChild(idx);
if (child instanceof TerminalNode) {
Token token = (Token) child.getPayload();
if (token.getType() == tokentype) {
return child;
}
}
}
return null;
}
This will get the first direct, i.e., child terminal, of the given type. Will need to recurse into non-TerminalNodes if the absolute first of type is desired.
If the latter is actually the desired function, there may be a better/more direct use of parse-tree walker to obtain the desired overall goal.
Related
I'm trying to apply ubiquitous language to my domain objects.
I want to convert a Data Transfer Object coming from a client into the domain object. The Aggregate's Constructor only accepts the required fields, and the rest of parameters should be passed using aggregate's API even when the Aggregate is being created(by say CreateAggregate command).
But the DTO to Aggregate mapping code becomes a bit messy:
if(DTO.RegistrantType == 0){
registrantType = RegistrantType.Person()
}
elseif(DTO.RegistrantType == 1){
registrantType = RegistrantType.Company()
}
//.....
//.....
var aggregate = new Aggregate(
title,
weight,
registrantType,
route,
callNumber,
)
//look at this one:
if(DTO.connectionType == 0){
aggregate.Route(ConnectionType.InCity(cityId))
}
elseif(DTO.connectionType == 1){
aggregate.Route(ConnectionType.Intercity(DTO.originCityId,DTO.DestinationCityId)
}
//..........
//..........
One thing I should mention is that this problem doesn't seem a domain specific problem.
How can I reduce these If-Else statements without letting my domain internals leakage, and with being sure that the aggregate(not a mapping tool) doesn't accept values that can invalide it's business rules, and with having the ubiquitous language applied?
Please don't tell me I can use AoutoMapper to do the trick. Please read the last part carefully.'
Thank you.
A typical answer would be to convert the DTO (which is effectively a message) into a Command, where the command has all of the arguments expressed as domain specific value types.
void doX(DTO dto) {
Command command = toCommand(dto)
doX(command)
}
void doX(Command command) {
// ...
aggregate.Route(command.connectionType)
}
It's fairly common for the toCommand logic use something like a Builder pattern to improve the readability of the code.
if(DTO.connectionType == 0){
aggregate.Route(ConnectionType.InCity(cityId))
}
elseif(DTO.connectionType == 1){
aggregate.Route(ConnectionType.Intercity(DTO.originCityId,DTO.DestinationCityId)
}
In cases like this one, the strategy pattern can help
ConnectionTypeFactory f = getConnectionFactory(DTO.connectionType)
ConnectionType connectionType = f.create(DTO)
Once that you recognize that ConnectionTypeFactory is a thing, you can think about building lookup tables to choose the right one.
Map<ConnectionType, ConnectionTypeFactory> lookup = /* ... */
ConnectionTypeFactory f = lookup(DTO.connectionType);
if (null == f) {
f = defaultConnectionFactory;
}
So why don't you use more inheritance
for example
class CompanyRegistration : Registration {
}
class PersonRegistraiton : Registration {
}
then you can use inheritance instead of your if/else scenario's
public class Aggregate {
public Aggregate (CompanyRegistration) {
registantType = RegistrantType.Company();
}
public Aggregate (PersonRegistration p) {
registrantType = RegistrantType.Person();
}
}
you can apply simmilar logic for say a setRoute method or any other large if/else situations.
Also, i know you don't want to hear it, you can write your own mapper (inside the aggegate) that maps and validates it's business logic
for example this idea comes from fluentmapper
var mapper = new FluentMapper.ThatMaps<Aggregate>().From<DTO>()
.ThatSets(x => x.title).When(x => x != null).From(x => x.title)
It isn't too hard to write your own mapper that allow this kind of rules and validates your properties. And i think it will improve readability
I am trying the code mentioned in question 11 from the URL.
I want to first give POS tagged input and second get sentiment analysis. First one I able to successfully get done. I able to print the tree and it looks fine. However second one returns me -1 (it should return me 4=very positive).
Please provide inputs/suggestions.
public static String test(){
try{
String grammer="/Users/lenin/jar/stanfordparser-master/stanford-parser/models/englishPCFG.ser.gz";
// set up grammar and options as appropriate
LexicalizedParser lp = LexicalizedParser.loadModel(grammer);
String[] sent3 = { "movie", "was","very", "good","." };
// Parser gets tag of second "can" wrong without help
String[] tag3 = { "PRP", "VBD", "RB", "JJ","." };
List sentence3 = new ArrayList();
for (int i = 0; i < sent3.length; i++) {
sentence3.add(new TaggedWord(sent3[i], tag3[i]));
}
Tree parse = lp.parse(sentence3);
parse.pennPrint();
int sentiment_score = RNNCoreAnnotations.getPredictedClass(parse);
System.out.println("score: "+sentiment_score);
}
catch(Exception e){
e.printStackTrace();
}
return "";
}
You're getting a value of -1 because you haven't run any sentiment analysis. You've only parsed the sentence for grammatical structure.
You can, of course, run the sentiment analyzer via code, but, unfortunately, at the moment there isn't an easy lower-level interface to do so. That would be a good thing to add sometime! You essentially need to duplicate the processing that happens in the class edu.stanford.nlp.pipeline.SentimentAnnotator:
Get a binarized tree from the parser (directly or by binarizing the tree returned)
Collapse unaries
Run the SentimentCostAndGradient class's forwardPropagateTree
I used the below to see how dart calls methods passed in to other methods to see what context the passed in method would/can be called under.
void main() {
var one = new IDable(1);
var two = new IDable(2);
print('one ${caller(one.getMyId)}'); //one 1
print('two ${caller(two.getMyId)}'); //two 2
print('one ${callerJustForThree(one.getMyId)}'); //NoSuchMethod Exception
}
class IDable{
int id;
IDable(this.id);
int getMyId(){
return id;
}
}
caller(fn){
return fn();
}
callerJustForThree(fn){
var three = new IDable(3);
three.fn();
}
So how does caller manager to call its argument fn without a context i.e. one.fn(), and why does callerJustForThree fail to call a passed in fn on an object which has that function defined for it?
In Dart there is a difference between an instance-method, declared as part of a class, and other functions (like closures and static functions).
Instance methods are the only ones (except for constructors) that can access this. Conceptually they are part of the class description and not the object. That is, when you do a method call o.foo() Dart first extracts the class-type of o. Then it searches for foo in the class description (recursively going through the super classes, if necessary). Finally it applies the found method with this set to o.
In addition to being able to invoke methods on objects (o.foo()) it is also possible to get a bound closure: o.foo (without the parenthesis for the invocation). However, and this is crucial, this form is just syntactic sugar for (<args>) => o.foo(<args>). That is, this just creates a fresh closure that captures o and redirects calls to it to the instance method.
This whole setup has several important consequences:
You can tear off instance methods and get a bound closure. The result of o.foo is automatically bound to o. No need to bind it yourself (but also no way to bind it to a different instance). This is way, in your example, one.getMyId works. You are actually getting the following closure: () => one.getMyId() instead.
It is not possible to add or remove methods to objects. You would need to change the class description and this is something that is (intentionally) not supported.
var f = o.foo; implies that you get a fresh closure all the time. This means that you cannot use this bound closure as a key in a hashtable. For example, register(o.foo) followed by unregister(o.foo) will most likely not work, because each o.foo will be different. You can easily see this by trying print(o.foo == o.foo).
You cannot transfer methods from one object to another. However you try to access instance methods, they will always be bound.
Looking at your examples:
print('one ${caller(one.getMyId)}'); //one 1
print('two ${caller(two.getMyId)}'); //two 2
print('one ${callerJustForThree(one.getMyId)}'); //NoSuchMethod Exception
These lines are equivalent to:
print('one ${caller(() => one.getMyId())}');
print('two ${caller(() => two.getMyId())}');
print('one ${callerJustForThree(() => one.getMyId())}';
Inside callerJustForThree:
callerJustForThree(fn){
var three = new IDable(3);
three.fn();
}
The given argument fn is completely ignored. When doing three.fn() in the last line Dart will find the class description of three (which is IDable) and then search for fn in it. Since it doesn't find one it will call the noSuchMethod fallback. The fn argument is ignored.
If you want to call an instance member depending on some argument you could rewrite the last example as follows:
main() {
...
callerJustForThree((o) => o.getMyId());
}
callerJustForThree(invokeIDableMember){
var three = new IDable(3);
invokeIDableMember(three);
}
I'll try to explain, which is not necessarily a strength of mine. If something I wrote isn't understandable, feel free to give me a shout.
Think of methods as normal objects, like every other variable, too.
When you call caller(one.getMyId), you aren't really passing a reference to the method of the class definition - you pass the method "object" specific for instance one.
In callerJustForThree, you pass the same method "object" of instance one. But you don't call it. Instead of calling the object fn in the scope if your method, you are calling the object fn of the instance three, which doesn't exist, because you didn't define it in the class.
Consider this code, using normal variables:
void main() {
var one = new IDable(1);
var two = new IDable(2);
caller(one.id);
caller(two.id);
callerJustForThree(one.id);
}
class IDable{
int id;
IDable(this.id);
}
caller(param){
print(param);
}
callerJustForThree(param){
var three = new IDable(3);
print(three.id); // This works
print(param); // This works, too
print(three.param); // But why should this work?
}
It's exactly the same concept. Think of your callbacks as normal variables, and everything makes sense. At least I hope so, if I explained it good enough.
I have the current method example:
public void MethodName(string param1,int param2)
{
object[] obj = new object[] { (object) param1, (object) param2 };
//Code to that uses this array to invoke dynamic methods
}
Is there a dynamic way (I am guessing using reflection) that will get the current executing method parameter values and place them in a object array? I have read that you can get parameter information using MethodBase and MethodInfo but those only have information about the parameter and not the value it self which is what I need.
So for example if I pass "test" and 1 as method parameters without coding for the specific parameters can I get a object array with two indexes { "test", 1 }?
I would really like to not have to use a third party API, but if it has source code for that API then I will accept that as an answer as long as its not a huge API and there is no simple way to do it without this API.
I am sure there must be a way, maybe using the stack, who knows. You guys are the experts and that is why I come here.
Thank you in advance, I can't wait to see how this is done.
EDIT
It may not be clear so here some extra information. This code example is just that, an example to show what I want. It would be to bloated and big to show the actual code where it is needed but the question is how to get the array without manually creating one. I need to some how get the values and place them in a array without coding the specific parameters.
Using reflection you can extract the parameters name and metadata but not the actual values :
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.testMethod("abcd", 1);
Console.ReadLine();
}
public void testMethod(string a, int b)
{
System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
StackFrame sf = st.GetFrame(0);
ParameterInfo[] pis = sf.GetMethod().GetParameters();
foreach (ParameterInfo pi in pis)
{
Console.Out.WriteLine(pi.Name);
}
}
}
I am attempting to create a ternary expression and I am getting the following error
"Type of conditional expression cannot be determined because there is no implicit conversion between LiveSubscription and DisconnectedSubscription"
The same logic works in an if statement, but I wanted to understand why it won't work in a ternary expression -
Here is the gist of what I am trying to do:
public interface IClientSubscription
{
bool TryDisconnect();
}
public class LiveSubscription : IClientSubscription
{
public bool TryDisconnect()
{
return true;
}
}
public class DisconnectedSubscription : IClientSubscription
{
public bool TryDisconnect()
{
return true;
}
}
public class ConnectionManager
{
public readonly IClientSubscription Subscription;
public ConnectionManager(bool IsLive)
{
// This throws the exception
Subscription = (IsLive)
? new LiveSubscription()
: new DisconnectedSubscription();
// This works
if (IsLive)
{
Subscription = new LiveSubscription();
}
else
{
Subscription = new DisconnectedSubscription();
}
}
}
I could always switch it to an if/else but I wanted to understand what is going wrong first!
You need to cast at least one of the operands to IClientSubscription:
Subscription = (IsLive)
? (IClientSubscription)new LiveSubscription()
: new DisconnectedSubscription();
The reason is that the ternary expression is of a certain type which is determined by the operands. Basically, it tries to cast the second operand to the type of the first or vice versa. Both fail here, because LiveSubscription isn't an DisconnectedSubscription and vice versa.
The compiler doesn't check whether both share a common base type.
Trying to answer your question in the comment:
No, ternary expressions are not some sort of object, but a ternary expression is the right hand part of an assignment. Each right hand part expression of an assignment has a certain type, otherwise it would be impossible to assign this expression to the variable on the left hand side.
Examples:
var x = Guid.NewGuid()
The right hand side expression (Guid.NewGuid()) is of type Guid, because the method NewGuid() returns a Guid.
var x = y.SomeMethod()
The right hand side expression is of the type of the return type of SomeMethod().
var x = IsLive ? "a" : 1
This is obviously invalid, isn't it? What type should x be? A string or an int?
This would lead to the exact same error message that you had with your code.
Your example a bit changed:
var subscription = (IsLive) ? new LiveSubscription()
: new DisconnectedSubscription();
Note the var before subscription, we now initialize a new variable, not an existing. I think even here, it is obvious what the problem is: What type should subscription be? LiveSubscription or DisconnectedSubscription? It can be neither, because depending on IsLive it needs to be either the one or the other.
About the comparison with if:
In your code where you assign a new LiveSubscription instance or a new DisconnectedSubscription instance to Subscription an implicit cast to IClientSubscription is occurring, because the compiler knows that Subscription is of type IClientSubscription and both LiveSubscription and DisconnectedSubscription can implicitly be converted to that interface.
The assignment with the ternary expression is a bit different, because the compiler first tries to evaluate the ternary expression and only afterwards it tries to assign it to Subscription. This means that the compiler doesn't know that the result of the ternary expression needs to be of type IClientSubscription.