Existential Operator / Null Propagation Operator

# Christoph Pojer (9 years ago)

Tim Yung and I have hacked on a reference implementation for the "Existential Operator" using esprima-fb and jstransform: "a?.b"

Example:

a?.b => (a == null ? void 0 : a.b) a?.b.c => (a == null ? void 0 : a.b.c)

This must also make sure that a only gets evaluated a single time.

Based on previous discussions on es-discuss and TC39, it seems that this was tabled for ES6. I think now is a good time to bring it up for ES7. There is precendence for this feature in other languages - it was recently added to C# and Hack and has always been in CoffeeScript. TypeScript is waiting for TC39: Microsoft/TypeScript#16

In the past, this topic has invited a lot of bikeshedding, but I'd like us to look past this. Several communities within and outside the JS community have identified the need for this operator. My understanding is that a decision needs to be made about whether the operator should short-circuit additional invocations in the call chain if the operand is null (aka. null propagation).

For example, if a is null, should a?.b.c:

  1. evaluate to (void 0).c and throw a TypeError?
  2. short-circuit at a and return void 0?

It appears that C# chose option #2 whereas Hack and CoffeeScript chose option #1. Our current implementation chose option #1 but we'd be happy to build a reference implementation for option #2.

I recall that another issue was that of transitivity. Right now, (a.b).c and a.b.c are equivalent. (a?.b).c and a?.b.c would not be equivalent expressions. I think we need some input from the people on this list about whether this is okay or why we value transitivity for this operator.

If we can come to an agreement on the existential operator for member expressions, we would also be setting a precedent for other features of the same family. For example, existential call expressions: fn?() which would conditionally invoke fn.

esprima-fb change: cpojer/esprima/tree/existential-operator jstransform change: yungsters/jstransform/tree/existential-operator

Previous discussions on es-discuss:

# Herby Vojčík (9 years ago)

Christoph Pojer wrote:

Tim Yung and I have hacked on a reference implementation for the "Existential Operator" using esprima-fb and jstransform: "a?.b"

Example:

a?.b => (a == null ? void 0 : a.b) a?.b.c => (a == null ? void 0 : a.b.c)

This must also make sure that a only gets evaluated a single time.

Based on previous discussions on es-discuss and TC39, it seems that this was tabled for ES6. I think now is a good time to bring it up for ES7. There is precendence for this feature in other languages - it was recently added to C# and Hack and has always been in CoffeeScript. TypeScript is waiting for TC39: Microsoft/TypeScript#16

In the past, this topic has invited a lot of bikeshedding, but I'd like us to look past this. Several communities within and outside the JS community have identified the need for this operator. My understanding is that a decision needs to be made about whether the operator should short-circuit additional invocations in the call chain if the operand is null (aka. null propagation).

For example, if a is null, should a?.b.c:

  1. evaluate to (void 0).c and throw a TypeError?
  2. short-circuit at a and return void 0?

I liked the result of using a Null Pattern inside and materializing it outside, which once seemed to be plausible, with that a?.b.c would be void 0 of course. I don't remember on what it all died back then (yes, I have a bias, I wanted a true null pattern, AWB than said it is good inside but not really good as first class person).

# Jordan Harband (9 years ago)

Wouldn't option 1 provide the transitivity you're discussing? If a?.b.c calls (void 0).c then (a?.b).c and a?.b.c would be identical, and both throw a TypeError.

From my reading, it seems like option 2 is the one that does not provide

transitivity, and tbh would surprise me greatly in the context of JS. If I want the short circuit in option 1, I'd do a?.b?.c to indicate that, whereas in option 2 if I don't want the short circuit, I'm forced to use separate variables.

# Kevin Smith (9 years ago)

If we can come to an agreement on the existential operator for member expressions, we would also be setting a precedent for other features of the same family. For example, existential call expressions: fn?() which would conditionally invoke fn.

In the meeting notes you linked to, Waldemar (WH) noted that some of these variations may have grammar issues.

Although not strictly ambiguous with conditional expressions, fn ? () would require the use of YACG (yet another cover grammar).

Also, what about computed property names? For example: obj ? [Symbol.iterator]. I'm not sure that even YACG will help here.

(Thanks for compiling the list of previous threads BTW).

# joe (9 years ago)

I hacked together something similar myself. IIRC, this particular transformation has issues with nested operators (e.g. a.b?.c.d?.e.f?.h). Of course that's an implementation detail, but the problem (if I'm remembering it right) is that people couldn't figure out what the implementation constraints are (I think there was consensus that the trinary transformation was unworkable), and without knowing those constraints it wasn't possible to write a spec for it.

I could be remembering all this wrong, but that's my recollection of how that conversation went. I think the consensus was to wait for the ? operator to become more mature in other languages.

# Matthew Robb (9 years ago)

On Mon, Apr 6, 2015 at 3:19 PM, Kevin Smith <zenparsing at gmail.com> wrote:

Although not strictly ambiguous with conditional expressions, fn ? () would require the use of YACG (yet another cover grammar).

Also, what about computed property names? For example: obj ? [Symbol.iterator]. I'm not sure that even YACG will help here.

​I have two thoughts:

  1. Could the language allow for a prefix operator instead (AKA 'The Maybe Operator'): ?a.b and ?obj() and ?obj[Symbol.iterator]

  2. ​You could make the postfix operator ?. which would be ugly but dodge the above issues: obj?.() and obj?.[Symbol.iterator]

  • Matthew Robb
# joe (9 years ago)

By the way, I don't remember having grammar issues (I use a LALR compiler-compiler). Looking at my code, it looked like I handled it in the tokenizer stage; I added a COND_DOT token:

COND_DOT : ?.

COND_DOT then became simply another binary operator in the Expression production.

However, this is a very simple use case. Supporting e.g. function calls would require more tokens (which raises the question: why stop at '.'? Should we have arithmetic versions too?). Given the proliferation of binary operator tokens in JS, I'm not sure if this is a good thing.

Joe

# Brendan Eich (9 years ago)

joe wrote:

By the way, I don't remember having grammar issues (I use a LALR compiler-compiler). Looking at my code, it looked like I handled it in the tokenizer stage; I added a COND_DOT token:

COND_DOT : ?.

Did you keep backward compatibility? x?.1:y must continue to work.

# Matthew Robb (9 years ago)

On Mon, Apr 6, 2015 at 5:42 PM, Brendan Eich <brendan at mozilla.org> wrote:

Did you keep backward compatibility? x?.1:y must continue to work.

​This is why I suggested a leading operator (?a.?b()) because it seems like it would have the least potential for conflict with existing valid syntax​

  • Matthew Robb
# Brendan Eich (9 years ago)

Yeah, and it would line up with cover grammar needed for refutable-by-default patterns.

# Christoph Pojer (9 years ago)

So I take it most would prefer this as a prefix operator. What would be the next steps involved to iterate on this idea?

# Ron Buckton (9 years ago)

Wouldn't .? as an infix operator be unambiguous, compared to ?.? There's no place other than decimal literals where this would be legal today, and decimal literals already require either parenthesis or an extra dot to perform a property access in any event. With that lexeme, x.?1:y would be unambiguously an error. 1.?x:y is unambiguously a conditional, while 1..?x:y is unambiguously a null-propagating property access on the numeric literal 1..

Ron

# Brendan Eich (9 years ago)

Implement it; user-test it; auto-check the grammar for ambiguity and other problems.

# Dmitry Soshnikov (9 years ago)

On Mon, Apr 6, 2015 at 11:33 AM, Christoph Pojer <christoph.pojer at gmail.com>

wrote:

Tim Yung and I have hacked on a reference implementation for the "Existential Operator" using esprima-fb and jstransform: "a?.b"

Example:

a?.b => (a == null ? void 0 : a.b) a?.b.c => (a == null ? void 0 : a.b.c)

This must also make sure that a only gets evaluated a single time.

Based on previous discussions on es-discuss and TC39, it seems that this was tabled for ES6. I think now is a good time to bring it up for ES7. There is precendence for this feature in other languages - it was recently added to C# and Hack and has always been in CoffeeScript. TypeScript is waiting for TC39: Microsoft/TypeScript#16

In the past, this topic has invited a lot of bikeshedding, but I'd like us to look past this. Several communities within and outside the JS community have identified the need for this operator. My understanding is that a decision needs to be made about whether the operator should short-circuit additional invocations in the call chain if the operand is null (aka. null propagation).

For example, if a is null, should a?.b.c:

  1. evaluate to (void 0).c and throw a TypeError?
  2. short-circuit at a and return void 0?

It appears that C# chose option #2 whereas Hack and CoffeeScript chose option #1. Our current implementation chose option #1

Hold on, I guess it's a typo, since as discussed in the internal conversation, and based on the implementation, your current prototype transform implements option (2). I.e. it's not yet compositional. CoffeeScript also has option (2), and is not compositional, since:

