Safe-dereference operator?
Craig Ringer
craig@2ndquadrant.com
Fri Jul 17 03:22:32 GMT 2020
Hi
TL;DR: Proposal to add a safe-dereference pseudo-operator like Groovy's ?.
to the language to simplify chasing pointer chains.
?. is basically an abbreviated ternary without the multiple-evaluation
hazard:
a ?. b ?. c
is (assuming that all expressions are pure and side-effect free) the same
as:
(!a ? 0 : (!a.b ? 0 : a.b.c))
i.e. this operator behaves like -> if the left operand is non-null. If the
left operand is null, it returns 0 and short-circuits out the right hand
expression. This is extremely useful when traversing chains of
possibly-null pointers.
Systemtap would possibly spell it as ?>, ?->, or similar, since the
systemtap convention is to use "->" for all dereferences.
Rationale:
When writing systemtap code I routinely find myself writing logic to
dereference a chain of pointers and return the result, unless any pointer
on the chain is null, in which case a default is returned.
Say I want to
return user_string($var->foo->bar)
I land up writing
ret = "";
foo = $var
if (foo != 0) {
bar = @cast(foo, "Foo")->bar;
if (bar != 0) {
ret = user_string(bar);
}
}
return ret
This is a tad tedious. Especially since systemtap does not track typeinfo
for locals, so you have to explicitly type everything.
It's possible to instead
try {
return user_string($var->foo->bar)
} catch (ex) {
return "";
}
but I'm not sure what performance implication that has, and more
importantly it may mask other unexpected errors that should not be caught
and swallowed.
A macro implementation is possible, but as noted above, prone to
multiple-eval hazards.
So - does this seem like something worth having in the language?
If so, would anyone here be willing to offer some advice on how feasible it
might be to implement, and where in the code I might want to start looking?
--
Craig Ringer http://www.2ndQuadrant.com/
2ndQuadrant - PostgreSQL Solutions for the Enterprise
More information about the Systemtap
mailing list