r/ProgrammingLanguages • github.com/mark-sed/moss-lang/ • 23d ago

Discussion Do you need a language to have context managers (with/using directive)?

In my language I was avoiding adding with or using directive for handling context of objects and tried to rather use a functional approach such as:

lines = with_open("f.txt", fun(f)=f.readlines(), "r")

But this does not always works or is convenient since often I need to do additional operations on the file afterwards. So lately I more and more lean towards actually adding support for using, otherwise I fear people would re-invent it anyway using try-finally blocks.

using (f = open("f.data", "rb")) {
    header = f.read(64)
    ~f.seek(128)
    data = f.read(32)
}

In this case in my language I would have to create a new function to do these 3 operations since lambdas can have only 1 expression:

fun handler(f:File) {
    header = f.read(64)
    ~f.seek(128)
    data = f.read(32)
    return [header, data]
}
header, data = with_open("f.data", handler, "rb")

So my question to you is, if you think that having context managers is really useful and a good addition to a language or rather an extra feature that can be avoided?

8 Upvotes

35 comments sorted by

23

u/PikachuKiiro 23d ago

lambdas can only have 1 expression

why

7

u/WittyStick 22d ago edited 22d ago

It's not entirely unusual in an expression based language - but there's usually syntax sugar for multiple expressions. Eg, Lisp uses a form (progn . exprs), and Scheme uses (begin . exprs), which are single expressions which evaluate each of the sub-expressions in sequence, ignoring intermediate results and returning the result of evaluating the last one as the result of the progn/begin expression.

The form:

(lambda (arg) expr expr2 expr3)

Is often syntax sugar for:

(lambda (arg) (begin expr1 expr2 expr3))

Where lambda might be a macro accepting different forms, but the underlying form is a one-expression bodied lambda and begin provides the multiple statements.

Also, the preferred function definition form:

(define (foo arg) expr1 expr2 expr3)

Is often syntax sugar for

(define foo (lambda (arg) (begin expr1 expr2 expr3)))

Python is a notable example of where there's no syntax sugar for multi-expression lambdas, but you can write your own begin to achieve the same thing - though you end up fulfilling Greenspun's tenth rule when you follow this approach.

1

u/mark-sed github.com/mark-sed/moss-lang/ 23d ago

A lambda in Moss is just a function that returns one expression so it has no code block:

fun sum(a, b) = a + b

Changing this would only make it so that lambdas would become the same as functions. So I would not change this, but what could be changed is to allow anonymous functions as arguments, but even then, my question about context managers would still stands.

30

u/latkde 23d ago

That's an odd choice. Lambdas and anonymous functions are generally the same thing (assuming that a nested function also captures its surrounding scope).

The odd one out is Python, which has to restrict lambdas to a single expression for purely syntactical reasons: statements are grouped by indentation, not by explicit delimiters. But your language clearly uses curly braces, so it need not inherit this Python misfeature.

7

u/mark-sed github.com/mark-sed/moss-lang/ 23d ago

They are internally (in bytecode) the same thing. I suppose I was lead astray with python's approach. I was hoping to also get something from the simplicity, such as some optimization opportunity, but so far that has not been the case.

Thanks for the comment, I'll look into this.

19

u/svick 23d ago

I think single-expression functions are not meaningfully different from multi-statement functions for optimization purposes. Especially once you start doing inlining.

-1

u/AromaticCredit1533 22d ago

I have always thought that the single-expression restriction is very interesting, one use case for lambdas is to re-bind function arguments to match a function signature to pass in as callback, a way to achieve something like partial application, but in a more declarative manner IMO. (you can also do partial application using partial of course, but I digress)

1

u/Key_River7180 Nain. 22d ago

Functional

30

u/latkde 23d ago

Pragmatically, any non-pure language will need some kind of deterministic resource management feature. Pick one of these:

  • RAII and scope guards
  • defer statements
  • with-statements / using / try-with-resource
  • lambdas that may contain arbitrary statements (relevant prior art: JS, Ruby)

A try-finally is generally not sufficient because the place that cleans up the resource tends to be far away from the place that acquires the resource, these should always be as close as possible. Also, it's easy to forget required cleanup steps if it's possible to acquire a resource through a mechanism that doesn't guarantee cleanup. Thus, defer-statements aren't a great idea either in new languages.

Your language sketch feels unsatisfactory because you've artificially restricted lambdas to a single expression. But even then, resource management via callbacks can be tricky when combined with other control flow, e.g. early returns out of a surrounding function, or breaking out of a surrounding loop. Ruby addresses this by having different kinds of nested functions that interact with control flow differently. In an imperative language that features control flow, introducing dedicated resource scope syntax will generally be more helpful.

3

u/mark-sed github.com/mark-sed/moss-lang/ 23d ago

Great points, thanks.

6

u/perlgeek 22d ago

So my question to you is, if you think that having context managers is really useful and a good addition to a language or rather an extra feature that can be avoided?

I've been doing quite a bit of programming in both Python (which has context managers) and Perl (which doesn't), and as a user I really like having context managers. It makes the lifetime of certain things (like file handles, in the open case) very obvious.

