9
$\begingroup$

How might one go about building a parser that can distinguish custom operators in prefix, infix or postfix positions.

For example:

# Hypothetical operator
@postfix(Precedence.Not)
let ~ = fn(a) = ...

@infixleft(Precedence.Addition)
let ~^ = fn(a, b) = ...

@prefix(Precedence.Not)
let ^ = fn(a) = ...

How can a parser distinguish a~^b deterministically?

Is it ~^(a, b) or ~(a)(^(b)) where a is a single argument function?

$\endgroup$
2
  • $\begingroup$ One option is to just have infix operators $\endgroup$
    – Seggan
    Commented May 17, 2023 at 19:16
  • $\begingroup$ This is, by definition, a syntactic ambiguity. $\endgroup$
    – ice1000
    Commented May 19, 2023 at 19:31

1 Answer 1

5
$\begingroup$

An easy solution is to require spaces between operators. Alternatively, you could enforce a policy that operators are parsed greedily left-to-right, for example, and then make it the programmer's responsibility to ensure unambiguity

$\endgroup$
4
  • $\begingroup$ I fear if I just force spaces in between it might look weird when there are multiple prefix or postfix operators chained. Like: a * - ~| ^ b and leaves amguity in determining which one in the chain is an infix. $\endgroup$ Commented May 17, 2023 at 18:57
  • 3
    $\begingroup$ @kaiserthe13th Personally I think allowing arbitrary custom operators is almost guaranteed to cause confusion and ambiguity. Even if the language always specifies a specific interpretation to be correct, it's still very easy to get confused and assume another interpretation. One thing that could help in this regard is a smart syntax highlighting plugin that would clearly outline the correct interpretation $\endgroup$
    – abel1502
    Commented May 17, 2023 at 19:02
  • 2
    $\begingroup$ @kaiserthe13th Requiring spaces between operators is a pretty common solution for languages with custom operators, and it's a small sacrifice to make (IMO). Also, programmers will usually put spaces around operators anyway $\endgroup$
    – user
    Commented May 17, 2023 at 20:45
  • $\begingroup$ If you don't require spaces, then declaring new operators could break existing code. $\endgroup$ Commented May 18, 2023 at 11:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .