eclipse-archived / ceylon

The Ceylon compiler, language module, and command line tools
http://ceylon-lang.org
Apache License 2.0
397 stars 62 forks source link

declaration name literals #6556

Open gavinking opened 7 years ago

gavinking commented 7 years ago

I propose adding a new string literal syntax, where the string must be:

  1. a legal Ceylon identifier, quoted by a leading $, and
  2. refer to some declaration that is in scope at the location the literal occurs.

    Example 1:

class Person(String name) {
    string => $Person + "(" + $name + "=" + name + ")";
}

Or:

class Person(String name) {
    string => "``$Person``(``$name``=``name``)";
}

Example 2:

class Book(String title, Person[] authors) {
    shared String json
            => Object {
                $name -> title,
                $authors -> Array(authors*.name)
            }.string;
}

Advantages

Scenarios where this would be used include:

  1. writing string implementations, as above,
  2. data serialization, e.g. ceylon.json, as above,
  3. logging,
  4. the JPA oneToMany(mappedBy=$property) annotation.

The advantage here is that the IDE would offer, along with errors when the identifier is misspelled:

lucaswerkmeister commented 7 years ago

This would be much more useful if we allowed qualified names as well, because otherwise it’s limited to operations implemented inside the class, which seems to counter the point that we don’t need extension methods in Ceylon because toplevel functions are just as useful.

shared class CeylonExpressionTransformer(…) … {
    transformAddAssignmentOperation(AddAssignmentOperation that)
            => "AddAssignmentOperation {
                ``that.$target`` = ``that.target.transform(this)``;
                ``that.$summand`` = ``that.summand.transform(this)``;
                }"; // indentation elided for clarity
    …
}
shared JsonObject writeBook(Book book)
        => JsonObject {
            book.$title -> book.title,
            book.$authors -> JsonArray(book.authors*.name)
        };
gavinking commented 7 years ago

otherwise it’s limited to operations implemented inside the class

Well that's not necessarily true; you could use import.

gavinking commented 7 years ago

But sure, I guess there's nothing wrong with something like Book.$title. It does make it something a bit more than a "string literal", however.