a?.b.c and (a?.b).c have different semantics in case if a is null.

but we'd be happy to build a reference implementation for option #2.

Yeah, (2) will make it compositional.

I recall that another issue was that of transitivity. Right now, (a.b).c and a.b.c are equivalent. (a?.b).c and a?.b.c would not be equivalent expressions. I think we need some input from the people on this list about whether this is okay or why we value transitivity for this operator.

Yeah, potentially we could agree it's being non-compositional. Otherwise, it will be full-chain "verbose" version. I.e. to get a null-safe d property, you should write ? after each property access:

var v = a?.b?.c?.d

In other words, it's the same as:

var v = (((a?.b)?.c)?.d)

and in this case it becomes compositional (the semantics doesn't change whether you apply grouping operator or not).

But again, as was mentioned in [1], probably it's "too verbose", and hence may not hit standardization. I'd say it's fine -- it works in most of the case, and usually should not be that verbose. OTOH, we still may have a non-compositional (short-circuiting) version.

FWIW, in Hack programming language I also implemented the "verbose" version, hence it's compositional. The details of the implementation can be found in [2] (we've just recently added it to Hack).

On the topic whether it should be prefix or postfix: I'd personally prefer postfix, since it will be intuitive from other languages. However, if we won't be able to solve all grammar challenges, prefix version could be fined as well.

[1] esdiscuss.org/topic/the-existential-operator#content-19 [2] facebook/hhvm/commit/35819cdcf2c80edc22fb3e2e4a6a27f352fb9305

Dmitry

# Dmitry Soshnikov (9 years ago)

On Mon, Apr 6, 2015 at 6:35 PM, Dmitry Soshnikov <dmitry.soshnikov at gmail.com

wrote:

On Mon, Apr 6, 2015 at 11:33 AM, Christoph Pojer < christoph.pojer at gmail.com> wrote:

Tim Yung and I have hacked on a reference implementation for the "Existential Operator" using esprima-fb and jstransform: "a?.b"

Example:

a?.b => (a == null ? void 0 : a.b) a?.b.c => (a == null ? void 0 : a.b.c)

This must also make sure that a only gets evaluated a single time.

Based on previous discussions on es-discuss and TC39, it seems that this was tabled for ES6. I think now is a good time to bring it up for ES7. There is precendence for this feature in other languages - it was recently added to C# and Hack and has always been in CoffeeScript. TypeScript is waiting for TC39: Microsoft/TypeScript#16

In the past, this topic has invited a lot of bikeshedding, but I'd like us to look past this. Several communities within and outside the JS community have identified the need for this operator. My understanding is that a decision needs to be made about whether the operator should short-circuit additional invocations in the call chain if the operand is null (aka. null propagation).

For example, if a is null, should a?.b.c:

  1. evaluate to (void 0).c and throw a TypeError?
  2. short-circuit at a and return void 0?

It appears that C# chose option #2 whereas Hack and CoffeeScript chose option #1. Our current implementation chose option #1

Hold on, I guess it's a typo, since as discussed in the internal conversation, and based on the implementation, your current prototype transform implements option (2). I.e. it's not yet compositional. CoffeeScript also has option (2), and is not compositional, since:

a?.b.c and (a?.b).c have different semantics in case if a is null.

but we'd be happy to build a reference implementation for option #2.

Yeah, (2) will make it compositional.

Err, option (1) I meant of course.

Dmitry

# Kevin Smith (9 years ago)

We should perhaps review this old thread:

esdiscuss.org/topic/fail-fast-object-destructuring-don-t-add-more-slop-to-sloppy-mode

