feat(run): show xcodebuild errors and warnings in Problems (#6848)

Xcode run and test configurations now publish the compiler and linker messages in their xcodebuild output to Problems and the editor as they arrive. A Format::Xcode on top of the GCC/Clang line parser folds in notes, project-level lines and Undefined symbols blocks; XcodebuildMessages resolves positions, maps symlinked paths back to the project, reports each message once across architectures and stops at the build result. A new run clears the files its previous run reported; messages without a location go on the project file.

Closes #6842

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-29 21:32:42 +08:00
1 джерело 55b23c90b8
коміт 3d6ad2e254
5 files changed
+432

No files matched your search

+135
Переглянути файл
@@ -815,6 +815,74 @@ pub fn run(
})
}
/// Messages of an `xcodebuild` whose output arrives line by line (an Xcode run configuration),
/// each reported once: xcodebuild prints a message for every architecture and again on retries.
pub struct XcodebuildMessages {
parser: OutputParser,
cwd: PathBuf,
paths: PathMap,
lines: Lines,
seen: HashSet<(Option<PathBuf>, Option<Range>, String)>,
/// xcodebuild printed its result (`** BUILD SUCCEEDED **`); what follows is the app's console.
done: bool,
}
impl XcodebuildMessages {
/// Relative paths resolve against `cwd`; paths under `root`'s canonical form map back to `root`.
pub fn new(root: &Path, cwd: &Path) -> Self {
XcodebuildMessages {
parser: OutputParser::new(Format::Xcode),
cwd: cwd.to_path_buf(),
paths: PathMap::new(root),
lines: Lines::default(),
seen: HashSet::new(),
done: false,
}
}
/// Messages completed by `line` (without its line break).
pub fn feed(&mut self, line: &str) -> Vec<BuildMessage> {
if self.done {
return Vec::new();
}
let result = parse::strip_ansi(line);
let result = result.trim();
if result.len() > 6 && result.starts_with("** ") && result.ends_with(" **") {
self.done = true;
return self.finish();
}
let raws = self.parser.feed(line).messages;
self.resolve(raws)
}
/// The message still waiting for detail lines.
pub fn finish(&mut self) -> Vec<BuildMessage> {
let raws = self.parser.finish();
self.resolve(raws)
}
fn resolve(&mut self, raws: Vec<RawMessage>) -> Vec<BuildMessage> {
raws.into_iter()
.map(|raw| {
let mut m = resolve(raw, &self.cwd, &self.paths, &mut self.lines);
// xcodebuild prints the folder it was started in, which may be a symlink to the project.
if let Some(path) = m.path.clone().map(PathBuf::from)
&& !path.starts_with(&self.paths.root)
&& let Ok(real) = dunce::canonicalize(&path)
&& let Some(real) = real.to_str()
{
let mapped = self.paths.resolve(real, &self.cwd, None);
if mapped.starts_with(&self.paths.root) {
m.path = Some(mapped.into());
}
}
m
})
.filter(|m| self.seen.insert((m.path.clone().map(Into::into), m.range, m.text.clone())))
.collect()
}
}
/// Per-file editor / Problems diagnostics of the messages that have a position.
pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
diagnostics_from(messages, DIAGNOSTICS_SOURCE)
@@ -1336,6 +1404,73 @@ mod tests {
}
use super::*;
#[test]
fn xcodebuild_messages_once_per_build() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("Warn.swift");
std::fs::write(&file, "func f() -> Int {\n var count = 1\n return count\n}\n").unwrap();
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
let warning = format!("{}:2:9: warning: variable 'count' was never mutated", file.display());
let mut out = Vec::new();
// One copy per architecture, then the linker's per-architecture lists.
for line in [
warning.as_str(),
"SwiftCompile normal arm64 Compiling\\ Warn.swift",
warning.as_str(),
"Undefined symbols for architecture x86_64:",
" \"_sym\", referenced from:",
"ld: symbol(s) not found for architecture x86_64",
"Undefined symbols for architecture arm64:",
" \"_sym\", referenced from:",
] {
out.extend(x.feed(line));
}
out.extend(x.finish());
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(file));
// `count`, 0-based, underlined.
assert_eq!(out[0].range, Some(Range::new(Pos::new(1, 8), Pos::new(1, 13))));
assert_eq!(
(out[1].path.is_none(), out[1].text.as_str()),
(true, "Undefined symbols\n\"_sym\", referenced from:")
);
}
#[test]
fn xcodebuild_messages_stop_at_the_build_result() {
let tmp = tempfile::tempdir().unwrap();
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
let mut out = Vec::new();
// An Xcode run configuration's output: the build, then the app's own console.
for line in [
"/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities'",
"** BUILD SUCCEEDED **",
"error: request failed",
"warning: low memory",
"Demo/ContentView.swift:12: Fatal error: Unexpectedly found nil while unwrapping an Optional value",
] {
out.extend(x.feed(line));
}
out.extend(x.finish());
let texts: Vec<_> = out.iter().map(|m| m.text.as_str()).collect();
assert_eq!(texts, ["Could not find or use auto-linked framework 'UIUtilities'"]);
}
#[cfg(unix)]
#[test]
fn xcodebuild_paths_through_a_symlink_map_to_the_project() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("Demo");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join("A.swift"), "let x = y\n").unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&root, &link).unwrap();
let mut x = XcodebuildMessages::new(&root, &root);
x.feed(&format!("{}/A.swift:1:9: error: cannot find 'y' in scope", link.display()));
let out = x.finish();
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(root.join("A.swift")));
}
/// Launch outputs use the platform separator throughout, so they compare equal to
/// the same directories as JDT LS reports them.
#[test]
+158
Переглянути файл
@@ -27,6 +27,10 @@ pub(crate) enum Format {
Gcc,
/// MSBuild (`dotnet build`): `C:\p\A.cs(12,5): error CS1002: msg [C:\p\App.csproj]`.
Msbuild,
/// `xcodebuild`: swiftc / clang lines like [`Format::Gcc`], their notes (`path:3:6: note:` or
/// Swift's `` `- note: `` in the code excerpt), `App.xcodeproj: App: ld: warning: msg` and
/// `Undefined symbols for architecture arm64:` with its indented details.
Xcode,
}
/// What a printed column counts.
@@ -331,6 +335,59 @@ fn gcc_line(line: &str) -> Option<RawMessage> {
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte).at(path, ln, col))
}
const UNDEFINED_SYMBOLS: &str = "Undefined symbols";
/// An `xcodebuild` message: a compiler line, a linker / build-system line without a location, or
/// the start of an undefined symbols list. Its architecture is dropped: every one prints the same.
fn xcode_line(line: &str) -> Option<RawMessage> {
if let Some(m) = gcc_line(line) {
return Some(m);
}
if line.starts_with("Undefined symbols for architecture ") {
return Some(RawMessage::new(Severity::Error, UNDEFINED_SYMBOLS, ColUnit::Byte));
}
// `/p/App.xcodeproj: App: ld: warning: msg`, `error: msg`, `xcodebuild: error: msg`.
let rest = [".xcodeproj: ", ".xcworkspace: "]
.into_iter()
.find_map(|c| line.find(c).map(|i| &line[i + c.len()..]))
.or_else(|| (!line.starts_with(char::is_whitespace)).then_some(line))?;
let (severity, msg) =
[("error: ", Severity::Error), ("warning: ", Severity::Warning)].into_iter().find_map(|(word, severity)| {
let at = rest.match_indices(word).map(|(i, _)| i).find(|&i| i == 0 || rest[..i].ends_with(": "))?;
// Only `tool: ` / `target: ` words may come before the severity, not a sentence.
rest[..at].split(": ").all(|w| !w.contains(' ')).then(|| (severity, rest[at + word.len()..].trim()))
})?;
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte))
}
/// Whether `line` belongs to the pending `xcodebuild` message (and is folded into it).
fn xcode_detail(msg: &mut RawMessage, line: &str) -> bool {
let t = line.trim_start();
// A `note:` with a location, as clang and `-diagnostic-style llvm` print it.
if let Some((_, _, _, rest)) = path_line_col(line)
&& let Some(note) = rest.strip_prefix(':').and_then(|r| r.trim_start().strip_prefix("note:"))
{
msg.text.push_str("\nnote: ");
msg.text.push_str(note.trim());
return true;
}
// The code excerpt: ` 9 | switch s {`, ` | `- note: add missing case`.
let excerpt = t.trim_start_matches(|c: char| c.is_ascii_digit()).trim_start().starts_with('|');
if excerpt {
if let Some(i) = t.find("- note: ") {
msg.text.push_str("\nnote: ");
msg.text.push_str(t[i + "- note: ".len()..].trim());
}
return true;
}
if msg.text.starts_with(UNDEFINED_SYMBOLS) && t.len() < line.len() && !t.is_empty() {
msg.text.push('\n');
msg.text.push_str(t);
return true;
}
false
}
/// rustc's JSON diagnostic (`reason: compiler-message`) → message and its rendered text.
fn cargo_json(v: &Value) -> Option<(Option<RawMessage>, String)> {
if v.get("reason")?.as_str()? != "compiler-message" {
@@ -412,6 +469,9 @@ impl OutputParser {
.map_or(line, |r| r.strip_prefix(' ').unwrap_or(r)),
_ => line,
};
if format == Format::Xcode {
return xcode_detail(&mut p.msg, line);
}
if matches!(format, Format::Maven | Format::Gradle | Format::Tsc)
&& body.starts_with(" ")
&& !body.trim().is_empty()
@@ -447,6 +507,7 @@ impl OutputParser {
Format::Go => go_line(&line),
Format::Gcc => gcc_line(&line),
Format::Msbuild => msbuild_line(&line),
Format::Xcode => xcode_line(&line),
Format::Cargo => None,
};
if let Some(msg) = parsed {
@@ -678,6 +739,103 @@ mod tests {
assert_eq!(out[2].text, "'missing.h' file not found");
}
// Real `xcodebuild build` output (Xcode 27.1, iOS Simulator, two architectures), paths shortened.
#[test]
fn xcodebuild_swift_error_warning_and_note() {
let out = parse(
Format::Xcode,
"SwiftCompile normal x86_64 Compiling\\ Warn.swift /p/Demo/Warn.swift (in target 'Demo' from project 'Demo')\n\
/p/Demo/Warn.swift:2:9: warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
\x201 | func warnMe() -> Int {\n\
\x202 | var count = 1\n\
\x20 | `- warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
\x203 | return count\n\
\x204 | }\n\
\n\
/p/Demo/Warn.swift:9:5: error: switch must be exhaustive\n\
\x207 | \n\
\x208 | func name(_ s: Shade) -> String {\n\
\x209 | switch s {\n\
\x20 | |- error: switch must be exhaustive\n\
\x20 | `- note: add missing case: '.dark'\n\
10 | case .light: return \"light\"\n\
11 | }\n\
\n\
[#VariableNeverMutated]: <https://docs.swift.org/compiler/documentation/diagnostics/variable-never-mutated>\n\
Failed frontend command:\n\
note: Removed stale file '/p/dd/Demo.swiftmodule'\n",
);
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].severity, Severity::Warning);
assert_eq!((out[0].path.as_deref(), out[0].line, out[0].col), (Some("/p/Demo/Warn.swift"), Some(2), Some(9)));
assert!(out[0].text.starts_with("variable 'count' was never mutated"), "{}", out[0].text);
assert_eq!(out[1].severity, Severity::Error);
assert_eq!(out[1].text, "switch must be exhaustive\nnote: add missing case: '.dark'");
assert_eq!((out[1].line, out[1].col), (Some(9), Some(5)));
}
#[test]
fn xcodebuild_clang_errors_with_note() {
let out = parse(
Format::Xcode,
"/p/Demo/Legacy.m:2:29: error: use of undeclared identifier 'undeclared_thing'\n\
\x20 2 | void legacy(void) { int x = undeclared_thing; }\n\
\x20 | ^~~~~~~~~~~~~~~~\n\
/p/Demo/Legacy.m:4:6: error: redefinition of 'twice'\n\
\x20 4 | void twice(void) {}\n\
\x20 | ^\n\
/p/Demo/Legacy.m:3:6: note: previous definition is here\n\
\x20 3 | void twice(void) {}\n\
\x20 | ^\n\
2 errors generated.\n",
);
assert_eq!(out.len(), 2, "{out:?}");
assert_eq!(out[0].text, "use of undeclared identifier 'undeclared_thing'");
assert_eq!((out[0].line, out[0].col), (Some(2), Some(29)));
assert_eq!(out[1].text, "redefinition of 'twice'\nnote: previous definition is here");
assert_eq!((out[1].line, out[1].col), (Some(4), Some(6)));
}
#[test]
fn xcodebuild_linker_errors_without_location() {
let out = parse(
Format::Xcode,
"Ld /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
\x20 cd /p/Demo\n\
\x20 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -Xlinker -reproducible -target arm64-apple-ios16.0-simulator -ferror-limit 19\n\
/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found\n\
Undefined symbols for architecture arm64:\n\
\x20 \"_missing_symbol_xyz\", referenced from:\n\
\x20 Demo.callMissing() -> () in Missing.o\n\
ld: symbol(s) not found for architecture arm64\n\
/p/Demo/Demo.xcodeproj: Demo: clang: error: linker command failed with exit code 1 (use -v to see invocation)\n\
\n\
** BUILD FAILED **\n\
\n\
The following build commands failed:\n\
\tLd /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
xcodebuild: error: Unable to find a destination matching the provided destination specifier\n",
);
let found: Vec<_> = out.iter().map(|m| (m.severity, m.text.as_str(), m.path.is_none())).collect();
assert_eq!(
found,
[
(
Severity::Warning,
"Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found",
true
),
(
Severity::Error,
"Undefined symbols\n\"_missing_symbol_xyz\", referenced from:\nDemo.callMissing() -> () in Missing.o",
true
),
(Severity::Error, "linker command failed with exit code 1 (use -v to see invocation)", true),
(Severity::Error, "Unable to find a destination matching the provided destination specifier", true),
]
);
}
#[test]
fn go_errors() {
let out = parse(
+124
Переглянути файл
@@ -540,6 +540,9 @@ async fn start_inner(
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
}
let xcode_container = matches!(config.kind.as_str(), "xcode" | "xcode-test")
.then(|| xcode_container(&config).map(|c| run_dir.join(c)))
.flatten();
if config.kind == "xcode" {
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
config = host
@@ -600,9 +603,130 @@ async fn start_inner(
previous.emit(event);
});
}
let on_output = match xcode_container {
Some(container) => {
let (output, problems) = xcodebuild_problems(&project, &config.id, &run_dir, container, on_output, sink);
sink = problems;
output
}
None => on_output,
};
host.processes.start(&project.root, &config, &options, sink, Box::new(move |c| on_output(c)))
}
/// The `-project` / `-workspace` an Xcode configuration builds, relative to its folder.
fn xcode_container(config: &RunConfig) -> Option<String> {
config.extras.params.get("container").cloned().or_else(|| {
let at = config.args.iter().position(|a| a == "-project" || a == "-workspace")?;
config.args.get(at + 1).cloned()
})
}
const XCODEBUILD_SOURCE: &str = "xcodebuild";
/// Sends the compiler messages in an Xcode configuration's `xcodebuild` output to Problems as they
/// arrive, after clearing the ones its previous run reported. Messages without a location (linker
/// errors) are listed on the project file (`project.pbxproj` / `contents.xcworkspacedata`).
fn xcodebuild_problems(
project: &crate::project::Project,
config_id: &str,
cwd: &Path,
container: PathBuf,
on_output: Emit<OutputChunk>,
sink: ide_core::SharedSink,
) -> (Emit<OutputChunk>, ide_core::SharedSink) {
use ide_build::compile::{BuildMessage, XcodebuildMessages, diagnostics_from};
use ide_core::IdeEvent;
use std::collections::BTreeMap;
let project_file = container.join(if container.extension().is_some_and(|e| e == "xcworkspace") {
"contents.xcworkspacedata"
} else {
"project.pbxproj"
});
let reported = project.xcodebuild_problems.clone();
let previous = reported.lock().insert(config_id.to_owned(), Vec::new()).unwrap_or_default();
for path in previous {
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: XCODEBUILD_SOURCE.into(), items: Vec::new() });
}
struct State {
parser: XcodebuildMessages,
/// Unfinished lines of stdout and stderr.
partial: [String; 2],
files: BTreeMap<PathBuf, Vec<BuildMessage>>,
}
let state = Arc::new(parking_lot::Mutex::new(State {
parser: XcodebuildMessages::new(&project.root, cwd),
partial: Default::default(),
files: BTreeMap::new(),
}));
let config_id = config_id.to_owned();
let publish = {
let sink = sink.clone();
move |state: &mut State, messages: Vec<BuildMessage>| {
let mut changed = Vec::new();
for mut m in messages {
if m.path.is_none() {
m.path = Some(project_file.clone().into());
m.range = Some(ide_core::Range::default());
}
let Some(path) = m.path.clone().map(PathBuf::from) else { continue };
if !state.files.contains_key(&path) {
reported.lock().entry(config_id.clone()).or_default().push(path.clone());
}
state.files.entry(path.clone()).or_default().push(m);
if !changed.contains(&path) {
changed.push(path);
}
}
for path in changed {
let items = diagnostics_from(&state.files[&path], XCODEBUILD_SOURCE).remove(&path).unwrap_or_default();
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: XCODEBUILD_SOURCE.into(), items });
}
}
};
let publish = Arc::new(publish);
let output: Emit<OutputChunk> = {
let (state, publish) = (state.clone(), publish.clone());
Arc::new(move |chunk: OutputChunk| {
let stream = match &chunk {
OutputChunk::Stdout { text } => Some((0, text)),
OutputChunk::Stderr { text } => Some((1, text)),
OutputChunk::System { .. } => None,
};
if let Some((i, text)) = stream {
let mut guard = state.lock();
let s = &mut *guard;
s.partial[i].push_str(text);
let mut messages = Vec::new();
while let Some(end) = s.partial[i].find('\n') {
let line: String = s.partial[i].drain(..=end).collect();
messages.extend(s.parser.feed(line.trim_end_matches(['\n', '\r'])));
}
publish(s, messages);
}
on_output(chunk);
})
};
let problems: ide_core::SharedSink = Arc::new(move |event: IdeEvent| {
if matches!(event, IdeEvent::RunExited { .. }) {
let mut guard = state.lock();
let s = &mut *guard;
let mut messages = Vec::new();
for i in 0..2 {
let rest = std::mem::take(&mut s.partial[i]);
if !rest.is_empty() {
messages.extend(s.parser.feed(rest.trim_end_matches('\r')));
}
}
messages.extend(s.parser.finish());
publish(s, messages);
}
sink.emit(event);
});
(output, problems)
}
/// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an
/// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a
/// run target gets none; the console says so, and why an approved agent was left out. A launch
+4
Переглянути файл
@@ -57,6 +57,8 @@ pub struct Project {
pub(crate) java_launches: crate::ops::java::cache::Sessions,
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
/// Files each Xcode configuration's last `xcodebuild` reported problems in, by configuration id.
pub(crate) xcodebuild_problems: Arc<Mutex<HashMap<String, Vec<PathBuf>>>>,
/// The completion only some plugins asked to complete again ([`crate::ops::lsp::lsp_completion`]).
pub(crate) completion_session: Mutex<Option<crate::ops::lsp::CompletionSession>>,
/// Database tool window: data sources and their connections.
@@ -708,6 +710,7 @@ impl Host {
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
xcodebuild_problems: Arc::default(),
completion_session: Mutex::default(),
db,
http_history,
@@ -989,6 +992,7 @@ impl Host {
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
xcodebuild_problems: Arc::default(),
completion_session: Mutex::default(),
db,
http_history,
+11
Переглянути файл
@@ -31,6 +31,17 @@ describe("findOutputLinks", () => {
expect(files(" at Object.<anonymous> (/abs/dir/x.js:1:2)")[0]).toMatchObject({ path: "/abs/dir/x.js" });
});
it("xcodebuild diagnostics", () => {
expect(files("/p/Demo/Warn.swift:9:5: error: switch must be exhaustive")).toEqual([
{ path: "/p/Demo/Warn.swift", line: 9, col: 5, resolve: "path", text: "/p/Demo/Warn.swift:9:5" },
]);
expect(files("/p/Demo/Legacy.m:3:6: note: previous definition is here")[0]).toMatchObject({
path: "/p/Demo/Legacy.m",
line: 3,
col: 6,
});
});
it("python tracebacks", () => {
const [link] = files(' File "app/main.py", line 3, in <module>');
expect(link).toEqual({ path: "app/main.py", line: 3, resolve: "path", text: 'File "app/main.py", line 3' });