Skip to content

c_import macro helpers still shell out to cc -E #348

Closed

Description

@ehartford

Summary

Remove the remaining cc -E shell-outs from the c_import macro/preprocessor helper paths so the normal header-import pipeline is fully served by the compiler-owned libclang bridge. The spec makes self-contained C parsing a hard property of c_import; any helper that silently requires a host C compiler is an implementation gap that breaks clean hosts and cross-compilation.

Spec

§16.1 c_import (Compiler-owned C parsing / Cross-compilation):

  • "c_import uses With's compiler-owned libclang bridge, not a random system C compiler."
  • "The normal c_import path parses the header with this embedded Clang resource setup. It does not probe a system LLVM install, does not depend on llvm-config, and does not invoke cc -E as the core header-import mechanism."
  • "Any remaining shell-out to host tools for SDK discovery or macro/preprocessor helper paths is an implementation gap, not a language requirement."

This is also an AGENTS.md invariant ("Self-Contained Toolchain") and a recorded memory rule: the compiler must never shell out for its own operations.

Current state

Three helpers in src/compiler/ClangBridge.w still build cc argv lines and run them via with_exec_argv_capture → capture_command_stdout (ClangBridge.w:620-633):

  1. Macro dump fallback — with_cimport_parse_macros (ClangBridge.w:2221) first tries the libclang path cimport_collect_macros_from_libclang (ClangBridge.w:2162, uses CXTranslationUnit_DetailedPreprocessingRecord and collect_macro_def) and returns early on success (ClangBridge.w:2227). Only when that fails does it fall back to cc ... -E -dM (argv built at ClangBridge.w:2243-2250) and parse the #define lines textually.
  2. Preprocessed source — with_cimport_preprocess_text (ClangBridge.w:2374) always shells out to cc ... -E (argv at ClangBridge.w:2390-2396). Its only caller is the migrator: src/CiMigrate.w:769 (g_migrate_preprocessed_source).
  3. Shared argv plumbing — append_cc_common_args (ClangBridge.w:635-647) feeds -isysroot (from get_sdk_path, see Darwin c_import SDK discovery still shells out to xcrun #349) and -I paths into these cc invocations.

Note with_cimport_collect_object_macro_types (ClangBridge.w:2406) already uses libclang typeof-probes, not cc. Weak fallback stubs for non-c_import builds live in rt/cimport_stubs.w:376-390.

The gap: when libclang macro collection fails, or whenever the migrator needs preprocessed text, the compiler silently depends on a host cc on PATH. On a host without cc these paths return empty strings — a silent degradation, not a diagnostic (forbidden by "No Silent Fallbacks").

Implementation plan

  1. Delete the cc -E -dM fallback in with_cimport_parse_macros (ClangBridge.w:2227 onward). If cimport_collect_macros_from_libclang fails, return the (empty) session and let the caller surface a parse diagnostic — a failed libclang parse already means the header import itself will fail with a real error. Do not keep a second engine that can disagree with the primary one.
  2. Harden the libclang macro path so it is the only engine: verify collect_macro_def records function-like macro params and bodies with parity to what the -dM text parser produced (names, fn_like flag, params, value text). Extend MacroSession population from libclang token streams (clang_tokenize over the macro definition extent) if any field is currently only available via -dM text.
  3. Reimplement with_cimport_preprocess_text on libclang: parse the text with the existing session setup (same -isysroot/-resource-dir/-I argument construction used at ClangBridge.w:2180-2210) and reconstruct expanded text via clang_tokenize on the translation unit, or — preferable if CiMigrate only needs macro-expansion of specific constructs — change src/CiMigrate.w:769 to query the macro session instead of a fully preprocessed dump. Decide based on what g_migrate_preprocessed_source is actually used for in CiMigrate (grep its uses before choosing).
  4. Fail loudly: where a helper genuinely cannot produce output (libclang parse error), emit a diagnostic naming the header/source and the failing phase ("c_import: macro collection failed for : "), and propagate non-zero. No empty-string returns that callers treat as "no macros".
  5. Remove append_cc_common_args once no cc argv remains; keep the -isysroot/include logic only in the libclang session-argument builder.
  6. Keep the rt/cimport_stubs.w weak stubs in sync (they only matter for binaries without the bridge linked; signatures unchanged, so no Link.w change → no bootstrap hazard). Pure compiler-source change; no rt/Link/seed ordering concerns beyond the normal fixpoint gate.

Test plan

  • test/behavior/behav_c_import_macros_no_cc.w: use c_import of a local header (pattern: test/behavior/behav_c_import_offsetof.h) defining object-like constants (#define A 7, arithmetic #define B (A*2)) and a function-like macro #define MAX(a,b) ...; assert constants are imported and usable. Run the focused regression with PATH stripped of cc (driver-level test or an internals test invoking the bridge with a sanitized environment) to prove no host-compiler dependency. //! expect-stdout: ok.
  • test/compile_errors/err_c_import_macro_parse_failure.w: header text that fails to parse; //! expect-error: naming the header and the c_import failure (not a missing-cc symptom).
  • Migrator coverage: a test/migrate/ case exercising the path behind with_cimport_preprocess_text (macro-expanded C source) to prove the libclang reimplementation feeds CiMigrate equivalently.
  • Negative guard: grep-style internals check (or code review gate) that src/compiler/ClangBridge.w contains no "cc" argv construction; at minimum the acceptance checklist below.

Acceptance criteria

  • No cc/-E argv construction remains in src/compiler/ClangBridge.w (helpers at old lines 2243-2250 and 2390-2396 removed).
  • with_cimport_parse_macros is libclang-only; failure is a loud diagnostic, not an empty fallback result.
  • with_cimport_preprocess_text no longer shells out (reimplemented or its CiMigrate caller redesigned).
  • Macro import behavior unchanged for the covered cases (constants, evaluated expressions per §16.2, function-like macro warnings).
  • Diagnostics distinguish missing target headers/SDK inputs from toolchain-internal failures.
  • with build && with build :fixpoint && with build :test pass.

Dependencies

Traceability

Per the BDFL ruling for problematic requirement #5 (spec §16.1 cross-compilation paragraph): remaining shell-outs for macro/preprocessor helper paths are implementation gaps, not language requirements.

Activity

  1. ehartford commented on Jun 17, 2026

    @ehartford
    ContributorAuthor

    Partial progress (commit c630d94): removed the cc -E -dM macro-collection shell-out in with_cimport_parse_macros — the normal c_import macro path is now libclang-only (test behav_c_import_macros_no_cc.w).

    Still open: the migrator-only with_cimport_preprocess_text still shells out cc -E. It feeds g_migrate_preprocessed_source, which CImport.w reads (via #line markers) to reconstruct macro-expanded text at source locations for string-macro sequences and variable initializers. libclang's C API has no -E equivalent, so replacing this needs either a C++ bridge preprocessor function (over the statically-linked clang frontend libs) or a migrator redesign that reconstructs text from libclang cursor source-ranges + constant evaluation instead of preprocessed text. That is a larger separate effort.

  2. added a commit that references this issue on Jun 19, 2026
  3. ehartford commented on Jun 22, 2026

    @ehartford
    ContributorAuthor

    Scope finding: this is not a "finish-the-list" swap — it's an onion

    Investigated the cc -E shell-out for replacement. The shell-out lives in with_cimport_preprocess_text (src/compiler/ClangBridge.w): it writes the source to a temp file, runs cc -E -x c <tmp>, and captures stdout. The output is fully preprocessed C with # <line> "<file>" line markers, consumed by ci_preprocessed_text_at_location (src/CImport.w) to recover the macro-expanded text of a declaration at a given source location (for value/initializer extraction).

    Why it doesn't transplant onto libclang the way -dM did. The -dM macro path could move in-process because libclang exposes macro definitions directly (with_cimport_parse_macros → cimport_collect_macros_from_libclang). The -E path has no equivalent: libclang's C API has no "give me the preprocessed source text" call. Producing it in-process means reconstructing fully-expanded text from clang_tokenize + cursor annotations — re-implementing macro expansion, include splicing, and # line file fidelity well enough that the existing location-based line scanner still finds declarations. That is a substantial sub-project, not adding a curated entry.

    No runtime fallback to our own clang. The self-contained-toolchain invariant means the release binary embeds libclang statically and ships no clang/cc binary; we cannot shell out to our own clang at runtime either. So the only sound replacement is genuine in-process libclang reconstruction.

    Current behavior is safe, not silently wrong. When libclang is present the strong impl shells out to system cc; when absent, the weak stub returns "" and consumers degrade gracefully (return ""). So this is a self-contained-toolchain dependency to remove (system cc), not a correctness bug.

    Recommendation: keep #348 open as its own scoped task (token-reconstruction of preprocessed text from libclang), not bundled into the Phase-8 finish-the-list. Deferred this run rather than grinding; no code changed.

  4. ehartford commented on Jul 2, 2026

    @ehartford
    ContributorAuthor

    Route investigation update (2026-07-02): the plan to add wcb_preprocess_text to "the existing clang_bridge C++ shim" rests on a wrong premise — clang_bridge.o is compiled from src/compiler/ClangBridge.w: the bridge is pure With over libclang's C API (89 extern fn clang_* decls). There is no C++ source anywhere in the toolchain, and clang's Preprocessor/-E printing is C++-only — libclang's C API does not expose it.

    So the real route choice is:

    • (a') Introduce the toolchain's first C++ file (compiled by the SDK clang++, linking clang frontend archives) — true -E fidelity, but new build/link plumbing on the sacred link path and a new language in the compiler build.
    • (c') A narrow With-side expander over the already-de-shelled CXTranslationUnit_DetailedPreprocessingRecord: the four consumers need only two shapes — string-literal macro sequences ("A" NAME "B") and variable-initializer text — not arbitrary C. Object-like recursive expansion covers the observed uses; function-like/## cases fail loudly as untranslatable (consistent with existing migrator behavior).

    Verified context: the consumers are migrate-only (g_migrate_preprocessed_source is set in ci_migrate_file), golden shapes confirmed working today via with migrate (string-macro sequence → merged literal; initializer recovery). (c') is smaller, stays pure-With, and honors the no-silent-fallback rule; (a') is the fidelity play. Needs a route ruling before implementation.

  5. ehartford commented on Jul 2, 2026

    @ehartford
    ContributorAuthor

    Route ruling: (c') — the narrow With-side expander over the DetailedPreprocessingRecord, by the compass: it keeps the toolchain pure With (introducing the first C++ source is a structural change nothing currently demands), it covers the complete consumer inventory (string-literal macro sequences + initializer text — verified migrate-only), and unsupported shapes (function-like in string position, ##) fail loudly as untranslatable, which is the migrator's existing honest posture. (a') stays available later if a real consumer ever needs arbitrary-C fidelity; nothing in (c') forecloses it.

    Implementation order (next session): golden .c fixtures in test/migrate first (string-macro sequence, nested object-like, initializer shapes), then the expander feeding g_migrate_preprocessed_source's consumers directly (dropping the line-marker text intermediary where possible), then delete capture_command_stdout + the cc -E exec — no fallback.

  6. ehartford commented on Jul 2, 2026

    @ehartford
    ContributorAuthor

    Closed by the commit above, on route (c') as ruled: ci_expand_macros_in_text — recursive object-like expansion from the compiler-owned libclang macro session — replaces slicing a cc -E dump. Every consumer already held the raw text it needed; the dump was only ever used to expand it. with_cimport_preprocess_text, capture_command_stdout, append_cc_common_args, and the line-marker parsers are deleted; no shell-out remains anywhere in the c_import/migrate path (the earlier -dM half was already libclang-only). Function-like invocations outside the dedicated stringify path fail loudly as before, per the no-silent-fallback rule. Golden migrations (string sequences, nested arithmetic initializers, stringify chains) verified byte-identical pre/post; goldens landed in test/migrate/. §16.1's "compiler-owned C parsing" is now true end to end — and the toolchain stays 100% With.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions