DanielXMoore / Civet

A TypeScript superset that favors more types and less typing
https://civet.dev
MIT License
1.36k stars 29 forks source link

Non-identifier operators #1382

Open bbrk24 opened 1 month ago

bbrk24 commented 1 month ago

I've talked about this before but I couldn't find an existing issue about it.

Swift requires operators to consist of non-alphanumeric characters, so they aren't valid identifiers. This allows custom operators like infix operator .* for dot multiplication, postfix operator %/postfix operator ° for unit conversion, and more. I've occasionally wanted this myself in Civet code, such as × for Cartesian product or for function composition.

Given the limitations of JavaScript, this would necessarily involve name mangling. As long as the mangling is consistent and depends only on the source symbol, though, this shouldn't be a problem and should even allow for importing/exporting such operators. (One such operation could be replacing illegal characters with something of the form _uXXXX, like becoming _u25B3.)

edemaine commented 1 month ago

Somewhat related is operator overloading: https://github.com/DanielXMoore/Civet/discussions/1081 (This used to be an issue but moved to a discussion.)

Related to name mangling is #555's mention of the idea to allow emoji in all Civet identifiers. If we extended this to mathematical operators and much of Unicode space, this would let a user immediately define a lot of custom operators (including e.g. ° and ) using the existing operator functionality.

I think we could extend Civet to allow defining new ASCII operators (that don't conflict with existing operators). Something like:

operator (.*) (a, b)  // inner product
  a.x * b.x + a.y * b.y

We'd need to define a set of ASCII letters that we'd like to allow in such binary operators, then (similar to how custom operators work today) check for them and see if they're defined.

I think we could even allow overriding built-in binary operators, at least to a limited extent, if we checked for this first in the grammar. This would be nice for when we inevitably add more binary operators to Civet.

I see you've also maybe suggested custom prefix and postfix operators. That's in principle doable too...

bbrk24 commented 1 month ago

We'd need to define a set of ASCII letters that we'd like to allow in such binary operators, then (similar to how custom operators work today) check for them and see if they're defined.

Swift's set is ./=-+!*%<>&|^?~, for the record.