1

u/mark-sed github.com/mark-sed/moss-lang/ 22d ago

Thanks for your input.

6

u/tdammers 22d ago

Honestly, the difference between with_open and using in your examples is just an unpleasant consequence of the artificial distinctions between a "function" and a "block of code".

In a language that supports proper first-class anonymous functions (or, more accurately, procedures), your using example could just be written as:

with_open("f.txt", "r", fun(f) { header = f.read(64); f.seek(128); data = f.read(32))

To answer the actual question though: yes, I am 100% convinced that in a typical (imperative) language, some sort of resource management feature is necessary.

But it doesn't necessarily need to be a core language feature. If people re-invent this particular wheel properly, a sound with- abstraction on top of your language's exception machinery that's straightforward and safe to use, and that thing becomes a de facto standard function, then I don't see a problem with that at all.

In fact, this is exactly how it works in Haskell. The language itself doesn't do anything special to make this possible, but the bracket family of functions is widely used for this exact purpose, and they are implemented as plain Haskell function, using Haskell's exception handling features behind the scenes. Here's what that would look like:

bracket (openFile "f.txt" ReadMode) hClose (\h -> doSomethingWithHandle h)

But you would rather actually just use withFile, which is another abstraction on top of bracket, like this:

withOpenFile "f.txt" ReadMode (\h -> doSomethingWithHandle h)

So yeah, you want to make this stuff possible, convenient, and obvious, but depending on how your language works, the bracketing itself doesn't necessarily need to be a core language feature.

1

u/mark-sed github.com/mark-sed/moss-lang/ 22d ago

In a language that supports proper first-class anonymous functions

Yes, I'll add these functions soon, I mean even the version where there is nested function passed in is not that awful imo...

Thanks for the Haskell example, interesting stuff.

2

u/WittyStick 22d ago edited 22d ago

There's a distinction for with in the Scheme family - they take a lambda argent, but the lambda itself doesn't take any arguments - it's a thunk. The file is accessed through a dynamic binding (parameter in scheme).

Eg, with-input-from-file sets the dynamic variable current-input-port and then invokes the thunk. read accesses the current-input-port, so it needs no file descriptor as an argument.

6

u/MrJohz 22d ago

One thing that I've not seen people mention here yet is that all of your examples here involve indentation — the using/with_open/whatever always creates a new scope, it can't be part of an existing scope. So something like:

def read_config():
    using (f = open("f.txt")):
        header = f.read(64)
        # ... etc

That second indent is completely unnecessary — there's nothing going on before the using that we need to create a new scope for.

JavaScript's using syntax is simple assignment for this reason:

function read_config() {
    using f = open("f.txt");
    const header = f.read(64);
    // ... etc
}

This will close f when the current scope (in this case the function body) ends. And you can create arbitrary scopes by wrapping code in blocks, if there is a situation where you need to be more explicit about scoping:

function read_config() {
    {
        using f = open("f.txt");
        const header = f.read(64);
        // ... etc
    }
    // `f` is now out of scope and the file has been closed
}

I believe C#'s using can take this form in addition to the block form. In general, as long as you can create explicit scopes, having using just be a kind of variable declaration is exactly as powerful as the other form, and in my experience it is consistently nicer to write.

Another approach is found in Gleam (and some other languages): use expressions. Take the with_open example in the OP. That could be rewritten with use as:

use f <- with_open("f.txt", "r")
lines = f.readlines()
// ... etc

// desugars to

with_open("f.txt", "r", fun(f) {
    lines = f.readlines()
    // ... etc
})

Basically, everything that follows the use f line gets turned into an anonymous function body, and the with_open() call gets that anonymous function as the final argument. This also eliminates indentations, but it has the advantage that the syntax is significantly more general. Rather than eliminating one specific type of indentation, this approach can flatten out all callbacks in general.

1

u/mark-sed github.com/mark-sed/moss-lang/ 22d ago

Thank you, this is an interesting insight. Also with the own scope, in moss the using i proposed does not create a new scope, the block is used to determine the end of the using so that exit method can be called (similar to what python does).

1

u/MrJohz 21d ago

That's true, I was using "scope" and "indentation level" somewhat interchangeably, but that doesn't have to be true. But to me it's often easier to understand code if that is case, i.e. if I can assume that any indentation (or brace block or whatever) automatically means a new scope has been created. Otherwise I find it harder to trace where variables will be visible, and which variables I'm currently overwriting.

3

u/cellman123 22d ago

JavaScript's using syntax is simple assignment...

I thought you were joking. Huh! TIL that JS has destructors of sorts.

1

u/MrJohz 21d ago

JS will eventually get all features of all languages... ;)

