Paste C ++ code using antlr and the line directive

I use antlr to translate a custom language into C ++ code. In this language, the user can insert fragments of C ++ code between the directives $code...$endcode , which are inserted into the translated C ++ code as is.

I have the following problem: when there is an error in the code snippet, I would like the compiler to point to the source file, and not to the translated C ++ code.

I tried using line directives as follows, but this did not work:

 "foo.custom_laguage" 1 $code 2 ...some c++ code... 3 $endcode 

translates to

 "auto-generated.cpp" 42 #line 2 "foo.custom_language" 43 ...some c++ code... 44 #line __LINE__ __FILE__ 

This does not work, I think, because the #line directive modifies what is later written by the __LINE__ macro. How can I set the line number for the actual line number in C ++ code translation? How does antlr do it?

Here is what I want the generated generated code to look like:

 "auto-generated.cpp" 42 #line 2 "foo.custom_language" 43 ...some c++ code... 44 #line 44 "auto-generated.cpp" //actual line in this file 45 ..some more C++ code ... 

edit: I just found out that there is a way to do this in C # using the #line default directive: http://msdn.microsoft.com/en-us/library/34dk387t.aspx But I could not find anything like this for C + +

+4
source share
1 answer

This is not clear from the question, but do you yourself generate the #line directives given by source-line and source-file ? Sorry, I am not familiar with Antlr.

Indeed, #line __LINE__ __FILE__ does nothing, but assigns the __LINE__ macro to itself.

Because of the semantics of preprocessor evaluation, you cannot easily assign a numerical value __LINE__ macro. (You can only define a new macro to map the __LINE__ macro literally, returning its current value.) But why do you need this? If Antlr itself does not use the __LINE__ macro, you do not need to restore it to its previous value.

If this is a problem, the easiest solution would be to put the C ++ source code in separate include files and abandon the embedded attachment. To prevent the distribution of header files, you can use a construct like

 $code #define USE_SNIPPET_FOO #include "snippets.h" $endcode $code #define USE_SNIPPET_BAR #include "snippets.h" $endcode 

and in the header, the protection type of the return header:

 #ifdef USE_SNIPPET_FOO #undef USE_SNIPPET_FOO class foo {}; #elif defined USE_SNIPPET_BAR #undef USE_SNIPPET_BAR class bar {}; #else #error no snippet selected #endif 
+1
source

Source: https://habr.com/ru/post/1414576/


All Articles