问题
I’m trying to figure out what the differences are between the above-mentioned routines, and if statements like
say $y.Bool;
say $y.so;
say ? $y;
say so $y;
would ever produce a different result.
So far the only difference that is apparent to me is that ? has a higher precedence than so. .Bool and .so seem to be completely synonymous. Is that correct and (practically speaking) the full story?
回答1:
What I've done to answer your question is to spelunk the Rakudo compiler source code.
As you note, one aspect that differs between the prefixes is parsing differences. The variations have different precedences and so is alphabetic whereas ? is punctuation. To see the precise code controlling this parsing, view Rakudo's Grammar.nqp and search within that page for prefix:sym<...> where the ... is ?, so, etc. It looks like ternary (... ?? ... !! ...) turns into an if. I see that none of these tokens have correspondingly named Actions.pm6 methods. As a somewhat wild guess perhaps the code generation that corresponds to them is handled by this part of method EXPR. (Anyone know, or care to follow the instructions in this blog post to find out?)
The definitions in Bool.pm6 and Mu.pm6 show that:
In
Mu.pm6the method.BoolreturnsFalsefor an undefined object and.definedotherwise. In turn.definedreturnsFalsefor an undefined object andTrueotherwise. So these are the default..defined is documented as overridden in two built in classes and .Bool in 19.
so,.so, and?all call the same code that defers toBool/.Bool. In theory classes/modules could override these instead of, or as well, as overriding.Boolor.defined, but I can't see why anyone would ever do that either in the built in classes/modules or userland ones.notand!are the same (except that use of ! with :exists dies) and both turn into calls tonqp::hllbool(nqp::not_i(nqp::istrue(...))). I presume the primary reason they don't go through the usual.Boolroute is to avoid marking handling of Failures.There are
.soand.notmethods defined inMu.pm6. They just call.Bool.There are boolean bitwise operators that include a
?. They are far adrift from your question but their code is included in the links above.
来源:https://stackoverflow.com/questions/56723974/differences-between-bool-so-and-so