Home > database >  How would one implement a standard library for a language they've developed?
How would one implement a standard library for a language they've developed?

Time:05-20

So for example I have a brand spanking new compiled language in my hands and no standard library. I want to implement a malloc function for this language. An approach that came to my mind is to write the function as extern in my language and link at compile time with a shared library that contains a function that simply calls malloc. I imagine it could cause a bit of a slowdown because of the wrapped function calls unless I add an inlining functionality. However, without inlining is this route still acceptable? Or is implementation from scratch better?

This goes for all standard library functions really, malloc is just an example I used, so an answer from that perspective would be appreciated.

(Also, not an avid user of SO so I don't really know what to tag this question, corrections are welcome in the comments and I will edit the questions to include the correct tags)

CodePudding user response:

One size doesn't fit all, in my experience.

  1. You can write some of the runtime library in your language, using a smaller subset of the runtime library.

  2. You can also write some of it in LLVM IR by hand, which is considerably simpler now that LLVM has untyped pointers.

  3. You can write C that writes IR. Normally a compiler creates IR based on source code it has parsed, but nothing prohibits you from creating IR using nearly-straight-line code without inputs.

  4. Finally, you can write parts of the standard library in a language such as C with a strict and weird coding style, and use clang plus a custom LLVM pass to map the C code to IR that fits your language. If your language is an OO language, that pass will map a certain C variable to this or self, etc.

I've used or seen all of these, and I haven't seen any compiler that restricts itself to just one technique.

CodePudding user response:

malloc is a part of C library. Instead of calling libc you can implement your own malloc in your language, which would call the kernel directly. The same goes for all other C functions.

CodePudding user response:

malloc is generally slow and a simple nested call won't break the bank.

But this case won't be the only one, so it might wise to check if you can't up your FFI handling (Foreign Function Interface) to directly call the extern libc malloc function, saving you an extra library to distribute and maintain.

For e.g. calls like read and write (bytes to a file/tty) the time aspect also might hurt more than for malloc.

Also it is not entirely either-or, you can use e.g. crt/libc functions on one (e.g. *nix) platform, and not on another (e.g. Dos/Windows).

  • Related