Skip to content

Add support for function-like $define macros - #554

Merged
cjeffery merged 2 commits into
uniconproject:masterfrom
Jafaral:macros
Mar 29, 2026
Merged

cjeffery merged 2 commits into
uniconproject:masterfrom
Jafaral:macros

Conversation

@Jafaral

@Jafaral Jafaral commented Mar 28, 2026

Copy link
Copy Markdown
Member

No description provided.

@Jafaral
Jafaral requested a review from cjeffery March 28, 2026 06:32
@Jafaral
Jafaral requested a review from Don-Ward March 28, 2026 06:32
@greptile-apps

greptile-apps Bot commented Mar 28, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR implements function-like $define macros (e.g. $define SUM(a,b) ((a)+(b))) in the Unicon preprocessor. It introduces a separate preproc_fun_table, a preproc_fmacro record, and five new procedures (preproc_scan_define_fmacro, preproc_expand_fmacro_call, preproc_scan_macro_args, preproc_subst_fmacro, preproc_defined) alongside careful integration with the existing object-like macro pipeline.

Key areas reviewed:

  • Parsing — preproc_scan_define_fmacro correctly handles zero-arg macros, duplicate-parameter detection, trailing-comma detection, and falls back to object-like parsing when no ( immediately follows the macro name (matching C preprocessor semantics). The preproc_fmacro_parse_error flag cleanly prevents a malformed function-like definition from silently creating a spurious object-like binding.
  • Argument scanning — preproc_scan_macro_args correctly tracks paren depth and treats quoted strings as opaque, so arguments containing commas (\"a,b\") or nested calls (f(1,2)) are split correctly.
  • Expansion and recursion guard — The done_set chain (&null → string → set) correctly handles arbitrarily-deep chains (the 5-level A→B→C→D→E test exercises this). The ? operator used in preproc_expand_fmacro_call preserves the outer scanning context's &pos across the re-scan of the expanded text.
  • $ifdef/$undef integration — preproc_defined and the delete(preproc_fun_table, sym) calls in undef and the object-like define branch keep the two tables consistent.
  • Tests — Solid coverage of success paths (nested macros, string args with commas/parens, CALL_WITH_SPACE, 5-level chains, $ifdef/$undef on function macros) and five compile-failure fixtures.
  • One minor finding — The arity-mismatch failure path in preproc_expand_fmacro_call does not restore &pos := start_pos before returning fail, unlike the other two failure paths. Runtime behavior is unaffected (the outer scanner restores via save_pos), but the inconsistency is worth tidying for readability.

Confidence Score: 5/5

Safe to merge — no P0 or P1 issues found; the single finding is a minor consistency nit on an error-recovery path that does not affect correctness.

All previously raised concerns (done_set chain expansion depth, trailing-comma double-put) have been resolved. The remaining comment is P2-only: an inconsistent but harmless omission of &pos restoration on the arity-error path. The feature logic, recursion guard, argument scanning, and table integration are all correct.

uni/unicon/preproce.icn — specifically the arity-mismatch path in preproc_expand_fmacro_call (lines 687–690), though it is not a blocker.

Important Files Changed

Filename Overview
uni/unicon/preproce.icn Core preprocessor: adds preproc_fun_table, five new procedures for parsing/expanding function-like macros, updates $ifdef/$undef to cover both tables; one minor arity-error path leaves &pos unreset before fail
tests/unicon/macros.icn New test driver covering basic calls, nested macros, 5-level chain expansion, string args with commas/parens, zero-arg macros, $ifdef/$undef, and five compile-fail cases
tests/unicon/stand/macros.std Expected output baseline for macros.icn; all 16 lines match the logical results of the test cases

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["preproc_scan_directive()\n$define NAME..."] --> B["preproc_fmacro_parse_error := 0"]
    B --> C{"preproc_scan_define_fmacro()"}
    C -->|"succeeds: NAME(p1,p2) body"| D["Store in preproc_fun_table\nDelete from preproc_sym_table"]
    C -->|"fails, no parse error\n(no leading '(')"| E{"preproc_scan_define_value()"}
    C -->|"fails, parse error\n(malformed params)"| F["Error already reported\nNo fallback"]
    E -->|"succeeds"| G["Store in preproc_sym_table\nDelete from preproc_fun_table"]
    E -->|"fails"| H["No definition created"]

    subgraph Expansion ["Text Expansion - preproc_scan_text()"]
        I["Scan identifier 'IDENT'"] --> J{"In preproc_fun_table?"}
        J -->|yes| K{"Check done_set\n(recursion guard)"}
        K -->|"not recursive"| L["preproc_expand_fmacro_call()"]
        L --> M["preproc_opt_space() + ='('"]
        M -->|"no '(' found"| N["Restore &pos, fail\n→ try object-like"]
        M -->|"'(' found"| O["preproc_scan_macro_args()"]
        O --> P{"arity matches?"}
        P -->|no| Q["Error: wrong number of args\nfail"]
        P -->|yes| R["preproc_subst_fmacro()"]
        R --> S["expanded ? preproc_scan_text(done_set + ident)"]
        K -->|"recursive"| T["skip fmacro\n→ try object-like"]
        J -->|no| U{"In preproc_sym_table?"}
        U -->|yes| V["Object-like expansion"]
        U -->|no| W["Leave as plain text"]
    end
Loading
Prompt To Fix All With AI
This is a comment left during a code review.
Path: uni/unicon/preproce.icn
Line: 687-690

Comment:
**`&pos` not restored before `fail` on arity mismatch**

The other two early-exit paths in this function both restore `&pos := start_pos` before failing, making it easy to reason that the caller's scanner position is always in a known state when the function returns `fail`. The arity-mismatch path skips that restore:

```icn
if *args ~== *fmacro.params then {
   preproc_error("wrong number of args in macro call to " || name)
   fail          -- &pos is still pointing after the closing ')'
}
```

This is not a runtime bug — `preproc_scan_text` does `&pos := save_pos` after any failure, so error recovery still works correctly. However, adding the restore here would make all failure paths consistent and reduce the cognitive load for anyone auditing the function later:

```suggestion
   if *args ~== *fmacro.params then {
      preproc_error("wrong number of args in macro call to " || name)
      &pos := start_pos
      fail
   }
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (10): Last reviewed commit: "tests/unicon: add macro preprocessor cov..." | Re-trigger Greptile

Comment thread uni/unicon/preproce.icn Resolved
@cjeffery

cjeffery commented Mar 28, 2026 •

Copy link
Copy Markdown
Contributor

The code looks awesome to me. I will review more when Greptile is happy, or when its issues are debunked. I would prefer not to have empty then-parts if they are not necessary, by reversing logic and using "not", etc. I would imagine that this has been tested with too many and too few parameters, omitted parameters, etc but I didn't see those tests. I was glad to see tests with macro calls inside parameters of other macro calls, as that is a common source of macro trouble. Actually, one might check out the worst examples of macro hell in C and see what this code does with similar cases.

I would suggest that trickier parts of the code, if there are any, might deserve a bit more commenting. Usually something as complex as macro parameters has some trickier parts.

@Jafaral
Jafaral force-pushed the macros branch 3 times, most recently from c10738a to 232c555 Compare March 28, 2026 19:06
Comment thread uni/unicon/preproce.icn Resolved
@Jafaral
Jafaral force-pushed the macros branch 2 times, most recently from f67b37f to 78b851c Compare March 28, 2026 20:14
@Jafaral

Jafaral commented Mar 28, 2026

Copy link
Copy Markdown
Member Author

The code looks awesome to me. I will review more when Greptile is happy, or when its issues are debunked. I would prefer not to have empty then-parts if they are not necessary, by reversing logic and using "not", etc. I would imagine that this has been tested with too many and too few parameters, omitted parameters, etc but I didn't see those tests. I was glad to see tests with macro calls inside parameters of other macro calls, as that is a common source of macro trouble. Actually, one might check out the worst examples of macro hell in C and see what this code does with similar cases.

I would suggest that trickier parts of the code, if there are any, might deserve a bit more commenting. Usually something as complex as macro parameters has some trickier parts.

I fixed a few rounds of greptile reviews, I think it is happy now. I added a few comments, and expanded the test to cover more cases.

@Jafaral

Jafaral commented Mar 28, 2026 •

Copy link
Copy Markdown
Member Author

@greptile, your assessment is wrong in this case:

This is a comment left during a code review.
Path: tests/unicon/macros.icn
Line: 31-44

Comment:
compile_fails returns &null instead of failing — all ASSERT_TRUE error checks pass trivially

In Icon/Unicon, not expr succeeds only when expr fails (generates no value). When expr produces any value — including &null — not expr fails, and the if branch (the stop call) is never reached.

compile_fails returns 1 when the needle is found, but falls off the end of the procedure (returning &null) when the needle is not found. Since &null is a value (not a failure), every call like:

ASSERT_TRUE(compile_fails("data/macros_bad_too_few.icn", "wrong number of args..."), "too few args should fail")

expands to if not (&null) then stop(...). not (&null) fails, so stop is never called and the assertion is silently satisfied regardless of whether the expected error was actually produced.

This means that if the preprocessor were to silently accept invalid input instead of emitting the expected diagnostic, all five error-path tests would still "pass" and "arity-checks-ok" would still be printed.

The fix is to add fail at the end of the procedure:

Correction:

In Unicon, a procedure doesn't return &null by default, it actually fails. I.e, there is an implicit fail if the end of the function is reached.

@greptile-apps

greptile-apps Bot commented Mar 28, 2026

Copy link
Copy Markdown

You're absolutely right - I apologize for the incorrect assessment.

In Unicon, procedures that fall off the end fail implicitly rather than returning &null. This means the code works correctly:

  • When the error message is found: compile_fails returns 1, not 1 fails, assertion passes
  • When the error message is not found: compile_fails fails (implicit), not <fail> succeeds, stop executes, test fails as expected

The assertions properly catch cases where the compiler silently accepts invalid input instead of producing the expected diagnostic. Thank you for the correction on Unicon's semantics.

@Jafaral
Jafaral force-pushed the macros branch 2 times, most recently from bc6142c to 6d1d720 Compare March 29, 2026 03:14
@Jafaral

Jafaral commented Mar 29, 2026

Copy link
Copy Markdown
Member Author

@greptile, I did push an update to fix the last two minor issues you pointed out.

Jafaral added 2 commits March 29, 2026 10:58
Extend the Unicon preprocessor to support function-style macro definitions
and calls (for example `$define sum(x,y) x+y` and `sum(1,2)`).
Keep object-like macro behavior unchanged while adding argument parsing,
substitution, recursion guards, and consistent handling across:
`define`, `undef`, `ifdef`, and `ifndef`.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Add a dedicated regression test for function-like $define macros,
including nested expansion, whitespace around invocation, zero-argument
macros, and ifdef/undef behavior. Cover tricky argument/nesting cases
and add dedicated arity-failure fixtures that verify too-few, too-many,
omitted, empty-middl, and duplicate-parameter cases fail with the
expected error.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
@Jafaral

Jafaral commented Mar 29, 2026

Copy link
Copy Markdown
Member Author

@greptile, I fixed the two-char \^x caret-escape sequence.

Comment thread uni/unicon/preproce.icn Resolved
@cjeffery
cjeffery merged commit a47bdfc into uniconproject:master Mar 29, 2026
25 checks passed
@Jafaral
Jafaral deleted the macros branch October 7, 2026 01:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants