dcr 0.8.4

DCR is a utility for managing C/C++ projects in a Cargo-like style.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// DCR — Cargo-like C/C++ project manager.
//
// Copyright (C) 2026 Dexoron (Bezotechestvo Vladimir) <main@dexoron.su>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

/// MSVC build backend for DCR.
///
/// This module provides the MSVC-specific build implementation for C and C++
/// projects, including object compilation and linking for executables, static
/// libraries, shared libraries, and flat binaries.
use crate::core::build::builder::BuildContext;
use crate::core::build::builder::artifact;
use crate::core::build::common;
use crate::platform;
use crate::utils::build::{is_compile_only, is_flat_bin};
use std::fs;
use std::path::Path;
use std::process::Command;
use std::time::Instant;

/// Builds the project target using the MSVC compiler.
pub fn build(ctx: &BuildContext) -> Result<f64, String> {
    let compiler = if ctx.compiler.is_empty() {
        "cl"
    } else {
        ctx.compiler
    };
    let lang = ctx.language.to_lowercase();
    if lang.contains("asm") {
        return Err("MSVC backend does not support build.language with asm".to_string());
    }
    if is_flat_bin(ctx.kind) && ctx.qt {
        return Err("flat-bin is not supported with build.qt = true".to_string());
    }
    let start_time = Instant::now();
    let sources = collect_sources(ctx)?;
    let obj_dir = match ctx.target_dir {
        Some(dir) => Path::new(dir).join("obj"),
        None => Path::new("./target").join(ctx.profile).join("obj"),
    };
    let objects = build_objects(compiler, &sources, &obj_dir, ctx, "obj")?;

    if is_compile_only(ctx.kind) && !is_flat_bin(ctx.kind) {
        return Ok(common::elapsed_secs(start_time));
    }

    if is_flat_bin(ctx.kind) {
        return link_flat_msvc(ctx, compiler, &objects, &obj_dir, start_time);
    }

    if ctx.kind == "staticlib" {
        let lib_path = platform::lib_path(ctx.profile, ctx.project_name, ctx.target_dir);
        if !common::needs_link(&objects, &lib_path) {
            let elapsed = common::elapsed_secs(start_time);
            return Ok(elapsed);
        }
        let archiver = ctx.archiver.unwrap_or("lib");
        let mut cmd = Command::new(archiver);
        if archiver == "lib" || archiver.eq_ignore_ascii_case("lib.exe") {
            cmd.arg("/nologo").arg(format!("/OUT:{lib_path}"));
        } else {
            cmd.arg("rcs").arg(&lib_path);
        }
        for obj in &objects {
            cmd.arg(obj);
        }
        if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
            eprintln!("[dcr] {:?}", cmd);
        }
        match cmd.status() {
            Ok(status) if status.success() => {
                let elapsed = common::elapsed_secs(start_time);
                return Ok(elapsed);
            }
            Ok(_) => return Err("Build failed".to_string()),
            Err(err) => return Err(format!("Build failed: {err}")),
        }
    }

    let mut cmd = Command::new(compiler);
    cmd.arg("/nologo");
    if ctx.kind == "sharedlib" {
        cmd.arg("/LD");
    }
    match ctx.language.to_lowercase().as_str() {
        "c" => {
            cmd.arg("/TC");
        }
        "c++" | "cpp" | "cxx" => {
            cmd.arg("/TP");
        }
        _ => {
            return Err("Unsupported language".to_string());
        }
    }

    if !ctx.standard.is_empty() {
        let std_flag = msvc_standard_flag(ctx.language, ctx.standard)?;
        cmd.arg(std_flag);
    }

    for obj in &objects {
        cmd.arg(obj);
    }
    if ctx.cflags.is_empty() {
        for flag in default_flags(ctx.profile) {
            cmd.arg(flag);
        }
    }
    for flag in ctx.cflags {
        cmd.arg(flag);
    }
    for dir in ctx.lib_dirs {
        cmd.arg(format!("/LIBPATH:{dir}"));
    }
    for lib in ctx.libs {
        if lib.to_lowercase().ends_with(".lib") {
            cmd.arg(lib);
        } else {
            cmd.arg(format!("{lib}.lib"));
        }
    }
    if !ctx.ldflags.is_empty() {
        cmd.arg("/link");
        for flag in ctx.ldflags {
            cmd.arg(flag);
        }
    }
    let out_path = if ctx.kind == "sharedlib" {
        platform::shared_lib_path(ctx.profile, ctx.project_name, ctx.target_dir)
    } else if ctx.kind == "elf" {
        platform::elf_path(ctx.profile, ctx.project_name, ctx.target_dir)
    } else {
        platform::bin_path(ctx.profile, ctx.project_name, ctx.target_dir)
    };

    if !common::needs_link(&objects, &out_path) {
        let elapsed = common::elapsed_secs(start_time);
        return Ok(elapsed);
    }
    cmd.arg("-o").arg(out_path);

    if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
        eprintln!("[dcr] {:?}", cmd);
    }
    match cmd.status() {
        Ok(status) if status.success() => {
            let elapsed = common::elapsed_secs(start_time);
            Ok(elapsed)
        }
        Ok(_) => Err("Build failed".to_string()),
        Err(err) => Err(format!("Build failed: {err}")),
    }
}

