YAWSI: an identity unary operator

Allen Wirfs-Brock allen at wirfs-brock.com
Mon Mar 19 13:13:17 PDT 2012


(Yet Another Wacky Syntax Idea)

Here is a relatively common coding pattern:

var a;
var obj = {
   get a() {return a},
   set a(v) {a=v}
};

Often the intent is that the variable a should only be used within the object literal.  The block scoping with let and do operator will allow the variable and object literal to be group in this manner:

let obj  = do {
    let a;
    ({get a() {return a},
      set a()v) {a=v}
    })
}

Unfortunately, the object literal has to be enclosed in parentheses because an expression statement cannot begin with an object literal.  The same would be the case if a function expression was involved rather than an object literal. 

Parens are annoying because you have to remember to close them and match them if any additional nesting is involved.

With completion reform, do expressions, and broader use of  blocks that produce values we should expect to see more situations where an ExpressionStatement needs to start with an object literal or function expression. It would be nice to have some way to do this that does not require parentheses.

Prefix the expression with an unary operator is sufficient to disambiguate such expression but unfortunately all of the existing unary operators perform conversions that would invalidate the value.  However, a new unary operator whose semantics was to simply return its operand value would do the job nicely.   Both . and = seem like good candidates for such an operator but any operator symbol that is not currently used in a unary form would be a possibility:

let obj  = do {
    let a;
    ={get a() {return a},
       set a(v) {a=v}
    }
}

let obj  = do {
    let a;
    .{get a() {return a},
       set a(v) {a=v}
    }
}

let obj  = do {
    let a;
    ^{get a() {return a},  //probably my favorite, but that may just be a leakage from my Smalltalk background...
        set a(v) {a=v}
    }
}

let obj  = do {
    let a;
    |{get a() {return a},
       set a(v) {a=v}
    }
}

let obj  = do {
    let a;
    /{get a() {return a},
       set a(v) {a=v}
    }
}

let obj  = do {
    let a;
    *{get a() {return a},
       set a(v) {a=v}
    }
}

What about ASI?  Adding a unary form of an existing binary operator doesn't introduce any new issues or break/change existing code:

x
    ={ };

parses as an assignment to x even if = is given a new meaning as a unary operator. 













More information about the es-discuss mailing list