Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6602443
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T18:52:40+00:00 2026-05-25T18:52:40+00:00

I’m trying to write a grammar to evaluate expressions. I’ve started with the given

  • 0

I’m trying to write a grammar to evaluate expressions.
I’ve started with the given example on the ANTLR website (it manage +,- and *).
I added the division. But I would like to notify user if he tries to divide by 0.
Moreover, I would like to add the pow in my evaluator (with an higher precedence than multiply and divide. (for example 2^3=8).
Hope it’s understandable.
Here’s my grammar Expr.g :

grammar Expr;

@header {  
import java.util.HashMap;  
}

@members {  
/** Map variable name to Integer object holding value */  
HashMap memory = new HashMap();  
}

prog:   stat+ ;

stat:   expr NEWLINE {System.out.println($expr.value);}  
    |   ID '=' expr NEWLINE  
        {memory.put($ID.text, new Integer($expr.value));}  
    |   NEWLINE  
    ;

expr returns [int value]
    :   e=multExpr {$value = $e.value;}
        ((   '+' e=multExpr {$value += $e.value;}
        |   '-' e=multExpr {$value -= $e.value;}
        ))*
    ;

multExpr returns [int value]
    :   e=atom {$value = $e.value;} 
        ('*' e=atom {$value *= $e.value;}
        |'/' e=atom {if (e != 0) $value /= $e.value; 
                else System.err.println("Division par 0 !");}
        )*
    ; 

atom returns [int value]
    :   INT {$value = Integer.parseInt($INT.text);}
    |   ID
        {
        Integer v = (Integer)memory.get($ID.text);
        if ( v!=null ) $value = v.intValue();
        else System.err.println("Variable indéfinie "+$ID.text);
        }
    |   '(' expr ')' {$value = $expr.value;}
    ;

ID  :   ('a'..'z'|'A'..'Z')+ ;
INT :   '0'..'9'+ ;
NEWLINE:'\r'? '\n' ;
WS  :   (' '|'\t')+ {skip();} ;

Thanks in advance.
Ed.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T18:52:41+00:00Added an answer on May 25, 2026 at 6:52 pm

    eouti wrote:

    I added the division. But I would like to notify user if he tries to divide by 0.

    Inside your multExpr rule, you shouldn’t do if (e != 0) ..., but you should access e‘s value attribute instead. Also, the left-hand-side of your expression is called e while the right-hand-side is also called e. You’d better give them unique names:

    multExpr returns [int value]
        :   e1=atom {$value = $e1.value;} 
            ( '*' e2=atom {$value *= $e2.value;}
            | '/' e2=atom {if ($e2.value != 0) $value /= $e2.value; 
                           else System.err.println("Division par 0 !");}
            )*
        ; 
    

    But, do you really want to warn the user? After this warning, the calculation will just continue at the moment. IMO, you should just let the exception be thrown.

    eouti wrote:

    I would like to add the pow in my evaluator (with an higher precedence than multiply and divide.

    Then add a powExpr rule in between multExpr and atom and let multExpr use this powExpr rule instead of the atom rule:

    multExpr returns [int value]
        :   e1=powExpr       {...} 
            ( '*' e2=powExpr {...}
            | '/' e2=powExpr {...}
            )*
        ;  
    
    powExpr returns [int value]
        :   atom      {...} 
            ('^' atom {...} 
            )*
        ;
    
    atom returns [int value]
        :   INT          {...}
        |   ID           {...}
        |   '(' expr ')' {...}
        ;
    

    (powExpr doesn’t literally need to be in between these rules of course…)

    Also, you might want to change returns [int value] into returns [double value], especially since you’re using division.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I used javascript for loading a picture on my website depending on which small
Seemingly simple, but I cannot find anything relevant on the web. What is the
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
i got an object with contents of html markup in it, for example: string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.