/// Links the flat binary output for MSVC build targets.
fn link_flat_msvc(
    ctx: &BuildContext,
    compiler: &str,
    objects: &[String],
    obj_dir: &Path,
    start_time: Instant,
) -> Result<f64, String> {
    let out_path = artifact::flat_output_path(ctx);
    if !common::needs_link(objects, &out_path) {
        return Ok(common::elapsed_secs(start_time));
    }
    fs::create_dir_all(obj_dir).map_err(|e| format!("obj dir error: {e}"))?;
    let intermediate = obj_dir
        .join(format!("{}.flat.exe", ctx.project_name))
        .to_string_lossy()
        .to_string();

    let mut cmd = Command::new(compiler);
    cmd.arg("/nologo");
    for obj in objects {
        cmd.arg(obj);
    }
    for flag in ctx.cflags {
        cmd.arg(flag);
    }
    for dir in ctx.lib_dirs {
        cmd.arg(format!("/LIBPATH:{dir}"));
    }
    for lib in ctx.libs {
        if lib.to_lowercase().ends_with(".lib") {
            cmd.arg(lib);
        } else {
            cmd.arg(format!("{lib}.lib"));
        }
    }
    cmd.arg(format!("/Fe:{intermediate}"));
    if !ctx.ldflags.is_empty() {
        cmd.arg("/link");
        for flag in ctx.ldflags {
            cmd.arg(flag);
        }
    }
    if ctx.verbose || std::env::var("DCR_DEBUG").is_ok() {
        eprintln!("[dcr] {:?}", cmd);
    }
    let status = cmd
        .status()
        .map_err(|e| format!("flat-bin link failed: {e}"))?;
    if !status.success() {
        return Err("flat-bin link failed".to_string());
    }
    artifact::objcopy_binary(ctx, &intermediate, &out_path)?;
    Ok(common::elapsed_secs(start_time))
}

/// Collects all source files for the build based on language extensions.
pub(crate) fn collect_sources(ctx: &BuildContext) -> Result<Vec<String>, String> {
    let extensions = source_extensions(ctx.language);
    common::collect_sources(
        ctx.source_roots,
        &extensions,
        ctx.exclude_dirs,
        ctx.include_paths,
    )
}

/// Source file extensions for `language` (owned `Vec` of static slices).
fn source_extensions(language: &str) -> Vec<&'static str> {
    crate::core::build::common::source_extensions(language)
}

/// Maps the language and standard version to the corresponding MSVC flag string.
fn msvc_standard_flag(language: &str, standard: &str) -> Result<String, String> {
    let lang = language.to_lowercase();
    let std = standard.to_lowercase();
    if lang == "c" {
        return match std.as_str() {
            "c11" => Ok("/std:c11".to_string()),
            "c17" => Ok("/std:c17".to_string()),
            _ => Err("Unsupported C standard for MSVC".to_string()),
        };
    }
    if lang == "c++" || lang == "cpp" || lang == "cxx" {
        return match std.as_str() {
            "c++11" => Ok("/std:c++11".to_string()),
            "c++14" => Ok("/std:c++14".to_string()),
            "c++17" => Ok("/std:c++17".to_string()),
            "c++20" => Ok("/std:c++20".to_string()),
            "c++23" => Ok("/std:c++latest".to_string()),
            _ => Err("Unsupported C++ standard for MSVC".to_string()),
        };
    }
    Err("Unsupported language".to_string())
}

/// Returns the MSVC architecture flag based on the target platform.
fn msvc_arch_flag(platform: Option<&str>) -> Option<&'static str> {
    let raw = platform?.trim();
    if raw.is_empty() {
        return None;
    }
    let p = raw.to_lowercase().replace('-', "_");
    if p == "x86" || (p.starts_with('i') && p.ends_with("86") && p.len() == 4) {
        return Some("/arch:IA32");
    }
    match p.as_str() {
        "sse2" => Some("/arch:SSE2"),
        "avx" => Some("/arch:AVX"),
        "avx2" => Some("/arch:AVX2"),
        _ => None,
    }
}

