Note that there are some explanatory texts on larger screens.

plurals
  1. POParsing percent expressions with antlr4
    text
    copied!<p>I'm trying to parse algebraic expressions with ANTLR4. One feature I tried to accomplish with my parser is the "intelligent" handling of percent expressions. </p> <p><strong>Edit:</strong> The goal is to make the calculation of discounts or tips in a restaurant easier. E.g. if you see an advert "30% off" you could enter "price - 30%" and get the correct result. Or in a restaurant you could enter the price of your meal plus 15% and get the sum you have to pay including a tip of 15%. But this interpretation should only occur if the expression looks like "expression1 (- or +) expression2". In all other cases the percent sign should be interpreted as usual. The Google Search box calculator behaves like that.<strong>/Edit</strong></p> <p><code>100-30%</code> should return <em>70</em><br> <code>100-(20+10)%</code> should also return <em>70</em><br> <code>3+(100-(20+10)%)</code> should return <em>73</em><br> <strong>but</strong><br> <code>5%</code> should return <em>0.05</em><br> <code>(5+5)%</code> should return <em>0.10</em></p> <p>My grammar looks like this:</p> <pre><code>expr: e EOF ; e: '-'a=e | '(' a=e ')' | a=e op=(ADD|SUB) b=e '%' | a=e op=(ADD|SUB) b=e | a=e'%' //**PERCENTRULE** | FLT ; ADD : '+' ; SUB : '-' ; FLT: [0-9]+(('.'|',')[0-9]+)?; NEWLINE:'\r'? '\n' ; WS : [ \t\n]+ -&gt; skip ; </code></pre> <p>For the expression <code>100-30%</code> I would <strong>expect</strong> the this tree:<br> <img src="https://i.stack.imgur.com/ZEQCz.png" alt="Expected parse tree for the expression &quot;100-30%&quot;"> </p> <p>But I get this:<br> <img src="https://i.stack.imgur.com/RNiOl.png" alt="parse tree for the expression &quot;100-30%"><br> How can I get the correct tree (without deleting PERCENTRULE)?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload