llvm-native-core 0.1.9

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! C++ Preprocessor Extensions — adds C++-specific preprocessing
//! directives and predefined macros beyond the base C preprocessor.
//!
//! Implements:
//! - `__has_include` / `__has_cpp_attribute` (C++17)
//! - `#include_next` for header wrappers
//! - `import` / `export` for header units (C++20)
//! - C++ predefined macros: `__cplusplus`, `__STDCPP_DEFAULT_NEW_ALIGNMENT__`,
//!   `__cpp_*` feature test macros
//! - `#embed` directive (C++26 / C23)
//! - `#warning` directive
//!
//! Clean-room behavioral reconstruction from the C++ standards
//! (ISO/IEC 14882:1998–2024) and published Clang documentation.

use super::cpp_token::CppStandard;

// ═══════════════════════════════════════════════════════════════════════════════
// C++ Predefined Macros
// ═══════════════════════════════════════════════════════════════════════════════

/// Returns the `__cplusplus` value for a given C++ standard.
pub fn cplusplus_value(standard: CppStandard) -> i64 {
    match standard {
        CppStandard::Cxx98 | CppStandard::GnuXx98 => 199711,
        CppStandard::Cxx03 | CppStandard::GnuXx03 => 199711,
        CppStandard::Cxx11 | CppStandard::GnuXx11 => 201103,
        CppStandard::Cxx14 | CppStandard::GnuXx14 => 201402,
        CppStandard::Cxx17 | CppStandard::GnuXx17 => 201703,
        CppStandard::Cxx20 | CppStandard::GnuXx20 => 202002,
        CppStandard::Cxx23 | CppStandard::GnuXx23 => 202302,
    }
}

/// All C++ predefined macros for the given standard and target.
pub fn cpp_predefined_macros(standard: CppStandard) -> Vec<(String, String)> {
    let mut macros = Vec::new();

    // __cplusplus
    macros.push(("__cplusplus".into(), cplusplus_value(standard).to_string()));

    // __STDCPP_DEFAULT_NEW_ALIGNMENT__
    macros.push(("__STDCPP_DEFAULT_NEW_ALIGNMENT__".into(), "16".into()));

    // C++ standard feature test macros
    macros.push(("__cpp_raw_strings".into(), "200710".into()));
    macros.push(("__cpp_unicode_characters".into(), "200704".into()));
    macros.push(("__cpp_user_defined_literals".into(), "200809".into()));
    macros.push(("__cpp_lambdas".into(), "200907".into()));
    macros.push((
        "__cpp_constexpr".into(),
        if standard >= CppStandard::Cxx14 {
            "201304".into()
        } else {
            "200704".into()
        },
    ));
    macros.push((
        "__cpp_range_based_for".into(),
        if standard >= CppStandard::Cxx17 {
            "201603".into()
        } else {
            "200907".into()
        },
    ));
    macros.push((
        "__cpp_static_assert".into(),
        if standard >= CppStandard::Cxx17 {
            "201411".into()
        } else {
            "200410".into()
        },
    ));
    macros.push(("__cpp_decltype".into(), "200707".into()));
    macros.push(("__cpp_attributes".into(), "200809".into()));
    macros.push(("__cpp_rvalue_references".into(), "200610".into()));
    macros.push(("__cpp_variadic_templates".into(), "200704".into()));
    macros.push(("__cpp_initializer_lists".into(), "200806".into()));
    macros.push(("__cpp_delegating_constructors".into(), "200604".into()));
    macros.push(("__cpp_nsdmi".into(), "200809".into()));
    macros.push((
        "__cpp_inheriting_constructors".into(),
        if standard >= CppStandard::Cxx17 {
            "201511".into()
        } else {
            "200802".into()
        },
    ));
    macros.push(("__cpp_ref_qualifiers".into(), "200710".into()));
    macros.push(("__cpp_alias_templates".into(), "200704".into()));

    // C++14 feature test macros
    if standard >= CppStandard::Cxx14 {
        macros.push(("__cpp_return_type_deduction".into(), "201304".into()));
        macros.push(("__cpp_decltype_auto".into(), "201304".into()));
        macros.push(("__cpp_generic_lambdas".into(), "201304".into()));
        macros.push(("__cpp_variable_templates".into(), "201304".into()));
        macros.push(("__cpp_binary_literals".into(), "201304".into()));
        macros.push(("__cpp_digit_separators".into(), "201309".into()));
        macros.push(("__cpp_init_captures".into(), "201304".into()));
        macros.push(("__cpp_aggregate_nsdmi".into(), "201304".into()));
    }

    // C++17 feature test macros
    if standard >= CppStandard::Cxx17 {
        macros.push(("__cpp_structured_bindings".into(), "201606".into()));
        macros.push(("__cpp_deduction_guides".into(), "201703".into()));
        macros.push(("__cpp_if_constexpr".into(), "201606".into()));
        macros.push(("__cpp_inline_variables".into(), "201606".into()));
        macros.push(("__cpp_fold_expressions".into(), "201603".into()));
        macros.push(("__cpp_capture_star_this".into(), "201603".into()));
        macros.push(("__cpp_namespace_attributes".into(), "201411".into()));
        macros.push(("__cpp_nested_namespace_definitions".into(), "201411".into()));
        macros.push(("__cpp_noexcept_function_type".into(), "201510".into()));
        macros.push(("__cpp_template_auto".into(), "201606".into()));
        macros.push(("__cpp_variadic_using".into(), "201611".into()));
        macros.push(("__cpp_guaranteed_copy_elision".into(), "201606".into()));
        macros.push(("__cpp_hex_float".into(), "201603".into()));
        macros.push(("__cpp_constexpr_dynamic_alloc".into(), "201907".into()));
    }

    // C++20 feature test macros
    if standard >= CppStandard::Cxx20 {
        macros.push(("__cpp_concepts".into(), "202002".into()));
        macros.push(("__cpp_coroutines".into(), "201902".into()));
        macros.push(("__cpp_modules".into(), "201907".into()));
        macros.push(("__cpp_using_enum".into(), "201907".into()));
        macros.push(("__cpp_constexpr_in_virtual".into(), "202002".into()));
        macros.push(("__cpp_aggregate_paren_init".into(), "201902".into()));
        macros.push(("__cpp_char8_t".into(), "201811".into()));
        macros.push(("__cpp_conditional_explicit".into(), "201806".into()));
        macros.push(("__cpp_consteval".into(), "201811".into()));
        macros.push(("__cpp_constinit".into(), "201907".into()));
        macros.push(("__cpp_designated_initializers".into(), "201707".into()));
        macros.push(("__cpp_implicit_move".into(), "202002".into()));
        macros.push(("__cpp_nontype_template_args".into(), "201911".into()));
        macros.push((
            "__cpp_nontype_template_parameter_auto".into(),
            "201606".into(),
        ));
        macros.push(("__cpp_range_based_for".into(), "201603".into()));
        macros.push(("__cpp_three_way_comparison".into(), "201907".into()));
        macros.push(("__cpp_lib_concepts".into(), "202002".into()));
        macros.push(("__cpp_lib_coroutine".into(), "201902".into()));
    }

    // C++23 feature test macros
    if standard >= CppStandard::Cxx23 {
        macros.push(("__cpp_explicit_this_parameter".into(), "202110".into()));
        macros.push(("__cpp_if_consteval".into(), "202106".into()));
        macros.push(("__cpp_multidimensional_subscript".into(), "202110".into()));
        macros.push(("__cpp_static_call_operator".into(), "202207".into()));
        macros.push(("__cpp_auto_cast".into(), "202110".into()));
        macros.push(("__cpp_lib_expected".into(), "202202".into()));
    }

    macros
}

// ═══════════════════════════════════════════════════════════════════════════════
// __has_include / __has_cpp_attribute
// ═══════════════════════════════════════════════════════════════════════════════

/// Evaluate `__has_include("header")` or `__has_include(<header>)`.
/// Returns true if the header is available.
pub fn eval_has_include(header: &str, _standard: CppStandard) -> bool {
    // In a real implementation, this would check the include paths.
    // For now, check common standard library headers.
    let known_headers = [
        "<iostream>",
        "<vector>",
        "<string>",
        "<map>",
        "<set>",
        "<algorithm>",
        "<memory>",
        "<functional>",
        "<utility>",
        "<type_traits>",
        "<tuple>",
        "<array>",
        "<queue>",
        "<stack>",
        "<bitset>",
        "<deque>",
        "<list>",
        "<forward_list>",
        "<unordered_map>",
        "<unordered_set>",
        "<regex>",
        "<thread>",
        "<mutex>",
        "<future>",
        "<chrono>",
        "<random>",
        "<filesystem>",
        "<optional>",
        "<variant>",
        "<any>",
        "<string_view>",
        "<span>",
        "<concepts>",
        "<coroutine>",
        "<compare>",
        "<format>",
        "<ranges>",
        "<source_location>",
        "\"stdio.h\"",
        "\"stdlib.h\"",
        "\"string.h\"",
        "\"math.h\"",
    ];
    known_headers.iter().any(|&h| {
        header == h
            || header.trim_matches(&['<', '>', '"'] as &[_])
                == h.trim_matches(&['<', '>', '"'] as &[_])
    })
}

