JuliaLang / julia

The Julia Programming Language
https://julialang.org/
MIT License
45.78k stars 5.49k forks source link

allow a package to forbid its users from overloading a function #54138

Open nsajko opened 7 months ago

nsajko commented 7 months ago

Motivation

Sometimes when designing an API, one wants to have a pair of public functions, where one is meant to be called by users, while the other is for users to overload (add methods to). An example in Base is the promote_type and promote_rule function pair. The promote_type doc string is clear about users being forbidden from overloading this function:

Don't overload this directly

To overload promotion for your own types you should overload promote_rule.

Still, many packages do overload promote_type:

https://juliahub.com/ui/Search?q=promote_type&type=symbols&u=define&t=function

Proposed solutions

Some alternatives:

  1. Allow a function to be marked as overloadable only from the module where it's declared
  2. Allow a function to be marked as overloadable only from the package where it's declared

Nota bene

This issue arguably ties into the function/method sealing issue: #31222.

This issue arguably ties into the API specification issue: #49973.

vtjnash commented 7 months ago

There is a hidden field of MethodTable that can be set to enable this (it exists for Builtin, as the runtime would likely segfault if someone unintentionally added a Method there). It is almost certainly not stable, but may be useful anyways to set inside Base, where overloading the wrong method may be common and lead to confusion (eg perhaps promote_type) or bugs (eg perhaps typejoin). However, it currently isn't general enough to prevent abusing getproperty to introduce unsoundness either, as it works at the MethodTable level, not on particular Methods