Is there a mechanism to pass a value to a lexer? (I'm working with C target in ANTLR 3)
Some other search results had suggested putting a function and var into the member area:
#members
{
bool read_flag;
void set_flag(bool b) {read_flag = b;}
}
however, that does not seem to work. The set_flag() is a global for the lexer, but not able to be called from outside
I want to be able to do something like this in the calling code:
//some input stream
pANTLR3_INPUT_STREAM input =
antlr3NewAsciiStringInPlaceStream((pANTLR3_UINT8)buf, len, NULL);
pmyLexer lxr = myLexerNew(input);
lxr->set_flag(true);
You can use the user pointer for that, which has been added exactly for this purpose:
lexer->pLexer->rec->state->userp = &context;
In my lexer I use this to store a reference to my RecognitionContext structure, which I then access via macros in my grammar:
#define PAYLOAD ((RecognitionContext*)RECOGNIZER->state->userp)->payload
#define SERVER_VERSION ((RecognitionContext*)RECOGNIZER->state->userp)->version
The structure is defined like this:
typedef struct {
long version;
void *payload;
...
} RecognitionContext;
Related
I'm looking at the algorithm for breadth-first sorting of a binary search tree, and there is a symbol used that I cannot understand. Funny enough, Google returns zero results.
// levelorder()
// q = empty queue
// q.enqueue(root)
// while not q.empty do
// node := q.dequeue() //Referring to this
// visit(node)
// if node.left != null then
// q.enqueue(node.left)
// if node.right != null then
// q.enqueue(node.right)
What is the operation being used here? I'm quite confused by this line.
The code you posted is pseudo code, and is not intended to be valid C++.
In C++, the assignment operator is =.
In other languages such as Ada, BCPL, Cecil, Dylan, E, Eiffel, Maple, Mathematica, Modula-3, Pascal, Pliant, Sather, Simula, Smalltalk, SML, the assignment operator is :=.
GNU make also uses := for a way of assigning.
Since the code you posted is a comment, it is not intended to be valid C++.
Here is a closer representation of the code you posted in valid C++:
#include <iostream>
#include <string>
#include <queue>
//A node might look like this:
struct Node{
Node* left;
Node* right;
};
//somewhere you have a node and a root
Node* node = new Node;
Node* root = new Node;
//a visit function is called in the pseudo code you posted
void visit(Node* node){
// ... code ...
return;
}
//here is what valid C++ that is similar to the pseudo code:
void levelorder(){
//empty queue
std::queue<Node*> q;
//add the root to the queue
q.push(root);
do {
visit(node);
if (node->left != nullptr){
q.push(node->left);
}
if (node->left != nullptr){
q.push(node->right);
}
}while(!q.empty());
return;
}
//I just added this main function so the whole code snippet compiles successfully
int main(){}
:= is assignment in pseudocode.
Or ADA. But that's kinda like psuedocode anyway.
It's inside a comment (per // prefix)... it's not compilable code and doesn't mean anything in C++.
It's not a C++ operator. It is used in some languages such as Pascal to mean the same thing as what an assignment = does.
See: Assignment operator (Computer science)
i have a Antlr generated Listener, and i call my tree walker to go through the tree from a parse function in another class. Looks like this:
public double calculate(){
ANTLRInputStream input = new ANTLRInputStream("5+2");
Lexer lexer = new Lexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
Parser parser = new Parser(tokens);
ParseTree tree = parser.calculate();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(new Listener(), tree);
return 0;
}
So the listener works perfect with the enter() and quit() Functions and prints the correct value in the end:
public void exitParser(ParserContext ctx) {
result = stack.peek();
System.out.println(result);
}
But i wanna receive the final value in my calculate() function to return it there. Since exitParser(...) is void i dont know how to deal with it.
With the visitor i was able to do it like that:
public double calculate(){
// ...
String value = new WRBVisitor().visit(tree);
return Double.parseDouble(value);
}
Hope someone understands my problem and knows a solution for it.
Best regards
As mentioned in the comments: a visitor might be a better option in your case. A visitor's methods will always return a value, which is what you seem to be after. That could be a Double if your expressions always evaluate to a numeric value, or some sort of home-grown Value that could represent a Double, Boolean, etc.
Have a look at my demo expression evaluator (using a visitor) on GitHub: https://github.com/bkiers/Mu
I am a developer in C-like languages (Java/JavaScript/C#) and I am attempting to convert some Objective-C code into Java.
For the most part, it is relatively straightforward but I have hit a stumbling block with the following bit of code:
typedef struct {
char *PAGE_AREA_ONE;
char *PAGE_AREA_TWO;
char *PAGE_AREA_THREE;
} CODES;
- (CODES*) getOpCode {
CODES *result = NULL;
result = malloc(sizeof(CODES));
result->PAGE_AREA_ONE = "\x1b\x1b\x1b";
result->PAGE_AREA_TWO = "\x2d\x2d\x2d";
result->PAGE_AREA_THREE = "\x40\x40";
return result;
}
What would the Java equivalent of this be? From what I can tell in other areas of the code, it is being used to store constants. But I am not 100% certain.
Thanks.
The typedef is just creating a structure that contains three string properties. The getOpCode method is apparently trying to create a new structure and assign values to those three properties. C# code would be:
public class Codes
{
public string PageAreaOne;
public string PageAreaTwo;
public string PageAreaThree;
}
public Codes GetCodes()
{
Codes result = new Codes();
result.PageAreaOne = "\x1b\x1b\x1b"; // three ESC characters
result.PageAreaTwo = "---";
result.PageAreaThree = "##";
return result;
}
The code in question is allocating a block of memory that the size of the CODES structure, filling it with some data, and returning a pointer to the new block. The data is apparently some operation codes (that is, instructions) for something, so perhaps the data is being sent to some other device where the instructions will be executed.
I want to write an llvm pass in order to make inline optimization therefore I call the method getAnalysis() but I have Segmentation fault.. Why? this is the code I am using:
using namespace llvm;
namespace {
struct MyInline : public ModulePass {
static char ID;
MyInline2() : ModulePass(ID) {}
virtual bool runOnModule(Module &M) {
errs() << "Hello2: ";
CallGraph &CG = getAnalysis<CallGraph>();
return false;
}
};
}
char MyInline::ID = 0;
static RegisterPass<MyInline> X("MyInline", "MyInline Pass", false, false);
To use getAnalysis(), you must first override getAnalysisUsage(), presumably to have the necessary analysis data set up for you.
getAnalysisUsage - This function should be overriden by passes that
need analysis information to do their job. If a pass specifies that it
uses a particular analysis result to this function, it can then use
the getAnalysis() function, below.
I've been wondering if there's an elegant way to derive a string from an enum in Objective-C or vanilla C. I'm currently using a switch statement like so:
switch (self.requestType)
{
case MSListRequest:
serverRequestType = #"List";
break;
case MSDetailsRequest:
serverRequestType = #"Details";
break;
case MSPurchaseRequest:
serverRequestType = #"PurchaseVolume";
break;
}
I'm curious if there's a cleaner way to derive strings than this.
-edit:
I'm also using the same enum elsewhere to interface to a different system that needs to map the same enums to a different set of strings.
There's no real nice way to do this. A very simple way is to create an array:
NSString *const ENUM_NAMES[] = {
#"List", #"Details", #"PurchaseVolume", ...
};
There are alternatives that use macros and some simple preprocessor hacks to define both the names and the enum itself from the same source. However, the resulting code is more difficult to read.
// some_enum.def
X(List),
X(Details),
X(PurchaseVolume)
// some_enum.h
enum {
#define X(x) x
#include "some_enum.def"
#undef X
};
// some_enum.c
char const *const ENUM_STRING[] = {
#define X(x) #x
#include "some_enum.def"
#undef X
};
I'm not sure of the best way to generate an NSString from the preprocessor, whether you can just stick an # in it or if it's better to use (NSString *)CFSTR(x).
When I need a bunch of code like this, I write a Python script to generate the code from a text file -- it generates GPerf output for converting strings to enum, and it generates the code for converting enum to string as well. Plain old C doesn't do reflection.