#P8289. Simple Preprocessor
Simple Preprocessor
Simple Preprocessor
The task is to implement a simplified C/C++ preprocessor.
In C/C++ languages, macros are used to perform textual substitution before compilation. For example, given the code snippet below:
#define PI 3.14159 double area = PI * r * r;
After macro expansion, it becomes:
double area = 3.14159 * r * r;
Your job is to simulate a simplified version of this preprocessor with the following rules:
-
The input consists of lines. Each line is either a preprocessor command (starting with
#
) or a normal text line. Every line (except for the newline character) consists of printable ASCII characters (ASCII codes 32 to 126). -
There are two types of preprocessor commands:
- Macro definition:
#define <name> <content>
- Macro cancellation:
#undef <name>
Here,
<name>
is an identifier that is a non-empty sequence of letters (both uppercase and lowercase), digits, or underscores, and<content>
is a sequence (possibly empty) of printable ASCII characters. A macro definition is active from its definition line until the next matching cancellation (#undef
) line (if any). - Macro definition:
-
When processing a normal text line, you must perform macro expansion. To do this, scan the line from left to right and view every maximal consecutive substring of letters, digits, and underscores as an identifier. For each identifier:
- If it is a valid and active macro, replace it with its expansion as specified by its definition. Then, if the replacement contains any identifiers, perform expansion on them as well (this is called multi-level expansion).
- However, if during expansion, a macro is encountered that is already in the process of being expanded (i.e. recursive expansion), it is left unexpanded to prevent infinite recursion.
- All other characters are left unchanged.
-
For any preprocessor command line, execute the command and output an empty line. For normal text lines, output the resulting line after macro expansion.
Note: This problem’s requirements are a simplified version and are not completely compliant with the full C/C++ standard.
inputFormat
The input consists of multiple lines. Each line is either a preprocessor command or a normal text line.
-
Preprocessor commands start with
#
and are of one of the forms:#define <name> <content>
#undef <name>
-
Normal text lines may contain identifiers (sequences of letters, digits, and underscores) and other characters.
outputFormat
For each input line, output a line as follows:
- If the input line is a preprocessor command, output an empty line.
- If it is a normal text line, output the line after performing macro expansion according to the rules described.
sample
#define PI 3.14159
double area = PI * r * r;
double area = 3.14159 * r * r;
</p>