Search code examples
c++compiler-construction

How to add keyword to a C++ compiler


I need to simply add a compile-time check to a compiler in the form of a keyword. (similiar to const)

It would change nothing about how the compiler function, only give compile-time errors when keyword is misused or omitted.

How would I do this for MSVC / Clang / GCC


Solution

  • I propose to do the following steps to achieve what I think you want:

    • Write a C++ parser, which is the easier the more assumptions you can make on possilbly occurring syntaxes. You might need/want to use an existing parser and extend it.
    • Have it preprocess the code files, to either remove the keyword (in case of correctness) or replace the line with a #error Misuse of keyword in: (quote of original line).
    • Insert that parser into your built chain, e.g. via make file, just before the compilation by normal compiler.

    That way you do not need to maintain your own compiler, get compiler errors (with useful context) in case of misuse and normally built results in case of correct use. Also the actual compiler does not get to see anything weird which could confuse it.