Skip to content

rust: Pass non-diagnostic JSON on rustc's stderr through - #1661

Closed
phr4nky wants to merge 1 commit into
meta:mainfrom
phr4nky:fix-rustc-action-non-object-json
Closed

phr4nky wants to merge 1 commit into
meta:mainfrom
phr4nky:fix-rustc-action-non-object-json

Conversation

@phr4nky

@phr4nky phr4nky commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Summary

prelude/rust/tools/rustc_action.py, which wraps every rustc invocation, treats each stderr line that json.loads accepts as a diagnostic object. rustc forwards what proc macros print verbatim, so a proc macro doing eprintln!("{:?}", names) on a Vec<String> prints ["pub", "fn"], and the wrapper fails with AttributeError although rustc succeeded. A number, null, true or a quoted string fail the same way (TypeError or AttributeError), and so does a stderr line that is not UTF-8 (UnicodeDecodeError).

Affected version

Checked at main 4b47e14; rustc_action.py is the same in the latest release tag 2026-11-15.

Reproduction

cat > pm.rs <<'EOF'
extern crate proc_macro;
use proc_macro::TokenStream;
#[proc_macro]
pub fn names(input: TokenStream) -> TokenStream {
    let names: Vec<String> = input.to_string().split_whitespace().map(String::from).collect();
    eprintln!("{:?}", names);
    "pub fn f() {}".parse().unwrap()
}
EOF
printf 'pm::names!(pub fn);\n' > lib.rs
rustc --edition 2021 --crate-type proc-macro pm.rs -o libpm.dylib   # libpm.so on Linux
python3 prelude/rust/tools/rustc_action.py --diag-json d.json --diag-txt d.txt "$(command -v rustc)" \
  --rustc-action-separator --edition 2021 --crate-type lib --crate-name lib --extern pm=libpm.dylib \
  --error-format=json --json=diagnostic-rendered-ansi lib.rs -o liblib.rlib; echo "exit=$?"

Expected

Exit 0 with ["pub", "fn"] on stderr, as plain rustc on the same input does; the wrapper already passes stderr lines that are not JSON through.

Actual

  File ".../rustc_action.py", line 422, in handle_output
    if diag.get("level") == "error":
       ^^^^^^^^
AttributeError: 'list' object has no attribute 'get'
exit=1

The rlib is written, but the action fails and the remaining diagnostics are lost.

Analysis

handle_output only catches json.JSONDecodeError and then uses the result as a dict ("unused_extern_names" in diag, diag.get(...)). Any JSON value that is not an object reaches those lines. A line that is not UTF-8 raises UnicodeDecodeError out of json.loads, which is not caught either.

Patch

Pass through every line that is not a JSON object (catch ValueError, which covers both decode errors, and check isinstance(diag, dict)). The new test in prelude/rust/tools/rustc_action_test.py feeds ["pub", "fn"], "quoted", 42, null, true, a Latin-1 byte and plain text followed by one error diagnostic through the wrapper: it fails before the change with the AttributeError above and passes after it. The reproduction above exits 0 with the change.

@meta-cla

meta-cla Bot commented Nov 25, 2026

Copy link
Copy Markdown

Hi @phr4nky!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

Summary:
rustc_action.py reads rustc's stderr line by line and treats every line that `json.loads` accepts as a diagnostic object. rustc also forwards what proc macros print, verbatim, and that output can be valid JSON without being an object: a proc macro that does `eprintln!("{:?}", names)` on a `Vec<String>` prints `["pub", "fn"]`, and a number, `null` or a quoted string parse as well. `diag.get(...)` and `"unused_extern_names" in diag` then raise AttributeError or TypeError, and the compile action fails with a Python traceback although rustc succeeded. A stderr line that is not UTF-8 raises UnicodeDecodeError out of `json.loads` and fails the same way.

Pass through every line that is not a JSON object, as non-JSON lines already are.

Test Plan:
`python3 prelude/rust/tools/rustc_action_test.py`: the new test feeds `["pub", "fn"]`, `"quoted"`, `42`, `null`, `true`, a Latin-1 byte and plain text, followed by one error diagnostic, through the wrapper. Before: AttributeError traceback. After: all lines passed through, the diagnostic written to `--diag-json`, exit 1 for the error.

