Wiki

Ticket #339 (assigned enhancement)

Opened 11 years ago

Last modified 11 years ago

Provide a nil safe dereference operator

Reported by: hopscc Owned by: Chuck
Priority: medium Milestone:
Component: Cobra Compiler Version: 0.9.4
Keywords: Cc:

Description

Provide an operator that will allow deref through a chain of calls and member accesses even if something in the chain returns nil.
(nilsafe/elvis operator)

Like DOT operator but returns nil if prior element return nil
See  Spaces around binary Ops

Preference for operator is ?. (QUESTION_DOT), Operation is analogous to DOT except that a nil ref short ccts and returns nil for the expression (chain).

# raw: name is nil or trimmed capitalized string
name = customer?.name?.trim.capitalized 

# w/nilCoalesce: name is empty string or trimmed capitalized string
name = customer?.name?.trim.capitalized ? ""

Should handle non idempotent calls/derefs.

If ambiguity between this and nil coalese op on trailing member ref then need space wrapped ops which should be done (if done) as a separate step.

Attachments

nil-safe-deref.patch Download (11.6 KB) - added by hopscc 11 years ago.
nil-safe-deref-updated.patch Download (13.0 KB) - added by hopscc 11 years ago.

Change History

Changed 11 years ago by hopscc

Changed 11 years ago by hopscc

  • owner changed from hopscc to Chuck
  • status changed from new to assigned

Code changes and tests for nilsafe deref (using '?.' as operator)
Always captures derefs to internal temp var for non idempotent call handling

No attention given to ambiguity to nil-coalesce with dot ref following

result = a.b ? .other # nil coalesce test
# treated as 
result = a.b?.other # nilsafe deref  to .other
# and probably fail

can correct using a tmp variable

tmpOther = .other
result = a.b ? tmpOther

Changed 11 years ago by Charles

related to ticket:341 - "Require (some) binary operators to have spaces around them"

Changed 11 years ago by hopscc

rework patch as suggested in Forum discussion page 4.
Use .isImplicit and add more commentary on what is being done with AST nodes synthesized for nilsafe deref op.
Comment tests as to use of inverse coalesce operator sequences vs nilSafe deref op.

Changed 11 years ago by hopscc

Note: See TracTickets for help on using tickets.