JS also has Python-style __del__ destructors, they're just a bit more complicated to use and require a separate object (the FinalizationRegistry). Although as others have pointed out, RAII-style destructors in a garbage collected language is generally not ideal, so they're very rarely used. (They're very important in the few cases where they're necessary, and a pure footgun the rest of the time, hence why they're so complicated to use.)

1

u/latkde 17d ago

Because I was also tripped up by this: using-statements are a (widely supported) proposal, but are not part of the current ECMAScript 2026 standard. Notably, Safari currently lacks support. This feature has been accepted for the upcoming ECMAScript 2027 though. Resources:

2

u/initial-algebra 22d ago

The problem with using and equivalent with* is that it forces resources to be cleaned up in reverse order, which is not always appropriate.  Destructors are better.

1

u/mark-sed github.com/mark-sed/moss-lang/ 22d ago

My language is interpreted and GCed, I don't have destructors. Also about forcing the reverse order it does not have to apply. In my case there would be handler functions in classes such as enter and exit which would be called and could handle resources the way they want - so in the case of a file the enter would do nothing (as it is already open) and exit would call close.

6

u/initial-algebra 22d ago

 My language is interpreted and GCed, I don't have destructors.

There is no rule against having both GC and destructors.

1

u/mark-sed github.com/mark-sed/moss-lang/ 22d ago

There is no rule against having both GC and destructors.

Of course it is possible, but it would introduce a new set of issues and take a different design route than I have chosen. In this exact case, with files, the GC might not run for some time and the file would remain open and I would need a way to make sure it does not get reopened by some later line.

So in the end I would need to solve this unpredictability of GC by some other means of triggering a destructor such as RAII which with my current bytecode would require a lot of reworking and extra analysis - all of which I don't find worth it for destructors.

1

u/initial-algebra 22d ago

I don't think anyone expects opening a file to be fast, so worst-case scenario you can just run the GC beforehand. You could also have a rule that prevents a garbage-collected object from owning a destructible resource in the first place (a weak reference/handle would be fine, though, which is what you currently have).

1

u/snugar_i 22d ago

This is one thing I've been thinking about and I'm still not sure if it can be done - can a language somehow have both a real GC (non.refcounted) and RAII (deterministic)? Or is it one or the other?

3

u/initial-algebra 22d ago

There is no reason at all that it couldn't be done. If a garbage-collected object owns a destructible resource, then of course the lifetime of that resource still becomes less predictable, but the same would be true if you implemented your own reference counting and had a resource owned by a reference-counted object; it could be even worse if a cycle is created and thus the resource is never destroyed at all.

2

u/the_horse_gamer 22d ago

you can implement your own GC in any RAII-based language. but that's probably against the spirit of the question.

2

u/alphaglosined 22d ago

Never used D I take it?

Because yup, its in production usage for well over 20 years.

1

u/marshaharsha 22d ago

I think it would be straightforward if you are willing for a reference (presumably a forgotten reference) to a resource to persist after the resource has been disabled. If the holder of that reference tried to use the resource, they would take a run-time error. But the reference wouldn’t be dangling. The useless resource object would be garbage collected in the usual way. 

I don’t think of such a run-time error as a problem. Most resources can throw off a run-time error at any time, anyway, so all users of the object would have to be ready for errors. 

The resource object would have to have a standard method like dispose(), and the defer mechanism would just call that method at end of scope or at end of lifetime or at the point of an explicit request. 

1

u/L8_4_Dinner (Ⓧ Ecstasy/XVM) 22d ago

I’m not following your statement. Please explain.

2

u/initial-algebra 22d ago edited 22d ago

Two lexical scopes cannot overlap without one being contained in the other. Thus, if a resource is created at the beginning of a scope, and destroyed at the end of that scope, only the most recently created resource can be destroyed.

Of course, if you can manually deallocate a resource before the end of the scope, that solves this problem, but introduces a whole host of other problems.

Not to mention, this style of programming causes "rightward drift" without further mitigation.

3

u/WittyStick 22d ago edited 22d ago

The same is true for defer too - the defer are run in the reverse order they're defined.

IMO this is clearly the most sane option, even if not appropriate 100% of the time, it should be the default to prevent obvious issues.

Consider a trivial example - if we implement a 2D array by using an array of pointers to other arrays:

int **grid = malloc(NUM_COLS * sizeof(int*));
defer { free(grid); }

for (int i = 0; i < NUM_COLS; i++)
    grid[i] = malloc(NUM_ROWS * sizeof(int));
defer {
    for (int i = 0; i < NUM_COLS; i++)
        free(grid[i]);
}

...

Anything other defer being run in the reverse order they're defined is clearly a mistake as it will introduce a use-after-free.

I'm not a fan of defer, but for this example in particular it's not clear how you would do it with using. We can't put the for loop in a using block and we can't put a using block in the for block - so we'd need to introduce a new kind of syntax that combines for and using into one construct - eg:

using (int **grid = malloc(NUM_COLS * sizeof(int*)); free(grid)) 
{
    using_for (int i = 0; i < NUM_COLS; i++; grid[i] = malloc(NUM_COLS * sizeof(int)); free(grid[i])) 
    {
        ...
    }
}

Which is quite awful.

5

u/initial-algebra 22d ago

You can make defer more flexible by linking it to one or more variables' lifetime(s). For example, defer (grid) { free(grid); } would run immediately after the last mention of grid.

Of course, the more flexible you make defer, the more it is just a poor imitation of destructors and related features like ownership transfer. You can then implement defer by constructing a dummy object that stores a lambda expression and calls it when destroyed.