A real proc macro that `eprintln!`s a `Vec<String>`, compiled into a library through rustc_action.py (rustc 1.99.0-nightly): before, exit 1 with `AttributeError: 'list' object has no attribute 'get'` (plain rustc: exit 0); after, exit 0 and `["pub", "fn"]` on stderr.
@phr4nky
phr4nky force-pushed the fix-rustc-action-non-object-json branch from efefa2c to ef51ace Compare November 25, 2026 21:48
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 25, 2026
@meta-codesync

meta-codesync Bot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

This pull request has been imported. If you are a Meta employee, you can view this in D134594572. (Because this pull request was imported automatically, there will not be any future comments.)

@dtolnay dtolnay left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@meta-codesync meta-codesync Bot closed this in f6264f6 Nov 26, 2026
meta-codesync Bot pushed a commit to meta/buck2-prelude that referenced this pull request Nov 26, 2026
Summary:
`prelude/rust/tools/rustc_action.py`, which wraps every rustc invocation, treats each stderr line that `json.loads` accepts as a diagnostic object. rustc forwards what proc macros print verbatim, so a proc macro doing `eprintln!("{:?}", names)` on a `Vec<String>` prints `["pub", "fn"]`, and the wrapper fails with `AttributeError` although rustc succeeded. A number, `null`, `true` or a quoted string fail the same way (TypeError or AttributeError), and so does a stderr line that is not UTF-8 (UnicodeDecodeError).

## Affected version

Checked at main 4b47e1430e; `rustc_action.py` is the same in the latest release tag `2026-11-15`.

## Reproduction

```
cat > pm.rs <<'EOF'
extern crate proc_macro;
use proc_macro::TokenStream;
#[proc_macro]
pub fn names(input: TokenStream) -> TokenStream {
    let names: Vec<String> = input.to_string().split_whitespace().map(String::from).collect();
    eprintln!("{:?}", names);
    "pub fn f() {}".parse().unwrap()
}
EOF
printf 'pm::names!(pub fn);\n' > lib.rs
rustc --edition 2021 --crate-type proc-macro pm.rs -o libpm.dylib   # libpm.so on Linux
python3 prelude/rust/tools/rustc_action.py --diag-json d.json --diag-txt d.txt "$(command -v rustc)" \
  --rustc-action-separator --edition 2021 --crate-type lib --crate-name lib --extern pm=libpm.dylib \
  --error-format=json --json=diagnostic-rendered-ansi lib.rs -o liblib.rlib; echo "exit=$?"
```

## Expected

Exit 0 with `["pub", "fn"]` on stderr, as plain `rustc` on the same input does; the wrapper already passes stderr lines that are not JSON through.

## Actual

```
  File ".../rustc_action.py", line 422, in handle_output
    if diag.get("level") == "error":
       ^^^^^^^^
AttributeError: 'list' object has no attribute 'get'
exit=1
```

The rlib is written, but the action fails and the remaining diagnostics are lost.

## Analysis

`handle_output` only catches `json.JSONDecodeError` and then uses the result as a dict (`"unused_extern_names" in diag`, `diag.get(...)`). Any JSON value that is not an object reaches those lines. A line that is not UTF-8 raises UnicodeDecodeError out of `json.loads`, which is not caught either.

## Patch

Pass through every line that is not a JSON object (catch `ValueError`, which covers both decode errors, and check `isinstance(diag, dict)`). The new test in `prelude/rust/tools/rustc_action_test.py` feeds `["pub", "fn"]`, `"quoted"`, `42`, `null`, `true`, a Latin-1 byte and plain text followed by one error diagnostic through the wrapper: it fails before the change with the AttributeError above and passes after it. The reproduction above exits 0 with the change.

X-link: meta/buck2#1661

Reviewed By: dtolnay

Differential Revision: D134594572

fbshipit-source-id: f09c765d02707e4154db055925eba8215c6a7f2d
@meta-codesync meta-codesync Bot added the Merged label Nov 26, 2026
@meta-codesync

meta-codesync Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

This pull request has been merged in f6264f6.

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

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. Merged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants