ocen-lang / ocen

Statically typed programming language
https://ocen-lang.github.io/autodoc/
80 stars 7 forks source link

explicit deferred attribute #8

Open iadityanath8 opened 4 months ago

iadityanath8 commented 4 months ago

As we know how much defer is important when freeing or delaying any resource such as memory management and file io etc

But i find the problem while implementing mutex locks such as every time i have to write defer which is kind of annoying sometime

def run(){
    m.lock()
    defer m.unlock()
    count += 1
}
def run(){
      m.guard()     // which automatically calls the defer m.unlock() at the end 
}

i think instead of doing this we should implement some kind of guarding mechanism which looks it cannot be implemented without constructors and destructors for example

A language known as odin implements this feature using deferred attribute above the function which tells which function to defer after the current function is ended for example

@(deferred_in=mutex_unlock) 
def guard(){
    m.lock()
}

Which will defer the mutex_unlock function which is similar to this syntax

m.guard()     // calls m.lock() and tells the compiler using deferred attribute which function to defer so that compiler will put the function automatically 
 // automactic generated by compiler 
 defer m.unlock()

Now introducing this kind of attribute will be very important because of the resources that will be freed within the blocks

mustafaquraish commented 4 months ago

I've been thinking about something like this too, but there's a few too many unknowns for me at this point to consider adding this into the language. Some questions about your suggested approach:

  1. What would this look like syntactically in ocen?
  2. What if the "destructor" needs extra arguments, how / when are those passed in?
  3. If it's on by default - we want some way to be able to opt-out of it in case you don't want this behaviour. What does that look like?
  4. How do we handle the case where we pass the lock (or file, or whatever object) to some other function. Who "owns" the object and is responsible for calling the defer?

If we can come up with a good design for this system that fits in well with the rest of the language - then definitely we should implement it.