/// Returns default compiler flags for the specified build profile.
fn default_flags(profile: &str) -> &'static [&'static str] {
    match profile {
        "release" => &["/O2", "/DNDEBUG"],
        "debug" => &["/Od", "/Zi", "/W4", "/DDCR_DEBUG", "/Oy-"],
        _ => &[],
    }
}

/// Compiles all sources into object files using parallel processing.
fn build_objects(
    compiler: &str,
    sources: &[String],
    obj_dir: &Path,
    ctx: &BuildContext,
    obj_ext: &str,
) -> Result<Vec<String>, String> {
    let objects: Vec<String> = sources
        .iter()
        .map(|s| common::object_path(obj_dir, s, obj_ext))
        .collect();

    common::parallel_build(
        sources.len(),
        |i| build_object(compiler, &sources[i], &objects[i], ctx),
        ctx.codegen_units,
    )?;

    Ok(objects)
}

/// Compiles a single source file to an object file.
fn build_object(
    compiler: &str,
    source: &str,
    obj_path: &str,
    ctx: &BuildContext,
) -> Result<(), String> {
    if let Some(parent) = Path::new(obj_path).parent() {
        fs::create_dir_all(parent).map_err(|err| format!("obj dir error: {err}"))?;
    }

    if !common::needs_rebuild(source, obj_path) {
        return Ok(());
    }

    let mut cmd = Command::new(compiler);
    cmd.arg("/nologo");

    let ext = Path::new(source)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("");
    let is_cpp = matches!(ext, "cpp" | "cxx" | "cc");
    if is_cpp {
        cmd.arg("/TP");
    } else {
        cmd.arg("/TC");
    }

    let std_val = if is_cpp && !ctx.cxx_standard.is_empty() {
        ctx.cxx_standard
    } else if !is_cpp && !ctx.standard.is_empty() {
        ctx.standard
    } else {
        ""
    };
    if !std_val.is_empty() {
        let std_flag = msvc_standard_flag(if is_cpp { "c++" } else { "c" }, std_val)?;
        cmd.arg(std_flag);
    }

    if let Some(flag) = msvc_arch_flag(ctx.platform) {
        cmd.arg(flag);
    }

    if ctx.cflags.is_empty() {
        for flag in default_flags(ctx.profile) {
            cmd.arg(flag);
        }
    }

    for flag in ctx.cflags {
        cmd.arg(flag);
    }

    for dir in ctx.include_dirs {
        cmd.arg(format!("/I{dir}"));
    }

    cmd.arg("/c").arg(source).arg(format!("/Fo:{}", obj_path));
    cmd.arg("/showIncludes");

    if std::env::var("DCR_DEBUG").is_ok() {
        eprintln!("[dcr] {:?}", cmd);
    }

    let output = cmd.output().map_err(|err| format!("Build failed: {err}"))?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    let mut headers = Vec::new();
    let mut clean_stdout = String::new();

    // Parse compiler output to extract include file notes for dependency generation
    for line in stdout.lines() {
        if let Some(stripped) = line.strip_prefix("Note: including file:") {
            headers.push(stripped.trim().to_string());
        } else if let Some(stripped) = line.strip_prefix("Примечание: включение файла:")
        {
            headers.push(stripped.trim().to_string());
        } else {
            clean_stdout.push_str(line);
            clean_stdout.push('\n');
        }
    }

    let _lock = common::get_output_lock().lock().unwrap();

    if !output.status.success() {
        eprint!("{}", clean_stdout);
        eprint!("{}", stderr);
        return Err("Build failed".to_string());
    }

    let trimmed_out = clean_stdout.trim();
    let trimmed_err = stderr.trim();
    let src_filename = Path::new(source)
        .file_name()
        .and_then(|v| v.to_str())
        .unwrap_or("");

    if !trimmed_out.is_empty() && trimmed_out != src_filename {
        print!("{}", clean_stdout);
    }

    if !trimmed_err.is_empty() {
        eprintln!("{}", trimmed_err);
    }

    let d_path = Path::new(obj_path).with_extension("d");
    let mut d_content = format!("{}: \\\n", obj_path.replace('\\', "/"));
    for h in headers {
        let escaped = h.replace('\\', "/").replace(" ", "\\ ");
        d_content.push_str(&format!("  {} \\\n", escaped));
    }
    fs::write(&d_path, d_content).map_err(|err| format!("d file error: {err}"))?;

    Ok(())
}