perlang-org / perlang

The Perlang Programming Language
https://perlang.org
MIT License
16 stars 1 forks source link

Support inline C++ #457

Closed perlun closed 1 month ago

perlun commented 4 months ago

Now that we are beginning the work on rewriting the Perlang compiler in Perlang (#454), we might find need for something interesting: inline C++.

Many C and C++ compilers support "inline assembly", i.e. being able to write certain methods in assembly language (and also take in/out parameters to these asm sections). We don't need that, at least not right now, but I think supporting similar for "inline C++" could be quite useful. One specific use case is when we will be called from C# code (using P/Invoke, i.e. [DllImport(...)]). In those cases, we might want to be able to e.g. receive a const char** args parameters (for easy marshalling of a string[] array on the C# side). However, this is currently not supported in Perlang and I really don't want to add support for unsafe, raw C-style strings (again, at least not right now). Letting the user specify sections of the program in C++ seems like a better and cleaner approach.

Suggested syntax

Inline C++ in a Perlang function

print "This is Perlang code";

c++ {
  // Raw C++ code here
  std::cout << "This is C++ code";
}

(The syntax for the above might be revised to be something like cpp {} instead, or even something like this:

`c++` {}

The problem with using something like c++ is that it would cause an undesired ambiguity with a normal c++; postfix increment operator for a variable named c. This would destroy the language too much to be a real option.

C++ prototypes (i.e. definitions)

This would be useful for defining the function prototypes for methods implemented in C++, for example if they need to be called from Perlang methods.

#c++-prototypes

static do_something_useful(int i);

#/c++prototypes

C++ declarations

This allows you to define one or more functions/methods in C++:

#c++-methods

extern "C" native_main(const char** args) 
{
    // ...
}

#/c++methods
perlun commented 1 month ago

I think we're fine with this as of #462, closing away.