for another possible way to avoid non-compositionality. (Look for the suggestion about "Nil". It's basically an exotic falsey object which returns itself for any property lookups or calls.)

# Brendan Eich (9 years ago)

That (putting the ? second) works for . ( and [, true. It's backwards compared to other languages, though. Oh well.

The deeper issue is semantic, assuming a viable syntax. See ksmith's latest message.

# Herby Vojčík (9 years ago)

Kevin Smith wrote:

We should perhaps review this old thread:

esdiscuss.org/topic/fail-fast-object-destructuring-don-t-add-more-slop-to-sloppy-mode

for another possible way to avoid non-compositionality. (Look for the suggestion about "Nil". It's basically an exotic falsey object which returns itself for any property lookups or calls.)

Yeah, that's the Null Pattern I mentioned few posts before. I remember I suggested this to be part of the language itself, as a first-class member, but it seems it wasn't legible; OTOH, it seemed to be good enough to use while still in the level of references, but when coming back to values, it was suggested to be changed to undefined.

It is still interesting question if it could be part of the language itself, but even if not and only applicable as a reference, it can be a good solution (it that case a?.b.c would yield undefined, not an error in case a is null).

# Nick Krempel (9 years ago)

On 6 April 2015 at 19:33, Christoph Pojer <christoph.pojer at gmail.com> wrote:

a?.b => (a == null ? void 0 : a.b) a?.b.c => (a == null ? void 0 : a.b.c)

Would it not be more generally useful if it returned "a" rather than "void 0" in the appropriate case, that is:

a?.b => (a == null ? a : a.b)

This way the notion of nullness/undefinedness the user is working with would be preserved.

# Nick Krempel (9 years ago)

On 6 April 2015 at 20:01, Jordan Harband <ljharb at gmail.com> wrote:

If I want the short circuit in option 1, I'd do a?.b?.c to indicate that, whereas in option 2 if I don't want the short circuit, I'm forced to use separate variables.

Worth noting that an option 1 a?.b?.c differs from an option 2 a?.b.c in that the latter is effectively asserting that if a != null then its b property is also != null, whereas the former is more lenient in what it accepts.

Also you are not forced to use separate variables in option 2, you can just use parentheses: (a?.b).c - hence the whole discussion of lack of transitivity (more correctly, associativity) for option 2. Or did I misunderstand what you're trying to achieve?

# Nick Krempel (9 years ago)

On 7 April 2015 at 18:03, Nick Krempel <ndkrempel at google.com> wrote:

On 6 April 2015 at 20:01, Jordan Harband <ljharb at gmail.com> wrote:

If I want the short circuit in option 1, I'd do a?.b?.c to indicate that, whereas in option 2 if I don't want the short circuit, I'm forced to use separate variables.

Worth noting that an option 1 a?.b?.c differs from an option 2 a?.b.c in that the latter is effectively asserting that if a != null then its b property is also != null, whereas the former is more lenient in what it accepts.

Also you are not forced to use separate variables in option 2, you can just use parentheses: (a?.b).c - hence the whole discussion of lack of transitivity (more correctly, associativity) for option 2. Or did I misunderstand what you're trying to achieve?

...but thinking about it further, wouldn't you always want the short circuit semantics? i.e. an option 1 a?.b.c is almost certainly a bug?

# Christoph Pojer (9 years ago)

it doesn't have to be a bug. It asserts that if a is not null/undefined, it must have a property b. This can be enforced through static typing.

# Brendan Eich (9 years ago)

Christoph Pojer wrote:

it doesn't have to be a bug. It asserts that if a is not null/undefined, it must have a property b. This can be enforced through static typing.

What do you mean? JS does not have static typing. Even if it got it via SoundScript, the new mode would be an opt-in. The default and vast majority of JS, which might like to use ?. (or whatever the syntax should be), could not rely on types.

Kevin's suggestion is that we solve the non-compositional CoffeeScript-like translation problem by converting null-ish (null or undefined) left operand of ?. (I'll use that syntax for now as it is familiar) to the Nil (h/t bbenvie) value proxy, which soaks up further property accesses by returning itself, and soaks up calls too.

As a sketch of semantics, this seems promising (no appeal to static typing) but I'm low on caffeine at the moment. What am I missing?

# Herby Vojčík (9 years ago)

Kevin Smith wrote:

We should perhaps review this old thread:

esdiscuss.org/topic/fail-fast-object-destructuring-don-t-add-more-slop-to-sloppy-mode

for another possible way to avoid non-compositionality. (Look for the suggestion about "Nil". It's basically an exotic falsey object which returns itself for any property lookups or calls.)

Going a bit deeper this way, this thing (changing ref to Nil which always returns Nil upon call, construct and get, and getting back undefined when value is needed) have nicely separated concerns:

Let's say '?foo', as an unary oper ator, when foo is a reference, returns Nil when foo is reference to null or undefined, otherwise leaves it unchanged. Then:

?a.b.c just works, ?d() just works, new ?ei just works, etc,. since ref is changed to Nil if the thing is null/undefined, it propagates through calls and gets, then changes itself to undefined value. The priority of ? must be pretty high, though, to only apply to nearest token.

Plus, it can be used for "normalizing" null/undefined to undefined:

var normalizedFoo = ?foo;

Seems sort of nice that it is separated and there are no special operations for ?., ?(, ?[.

# Kevin Smith (9 years ago)

Plus, it can be used for "normalizing" null/undefined to undefined:

var normalizedFoo = ?foo;

Seems sort of nice that it is separated and there are no special

operations for ?., ?(, ?[.

I agree, that is nice. But how does Nil get transformed into undefined?

# Herby Vojčík (9 years ago)

Christoph Pojer wrote:

it doesn't have to be a bug. It asserts that if a is not null/undefined, it must have a property b. This can be enforced

Oh, that is completely different semantics. IMNSHO, it goes against DWIM.

# Herby Vojčík (9 years ago)

Kevin Smith wrote:

Plus, it can be used for "normalizing" null/undefined to undefined:

var normalizedFoo = ?foo;

Seems sort of nice that it is separated and there are no special operations for ?., ?(, ?[.

I agree, that is nice. But how does Nil get transformed into undefined?

While you do operations like call, construct, get on the reference (obtaining another reference), it shortcuts to return Nil. Whenever you are not in position to shortcut ref-to-ref (end of expression, for example), and you actually needs a value, it just converts to undefined.

?a.b()['foo'] => "smalltalk-like" (((('a' asRefIn: env) nilRefIfValueNullOrUndefined "ref, may be nil" at: 'b') "returns ref, may be Nil" callWithArguments: #()) "returns ref, may be Nil" at: 'foo') "returns ref, may be Nil") value "now, value is needed, ref needs to dereference"

Hopefully this sheds some light. If not, then I don't know how to explain it someone with better pedagogy skill must weight in.

# Nathan White (9 years ago)

Am I crazy to think that "Nil" could allow the Existential Operator to be used in assignments as well?

var a = undefined; a?.b?.c?.d = 1; console.log(a); // {b: {c: {d: 1}}}

Too powerful / abusive?

Day dreaming, use U+02D9 (DOT ABOVE) as the operator.

a˙b˙c.d

# Brendan Eich (9 years ago)

Nathan White wrote:

Am I crazy to think that "Nil" could allow the Existential Operator to be used in assignments as well?

var a = undefined; a?.b?.c?.d = 1; console.log(a); // {b: {c: {d: 1}}}

Too powerful / abusive?

Too error-prone. E4X (ECMA-357) and languages such as Borland's mid-nineties "Lucy" (Loose C) allow you to cons up deep structures just be expressing member references. One typo and you're lost.

Day dreaming, use U+02D9 (DOT ABOVE) as the operator.

a˙b˙c.d

Object literal notation is explicit and pretty concise. What's the hot use-case driving your desire here?

# Caitlin Potter (9 years ago)

On Mon, Apr 6, 2015 at 5:42 PM, Brendan Eich <brendan at mozilla.org, mail.mozilla.org/listinfo/es-discuss> wrote:

  • Did you keep backward compatibility? x?.1:y must continue to work. *>

​This is why I suggested a leading operator (?a.?b()) because it seems like it would have the least potential for conflict with existing valid syntax​

What about something like

MemberExpression[?Yield] ? . IdentifierName MemberExpression[?Yield] ? [ Expression[In, ?Yield] ]

Context specific to MemberExpressions, as far as I'm aware there's no otherwise valid ternary expression that could be mixed up for it, and it wouldn't need a cover grammar?

# Brendan Eich (9 years ago)

Caitlin Potter wrote:

6, 2015 at 5:42 PM, Brendan Eich<brendan at mozilla.org, mail.mozilla.org/listinfo/es-discuss> wrote:

/ Did you keep backward compatibility? x?.1:y must continue to work. />

​This is why I suggested a leading operator (?a.?b()) because it seems like it would have the least potential for conflict with existing valid syntax​

What about something like MemberExpression[?Yield] ?|.| IdentifierName MemberExpression[?Yield] ?[ Expression[In, ?Yield] |]| Context specific to MemberExpressions, as far as I'm aware there's no otherwise valid ternary expression that could be mixed up for it, and it wouldn't need a cover grammar?

We can try being this precise, as you say -- but we cannot then handle x?(y) as CoffeeScript does. Instead of being neither fish nor fowl, better to be fowl with leading ?, or use a distinct and regular syntax that handles all the cases we want. My two cents,

# Brendan Eich (9 years ago)

Brendan Eich wrote:

Caitlin Potter wrote:

6, 2015 at 5:42 PM, Brendan Eich<brendan at mozilla.org, mail.mozilla.org/listinfo/es-discuss> wrote:

/ Did you keep backward compatibility? x?.1:y must continue to work. />

​This is why I suggested a leading operator (?a.?b()) because it seems like it would have the least potential for conflict with existing valid syntax​

What about something like MemberExpression[?Yield] ?|.| IdentifierName MemberExpression[?Yield] ?[ Expression[In, ?Yield] |]| Context specific to MemberExpressions, as far as I'm aware there's no otherwise valid ternary expression that could be mixed up for it, and it wouldn't need a cover grammar?

We can try being this precise, as you say -- but we cannot then handle x?(y) as CoffeeScript does. Instead of being neither fish nor fowl, better to be fowl with leading ?, or use a distinct and regular syntax that handles all the cases we want. My two cents,

Worse, we can't even do ?[ as you propose with LR(1) or any similar approach. Here's a bison toy grammar:

%token ID

%%

start: E ;

E: A | E ',' A ;

A: C | M '=' A ;

C: M : M '?' A ':' A ;

M: M '[' E ']' | M '?' '[' E ']' | P ;

P: ID | '(' E ')' | '[' E ']' ;

(P for Primary, M for Member, C for Conditional, A for Assignment.)

The reduce/reduce conflict recognizing a left sentential form '[' E ']' vs. M '?' '[' E ']' shows the fatal ambiguity.

# Ron Buckton (9 years ago)

Brendan Eich wrote:

Brendan Eich wrote:

Caitlin Potter wrote:

6, 2015 at 5:42 PM, Brendan Eich<brendan at mozilla.org, mail.mozilla.org/listinfo/es-discuss> wrote:

/ Did you keep backward compatibility? x?.1:y must continue to work. />

​This is why I suggested a leading operator (?a.?b()) because it seems like it would have the least potential for conflict with existing valid syntax​

What about something like MemberExpression[?Yield] ?|.| IdentifierName MemberExpression[?Yield] ?[ Expression[In, ?Yield] |]| Context specific to MemberExpressions, as far as I'm aware there's no otherwise valid ternary expression that could be mixed up for it, and it wouldn't need a cover grammar?

We can try being this precise, as you say -- but we cannot then handle x?(y) as CoffeeScript does. Instead of being neither fish nor fowl, better to be fowl with leading ?, or use a distinct and regular syntax that handles all the cases we want. My two cents,

The reduce/reduce conflict recognizing a left sentential form '[' E ']' vs. M '?' '[' E ']' shows the fatal ambiguity.

/be

There is also ambiguity due to ASI vs. a ConditionalExpression:

obj ? [ expr ] 
:label 

Ron

# joe (9 years ago)

That's a good point. Are lexical non-DFA grammars allowed? It would be trivial to solve that with a regular expression lookahead. Although I suppose at that point you might as well call it a cover grammar.

Joe

On Mon, Apr 6, 2015 at 2:42 PM, Brendan Eich <brendan at mozilla.org> wrote:

joe wrote:

By the way, I don't remember having grammar issues (I use a LALR compiler-compiler). Looking at my code, it looked like I handled it in the tokenizer stage; I added a COND_DOT token:

COND_DOT : ?.

Did you keep backward compatibility? x?.1:y must continue to work.

/be

No, it looks like I didn't.

# Brendan Eich (9 years ago)

Ron Buckton wrote:

The reduce/reduce conflict recognizing a left sentential form '[' E ']' vs. M '?' '[' E ']' shows the fatal ambiguity.

/be

There is also ambiguity due to ASI vs. a ConditionalExpression:

obj ? [ expr ]
:label

Ron

Colon goes after label :-P. But the problem is bounded lookahead, ideally k=1. We are not specifying backtracking...

# Brendan Eich (9 years ago)

joe wrote:

That's a good point. Are lexical non-DFA grammars allowed? It would be trivial to solve that with a regular expression lookahead.
Although I suppose at that point you might as well call it a cover grammar.

We must avoid being too clever -- it complicates implementations and inevitably incurs future-hostility to extensions we may want, if not outright bugginess.

All of this suggests prefix ? is the better course. Anyone have counterexamples?

# Ron Buckton (9 years ago)

Oops, was think in batch for a minute there.

Sent from my Windows Phone

# joe (9 years ago)

Okay. I've updated my transpiler to demonstrate how (and why) this could work at the VM level (I do think VM devs will have to add new opcodes for this), and I've appended an example transformation to this email.

Why is this so complicationed? The answer is that when you start nesting ?. operators, it's pretty easy to cause some operators to be called twice.

E.g, if you transformed the following to the NULL syntax:

a?.d().f?.b

You would get: (a != undefined ? (a.d() != undefined ? (a.d().f != undefined ? a.d().f.b : undefined) : undefined)));

Notice how a.d() gets called multiple times.

The solution is probably new VM opcodes. Since my transpiler is obviously not a VM, it transforms ?. operators into auto-generated functions. Anyway, here's the example I transpiler:

a?.b.c.e?.f.g?.h.t.c?.d()?.e;

Which turned into this:

function q0eILlfx7_3(obj) { var _t=obj;

if (_t==undefined)
  return undefined;
_t = _t.b.c.e;

if (_t==undefined)
  return undefined;
_t = _t.f.g;

if (_t==undefined)
  return undefined;
_t = _t.h.t.c;

if (_t==undefined)
  return undefined;
_t = _t.d();

return _t;

}

q0eILlfx7_3(a);

# Sebastian McKenzie (9 years ago)

No, you’d just memoise it to a variable:

a?.d().f?.b

to:

var _temp, _temp2;

(a != undefined ? (temp = a.d() != undefined ? (_temp2 = _temp.f != undefined ? _temp2.b : undefined) : undefined)));

You’re going to need to memoise all member expressions anyway as they might be accessing a getter and you don’t want to call it twice.

# joe (9 years ago)

That looks workable. Does anyone have any more comments on '.?' versus '?.' ?

Joe

# Nick Krempel (9 years ago)

On 7 April 2015 at 18:33, Christoph Pojer <christoph.pojer at gmail.com> wrote:

it doesn't have to be a bug. It asserts that if a is not null/undefined, it must have a property b. This can be enforced through static typing.

Under option 1, that's not what it does. Since it's equivalent to (a?.b).c, if a is null/undefined, it will always raise an error, so it's more or less the same as just doing a.b.c.

# Nick Krempel (9 years ago)

The prefix ? for an absorbing Nil value sounds good.

The semantics of delete may need clarifying; what should the following construct do?

delete ?a.b.c

Most intuitive would be to not raise an error and return true if either the b or c properties are missing, whether or not in strict mode. Does that hold up?

Nick

# Claude Pache (9 years ago)

Le 7 avr. 2015 à 21:09, Herby Vojčík <herby at mailbox.sk> a écrit :

Kevin Smith wrote:

Plus, it can be used for "normalizing" null/undefined to undefined:

var normalizedFoo = ?foo;

Seems sort of nice that it is separated and there are no special operations for ?., ?(, ?[.

I agree, that is nice. But how does Nil get transformed into undefined?

While you do operations like call, construct, get on the reference (obtaining another reference), it shortcuts to return Nil. Whenever you are not in position to shortcut ref-to-ref (end of expression, for example), and you actually needs a value, it just converts to undefined.

?a.b()['foo'] => "smalltalk-like" (((('a' asRefIn: env) nilRefIfValueNullOrUndefined "ref, may be nil" at: 'b') "returns ref, may be Nil" callWithArguments: #()) "returns ref, may be Nil" at: 'foo') "returns ref, may be Nil") value "now, value is needed, ref needs to dereference"

Hopefully this sheds some light. If not, then I don't know how to explain it someone with better pedagogy skill must weight in.

Here is another, more thorough explanation (and how it could be implemented in the spec):

We introduce a special unique additional Reference [6.2.3 ReferenceType], that we call “the Nil Reference”. Unlike other resolvable References, it does not have a concrete binding at its backend, but it is more like a /dev/null or /dev/zero device. The Nil Reference has the following properties:

  • when read [6.2.3.1 GetValue], it produces undefined;

  • when written [6.2.3.2 PutValue] or deleted [12.5.4 deleteOperator], it acts like a blackhole;

  • as a more exotic behaviour, when it appears when evaluating the leftmost term of a property accessor [12.3.2 PropertyAccessors] or a function call [12.3.4 FunctionCalls], it is not dereferenced to undefined so that a TypeError would be thrown. Rather, the subexpression evaluates to the Nil Reference again. For example, here is how some algorithms of the of the spec could be modified in order to implement the "forwarding" behaviour of the Nil Reference:

    MemberExpression : MemberExpression [ Expression ] (section 12.3.2.1)

    1. Let baseReference be the result of evaluating MemberExpression.
    2. ReturnIfAbrupt(baseReference).
    3. If baseReference is the Nil Reference, return the Nil Reference.
    4. Let baseValue be RequireObjectCoercible(GetValue(baseReference)).
    5. ReturnIfAbrupt(baseValue). 6, Let propertyNameReference be the result of evaluating Expression.
    6. Let propertyKey be ToPropertyKey(GetValue(propertyNameReference)).
    7. ReturnIfAbrupt(propertyKey).
    8. Return a Reference whose base is baseValue and whose referenced name is propertyKey, (and whose “strict” flag, etc.)

    CallExpression : MemberExpression Arguments (section 12.3.4.1)

    1. Let ref be the result of evaluating MemberExpression.
    2. ReturnIfAbrupt(ref).
    3. If ref is the Nil Reference, return the Nil Reference.
    4. Let func be GetValue(ref).
    5. etc.

[6.2.3 ReferenceType]: people.mozilla.org/~jorendorff/es6-draft.html#sec-reference-specification-type, people.mozilla.org/~jorendorff/es6-draft.html#sec-reference-specification-type [6.2.3.1 GetValue]: people.mozilla.org/~jorendorff/es6-draft.html#sec-getvalue, people.mozilla.org/~jorendorff/es6-draft.html#sec-getvalue [6.2.3.2 PutValue]: people.mozilla.org/~jorendorff/es6-draft.html#sec-putvalue, people.mozilla.org/~jorendorff/es6-draft.html#sec-putvalue [12.5.4 deleteOperator]: people.mozilla.org/~jorendorff/es6-draft.html#sec-delete-operator, people.mozilla.org/~jorendorff/es6-draft.html#sec-delete-operator [12.3.2 PropertyAccessors]: people.mozilla.org/~jorendorff/es6-draft.html#sec-property-accessors, people.mozilla.org/~jorendorff/es6-draft.html#sec-property-accessors [12.3.4 FunctionCalls]: people.mozilla.org/~jorendorff/es6-draft.html#sec-function-calls, people.mozilla.org/~jorendorff/es6-draft.html#sec-function-calls

# Kevin Smith (9 years ago)

I think it's a good idea to attempt to express these ideas using existing syntax and see what that might look like.

So, for a bit of fun, I wrote this:

gist.github.com/zenparsing/9ff3036b6eb15fa436e4

Basically, there's a Maybe function which returns a proxy over a target, and returns Maybes for calls and gets. Then there's a Definitely function that unwraps the Maybe (unwrapping Nothing to undefined of course).

let scriptParent =

Definitely(Maybe(window).document.scripts[0].parentNode);

If you wanted syntactic sugar for this kind of thing, you'd probably want postfix operators to replace the Maybe and Definitely function calls.

Swift does something similar with "?" and "!":

developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

This is kind of a generic monad pattern though, so it would be cool if the syntax could be applied to other monad-ish things.

# Sander Deryckere (9 years ago)

(I hope this arrives in the right thread, it's meant as a reply for esdiscuss.org/topic/existential-operator-null-propagation-operator )

I very much like the proposal, our JS code is full with cases where certain components can be null, but we need to execute an action with the component when it's not null.

However, the collisions with existing syntax is indeed troublesome. So far, I liked the ?., ?[ and ?( operators the most.

But what should be done with cases like obj?[1]?[2]:[3]. Does it test obj?[1] and returns [2] or [3] depending on the result, or does it test obj and return [1]?[2] or [3] depending on the result.

A similar case with functions: func1?(func2)?(func3):(func4). Does it test func1?(func2), or can it return (func2)?(func3)?

Both cases depend on the binding to the : of the ternary operator. Which might cause too many changes to the spec, and too many exceptions to keep the language compatible.

The .? operator seems to have no alternative for variable keys (obj[key]), which is IMO the most usefull use-case (testing explicitly for null is most likely to happen when you don't know a lot about the object when writing the code, so likely you also don't know the key). As such .? isn't an option for me.

For the prefix operator, it's unclear to me how you would do the following: Say you know obj is non-null, you want to test if it has a key k1, but if k1 exists, you know it will also have a key k2 a level deeper. With the suffix operator, this would be obj[k1]?[k2], but with the prefix operator, it could be obj?[k1][k2] (which again has the same problems as first described with the ?[ operator), while it could also be obj[?k1][k2] (which even conflicts with itself, as it could also test if k1 as a variable is non-null).

As such, all these proposals have at least as many issues as ?.. And ?. already has too many issues to implement it.

So, I'd like to propose another operator: ?? (with ??[ and ??()

In current syntax, the ? is only used for the ternary operator, and requires something else before and after it. Which means that any code that has ?? is currently invalid.

We currently sometimes use the logical && to test nullness of a value, and access its properties. Like:

var result = obj && obj.key;

Which tests if obj exists (assuming obj is an object when defined), and returns obj.key if it does. With the ?? operator, it can be simplified to

var result = obj??key;

Combined with arr??[idx] and func??(arg), I think this will work very fine.

, Sander

# Brendan Eich (9 years ago)

Sander Deryckere wrote:

For the prefix operator, it's unclear to me how you would do the following: Say you know obj is non-null, you want to test if it has a key k1, but if k1 exists, you know it will also have a key k2 a level deeper. With the suffix operator, this would be obj[k1]?[k2], but with the prefix operator, it could be obj?[k1][k2]

You circled back to the incompatible syntax, ?[, but the prefix idea would have ?obj[k1][k2]. The ? goes in front at the start of an operand, and is thus unambiguous with respect to the ternary operator.

# Sander Deryckere (9 years ago)

2015-06-02 17:49 GMT+02:00 Brendan Eich <brendan at mozilla.org>:

Sander Deryckere wrote:

For the prefix operator, it's unclear to me how you would do the following: Say you know obj is non-null, you want to test if it has a key k1, but if k1 exists, you know it will also have a key k2 a level deeper. With the suffix operator, this would be obj[k1]?[k2], but with the prefix operator, it could be obj?[k1][k2]

You circled back to the incompatible syntax, ?[, but the prefix idea would have ?obj[k1][k2]. The ? goes in front at the start of an operand, and is thus unambiguous with respect to the ternary operator.

The question is not about the existence of obj, but if obj has a key k1. AFAICS, ?obj[k1][k2] would test the existence of obj, which I don't need in this example. To test the existence of a key inside obj, a prefix operator should come somewhere before the key.

# Brendan Eich (9 years ago)

Sander Deryckere wrote:

2015-06-02 17:49 GMT+02:00 Brendan Eich <brendan at mozilla.org <mailto:brendan at mozilla.org>>:

Sander Deryckere wrote:

    For the prefix operator, it's unclear to me how you would do
    the following: Say you know `obj` is non-null, you want to
    test if it has a key `k1`, but if `k1` exists, you know it
    will also have a key `k2` a level deeper. With the suffix
    operator, this would be `obj[k1]?[k2]`, but with the prefix
    operator, it could be `obj?[k1][k2]`


You circled back to the incompatible syntax, `?[`, but the prefix
idea would have `?obj[k1][k2]`. The `?` goes in front at the start
of an operand, and is thus unambiguous with respect to the ternary
operator.

The question is not about the existence of obj, but if obj has a key k1. AFAICS, ?obj[k1][k2] would test the existence of obj, which I don't need in this example. To test the existence of a key inside obj, a prefix operator should come somewhere before the key.

You might hope for that, but as we both noted, ?[ is not going to fly. Don't break the (minified) Web.

The prefix idea generalizes:

?obj[key] obj[?key] obj[key1][?key2]

and if you are not using computed property names, rather literal ones:

obj.?prop1 etc.

# Andreas Rossberg (9 years ago)

On 2 June 2015 at 18:57, Brendan Eich <brendan at mozilla.org> wrote:

Sander Deryckere wrote:

2015-06-02 17:49 GMT+02:00 Brendan Eich <brendan at mozilla.org <mailto: brendan at mozilla.org>>:

Sander Deryckere wrote:

    For the prefix operator, it's unclear to me how you would do
    the following: Say you know `obj` is non-null, you want to
    test if it has a key `k1`, but if `k1` exists, you know it
    will also have a key `k2` a level deeper. With the suffix
    operator, this would be `obj[k1]?[k2]`, but with the prefix
    operator, it could be `obj?[k1][k2]`


You circled back to the incompatible syntax, `?[`, but the prefix
idea would have `?obj[k1][k2]`. The `?` goes in front at the start
of an operand, and is thus unambiguous with respect to the ternary
operator.

The question is not about the existence of obj, but if obj has a key k1. AFAICS, ?obj[k1][k2] would test the existence of obj, which I don't need in this example. To test the existence of a key inside obj, a prefix operator should come somewhere before the key.

You might hope for that, but as we both noted, ?[ is not going to fly. Don't break the (minified) Web.

The prefix idea generalizes:

?obj[key] obj[?key] obj[key1][?key2]

Hm, what's the meaning of

a[?b[c]]

?

# Sander Deryckere (9 years ago)

2015-06-02 18:57 GMT+02:00 Brendan Eich <brendan at mozilla.org>:

You might hope for that, but as we both noted, ?[ is not going to fly. Don't break the (minified) Web.

Which is why my proposal was about ??. I believe there's currently no valid way to use a double question mark in JS, so even ??[ should be easy to figure out what it means.

The prefix idea generalizes:

?obj[key] obj[?key] obj[key1][?key2]

and if you are not using computed property names, rather literal ones:

obj.?prop1 etc.

I found this syntax to conflict with itself. As Andreas Rossberg says, what does orders[?client.key].price mean? Does it mean "check if the client exists, and if not, return the price of the null order", or does it mean "check if the order for this client exists, and return null if it doesn't"? I don't see a way how both meanings can be made possible with this form of prefix notation.

# Sam Ruby (9 years ago)

On Tue, Jun 2, 2015 at 1:31 PM, Sander Deryckere <sanderd17 at gmail.com> wrote:

2015-06-02 18:57 GMT+02:00 Brendan Eich <brendan at mozilla.org>:

You might hope for that, but as we both noted, ?[ is not going to fly. Don't break the (minified) Web.

Which is why my proposal was about ??. I believe there's currently no valid way to use a double question mark in JS, so even ??[ should be easy to figure out what it means.

The prefix idea generalizes:

?obj[key] obj[?key] obj[key1][?key2]

and if you are not using computed property names, rather literal ones:

obj.?prop1 etc.

I found this syntax to conflict with itself. As Andreas Rossberg says, what does orders[?client.key].price mean? Does it mean "check if the client exists, and if not, return the price of the null order", or does it mean "check if the order for this client exists, and return null if it doesn't"? I don't see a way how both meanings can be made possible with this form of prefix notation.

Um, if I'm reading Brenden correctly, neither?

"check if the client exists, and if not, return the price of the null order"

===> orders[client.?key].price

"check if the order for this client exists, and return null if it doesn't"

===> orders[client.key].?price

I would suggest a third interpretation for orders[?client.key].price:

===> (orders ? orders[client.key] : null).price

I think that the problem here isn't that it is ambiguous, it is that it isn't obvious. Something that might be more obvious but requires an additional character: orders.?[client.key].price.

More precisely, the suggestion is to standardize on .? and allow it to be followed by either a simple name, a square bracket, or a left paren.


es-discuss mailing list es-discuss at mozilla.org, mail.mozilla.org/listinfo/es-discuss

  • Sam Ruby
# Brendan Eich (9 years ago)

Sam Ruby wrote:

I think that the problem here isn't that it is ambiguous, it is that it isn't obvious.

Fair point!

Something that might be more obvious but requires an additional character: orders.?[client.key].price.

That's not bad. The whole proposal may founder, though, on "grawlix" objections.

And some still want the ?obj.foo.bar to "soak" null/undefined obj and missing foo or null/undefined value of foo. CoffeeScript fans for sure, but it's in principle and practice at least as valid a use-case as obj.?foo is.

# Sander Deryckere (9 years ago)

@Sam Ruby: I think we should indeed go for an extra character. In the proposals that result in ?[ and similar, it may be possible to define correctly in the spec, but it would indeed be non-obvious for humans to interprete, and potentially make the parser slower.

I proposed ?? as a unique double character, but .? could also work, and perhaps be easier to read (?? is a bit heavy on the eye with two big glyphs). The only confusion that could happen (AFAICS) is when mixing the decimal point with the ternary operator. But the spec already states that a digit followed by a point is always a decimal point (which is why we need to do (255).toString(2)). So the parser only has to look very locally to find the correct interpretation. And it helps humans too.

@Brendan: yes, soaking up all null/undefined values will probably be wanted by some. But personally, I'd prefer to show in my code where exactly null values can be expected, and where stuff should always be defined. Using the null-soaking syntax too much might result in code that's hard to debug (some null is coming from somewhere, but nobody has an idea from where, as it's just propagating through all accessors).

Thanks for all your comments.

, Sander

2015-06-02 20:30 GMT+02:00 Brendan Eich <brendan at mozilla.org>:

# Tingan Ho (9 years ago)

One thing to keep in mind is that with prefix operator ?a.b will also let people move back and forth with their caret. Since most people type the identifier first and then the operator. So they type a first and the move the caret in front of a and type ? and then move the caret back to the last position and then type .b. This has been a big problem in typing type assertions in TS which had a prefix operator. They later introduced the as operator which is a postfix operator.

What about a!?.b since semantically the symbol ! has a meaning of non-nullable in JSDoc[1]. So the semantics of a!?. is is it not null then the accessor ....

Or just a!.b?

[1]: Non-nullable type — usejsdoc.org/tags-type.html

# Isiah Meadows (9 years ago)

-1 for the ! idea. It feels redundant to me, since if you try calling an undefined value, it'll throw errors at you. It doesn't seem to insure anything extra beyond current behavior.

# Tingan Ho (9 years ago)

I don't see the redundancy? In my proposal the original proposed symbol ? is switched with !. So it shouldn't throw any error?

# Kevin Smith (9 years ago)

What about a!?.b since semantically the symbol ! has a meaning of non-nullable in JSDoc[1].

"!" in this context typically means non-optional, or "throw if the value is nill". See Swift for example.

Or just a!.b?

Same thing.

# Tingan Ho (9 years ago)

In TypeScript ? means optional. But throw if the value is nil is the same same as non-nullable?

# Kevin Smith (9 years ago)

In TypeScript ? means optional. But throw if the value is nil is the same same as non-nullable?

In Swift, the postfix "!" operator unwraps an optional value, throwing if nil.

See developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/OptionalChaining.html

# Tingan Ho (9 years ago)

Strange why do they need an operator for that? Probably to make it less error prone with access nil errors. But that could be fixed with static code analysis.

# Andreas Rossberg (9 years ago)

On 19 August 2015 at 16:21, Tingan Ho <tingan87 at gmail.com> wrote:

Strange why do they need an operator for that? Probably to make it less error prone with access nil errors. But that could be fixed with static code analysis.

OT but: The whole point of optional values (as opposed to null/nil/undefined inhabiting everything) is to make the boundaries of optionality explicit, thereby avoiding Hoare's billion dollar mistake.

That said, "convenient" operators like ! already destroy half the benefit. Plenty of experience from other languages like ML or Haskell shows that they are almost always used incorrectly (read: over-optimistically). If a language has to have such an operator, it should at least be very explicit and as inconvenient as bearable.

# Laurentiu Macovei (8 years ago)

This would be amazing operator!!

var error = a.b.c.d; //this would fail with error if a, b or c are null or undefined. var current = a && a.b && a.b.c && a.b.c.d; // the current messy way to handle this var typeScript = a?.b?.c?.d; // The typescript way of handling the above mess with no errors

However I propose a more clear one - as not to confuse ? from the a ? b : c statements with a?.b statements:

var x = a..b..c..d; //this would be ideal to understand that you assume that if any of a, b, c is null or undefined the result will be null or undefined.

Two dots, means if its null or undefined stop processing further and assume the result of expression is null or undefined. (as d would be null or undefined).

Two dots make it more clear, more visible and more space-wise so you understand what's going on.

What do you think folks?

Best , Laurenţiu Macovei DotNetWise

# Sander Deryckere (8 years ago)

2015-10-29 19:22 GMT+01:00 Laurentiu Macovei <alonecomp at gmail.com>:

This would be amazing operator!!

var error = a.b.c.d; //this would fail with error if a, b or c are null or undefined. var current = a && a.b && a.b.c && a.b.c.d; // the current messy way to handle this var typeScript = a?.b?.c?.d; // The typescript way of handling the above mess with no errors

However I propose a more clear one - as not to confuse ? from the a ? b : c statements with a?.b statements:

var x = a..b..c..d; //this would be ideal to understand that you assume that if any of a, b, c is null or undefined the result will be null or undefined.

Two dots, means if its null or undefined stop processing further and assume the result of expression is null or undefined. (as d would be null or undefined).

Two dots make it more clear, more visible and more space-wise so you understand what's going on.

What do you think folks?

Do you also have a proposal on how to handle a["b"]["c"]["d"], so with possibly variable keys.

In any case, I think that the existential operator (whatever the exact sign used is) will be better then the current way of chaining &&.

, Sander

# Eli Perelman (8 years ago)

2 dots may be problematic when parsing numbers (yeah, I know it's probably not common, but it's still valid):

3..toString()

Eli Perelman

# Angel Java Lopez (8 years ago)

Proposal for variable keys:

a.["b"].["c"].["d"]

# Laurentiu Macovei (8 years ago)

Yes! I have updated my answer using markdown and also posted on the original issue of TypeScript. Microsoft/TypeScript#16

Is there a better place to propose it for ES6/ES7 ?

This would be amazing operator!! Especially for ES6/ES7/TypeScript

var error = a.b.c.d; //this would fail with error if a, b or c are null or
undefined.
var current = a && a.b && a.b.c && a.b.c.d; // the current messy way to
handle this
var currentBrackets = a && a['b'] && a['b']['c'] && a['b']['c']['d']; //the
current messy way to handle this
var typeScript = a?.b?.c?.d; // The typescript way of handling the above
mess with no errors
var typeScriptBrackets = a?['b']?['c']?['d']; //The typescript of handling
the above mess with no errors

However I propose a more clear one - as not to confuse ? from the a ? b : c statements with a?.b statements:

var doubleDots = a..b..c..d; //this would be ideal to understand that you
assume that if any of a, b, c is null or undefined the result will be null
or undefined.
var doubleDotsWithBrackets = a..['b']..['c']..['d'];

For the bracket notation, I recommend two dots instead of a single one as it's consistent with the others when non brackets are used. Hence only the property name is static or dynamic via brackets.

Two dots, means if its null or undefined stop processing further and assume the result of expression is null or undefined. (as d would be null or undefined).

Two dots make it more clear, more visible and more space-wise so you understand what's going on.

This is not messing with numbers too - as is not the same case e.g.

1..toString(); // works returning '1'
var x = {};
x.1 = {y: 'test' }; //fails currently
x[1] = {y: 'test' }; //works currently
var current = x[1].y; //works
var missing= x[2].y; //throws exception
var assume= x && x[2] && x[2].y; // works but very messy

About numbers two options: Your call which one can be adopted, but I recommend first one for compatibility with existing rules!

  1. Should fail as it does now (x.1.y == runtime error)
var err = x..1..y; // should fail as well, since 1 is not a good property
name, nor a number to call a method, since it's after x object.
  1. Should work since it understands that is not a number calling a property from Number.prototype
var err = x..1..y; // should work as well, resulting 'test' in this case
var err = x..2..y; // should work as well, resulting undefined in this case

With dynamic names:

var correct1 = x..[1]..y; //would work returning 'test'
var correct2 = x..[2]..y; //would work returning undefined;

What do you think folks?

Best , Laurenţiu Macovei

On Thu, Oct 29, 2015 at 7:29 PM, Sander Deryckere <sanderd17 at gmail.com>

wrote:

# Maël Nison (8 years ago)

As a side note, this feature has recently been added to Ruby (issue bugs.ruby-lang.org/issues/11537). They use the "foo.?bar" syntax instead of "foo?.bar" because of a grammar conflict (ruby identifiers may end with an interrogation mark).

Is there something wrong with the "foo?.bar" syntax? It seems to be supported about anywhere (where this feature is implemented, at least), so anything else might be a bit confusing for most users.

The following language implement this feature and syntax: C#, Groovy, Swift, Ruby (with a twist)

Le jeu. 29 oct. 2015 à 19:53, Laurentiu Macovei <laurentiu.macovei at gmail.com>

a écrit :

# Laurentiu Macovei (8 years ago)

foo?.bar and foo?['bar'] syntax would work too.

However the using both current ? : operator and ?. might be very confusing on the same line.

e.g. using ?. and ?['prop']

var a = { x: { y: 1 } };
var b = condition ? a?.x.?y : a?.y?.z;
var c = condition ? a?['x']?['y'] : a?['y']?['z'];

as opposed to double dots .. and ..['prop']

var a = { x: { y: 1 } };
var b = condition ? a..x..y : a..y..z;
var c = condition ? a..['x']..['y'] : a..['y']..['z'];
Which one does look more clear to you?
# Waldemar Horwat (8 years ago)

On 10/29/2015 12:19, Laurentiu Macovei wrote:

foo?.bar and foo?['bar'] syntax would work too.

No. It would break existing code:

x = foo?.3:.5;

x = foo?[a]:[b];

On the other hand, turning .. into a token should be fine.

 Waldemar
# Claude Pache (8 years ago)

Le 29 oct. 2015 à 19:32, Eli Perelman <eli at eliperelman.com> a écrit :

2 dots may be problematic when parsing numbers (yeah, I know it's probably not common, but it's still valid):

3..toString()

Eli Perelman

Treating .. as one token would be a breaking change, but I don't think it is a problem in practice, as 3..toString() would continue to work. In some cases – as in 3..toStrign() –, undefined will be produced where an error was thrown.

# Claude Pache (8 years ago)

Le 29 oct. 2015 à 21:04, Waldemar Horwat <waldemar at google.com> a écrit :

On 10/29/2015 12:19, Laurentiu Macovei wrote: foo?.bar and foo?['bar'] syntax would work too.

No. It would break existing code:

x = foo?.3:.5;

That could be resolved by a simple lookahead, I think.

x = foo?[a]:[b];

That one is more problematic. IIRC, it was once suggested to use?.[ instead.

# Isiah Meadows (8 years ago)
  1. foo?.3:.5 should be unambiguously foo ? 0.3 : 0.5, because 3 is a number, not an identifier. foo?.3 in any other context should be a syntax error. It's also inconsistent with array access otherwise.
  2. I wouldn't have a problem with object?.[prop], since that's only one character more. It's still a lot easier.
# Waldemar Horwat (8 years ago)

On 10/29/2015 14:20, Claude Pache wrote:

Le 29 oct. 2015 à 19:32, Eli Perelman <eli at eliperelman.com> a écrit :

2 dots may be problematic when parsing numbers (yeah, I know it's probably not common, but it's still valid):

3..toString()

Eli Perelman

Treating .. as one token would be a breaking change,

Exactly what existing code would it break?

but I don't think it is a problem in practice, as 3..toString() would continue to work.

It would continue to work for the trivial reason that 3..toString() doesn't contain a .. token. It's the number 3. followed by a . and then an identifier and parentheses.

This is no different from 3.e+2 not containing a + token.

In some cases – as in 3..toStrign() –, undefined will be produced where an error was thrown.

No, this would continue to throw an error.

 Waldemar
# Claude Pache (8 years ago)

Le 30 oct. 2015 à 00:07, Waldemar Horwat <waldemar at google.com> a écrit :

On 10/29/2015 14:20, Claude Pache wrote:

In some cases – as in 3..toStrign() –, undefined will be produced where an error was thrown.

No, this would continue to throw an error.

Oops, you're right. So, .. is 100% backward-compatible.

# Ron Waldon (8 years ago)

Yep. I agree now. I see that this would break loads of existing code. Thanks.

On Fri, 30 Oct 2015, 12:23 <es-discuss-request at mozilla.org> wrote:

Send es-discuss mailing list submissions to es-discuss at mozilla.org

To subscribe or unsubscribe via the World Wide Web, visit https mail.mozilla.org/listinfo/es-discuss:// mail.mozilla.org/listinfo/es-discussmail.mozilla.org, mail.mozilla.org/listinfo/es-discuss/ mail.mozilla.org/listinfo/es-discusslistinfo mail.mozilla.org/listinfo/es-discuss/ mail.mozilla.org/listinfo/es-discusses-discuss mail.mozilla.org/listinfo/es-discuss

or, via email, send a message with subject or body 'help' to es-discuss-request at mozilla.org

You can reach the person managing the list at es-discuss-owner at mozilla.org

When replying, please edit your Subject line so it is more specific than "Re: Contents of es-discuss digest..." Today's Topics:

  1. Re: Re: Existential Operator / Null Propagation Operator (Laurentiu Macovei) (Isiah Meadows)
  2. Re: Existential Operator / Null Propagation Operator (Waldemar Horwat)
  3. Re: Existential Operator / Null Propagation Operator (Claude Pache)
  4. Re: Map literal (Alexander Jones)

---------- Forwarded message ---------- From: Isiah Meadows <isiahmeadows at gmail.com>

To: Ron Waldon <jokeyrhyme at gmail.com>, es-discuss at mozilla.org

Cc: Date: Thu, 29 Oct 2015 23:03:28 +0000 Subject: Re: Re: Existential Operator / Null Propagation Operator (Laurentiu Macovei)

I strongly oppose. I already write a ton of code that relies on that throwing, using that for testing purposes. I'd rather something throw violently than to silently fail in an unexpected, potentially seemingly unrelated place. Not even pure functional programming can act as a safety net for implicit undefined/null access.

On Thu, Oct 29, 2015, 15:30 Ron Waldon <jokeyrhyme at gmail.com> wrote:

Has anyone considering just making dot-property access return intermediate undefined or null values by default?

Not having to introduce new syntax would be a bonus. I'm trying to think of existing code that this would break and can't think of any good examples.

The only compatibility issue I have thought of so far is code that relies on an Error being thrown but also does not check the value:

let value;
try { value = deep.deep.deep.prop; } catch (err) { /* ... */ }
// use value without even a basic truthy test
# Isiah Meadows (8 years ago)

It's visually ambiguous. I'd rather not read 1..toString() and foo..bar in the same file. Not with greatly differing meanings.

# Claude Pache (8 years ago)

Le 30 oct. 2015 à 11:11, Isiah Meadows <isiahmeadows at gmail.com> a écrit :

It's visually ambiguous. I'd rather not read 1..toString() and foo..bar in the same file. Not with greatly differing meanings.

No, (1.).toString() and (1)..toString() have strictly the same observable effect, so that their formal difference of semantics can be happily ignored.

# Isiah Meadows (8 years ago)

Observable effect doesn't mean same process. Granted, the case with a number literal is very obscure, anyways, so I'm not that worried about it.

# mads.k at jubii.dk (8 years ago)

Why isn't it possible to use the obj.property?.sub syntax in combination with lookahead as suggested by Brendan Eich 4 years ago?

strawman:existential_operator

# John Lenz (8 years ago)

It is a parser problem:

obj.prop?.2:.1

You need arbitrary look ahead to disambiguate ?. from ?: solve the problem.

# Claude Pache (8 years ago)

Le 19 mai 2016 à 18:46, John Lenz <concavelenz at gmail.com> a écrit :

It is a parser problem:

obj.prop?.2:.1

You need arbitrary look ahead to disambiguate ?. from ?: solve the problem.

No, you just need a one-character lookahead checking for a digit.

The response of the original question is "mu", because it is possible.

# Isiah Meadows (8 years ago)

I will note that JavaScript does already require n-token lookahead worst case to disambiguate arrow functions from sequence expressions.

foo((a, {b}) => b)

foo((a, {b}) <= b)

Also, that proposal is not syntactically ambiguous, since numbers are not allowed to start an identifier.

# Kevin Smith (8 years ago)

I will note that JavaScript does already require n-token lookahead worst case to disambiguate arrow functions from sequence expressions.

The syntax is actually specified in terms of cover grammars, not arbitrary lookahead.

# Isiah Meadows (8 years ago)

I'm aware it's specified as a cover grammar, which is the easiest way I'm aware of to do it in a traditional declarative grammar. If you're writing a parser, though, you'll probably be using a mixture of lookahead and speculative parsing, or something to that effect, in practice, since it's faster.

# Brendan Eich (8 years ago)

You need to be very careful hacking around in an ad-hoc parser. It's easy to diverge from the formal (and verified) grammar by accident. Ambiguous grammars with ad-hoc disambiguation rules codified only by your parser's source code are bad business. Voice of experience here.

# Ron Waldon (8 years ago)

Once upon a time, there was a fascinating proposal on this subject:

Rather than introduce new syntax, Sebastian's proposal was to automatically propagate undefined values: if we're about to throw a dot-property-access-on-undefined error, we just return undefined instead.

I could find much discussion about this here, but I did find lots of discussions about approaches involving alternative syntax.

# Oriol Bugzilla (8 years ago)

I disagree with silently ignoring property access on null/undefined.

Early errors are nice

Yes, exactly. Errors should fail early and loudly. That's why the strictness of strict mode is useful.

It's no weirder that 123.foo not throwing.

No, it's entirely different, because numbers are object-coercible.

# Michał Wadas (8 years ago)

Would break the web.

# Ron Waldon (8 years ago)

Once upon a time, there was a fascinating proposal on this subject:

Rather than introduce new syntax, Sebastian's proposal was to automatically propagate undefined values: if we're about to throw a dot-property-access-on-undefined error, we just return undefined instead.

I could find much discussion about this here, but I did find lots of discussions about approaches involving alternative syntax.

# Kagami Rosylight (8 years ago)

Is the only problem here is the parser problem with obj.prop?.2:.1? Then how about ??. instead of ?.?

Once upon a time, there was a fascinating proposal on this subject:

Why are you posting twice? :/

# Oriol Bugzilla (8 years ago)

I disagree with silently ignoring property access on null/undefined.

Early errors are nice

Yes, exactly. Errors should fail early and loudly. That's why the strictness of strict mode is useful.

It's no weirder that 123.foo not throwing.

No, it's entirely different, because numbers are object-coercible.

# Michał Wadas (8 years ago)

Would break the web.

# Kagami Rosylight (8 years ago)

Or !., which unfortunately is now being used by TypeScript?

# Isiah Meadows (8 years ago)

TypeScript can change if it has to, and it's done so before (ES modules are a good example of this). They try their best to be a strict superset of ECMAScript, and this even goes as far as making type errors early warnings, not early errors, by default (the latter would technically be a violation of section 16, paragraph 3).

# Claude Pache (8 years ago)

Le 13 oct. 2016 à 14:37, Kagami Rosylight <saschanaz at outlook.com> a écrit :

Or !., which unfortunately is now being used by TypeScript?

What is exactly the issue you're trying to solve? The token ?. works fine (technically with a simple lookahead for excluding digit after it).

# Kagami Rosylight (8 years ago)

The token ?. works fine

I think more than half of this thread is about syntactic ambiguity, regardless of whether the ambiguity is real or not. For example, from an earlier post of this thread:

But what should be done with cases like obj?[1]?[2]:[3].

A formatter may help this and make it obj?[1] ? [2] : [3] or obj ? [1]?[2] : [3] depending on operator precedence, but shouldn’t it be more clear? obj![1]?[2]:[3] will not be confused with ternary operator.

# Isiah Meadows (8 years ago)

IIRC the proposed syntax for computed properties was x?.[y], to avoid the ambiguity.

# Kagami Rosylight (8 years ago)

IIRC the proposed syntax for computed properties was x?.[y],

Yes you’re right, sorry :/

IMO it still seems the syntax problem is the main reason why this proposal has stalled. If not, what is the problem here? I’m curious why this proposal is not even listed in stage 0 proposal list.

# Isiah Meadows (8 years ago)

It may be a good idea to create a pull request for it if it isn't listed yet (search "null propagation JavaScript"). I know there's a proposal written out (I've seen it), I just don't recall the exact URL offhand nor if there's a champion or not, but I thought it did. It could be one of those looking for a new champion (that's why the bind operator proposal has also stagnated).

# Claude Pache (8 years ago)

Le 13 oct. 2016 à 17:14, Kagami Rosylight <saschanaz at outlook.com> a écrit :

IIRC the proposed syntax for computed properties was x?.[y],

Yes you’re right, sorry :/

IMO it still seems the syntax problem is the main reason why this proposal has stalled. If not, what is the problem here?

The issue with ?.[ is that it is considered as not pretty by some people. A syntax that is at the same time pretty, technically working, and not confusing is difficult to find.

Concerning your suggestion of using !: From a technical point of view, using ![ instead of ?.[ may work only if you forbid a line terminator before the !, because the following program is valid as of today (with implied semicolons):

foo
![42]

I’m curious why this proposal is not even listed in stage 0 proposal list.

Because no representative of TC39 has volunteered to champion it.

# Claude Pache (8 years ago)

Le 13 oct. 2016 à 17:32, Isiah Meadows <isiahmeadows at gmail.com> a écrit :

It may be a good idea to create a pull request for it if it isn't listed yet

I've already tried some time ago: tc39/ecma262#340

# Bob Myers (8 years ago)

Why is this needed? Why are people trying to get the property of an object which is null? Why is the object null in the first place? This can probably be considered poor program design. It's sort of like trying to dereference a null pointer. In addition, parameter defaults and defaults in destructuring may make this somewhat less of an issue.

Note that TS2 is explicitly moving away from permitting null to be assigned to something which is alleged to be an object. (Although TS2 has "stolen" the ! operator, it is merely a type assertion--a narrowing from object | null to object as I understand it. It is not a run-time check.)

But let's say we nevertheless think this is an important feature. It has been discussed at great length here. No proposal has ever had the inevitability, generality, or intuitiveness that would allow it to gain traction. All the proposals are essentially little syntactic hacks.

Can we find some more general extension to JS syntax that solves or mitigates this problem as well as others? Kills two birds with one stone? One that seems like a natural extension to current syntax, instead of an extra magic character we stick somewhere to solve one specific problem?

Just as an example, consider the following idiom for null propagation:

a ? a.b ? a.b.c : undefined : undefined

We can leverage this pattern by allowing the : in the ternary operator to be omitted (defaulting to undefined), allowing us to write:

a ? a.b ? a.b.c

Whether you love it or hate it, at least this solves more problems that just null propagation. I'm not seriously suggesting this. I'm just saying we need to be more creative in brainstorming possible solutions to the problem.

-- Bob

# Kagami Rosylight (8 years ago)

Why is this needed? Why are people trying to get the property of an object which is null?

I will appreciate null propagation when a function receives an “option bag”

function someFunction(options) {
  if(options?.foo) {
    doSomething();
  };
}

someFunction();
someFunction({ foo: true });
# Mark Volkmann (8 years ago)

I think the point is that people would like to write something like this:

if (person?.address?.zipcode)

instead of this:

if (person && person.address && person.address.zipcode)

That appeals to me.

# Claude Pache (8 years ago)

Le 13 oct. 2016 à 19:20, Bob Myers <rtm at gol.com> a écrit :

Why is this needed? Why are people trying to get the property of an object which is null? Why is the object null in the first place?

This is not about trying to get something from null, but about taking different paths according to when a reference is null or not without needing to assign to temporary variables, writing complete if structures, and/or repeating oneself.

(...)

Just as an example, consider the following idiom for null propagation:

a ? a.b ? a.b.c : undefined : undefined

We can leverage this pattern by allowing the : in the ternary operator to be omitted (defaulting to undefined), allowing us to write:

a ? a.b ? a.b.c

Whether you love it or hate it, at least this solves more problems that just null propagation. I'm not seriously suggesting this. I'm just saying we need to be more creative in brainstorming possible solutions to the problem.

You can already writea && a.b && a.b.c in JS... but you still have to repeat a thrice andb twice, which is an issue if a and b are complex or lengthy expressions. Sometimes I am tempted to write something in the lines of (_ = a.b) && _.c in order to avoid the issue, but it is less readable.

Here is a more complex although somewhat contrived example: If an <input> element named "foo" is inside a <details> section, open the latter in order to reveal the former:

document.querySelector("input[name=foo]")?.closest(".details")?.open = true

(The short-circuiting mechanism, which is an important part of the semantics in my proposal, ensures that the assignment is performed only when the expressions just before the ?s are not null/undefined.)

# Isiah Meadows (8 years ago)

On Thu, Oct 13, 2016, 12:07 Claude Pache <claude.pache at gmail.com> wrote:

Le 13 oct. 2016 à 17:14, Kagami Rosylight <saschanaz at outlook.com> a écrit :

IIRC the proposed syntax for computed properties was x?.[y],

Yes you’re right, sorry :/

IMO it still seems the syntax problem is the main reason why this proposal has stalled. If not, what is the problem here?

The issue with ?.[ is that it is considered as not pretty by some people. A syntax that is at the same time pretty, technically working, and not confusing is difficult to find.

I agree with both points here. It's not very pretty, and it's also inconsistent with the rest of the language. I was just clarifying what I believed to be the primary contender, independent of bias.

Concerning your suggestion of using !: From a technical point of view, using ![ instead of ?.[ may work only if you forbid a line terminator before the !, because the following program is valid as of today (with implied semicolons):

foo
![42]

I want to like the idea, but many languages (e.g. Swift, Kotlin, and I think TypeScript 2.0) use it in the inverse direction: non-null assertion for nullable types. I'm not sure I like the syntax in either form (it has at least the ability to be non-ambiguous).

I’m curious why this proposal is not even listed in stage 0 proposal list.

Because no representative of TC39 has volunteered to champion it.

# Kagami Rosylight (8 years ago)

From a technical point of view, using ![ instead of ?.[ may work only if you forbid a line terminator before the !

I tried this on TS Playground and it interestingly changes behavior when there is a line break before !.

var a = {};

a![3]; // works as a[3]
a
![3]; // preserves original behavior

but many languages (e.g. Swift, Kotlin, and I think TypeScript 2.0) use it in the inverse direction: non-null assertion for nullable types.

Right. :/

# Igor Baklan (7 years ago)

For me .?. looks more strict. With variations: a.?.b.?.c, a.?(args), a.?[key]. Since I would rather look on it like on something similar to C# extension method (or Scala implicit method), and then in its "full/extended form" it can be

a.$selfOrNullObj().b.$selfOrNullObj().c

Where .$selfOrNullObj(). exactly corresponds to .?. (or in other words .?. might be shortcut for .$selfOrNullObj().)

And in terms of extension method this-argument not required to be not-null (it is valid case when null passed in place of this-argument into that static method which is extension method for some other class).

Then in this case (inspired by that approach) it can be approximately declared like:

obj.?

<==>

obj.$selfOrNullObj()

<==>

(obj != null ? obj : {_proto_:null} )
// or (obj != null ? obj : ()=>{}) to be compatible with ``a.?(args)``

Then it also could be proposed some variation with fallback to particular default, like

obj.$selfOrDefault(defObj)

<==>

obj.??(defObj)

<==>

(obj != null ? obj : defObj )

Combining with Nil approach (some null object which semantically the same as null, but returns itself for any operation - ., [], () ; can be easily implemented as Proxy object for ()=>{}), we can achieve some sort of transitiveness

a.??(nil).b.c.d.??(null)

But in general it fails if for example a.b != null but a.b.c == null, and in this case this construct should work in more advanced way - like, default value should be used not only for that particular .??(Nil). operation, but for all consequent . operations too, until that default value will not be reset back to null by trailing .??(null) operation (which also should replace nil with null).