/// Evaluate `__has_cpp_attribute(attribute_name)`.
/// Returns the attribute version or 0 if not supported.
pub fn eval_has_cpp_attribute(attr: &str, standard: CppStandard) -> u32 {
    match attr {
        // C++11 attributes
        "noreturn" if standard >= CppStandard::Cxx11 => 200809,
        "carries_dependency" if standard >= CppStandard::Cxx11 => 200809,
        // C++14 attributes
        "deprecated" if standard >= CppStandard::Cxx14 => 201309,
        // C++17 attributes
        "fallthrough" if standard >= CppStandard::Cxx17 => 201603,
        "nodiscard" if standard >= CppStandard::Cxx17 => 201603,
        "maybe_unused" if standard >= CppStandard::Cxx17 => 201603,
        // C++20 attributes
        "likely" if standard >= CppStandard::Cxx20 => 201803,
        "unlikely" if standard >= CppStandard::Cxx20 => 201803,
        "no_unique_address" if standard >= CppStandard::Cxx20 => 201803,
        // C++23 attributes
        "assume" if standard >= CppStandard::Cxx23 => 202207,
        _ => 0,
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// #include_next support
// ═══════════════════════════════════════════════════════════════════════════════

/// Determines if include_next should be used for a given header,
/// skipping the current include directory and searching the rest of the path.
pub struct IncludeNextResolver {
    /// The include paths, in search order.
    include_paths: Vec<String>,
    /// The current include directory (to skip).
    current_dir: String,
}

impl IncludeNextResolver {
    pub fn new(include_paths: Vec<String>, current_dir: &str) -> Self {
        Self {
            include_paths,
            current_dir: current_dir.to_string(),
        }
    }

    /// Resolve an `#include_next "header"` directive.
    /// Returns the resolved file path, if found.
    pub fn resolve(&self, header: &str) -> Option<String> {
        let mut found_current = false;
        for path in &self.include_paths {
            if path == &self.current_dir {
                found_current = true;
                continue;
            }
            if found_current {
                let candidate = std::path::Path::new(path).join(header);
                if candidate.exists() {
                    return Some(candidate.to_string_lossy().to_string());
                }
            }
        }
        None
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// #warning directive
// ═══════════════════════════════════════════════════════════════════════════════

/// Process a `#warning "message"` directive.
pub fn process_warning_directive(message: &str) -> String {
    format!("#warning: {}", message)
}

// ═══════════════════════════════════════════════════════════════════════════════
// #embed directive (C++26 / C23)
// ═══════════════════════════════════════════════════════════════════════════════

/// Process a `#embed "filename"` directive.
/// Reads a file and embeds its binary content as an initializer list.
pub struct EmbedProcessor;

impl EmbedProcessor {
    /// Process an `#embed` directive.
    /// Returns the embedded data as a comma-separated list of byte values.
    pub fn process_embed(filename: &str, limit: Option<usize>) -> Result<String, String> {
        let data =
            std::fs::read(filename).map_err(|e| format!("cannot embed '{}': {}", filename, e))?;

        let limit = limit.unwrap_or(data.len());
        let bytes: Vec<String> = data.iter().take(limit).map(|b| format!("{}", b)).collect();

        Ok(bytes.join(", "))
    }

    /// Generate an `#embed` result as an LLVM IR constant array.
    pub fn embed_to_ir(filename: &str, limit: Option<usize>) -> Result<String, String> {
        let data =
            std::fs::read(filename).map_err(|e| format!("cannot embed '{}': {}", filename, e))?;
        let limit = limit.unwrap_or(data.len());
        let bytes: Vec<String> = data
            .iter()
            .take(limit)
            .map(|b| format!("i8 {}", b))
            .collect();
        Ok(format!("[{} x i8] [{}]", bytes.len(), bytes.join(", ")))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Header Unit Support (C++20)
// ═══════════════════════════════════════════════════════════════════════════════

/// Support for C++20 header units: `import <header>;` and `export import <header>;`
pub struct HeaderUnitProcessor {
    pub standard: CppStandard,
}

impl HeaderUnitProcessor {
    pub fn new(standard: CppStandard) -> Self {
        Self { standard }
    }

    /// Check if a header can be imported as a header unit.
    pub fn is_importable_header(&self, header: &str) -> bool {
        if self.standard < CppStandard::Cxx20 {
            return false;
        }
        // Common importable headers
        let importable = [
            "<iostream>",
            "<vector>",
            "<string>",
            "<algorithm>",
            "<memory>",
            "<map>",
            "<set>",
            "<utility>",
        ];
        importable.iter().any(|&h| h == header)
    }

    /// Generate the BMI (Binary Module Interface) filename for a header unit.
    pub fn bmi_filename(&self, header: &str) -> String {
        let clean = header
            .replace(&['<', '>', '"'] as &[_], "")
            .replace('/', "_");
        format!("{}.pcm", clean)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Preprocessor expression evaluator
// ═══════════════════════════════════════════════════════════════════════════════

/// Evaluate C++ preprocessor constant expressions.
pub struct CppPreprocessorExpr;

impl CppPreprocessorExpr {
    /// Evaluate a simple integer expression in #if context.
    pub fn eval(expr: &str, macros: &std::collections::HashMap<String, String>) -> Option<i64> {
        // Substitute known macros
        let mut substituted = expr.to_string();
        for (name, value) in macros {
            substituted = substituted.replace(name, value);
        }

        // Handle __has_include directives in #if
        if substituted.contains("__has_include") {
            return Some(1); // assume available
        }
        if substituted.contains("__has_cpp_attribute") {
            return Some(1); // assume available
        }

        // Try to parse as integer
        substituted.parse::<i64>().ok()
    }

    /// Check if an expression is defined (for #ifdef).
    pub fn is_defined(name: &str, macros: &std::collections::HashMap<String, String>) -> bool {
        macros.contains_key(name)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Feature Test Macro Database
// ═══════════════════════════════════════════════════════════════════════════════

/// A database of C++ feature test macros and their values per standard.
pub struct FeatureTestMacroDb;

impl FeatureTestMacroDb {
    /// Look up a feature test macro and return its value for the given standard.
    pub fn lookup(macro_name: &str, standard: CppStandard) -> Option<String> {
        let macros = cpp_predefined_macros(standard);
        macros
            .iter()
            .find(|(name, _)| name == macro_name)
            .map(|(_, value)| value.clone())
    }

    /// List all feature test macros for a standard.
    pub fn list_all(standard: CppStandard) -> Vec<&'static str> {
        let macros = cpp_predefined_macros(standard);
        macros.iter().map(|(name, _)| name.as_str()).collect()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cplusplus_value() {
        assert_eq!(cplusplus_value(CppStandard::Cxx98), 199711);
        assert_eq!(cplusplus_value(CppStandard::Cxx11), 201103);
        assert_eq!(cplusplus_value(CppStandard::Cxx14), 201402);
        assert_eq!(cplusplus_value(CppStandard::Cxx17), 201703);
        assert_eq!(cplusplus_value(CppStandard::Cxx20), 202002);
        assert_eq!(cplusplus_value(CppStandard::Cxx23), 202302);
    }

    #[test]
    fn test_cpp_predefined_macros() {
        let macros = cpp_predefined_macros(CppStandard::Cxx17);
        assert!(macros.iter().any(|(n, _)| n == "__cplusplus"));
        assert!(macros.iter().any(|(n, _)| n == "__cpp_constexpr"));
        assert!(macros.iter().any(|(n, _)| n == "__cpp_fold_expressions"));
    }

    #[test]
    fn test_cpp_feature_macros_cxx14() {
        let macros = cpp_predefined_macros(CppStandard::Cxx14);
        assert!(macros.iter().any(|(n, _)| n == "__cpp_generic_lambdas"));
        assert!(macros.iter().any(|(n, _)| n == "__cpp_binary_literals"));
    }

    #[test]
    fn test_cpp_feature_macros_cxx20() {
        let macros = cpp_predefined_macros(CppStandard::Cxx20);
        assert!(macros.iter().any(|(n, _)| n == "__cpp_concepts"));
        assert!(macros.iter().any(|(n, _)| n == "__cpp_coroutines"));
        assert!(macros
            .iter()
            .any(|(n, _)| n == "__cpp_three_way_comparison"));
    }

    #[test]
    fn test_eval_has_include() {
        assert!(eval_has_include("<iostream>", CppStandard::Cxx17));
        assert!(eval_has_include("<vector>", CppStandard::Cxx17));
        assert!(!eval_has_include("<nonexistent>", CppStandard::Cxx17));
    }

    #[test]
    fn test_eval_has_cpp_attribute() {
        assert_eq!(
            eval_has_cpp_attribute("noreturn", CppStandard::Cxx11),
            200809
        );
        assert_eq!(
            eval_has_cpp_attribute("deprecated", CppStandard::Cxx14),
            201309
        );
        assert_eq!(
            eval_has_cpp_attribute("nodiscard", CppStandard::Cxx17),
            201603
        );
        assert_eq!(eval_has_cpp_attribute("likely", CppStandard::Cxx20), 201803);
        assert_eq!(eval_has_cpp_attribute("assume", CppStandard::Cxx23), 202207);
        assert_eq!(eval_has_cpp_attribute("noreturn", CppStandard::Cxx98), 0);
    }

    #[test]
    fn test_include_next_resolver() {
        let resolver = IncludeNextResolver::new(
            vec!["/usr/include".into(), "/usr/local/include".into()],
            "/usr/include",
        );
        // This is a unit test; we can't check actual filesystem in test
        // But the resolver structure should be sound
        assert_eq!(resolver.include_paths.len(), 2);
    }

    #[test]
    fn test_warning_directive() {
        let msg = process_warning_directive("deprecated header");
        assert!(msg.contains("deprecated header"));
    }

    #[test]
    fn test_header_unit_processor() {
        let hp = HeaderUnitProcessor::new(CppStandard::Cxx20);
        assert!(hp.is_importable_header("<iostream>"));
        assert!(hp.is_importable_header("<vector>"));
        assert!(!hp.is_importable_header("<nonexistent>"));
        assert_eq!(hp.bmi_filename("<iostream>"), "iostream.pcm");
    }

    #[test]
    fn test_feature_test_macro_db() {
        let val = FeatureTestMacroDb::lookup("__cpp_constexpr", CppStandard::Cxx17);
        assert!(val.is_some());
        let val = FeatureTestMacroDb::lookup("__cpp_concepts", CppStandard::Cxx17);
        assert!(val.is_none()); // not in C++17
        let val = FeatureTestMacroDb::lookup("__cpp_concepts", CppStandard::Cxx20);
        assert!(val.is_some()); // in C++20
    }
}