Fixed preproc recursive replacement in a better way
authorLukas Krickl <lukas@krickl.dev>
Wed, 27 Dec 2023 17:08:28 +0000 (18:08 +0100)
committerLukas Krickl <lukas@krickl.dev>
Wed, 27 Dec 2023 17:08:28 +0000 (18:08 +0100)
src/test.c
src/ulas.c

index 66091a2690071b72595e48ce25653bafdb1931cf..1238ab690b03bc6ddd5660c12c2a88fd4ba6066f 100644 (file)
@@ -87,6 +87,7 @@ void test_strbuf(void) {
     assert(ulas_preproc(dst, src) == (expect_ret));                            \
     fclose(src);                                                               \
     fclose(dst);                                                               \
+    puts(dstbuf);                                                              \
     assert(strcmp(dstbuf, (expect_dst)) == 0);                                 \
   }
 
@@ -104,9 +105,10 @@ void test_preproc(void) {
   assert_preproc("", -1, "  #define\n");
   assert_preproc("this is a 123 for defs", 0,
                  "  #define test 123\nthis is a test for defs");
-  // define used inside define 
-  assert_preproc("this is a 123 for defs", 0,
-                 "  #define ftest 123\n#define test ftest\nthis is a test for defs");
+  // define used inside define
+  assert_preproc(
+      "this is a 123 for defs", 0,
+      "  #define ftest 123\n#define test ftest\nthis is a test for defs");
 
   // undefined
   assert_preproc("123\ntest", 0,
index da38d981c95bb45a69ac58f501e154e81c0c8f47..c850bdf0c11e4b692183ebf33b6ec616a7d088ef 100644 (file)
@@ -707,23 +707,27 @@ char *ulas_preprocexpand(struct ulas_preproc *pp, const char *raw_line,
 
   int read = 0;
   int first_tok = 1;
+  int skip_next_tok = 0;
 
   // go through all tokens, see if a define matches the token,
   // if so expand it
   // only expand macros if they match toks[0] though!
   // otherwise memcpy the read bytes 1:1 into the new string
   while ((read = ulas_tok(&pp->tok, &praw_line, *n))) {
+    struct ulas_ppdef *def =
+        ulas_preprocgetdef(pp, pp->tok.buf, pp->tok.maxlen);
+    ;
+
     // if it is the first token, and it begins with a # do not process at all!
-    // only apply this to certain preproc types such as #undefine, #ifdef and #ifndef 
-    if (first_tok && pp->tok.buf[0] == ULAS_TOK_PREPROC_BEGIN && strcmp(ULAS_PPSTR_DEF, pp->tok.buf) != 0) {
-      ulas_strensr(&pp->line, (*n) + 1);
-      strncat(pp->line.buf, raw_line, *n);
-      break;
+    // if the first token is a # preproc directive skip the second token at all
+    // times
+    if ((first_tok && pp->tok.buf[0] == ULAS_TOK_PREPROC_BEGIN) ||
+        skip_next_tok) {
+      def = NULL;
+      skip_next_tok = !skip_next_tok;
     }
     first_tok = 0;
 
-    struct ulas_ppdef *def =
-        ulas_preprocgetdef(pp, pp->tok.buf, pp->tok.maxlen);
     if (def) {
       // if so... expand now and leave
       switch (def->type) {