help-bison
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: are there user defined infix operators?


From: Hans Åberg
Subject: Re: are there user defined infix operators?
Date: Thu, 8 Nov 2018 21:58:12 +0100

> On 8 Nov 2018, at 20:21, Uxio Prego <address@hidden> wrote:
> 
>> You can write general rules say for prefix, infix, and postfix operators, 
>> [...]
> 
> For simplicity I would be happy to consider only infix operators.

For fixity overloads (same name but different fixity), one can have the 
overloads used in C/C++: prefix and postfix (as in ++), or prefix and infix (as 
in -), but not infix and postfix. This requires extra processing, keeping track 
of the token that was before; Bison cannot do that, so the lexer must do it. A 
grammar might look like, with the lexer figuring out what to return:

%left binary_operator
%left prefix_operator
%left binary_or_postfix_operator
%left postfix_operator

%%

expression:
    value
  | prefix_operator expression
  | expression postfix_operator
  | expression binary_or_postfix_operator // Postfix operator
  | expression binary_or_postfix_operator expression // Binary operator:
  | expression binary_operator expression
;

>> [...] the actions put them onto to a stack with precedences and another for
>> values. Then, when a new operator comes by, let the operators on the
>> stack with higher precedences act on the value stack until something with
>> a lower precedence appears, [...]
> 
> I read this twice and didn't understand anything. I read it once again and now
> I understand you are proposing that when operators are used, I don’t really
> use the syntax tree I'm generating with Bison _straightly_, but a more complex
> syntax tree I'd be generating combining the natural tree that arises from the
> grammar and other information in those data structures you propose. Did I
> understand that right?

Take a simple example, a + b*c #, where # is the end marker. First put the a on 
the value stack, and the + on the operator stack, and then the b on the value 
stack. When the * comes by, it has higher precedence than the + on top of the 
operator stack, so it must be stacked. Then the c comes by, so put it on the 
value stack. Finally the end marker #, which has lower precedence than *, so 
let * operate on the value stack, and put back its value, b*c. Next is the +, 
and # has lower precedence, so + operates on the value stack, computing a + 
(b*c), which is put back onto the value stack. Then the operator stack empty, 
so the process is finished, and the value stack has the value.

One can also use a single stack, and an operator precedence grammar [1]. It 
might give better error reporting, but then you need to figure out how to 
integrate it into the Bison grammar.

1. https://en.wikipedia.org/wiki/Operator-precedence_grammar





reply via email to

[Prev in Thread] Current Thread [Next in Thread]