Search code examples
c++classcompiler-construction

Declare classes based on user input


I'm attempting to write a compiler in C++ for my simple language, but I'm not sure how I should go about declaring a user-defined class when the language in question declares a user-defined class.

For example, in this supposed language, the user writes:

CLASS Foo {
    int bar;
}

How would my compiler read that to then subsequently make the equivalent in C++? I would like the compiler to then execute the following code in C++:

class Foo {
    int bar;
}

The syntax is identical. Is this possible in C++?


Solution

  • What you are describing is a transpiler, converting the source of one language into that of another language, in this case C++.

    To achieve this you need to understanding how to map the semantics of your language to the target language. So, start small and iteratively extend as you get the machinery in place. You will face challenges, to name a few:

    1. Are my classes just for data or data and behavior?
    2. Does my language have inheritance? Single? Multiple?
    3. Does my language support the notion of public vs. private?
    4. Can the user include statements they've made in other files?

    Once you've figured out the fundamentals you will then need to ensconce it all in a working framework. Just like a compiler you will have file management, symbol management and resolution, etc. Finally, you need to hook up a tool chain. I assume that you will want the user experience to be:

    1. Write source in you language
    2. Invoke your transpiler
    3. Your transpiler converts source to C++
    4. Your transpiler invokes the C++ compiler against what you just emitted
    5. Finally, if all goes well, the file is linked to produce executable/library