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 6871475
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T03:48:41+00:00 2026-05-27T03:48:41+00:00

I’m using ANTLR to parse strings of mathematical expressions and tag them using MathML.

  • 0

I’m using ANTLR to parse strings of mathematical expressions and tag them using MathML.

Right now I have the grammar below. Now I have three questions:

  1. The grammar allows for complete expressions like 2*(3+4). I want
    it to also allow incomplete expressions, e.g. 2*(3+. Being a
    complete newbie at ANTLR I have no idea how to accomplish this.
    Please point me to the right document or give an example.
  2. The location of the square root rule sqrt among the atomics seems
    to work but I’m pretty sure it should be somewhere in the exponent
    rule? Or should it?
  3. If I want to extend this grammar to also actually perform the
    calculation, can I somehow reuse it or do I have to copy and paste?

Any other comments or suggestions on my grammar is also appreciated, as my total experience with ANTLR is now about four hours.

grammar Expr;

parse returns [String value]
    :   stat+ {$value = $stat.value;}
    ;

stat returns [String value]
    :   exponent NEWLINE {$value = "<math>" + $exponent.value + "</math>";}
    |   NEWLINE
    ;

exponent returns [String value]
    :   e=expr {$value = $e.value;}
        (   '^' e=expr {$value = "<msup><mrow>" + $value + "</mrow><mrow>" + $e.value + "</mrow></msup>";}
        )*
    ;

expr returns [String value]
    :   e=multExpr {$value = $e.value;}
        (   '+' e=multExpr {$value += "<mo>+</mo>" + $e.value;}
        |   '-' e=multExpr {$value += "<mo>-</mo>" + $e.value;}
        )*
    ;

multExpr returns [String value]
    :   e=atom {$value = $e.value;} 
        (   '*' e=atom {$value += "<mo>*</mo>" + $e.value;}
        |   '/' e=atom {$value += "<mo>/</mo>" + $e.value;}
        )*
    ; 

atom returns [String value]
    :   INT {$value = "<mn>" + $INT.text + "</mn>";}
    |   '-' e=atom {$value = "<mo>-</mo>" + $e.value;}
    |   'sqrt[' exponent ']' {$value = "<msqrt><mrow>" + $exponent.value + "</mrow></msqrt>";}
    |   '(' exponent ')' {$value = "<mo>(</mo>" + $exponent.value + "<mo>)</mo>";}
    ;

INT :   '0'..'9'+ ;
NEWLINE:'\r'? '\n' ;
WS  :   (' '|'\t')+ {skip();} ;
  • 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-27T03:48:42+00:00Added an answer on May 27, 2026 at 3:48 am

    First a few remarks about your grammar:

    • you should give the rules unique labels for left- and right hand sides (e1=atom ('*' e2=atom ...);
    • you’ll probably want to create separate sqrt and [ tokens instead of 1 single sqrt[, otherwise input like "sqrt [ 9 ]" (a space between sqrt and [) would not be handles properly;
    • unary minus usually has a lower precedence than exponentiation.

    rickythefox wrote:

    The location of the square root rule sqrt among the atomics seems to work but I’m pretty sure it should be somewhere in the exponent rule? Or should it?

    No, it’s fine there: it should have the highest precedence. Talking of precedence, the usual precedence table (from lowest to highest) in your case would be:

    • addition & subtraction;
    • multiplication & division;
    • unary minus;
    • exponentiation;
    • parenthesized expressions (including function calls, like sqrt[...]).

    rickythefox wrote:

    The grammar allows for complete expressions like 2*(3+4). I want it to also allow incomplete expressions, e.g. 2*(3+. Being a complete newbie at ANTLR I have no idea how to accomplish this. Please point me to the right document or give an example.

    That’s tricky.

    I really only see one way: inside your stat rule, you first force the parser to look ahead in the token stream to check if there really is an expr ahead. This can be done using a syntactic predicate. Once the parser is sure there is an expr, only then parse said expression. If there isn’t an expr, try to match a NEWLINE, and if there’s also no NEWLINE, simply consume a single token other than NEWLINE (which must be a part of an incomplete expression!). (I will post a small demo below)

    rickythefox wrote:

    If I want to extend this grammar to also actually perform the calculation, can I somehow reuse it or do I have to copy and paste?

    ANTLR parser rules can return more than one object. That’s not really true of course since Java methods (which parser rule essentially are) can only return a single object. Parser rule return an object that holds references to more than one object. So you could do:

    stat returns [String str, double num]
      :  ...
      ;
    

    A demo

    Taking all my hints into account, a small working demo could look like this:

    grammar Expr;
    
    parse returns [String str, double num]
    @init{$str = "";}
      :  (stat 
         {
           $str += $stat.str;
           $num = $stat.num;
           if(!Double.isNaN($num)) {
             System.out.println($stat.text.trim() + " = " + $num);
           }
         })+
      ;
    
    stat returns [String str, double num]
      : (expr)=> expr NEWLINE      {$str = "<math>" + $expr.str + "</math>"; $num = $expr.num;}
      |          NEWLINE           {$str = ""; $num = Double.NaN;}
      |          ~NEWLINE          {$str = ""; $num = Double.NaN; System.err.println("Ignoring: " + $text);}
      ;
    
    expr returns [String str, double num]
      :  e1=multExpr       {$str = $e1.str; $num = $e1.num;}
         ( '+' e2=multExpr {$str += "<mo>+</mo>" + $e2.str; $num += $e2.num;}
         | '-' e2=multExpr {$str += "<mo>-</mo>" + $e2.str; $num -= $e2.num;}
         )*
      ;
    
    multExpr returns [String str, double num]
      :  e1=unaryExpr       {$str = $e1.str; $num = $e1.num;} 
         ( '*' e2=unaryExpr {$str += "<mo>*</mo>" + $e2.str; $num *= $e2.num;}
         | '/' e2=unaryExpr {$str += "<mo>/</mo>" + $e2.str; $num /= $e2.num;}
         )*
      ; 
    
    unaryExpr returns [String str, double num]
      :  '-' e=expExpr {$str = "<mo>-</mo>" + $e.str; $num = -1 * $e.num;}
      |  e=expExpr     {$str = $e.str; $num = $e.num;}
      ;
    
    expExpr returns [String str, double num]
      :  e1=atom       {$str = $e1.str; $num = $e1.num;}
         ( '^' e2=atom {$str = "<msup><mrow>" + $str + "</mrow><mrow>" + $e2.str + "</mrow></msup>"; $num = Math.pow($num, $e2.num);}
         )*
      ;
    
    atom returns [String str, double num]
      :  INT                 {$str = "<mn>" + $INT.text + "</mn>"; $num = Double.valueOf($INT.text);}
      |  'sqrt' '[' expr ']' {$str = "<msqrt><mrow>" + $expr.str + "</mrow></msqrt>"; $num = Math.sqrt($expr.num);}
      |  '(' expr ')'        {$str = "<mo>(</mo>" + $expr.str + "<mo>)</mo>"; $num = $expr.num;}
      ;
    
    INT     : '0'..'9'+;
    NEWLINE : '\r'? '\n';
    WS      : (' '|'\t')+ {skip();};
    

    (note that the (...)=> is this so-called syntactic predicate)

    You can test the parser generated from the grammar above with the following class:

    import org.antlr.runtime.*;
    
    public class Main {
      public static void main(String[] args) throws Exception {
        String src =
            "sqrt [ 9 ] \n" +  
            "1+2*3      \n" + 
            "2*(3+      \n" +
            "2*(3+42)^2 \n";
        ExprLexer lexer = new ExprLexer(new ANTLRStringStream(src));
        ExprParser parser = new ExprParser(new CommonTokenStream(lexer));
        ExprParser.parse_return returnValue = parser.parse();
        String mathML = returnValue.str;
        double eval = returnValue.num;
        // ...
      }
    }
    

    And if you now run the class above, you will see that the input

    sqrt [ 9 ]
    1+2*3
    2*(3+
    2*(3+42)^2
    

    will produce the following output:

    sqrt[9] = 3.0
    1+2*3 = 7.0
    Ignoring: 2
    Ignoring: *
    Ignoring: (
    Ignoring: 3
    Ignoring: +
    2*(3+42)^2 = 4050.0
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

this is what i have right now Drawing an RSS feed into the php,
I have a jquery bug and I've been looking for hours now, I can't
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I have thousands of HTML files to process using Groovy/Java and I need to
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I am reading a book about Javascript and jQuery and using one of the

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.