nim-lang / RFCs

A repository for your Nim proposals.
135 stars 26 forks source link

Document guarantees on common "interfaces" #335

Open mratsim opened 3 years ago

mratsim commented 3 years ago

We have common idioms on types and collections and it would be useful to document what they imply so that new libraries avoid surprising their users.

For example for a long time the builtin sets (not hashsets) didn't provide len but instead card (cardinality). That was because counting the number of elements required checking all bits for 1. From an old discussion with @Araq on IRC, len was supposed to be O(1) or very cheap. Once Nim used the compiler builtin popcount instruction which counted that in 1 cycles (or 2 for 2 bytes sets) len could be used.

There are other assumptions that would be helpful to clarify.

For example items for large objects should return a borrowed element so that it does not copy, or we get this: https://github.com/nim-lang/Nim/issues/14421.

get in Options, Result and other monad unwrappers should return a lent on get to avoid copies as well, or we get slowness (https://github.com/nim-lang/Nim/pull/14417) or we can even run out of stack space https://github.com/nim-lang/Nim/pull/15208. Additionally they likely should be inlined.

haxscramper commented 3 years ago

I could say some interfaces are partially documented in nep1 naming conventions, though it only implicitly hints that you should have names like len, []= etc. Adding a new section for style guide should not be particularly difficult, especially when it comes to specifying interfaces for common collections.

Such assumptions might potentially be formalized with use of concepts (when they are ready), and maybe even used in stdlib like it was proposed in https://github.com/nim-lang/RFCs/issues/41, though I'm not sure how relevant this is overall. This is also related to https://github.com/nim-lang/RFCs/issues/247 which describes needed interfaces using concepts.