Suffix-based literal syntax

Robert Fraser fraserofthenight at gmail.com
Wed May 30 11:29:22 PDT 2007


I like it; it'd make working with JNI types a lot easier. Would this work with the current parser, though?

Reiner Pope Wrote:

> Here's a small thought to improve the syntax for some user-defined 
> types: can we perhaps overload the suffix on literals, to give some user 
> types nicer literals?
> 
> One of Walter's rationale for natively supporting complex numbers is to 
> get nice looking literals:
>     3 + 5i
>   instead of
>     3 + 5 * i
>   or the more realistic
>     complex(3, 5)
> 
> 
> I propose that, for number and string literals (which already sport 
> suffixes at the moment) if a suffix is found not from the language, it 
> be rewritten as an opSuffix call, so
>         5km
>     turns into
>         opSuff_km(5)
> 
> For reasons of sanity, the suffix should probably only be alphabetical, 
> upper and lower case.
> 
> 
> This isn't a general solution to literals for user types, but I can 
> imagine it as useful for:
> 
> 1. Complex numbers:
> You could get the same syntax as we currently get, but in a library. 
> That seems pretty impressive.
> 
> 2. SI units libraries:
> Instead of (acceptable) 5 * km, you can write 5km as a literal.
> 
> 3. Some kind of native type wrapper:
> Perhaps for dstring, or some other class that wraps strings, you could 
> write:
>     "foo"s
> denoting a dstring literal, as opposed to char[]/wchar[]/dchar[] literal.
> 
> Similarly, you might want to write a vector class for this:
>      [5, 4, 3]v
> being the same as Vec([5, 4, 3]) but much more visually pleasing.
> 
> 4. Wacky syntax extensions. I remember seeing Bill Baxter use the suffix 
> 'i' to denote 'inclusive' for ranges. I'm sure many other (ab)uses could 
> come to mind.
> 
> ----
> 
> If problems come with suffix clashes, renaming of imports could help:
> 
> import foo.string: opSuff_fs = opSuff_s;
> import bar.string: opSuff_bs = opSuff_s;
> 
> ...
> auto a = "abc"fs; // a is a foo string
> auto b = "abc"bs; // b is a bar string
> 
> 
> I think it's kind of a nice idea, since it can give some user types a 
> nicer syntax without creating any new ambiguities.
> 
> 
> Of course, given how much is going on with const et al at the moment, I 
> don't expect anything to come of this at the moment, but I hope someone 
> likes it.
> 
> 
>     -- Reiner




More information about the Digitalmars-d mailing list