This is my image structure ANTLR 4 parsing tree gui:
This my listener rule enterDeclaration :
public void enterDeclaration(ADTCParser.DeclarationContext ctx) {
TokenStream tokens = parser.getTokenStream();
String initDeclarationList = tokens.getText(ctx.initDeclarationList());
}
to get tokens from initDeclarationList such as :
String initDeclarationList = tokens.getText(ctx.initDeclarationList());
String parameterDeclaration = ???
And my questions is "How to get tokens from sub-rule "parameterDeclaration" from " structure based on the image above ?
BTW, im using grammar C in ANTLR 4
this is link for grammar : https://github.com/antlr/grammars-v4/blob/master/c/C.g4
Like this:
ADTCParser.ParameterDeclarationContext context = parser.declaration()
.initDeclaratorList()
.initDeclarator()
.declarator()
.directDeclarator()
.parameterTypeList()
.parameterList()
.parameterDeclaration();
where parser.declaration() is your ADTCParser.DeclarationContext ctx parameter.
Related
I have a rule like this
top_clause returns [TopClause tc] :
tat = top_or_any_top
SP
e = expr
EP
{
var ln = getLineNum($tat);
$tc = new TopClauseExtant(ln, [...other params...]);
};
Note I'm trying to get the line number and pass it to the AST object I'm creating. getLineNum() is
public static LineNum getLineNum(ParserRuleContext pr) {
return new LineNum(pr.Start.Line);
}
getLineNum() may later get more from the token and return more, so I'm while I am getting an integer now (the pr.Start.Line) that may change and the return type LineNum (which currently just wraps an the int that is the line number) may hold more detail. Hence the getLineNum() func + LineNum class abstraction.
Unfortunately antlr complains: missing attribute access on rule reference tat in $tat. It basically wants $tat.<something> but I specifically want to pass the whole rule $tat so I can pick it apart more later.
Does that make sense? Any ideas on how to get what I want?
Answered by kaby76; use .ctx, as in $e.ctx
I am trying to parse this using ANTLR4 :
FSM
name type String
state type State
Relation
name type String
Mathieu
name type String
Someone helped me, corrected my grammar and i got this thanks to him
grammar Generator;
parse
: classToGenerate+ EOF;
classToGenerate
: name=Name attributes+;
attributes
: attribute=Name 'type' type=Name;
Name : [a-zA-Z]+;
Spaces : [ \t\r\n] -> skip;
I am using the parser generated by ANTLR4 this way :
GeneratorLexer l = new GeneratorLexer(new ANTLRInputStream(GeneratorFactory.class.getResourceAsStream("/example.generator")));
GeneratorParser p = new GeneratorParser(new CommonTokenStream(l));
p.addParseListener(new GeneratorBaseListener() {
#Override public void exitClassToGenerate(GeneratorParser.ClassToGenerateContext ctx) {
System.out.println(ctx.name.getText());
}
#Override
public void exitAttributes(GeneratorParser.AttributesContext ctx) {
System.out.println(ctx.type.getText());
System.out.println(ctx.attribute.getText());
}
});
Here is the result after executing
String
name
State
state
FSM
Where is the rest ?
It didn't print Relation name String // Mathieu name String
Any idea ?
EDIT : Okay it seems i was able to print the rest of the files but i've still have something to figure out.
When i do :
p.classToGenerate();
It parses the first structure which results in the print i had.
If i want to find another structure i need to do another
p.classToGenerate();
The thing is, how should i know how much structure i have to parse?
Imagine i have 5 or 20 same structures, how can i know it ?
Thanks !
In your grammar you've called your main rule parse. The rule classToGenerate only matches a single class. So in order to match all classes in the file, you should call p.parse();, not p.classToGenerate();.
I am trying to pass a string as value in the mapper, but getting error that it is not Writable. How to resolve?
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String TempString = value.toString();
String[] SingleRecord = TempString.split("\t");
//using Integer.parseInt to calculate profit
int Amount = Integer.parseInt(SingleRecord[7]);
int Asset = Integer.parseInt(SingleRecord[8]);
int SalesPrice = Integer.parseInt(SingleRecord[9]);
int Profit = Amount*(SalesPrice-Asset);
String ValueProfit = String.valueOf(Profit);
String ValueOne = String.valueOf(one);
custID.set(SingleRecord[2]);
data.set(ValueOne + ValueProfit);
context.write(custID, data);
}
Yahoo's tutorial says :
Objects which can be marshaled to or from files and across the network must obey a particular interface, called Writable, which allows Hadoop to read and write the data in a serialized form for transmission.
From Cloudera site :
The key and value classes must be serializable by the framework and hence must implement the Writable interface. Additionally, the key classes must implement the WritableComparable interface to facilitate sorting.
So you need an implementation of Writable to write it as a value in the context. Hadoop ships with a few stock classes such as IntWritable. The String counterpart you are looking for is the Text class. It can be used as :
context.write(custID, new Text(data));
OR
Text outValue = new Text();
val.set(data);
context.write(custID, outValue)
I case, you need specialized functionality in the value class, you may implement Writable (not a big deal after all). However seems like Text is just enough for you.
you havent set data in map function according to import text in above,and TextWritable is wrong just use Text as well.
Hi ,
I am facing very strange issue while parsing SOAP Response with Jaxb. I am not able to get complete list of tags while parsing .Stax parser is able to parse only one tag ,its not giving any error or exception.However if I try to format the xml response(which is stored in string) Everything works perfectly fine. Here is what I am doing to parse it :-
public void parseResponse(){
String response="<SOAP:Body><response><result><myTag></myTag><myTag></myTag>/result</response</SOAP:Body>";
getUnmarshalledObject(response,myTag,MyTag.class,"com.mylearning.parseXml");
}
public <T> List<T> getUnmarshalledObject( String response ,String TAG_TO_SEARCH ,Class<T> clazz , String basePkg)
throws XMLStreamException, JAXBException{
Reader reader = new StringReader(response);
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader xsr = xif.createXMLStreamReader(reader);
List<T> listOfUnmarshalledObjects = new ArrayList<T>();
while (xsr.hasNext()) {
if (xsr.getEventType() == XMLStreamReader.START_ELEMENT && TAG_TO_SEARCH.equals(xsr.getLocalName())) {
T unmarshalledObj = unmarshalXml( clazz ,xsr, basePkg);
listOfUnmarshalledObjects .add(unmarshalledObj);
}
xsr.next();
}
return listOfUnmarshalledObjects;
}
Here are different use cases of the problem:-
Case 1:- Input String response is unformatted.
Result :- listOfUnmarshalledObjects is 1.
Case 2:- Format response with response.replaceAll("><",">\n<");
Result:- listOfUnmarshalledObjects is 2.
Case 3 : Input String unformatted , just give space b/w </myTag><myTag>
Result: listOfUnmarshalledObjects is 2.
I tried my best to explain the question, please help me.
> Blockquote
I turns out that main culprit was missing else condition.
Parsing cursor was able to find the first block of ..tag but once it’s done with it , xsr.next is also getting executed in each iteration.
So in case where xml is not formatted :-
1. Parser finds the first complete block of and store it in list , now cursor is at next tag but before control goes to the next iteration xsr.next gets executed and moves cursor to the next immediate tag.
In case of formatted xml :-
1. There will be \n character between two continuous block \n so even if xsr.next gets executed at each iteration
it will just eat \n character and cursor will be right on track to parse next block of tag.
Here is the updated code with else condition :-
while (xsr.hasNext()) {
if (xsr.getEventType() == XMLStreamReader.START_ELEMENT && TAG_TO_SEARCH.equals(xsr.getLocalName())) {
T unmarshalledObj = unmarshalXml( clazz ,xsr, basePkg);
listOfUnmarshalledObjects .add(unmarshalledObj);
}else{
xsr.next();
}
}
I am very, very new to programming and I'm currently trying to learn it as fast as I can as a requirement of my research. I am trying to create a class from a text document. I have produced the code below, however it is returning errors in when I debug which I am unsure of how to fix.
List<Partitions> ListofPartitions = new List<Partitions>();
System.IO.StreamReader sr = new System.IO.StreamReader("C:\\Partitions.csv")
{
string line = sr.ReadToEnd();
Partitions Pname = new Partitions(line);
Partitions Plength = new Partitions(line);
Partitions Pdepth = new Partitions(line);
Partitions Pheight = new Partitions(line);
}
}
public class Partitions
{
string parameters;
public int Pname;
public double Plength;
public double Pdepth;
public double Pheight;
public Partitions(string inputLine)
{
parameters = inputLine;
string[]split = parameters.Split(',');
Pname = Convert.ToInt16(split[0]);
Plength = Convert.ToDouble(split[1]);
Pdepth = Convert.ToDouble(split[2]);
Pheight = Convert.ToDouble(split[3]);
}
Returning errors:
GA.xaml.cs(39,24): error CS1525: Invalid expression term 'string'
GA.xaml.cs(39,45): error CS1003: Syntax error, ',' expected
Any help would be much appreciated.
I would bet it is
string[]split = ...
there should be space between [] and split like this
string[] split = ...