r/ProgrammingLanguages • u/Big-Rub9545 • May 24 '26
References in pass-by-sharing languages
Returning with yet another design question to get some opinions from people here.
My language currently uses a pass-by-sharing model to move data around. Each object is just a type tag + data (which is either actual data, like a number, or a pointer to a larger structure).
Languages that use this model (e.g., Python and Java) typically do not provide any way to actually *reassign* an object to a different value in a function and have that change be reflected outside it, while systems languages, which I’m more accustomed to, provide that through references (in C++) or mutable borrowing (in Rust). In the former group, you can still modify an object’s internal data, but reassigning it to something else immediately breaks the connection between it and the original object argument that was passed in.
I added “references” (which are wrappers around locations of existing objects so you can modify the actual objects stored elsewhere) to my language to allow this. However, this leads to some issues. First, since it’s dynamically typed, you can only indicate that a particular function parameter/argument will be a reference at the call-site (except if you use unenforced type hints in the function signature). Second, there is some additional overhead since every reference has to effectively be dereferenced (unwrapped, if you will) every time it is used. Likely some other issues that aren’t coming to mind right now.
I wanted to ask people on here (primarily as language users) whether they think pass-by-reference (in the way the term is used in C++, not Java) would be a useful feature with the above object model (consider languages like Python or Java), and if not, what alternative approaches/features they find useful or conventional to mutate variables through function calls.
Edit: rewrote the post to be less confusing (hopefully).
19
u/Pleasant-Form-1093 May 24 '26
In languages like Java or Python, all composite types are inherently references and are always allocated on the heap, these languages don't have the concept of allocating memory for composite types on the stack. (In fact afaik the JVM spec only allows the stack frame slots to be either of primitive types or hold references to objects).
This means that adding references to a language like this (which I think your language is also like, correct me if I am wrong) is kind of redundant. All objects are references to the heap anyway. But if your language allows creating objects on the stack as well, then there is a critical distinction because now objects can either be passed by value or reference (in Python and Java, composite types can't be passed by value unless you create a copy explicitly and pass said copy).
So, from what I can gather unless you allow objects to be created on the stack, references to objects are not really required as a distinct concept as objects are references.
3
u/AustinVelonaut Admiran May 24 '26
What you are talking about are also referred to as
inoutparameters in e.g. Ada, Swift, Pascal. They are used in place of multiple return values that some other languages like Lisp, Dylan have. Since Lisp tends to be dynamically-typed, like your language, you might investigate how multiple-return values are implemented there, for ideas.2
u/sazasoo May 25 '26
pass-by-sharing means variables are essentially pointers to objects passed by value, if you introduce a reference to a variable, you are creating a pointer to a pointer, a big issue with that is memory safety and escaping references.
Local variables live on the execution stack, if you pass a reference to a local variable into a function, you are passing a stack memory address, if that function saves this reference in a global state and the caller function returns, the original stack frame is destroyed and the global reference points to garbage. dynamic languages usually relies on a GC or reference counting, which manages objects, not stack-bound variable references.
One alternative you could look into is explicit boxing by wrapping the data in a mutable container.
1
u/dnabre May 24 '26
This may just be terminology. Java explicitly has references but not pointers. Where references provide extra guarantees than pointers (e.g. not point to dead memory, being either `null` or a valid object). I don't know what terms Python uses. But "handle-like object" is really confusing here. I think you are mixing language implementation and language semantics in a way that is hard to follow.
3
u/phischu Effekt May 25 '26
Instead of these awkward parameter passing modes, functional languages like Scheme and OCaml have a separate type of mutable references that you create explicitly. So your example becomes:
No confusion arises.
2
u/binarycow May 25 '26
C# works the same as Java, but also allows for pass by reference.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref
2
u/processeus1 May 27 '26
You can always take a parameter and reassign it at the call site to a returned value.
x = f(x)
Nonetheless, I'd encourage you to use value types instead, without all the implicit sharing that can get you in trouble when starting to mutate stuff.
See mutable value semantics https://www.jot.fm/issues/issue_2022_02/article2.pdf and Hylo's `inout` passing convention: https://hylo-lang.org/docs/user/language-tour/functions-and-methods/#parameter-passing-conventions
1
u/initial-algebra May 24 '26 edited May 24 '26
First, to clear up some terminology. What you call an "object" is more commonly called a value, a fixed-size (today, usually 64-bit) pair of a tag and payload. Objects are larger bundles of data, allocated on the heap and pointed to by references, with references just being a particular kind of value (other kinds of values could include integers, floating-point numbers, symbols and so on). Arrays and "stack" frames are usually also objects.
Normally, references only point to entire objects, because it tends to be a hard requirement of the garbage collector. In order for the GC to work, it needs to know the size and layout of each object, which is stored as a header next to the object's data. If you want to have a reference to an individual object's field (equivalently, an element of an array, or a variable on the stack) then you need a "fat reference" that contains a reference to the entire object/array/frame and a symbol or offset that indicates a particular field/element/variable. I'm guessing this is what you mean when you say "Second, there is some additional overhead since every reference has to effectively be dereferenced every time it is used.", because normally a fat reference would have to be an object, adding another layer of indirection.
There are basically two alternatives.
1
u/Brave-Ad-8201 May 24 '26
Eu teria um pouco de receio de adicionar referências como mecanismo comum. Em linguagens como Python ou Java, a ideia que eu tenho é que a função pode alterar o estado interno de um objeto mutável, mas não trocar diretamente a variável do chamador. Então permitir isso por referência parece mudar bastante o modelo mental da linguagem.
Talvez seja útil em alguns casos, tipo swap ou parâmetros de saída, mas numa linguagem dinâmica eu acho que pode ficar menos claro saber quando uma função está só usando um valor e quando ela pode alterar uma variável de fora. Eu provavelmente preferiria retornar o novo valor ou retornar múltiplos valores
Então não acho que seja uma ideia errada, mas eu deixaria como algo bem explícito e mais excepcional, não como o jeito principal de passar parâmetros.
1
u/wiremore May 25 '26
My scripting language is dynamically typed and has references similar to what you describe. My vm is written in C++ so I was also inspired by C++ reference types.
It lets you write functions that would need to be macros without references. For example
`(defn += (&a b) (set a (+ a b)))`. Neat. Also, `set` itself takes a reference as the first argument, which I think is in some ways more elegant than the classic lisp setq taking a symbol. You can also just say `(set (cdr a) b)` directly without needing setcdr or fancy setf macros, if cdr returns a reference.
Reference types are useful for implementing “upvals”, variables captured in a closure, which basically behave exactly like references under assignment, etc.
I also end up using it for efficient multiple return values. Returning a composite type also works but it allocates (i know it’s possible to implement it without allocating, but my language does). I’m used to programming in C++ with references and it frequently seems useful.
References complicate other things. It makes the language a little slower, because you need to push a reference to a stack variable instead of the value itself, and functions need to check if arguments are a reference type and automatically dereference. It makes escape analysis harder in the compiler, because any function call can theoretically modify any argument. The GC has to be aware, e.g. a heap reference to an element in the middle of a tuple needs to be updated when the tuple is moved by the compacting collector.
One neat thing is that you can tell if an argument is an rvalue or not (to borrow C++ terminology). My array library uses this information to reuse arrays that are about to be collected anyway, for example in `(+ (* a b) c)`, (* a b) allocates a new result array, but the + operation can reuse it because it is not passed in as a reference so it must be and rvalue (c is passed in as a reference).
I currently have 3 kinds of reference types, stack references, heap references, and pointers to C++ types, which are handled similarly in some ways. It’s feels a bit messy sometimes. I haven’t programmed in another dynamically typed language with references so I appreciate the novelty. I can’t say conclusively whether it was a good idea for my language, I think maybe the benefits outweigh the complexity, but hopefully my experience gives you some context.
1
u/gplgang May 26 '26
I think Ref<T> (essentially
type Ref<T> = { mutable value: T }) covers this for languages like Java.NET has both value types and reference types and has in/out/ref parameters where it does pass the variable reference
1
u/iMandy1005 Jun 07 '26
Assim, opinião de uma leiga, >eu< manteria a passagem por compartilhamento como padrão e deixaria referências como algo explícito. Acho que ela oferece um trade-off bom entre flexibilidade e previsibilidade. Referências podem ser úteis para alguns casos, mas quando tudo pode ser modificado indiretamente através de chamadas de função fica mais difícil raciocinar sobre o estado do programa e entendê-lo. Por isso eu as deixaria como um recurso explícito, usado apenas quando o programador realmente precisa desse comportamento.
1
u/SuspiciousEbb4734 Jun 10 '26
I think pass-by-reference like in C++ can be useful in a pass-by-sharing language, but it often comes with complexity that users may not expect in a Python- or Java-style environment.
A few considerations:
Predictability – Many users of dynamically typed, pass-by-sharing languages expect that reassigning a parameter won’t affect the caller. Introducing references changes that mental model, so it should be clearly documented and optionally explicit.
Alternatives – Instead of full pass-by-reference, you could provide mutable container types, like lists, dicts, or structs, that users can modify in-place. That’s essentially how Python handles mutability.
Selective usage – Consider making references opt-in only for functions that need them, instead of implicitly allowing it for all parameters.
Overall, yes, references can be useful if your language aims to give low-level control similar to C++, but for most cases, in-place mutation of objects and immutable-by-default reassignment is simpler and safer for users coming from dynamic languages.
0
u/[deleted] May 25 '26
[deleted] — view deleted comment