JavaCC dump method to print AST - dump

I am using JavaCC to print an AST in a particular format.
I need it to be like this :
LetNode( Identier(X), ExprNode( PlusNode( IntegerLiteral(8), IntegerLiteral(2) )))
but I am getting:
Start(LetNode(Identifier(x)(ExprNode(IntegerLiteral(5)(PlusNode(IntegerLiteral(5)()))
I am using the dump method to print this:
public void dump(String prefix) {
System.out.print(toString(prefix));
System.out.print("(");
if (children != null) {
for (int i = 0; i < children.length; ++i) {
SimpleNode n = (SimpleNode)children[i];
if (n != null) {
n.dump(prefix +"");
}
}
System.out.print(")");
}
}
}
The output without any modification is :
Start
Sxl
Statement
VariableDecl
Identifier
Type
Expression
SimpleExpression
Term
Factor
Literal
IntegerLiteral
AdditiveOp
Term
Factor
Literal
IntegerLiteral
My method:
void AdditiveOp():
{}
{
(Plus() /*#Add(2)*/ | Minus() | Or())
}
void Plus():
{
}
{
(< PLUS >)
#PlusNode
}
If I remove the /* */ it does not work as it says it expects something else not +
Any help would be greatly appreciated!

The usual way to make an AST with JJT for an expression grammar is to do something like this
void AdditiveExpression() #void :
{ Token t ; }
{
MultiplicativeExpression()
( "+" MultiplicativeExpression() #Add(2)
| "-" MultiplicativeExpression() #Subtract(2)
)*
}

Related

Converting an infix notation into postfix by passing Array of string C#

static string[] infixToPostfix(string[] exp)
{
Stack<string> result = new Stack<string>();
Stack<string> stack = new Stack<string>();
stack.Push("#");
// iterating through each token
foreach (string s in exp)
{
if (isNumber(s))
{
result.Push(s);
}
else if (s == "(")
{
stack.Push(s);
}
else if (s == ")")
{
while ((stack.Peek() != "(") && (stack.Count > 0))
{
result.Push(stack.Peek());
stack.Pop();
}
stack.Pop();
}
else
{
while ((stack.Peek() != "#") && (getPriority(s) <= getPriority(stack.Peek())))
{
result.Push(stack.Peek());
stack.Pop();
}
stack.Push(s);
}
}
while (stack.Peek() != "#")
{
result.Push(stack.Peek());
stack.Pop();
}
return result.ToArray();
}
That is my alghorithm, i've got an assignment to create an expression tree based calculator and i've been succeded to built tree based on a right postfix notation, the problem is that i still cant figure out how to convert an array of string into a right postfix notation, can somebody please help me figure it out

C++ overloading operator, compiler doesn't see the operator

CMagazin.h
class CMagazin
{
char *m_nume;
list<CProdus*>List_produse;
public:
void printExpirabile( const char* data);
~CMagazin();
};
CMagazin.cpp
void CMagazin::printExpirabile(const char *xdata)
{
list<CProdus*>::iterator it;
for (it = List_produse.begin(); it != List_produse.end(); ++it)
{
CProdus* p = *it;
if (p->get_tip()=='A')
{
**if (p > xdata)**->this problem
}
}
}
CAliment.h
class CAliment :
public CProdus
{
char *m_expirare;
public:
bool operator >(const char*date);
~CAliment();
};
CAliment.cpp
bool CAliment::operator>(const char * date)
{
if (atoi(this->m_expirare) < atoi(date))
{
return 1;
}
else
{
return 0;
}
}
its about ">" operator.in CMagazin.cpp dont use my operator...i need help.
what can i do?I need ">" in CMagazin class. class CAliment its a class derived from CProdus.
Answer is: in Class CProdus the operator must be declared virtual, and in
CMagazin.cpp
void CMagazin::printExpirabile(const char *xdata)
{
list<CProdus*>::iterator it;
for (it = List_produse.begin(); it != List_produse.end(); ++it)
{
CProdus* p = *it;
if (p->get_tip()=='A')
{
if (p->operator>( xdata))-> make this!
{
p->print();
}
}
}
}
CProdus*p - is a pointer , need to have object for use this operator -> Try (*p)>xdata
void CMagazin::printExpirabile(const char *xdata)
{
list<CProdus*>::iterator it;
for (it = List_produse.begin(); it != List_produse.end(); ++it)
{
CProdus* p = *it;
if (p->get_tip()=='A')
{
if ((*p)>( xdata))-> make this!
{
p->print();
}
}
}
}

How to match Rust's `if` expressions in a macro?

I'm trying to write a macro that will rewrite certain Rust control flow, but I'm having difficulty matching an if expression. The problem is that the predicate is an expression, but an expr is not permitted to be followed by a block or {.
The best I've got is to use tt:
macro_rules! branch {
(
if $pred:tt
$r1:block
else
$r2:block
) => {
if $pred {
$r1
} else {
$r2
}
};
}
Which works fine with single-token or grouped predicates:
branch! {
if (foo == bar) {
1
} else {
2
}
}
But fails if the predicate was not grouped:
branch! {
if foo == bar {
1
} else {
2
}
}
error: no rules expected the token `==`
I also tried to use a repeating pattern of tt in the predicate:
macro_rules! branch {
(
if $($pred:tt)+
$r1:block
else
$r2:block
) => {
if $($pred)+ {
$r1
} else {
$r2
}
};
}
But this produces an error because it's now ambiguous whether subsequent block should match the tt too:
error: local ambiguity: multiple parsing options: built-in NTs tt ('pred') or block ('r1').
Is there a way to do this, or am I stuck with inventing special syntax to use in the macro?
You could use a TT muncher to parse the predicate:
macro_rules! branch {
{
if $($rest:tt)*
} => {
branch_parser! {
predicate = ()
rest = ($($rest)*)
}
};
}
macro_rules! branch_parser {
{
predicate = ($($predicate:tt)*)
rest = ({ $($then:tt)* } else { $($else:tt)* })
} => {
println!("predicate: {}", stringify!($($predicate)*));
println!("then: {}", stringify!($($then)*));
println!("else: {}", stringify!($($else)*));
};
{
predicate = ($($predicate:tt)*)
rest = ($next:tt $($rest:tt)*)
} => {
branch_parser! {
predicate = ($($predicate)* $next)
rest = ($($rest)*)
}
};
}
fn main() {
branch! {
if foo == bar {
1
} else {
2
}
}
}
Output:
predicate: foo == bar
then: 1
else: 2

Is it possible to de-duplicate if statements and their body in Rust, perhaps by using macros?

Say we have a large block:
mod module {
pub const fiz: u32 = (1 << 0);
// etc...
}
flag = {
if (var & module::fiz) != 0 { module::fiz }
else if (var & module::foo) != 0 { module::foo }
else if (var & module::bar) != 0 { module::bar }
else if (var & module::baz) != 0 { module::baz }
// .. there could be many more similar checks
};
With simply replacement macro its possible to do:
#define TEST(f) ((var) & (f)) != 0 { f }
Allowing:
flag = {
if TEST(module::fiz)
else if TEST(module::foo)
else if TEST(module::bar)
else if TEST(module::baz)
}
It seems Rust doesn't allow a macro to declare part of an if statement.
I managed to avoid repetition using assignment, but its quite ugly.
flag = {
let f;
if (var & {f = module::fiz; f }) != 0 { f }
else if (var & {f = module::foo; f }) != 0 { f }
else if (var & {f = module::bar; f }) != 0 { f }
else if (var & {f = module::baz; f }) != 0 { f }
};
Does Rust provide some convenient/elegant way to allow repetition in this case?
I don't think flag checking is the important part of this question, the issue is that you may want to repeat content in the check again in the body of an if statement, e.g.:
if (foo && OTHER_EXPRESSION) { do(); something_with(OTHER_EXPRESSION) }
else if (foo && SOME_EXPRESSION) { do(); something_with(SOME_EXPRESSION) }
I think you have an X/Y problem here, so I am going to solve this without using if/else.
What you seem to be doing is checking for the presence of a bit pattern, and prioritise the order in which said patterns are checked for (unclear if it matters, but let's assume it does).
So, let's do this the functional way:
let constants = [fiz, foo, bar, baz];
let flag = constants.iter().filter(|v| var & *v == **v).next();
And it just works, no macro or repetitive stuff.
If you want to use macros, you can write it like this:
mod module {
pub const fiz: u32 = (1 << 0);
pub const foo: u32 = (1 << 1);
pub const bar: u32 = (1 << 2);
pub const baz: u32 = (1 << 3);
}
macro_rules! check_bits {
([$($Constant:expr),*]) => {
|var: u32| {
$(if ($Constant & var) != 0 {
return $Constant;
})*
return 0;
}
}
}
fn main() {
let var = 5;
let checker = check_bits!([module::bar, module::fiz, module::foo, module::baz]);
assert_eq!(checker(var), module::bar);
println!("All OK");
}

Issue with getting 2 chars from string using indexer

I am facing an issue in reading char values.
See my program below. I want to evaluate an infix expression.
As you can see I want to read '10' , '*', '20' and then use them...but if I use string indexer s[0] will be '1' and not '10' and hence I am not able to get the expected result.
Can you guys suggest me something? Code is in c#
class Program
{
static void Main(string[] args)
{
string infix = "10*2+20-20+3";
float result = EvaluateInfix(infix);
Console.WriteLine(result);
Console.ReadKey();
}
public static float EvaluateInfix(string s)
{
Stack<float> operand = new Stack<float>();
Stack<char> operator1 = new Stack<char>();
int len = s.Length;
for (int i = 0; i < len; i++)
{
if (isOperator(s[i])) // I am having an issue here as s[i] gives each character and I want the number 10
operator1.Push(s[i]);
else
{
operand.Push(s[i]);
if (operand.Count == 2)
Compute(operand, operator1);
}
}
return operand.Pop();
}
public static void Compute(Stack<float> operand, Stack<char> operator1)
{
float operand1 = operand.Pop();
float operand2 = operand.Pop();
char op = operator1.Pop();
if (op == '+')
operand.Push(operand1 + operand2);
else
if(op=='-')
operand.Push(operand1 - operand2);
else
if(op=='*')
operand.Push(operand1 * operand2);
else
if(op=='/')
operand.Push(operand1 / operand2);
}
public static bool isOperator(char c)
{
bool result = false;
if (c == '+' || c == '-' || c == '*' || c == '/')
result = true;
return result;
}
}
}
You'll need to split the string - which means working out exactly how you want to split the string. I suspect you'll find Regex.Split to be the most appropriate splitting tool in this case, as you're dealing with patterns. Alternatively, you may want to write your own splitting routine.
Do you only need to deal with integers and operators? How about whitespace? Brackets? Leading negative numbers? Multiplication by negative numbers (e.g. "3*-5")?
Store the numerical value in a variable, and push that when you encounter an operator or the end of the string:
int num = 0;
foreach (char c in s) {
if (isOperator(c)) {
if (num != 0) {
operand.Push(num);
num = 0;
}
operator1.Push(c);
if (operand.Count == 2) {
Compute(operand, operator1);
}
} else {
num = num * 10 + (int)(c - '0');
}
}
if (num != 0) {
operand.Push(num);
}