llvm-native-core 0.1.16

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
//! LLVM StringRef — non-owning reference to a string.
//!
//! Clean-room behavioral reconstruction.
//! @llvm_behavior: StringRef represents a constant reference to a string
//! (character array). It does NOT own the data and does NOT guarantee
//! null termination. It is the primary string type in LLVM.
//!
//! Key behaviors reconstructed from oracle observation:
//! - Construction from &str, string literals, and byte slices
//! - Empty string sentinel
//! - Substring operations (slice, substr, take_front, take_back, drop_front, drop_back)
//! - Search operations (find, rfind, find_first_of, find_first_not_of)
//! - Comparison (==, !=, <, >, starts_with, ends_with, equals)
//! - Transformation (lower, upper, trim, ltrim, rtrim)
//! - Splitting (split on character or StringRef)
//! - Numeric conversion (getAsInteger with radix)
//! - Byte access (front, back, indexing)

use std::fmt;

/// A non-owning reference to a string (character array).
///
/// StringRef does not own its data and does not guarantee null termination.
/// It is conceptually equivalent to `&str` but with LLVM-specific
/// behavioral semantics (e.g., empty string sentinel, split behavior).
#[derive(Clone, Copy)]
pub struct StringRef<'a> {
    data: &'a str,
}

impl<'a> StringRef<'a> {
    /// Construct a StringRef from a string slice.
    #[inline]
    pub fn new(s: &'a str) -> Self {
        Self { data: s }
    }

    /// An empty StringRef.
    #[inline]
    pub fn empty() -> Self {
        Self { data: "" }
    }

    /// The length of the string in bytes.
    /// @llvm_behavior: size() returns the number of bytes, not characters.
    #[inline]
    pub fn size(&self) -> usize {
        self.data.len()
    }

    /// Returns true if the StringRef is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Returns a pointer to the start of the string data.
    /// In Rust, this returns the underlying &str.
    #[inline]
    pub fn data(&self) -> &'a str {
        self.data
    }

    /// Returns the underlying bytes.
    #[inline]
    pub fn bytes(&self) -> &'a [u8] {
        self.data.as_bytes()
    }

    /// Returns the first byte of the StringRef.
    /// Panics if empty (matching LLVM's undefined behavior).
    #[inline]
    pub fn front(&self) -> u8 {
        self.data.as_bytes()[0]
    }

    /// Returns the last byte of the StringRef.
    /// Panics if empty.
    #[inline]
    pub fn back(&self) -> u8 {
        self.data.as_bytes()[self.data.len() - 1]
    }

    /// Returns the character at the given index as a byte.
    #[inline]
    pub fn get(&self, index: usize) -> Option<u8> {
        self.data.as_bytes().get(index).copied()
    }

    // === Substring Operations ===

    /// Return a StringRef equal to this[start..start+N].
    /// Clamps N to available length.
    /// @llvm_behavior: substr(Start, N) — if Start+N exceeds size(),
    ///   returns substr(Start, size()-Start).
    #[inline]
    pub fn substr(&self, start: usize, n: usize) -> StringRef<'a> {
        if start >= self.data.len() {
            return StringRef::empty();
        }
        let end = (start + n).min(self.data.len());
        StringRef::new(&self.data[start..end])
    }

    /// Return a slice of this[start..end].
    #[inline]
    pub fn slice(&self, start: usize, end: usize) -> StringRef<'a> {
        let start = start.min(self.data.len());
        let end = end.min(self.data.len());
        if start >= end {
            return StringRef::empty();
        }
        StringRef::new(&self.data[start..end])
    }

    /// Return the first N characters.
    /// @llvm_behavior: take_front(N) — returns at most N characters.
    #[inline]
    pub fn take_front(&self, n: usize) -> StringRef<'a> {
        let end = n.min(self.data.len());
        StringRef::new(&self.data[..end])
    }

    /// Return the last N characters.
    #[inline]
    pub fn take_back(&self, n: usize) -> StringRef<'a> {
        let n = n.min(self.data.len());
        StringRef::new(&self.data[self.data.len() - n..])
    }

    /// Drop the first N characters.
    #[inline]
    pub fn drop_front(&self, n: usize) -> StringRef<'a> {
        let start = n.min(self.data.len());
        StringRef::new(&self.data[start..])
    }

    /// Drop the last N characters.
    #[inline]
    pub fn drop_back(&self, n: usize) -> StringRef<'a> {
        let n = n.min(self.data.len());
        StringRef::new(&self.data[..self.data.len() - n])
    }

    // === Search Operations ===

    /// Find the first occurrence of a character.
    /// Returns None if not found.
    #[inline]
    pub fn find_char(&self, c: char) -> Option<usize> {
        self.data.find(c)
    }

    /// Find the first occurrence of a substring.
    /// Returns None if not found.
    #[inline]
    pub fn find(&self, needle: &str) -> Option<usize> {
        self.data.find(needle)
    }

    /// Find the last occurrence of a character.
    #[inline]
    pub fn rfind_char(&self, c: char) -> Option<usize> {
        self.data.rfind(c)
    }

    /// Find the last occurrence of a substring.
    #[inline]
    pub fn rfind(&self, needle: &str) -> Option<usize> {
        self.data.rfind(needle)
    }

    /// Find the first occurrence of any character in the set.
    /// @llvm_behavior: find_first_of(Chars) returns the index of the
    ///   first character that appears in Chars.
    #[inline]
    pub fn find_first_of(&self, chars: &str) -> Option<usize> {
        self.data.find(|c: char| chars.contains(c))
    }

    /// Find the first character NOT in the given set.
    #[inline]
    pub fn find_first_not_of(&self, chars: &str) -> Option<usize> {
        self.data.find(|c: char| !chars.contains(c))
    }

    /// Check if this StringRef contains the given substring.
    #[inline]
    pub fn contains(&self, needle: &str) -> bool {
        self.data.contains(needle)
    }

    /// Check if this StringRef contains the given character.
    #[inline]
    pub fn contains_char(&self, c: char) -> bool {
        self.data.contains(c)
    }

    // === Prefix/Suffix ===

    /// Check if this StringRef starts with the given prefix.
    #[inline]
    pub fn starts_with(&self, prefix: &str) -> bool {
        self.data.starts_with(prefix)
    }

    /// Check if this StringRef ends with the given suffix.
    #[inline]
    pub fn ends_with(&self, suffix: &str) -> bool {
        self.data.ends_with(suffix)
    }

    // === Comparison ===

    /// Case-insensitive equality check.
    /// @llvm_behavior: equals_insensitive compares strings ignoring ASCII case.
    #[inline]
    pub fn equals_insensitive(&self, other: &str) -> bool {
        self.data.eq_ignore_ascii_case(other)
    }

    /// Compare two StringRefs lexicographically.
    /// Returns Less, Equal, or Greater.
    #[inline]
    pub fn compare(&self, other: &str) -> std::cmp::Ordering {
        self.data.cmp(other)
    }

    /// Compare two StringRefs case-insensitively.
    #[inline]
    pub fn compare_insensitive(&self, other: &str) -> std::cmp::Ordering {
        self.data
            .to_ascii_lowercase()
            .cmp(&other.to_ascii_lowercase())
    }

    // === Transformation ===

    /// Return a lowercased copy of this StringRef (ASCII only).
    /// @llvm_behavior: lower() returns a new string, does not modify in place.
    #[inline]
    pub fn lower(&self) -> String<'a> {
        String::Owned(self.data.to_ascii_lowercase())
    }

    /// Return an uppercased copy of this StringRef (ASCII only).
    #[inline]
    pub fn upper(&self) -> String<'a> {
        String::Owned(self.data.to_ascii_uppercase())
    }

    /// Return a StringRef with leading whitespace removed.
    /// @llvm_behavior: ltrim() strips ASCII space, tab, newline, carriage return,
    ///   vertical tab, and form feed characters.
    #[inline]
    pub fn ltrim(&self) -> StringRef<'a> {
        let trimmed = self.data.trim_start_matches(|c: char| {
            c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\x0b' || c == '\x0c'
        });
        StringRef::new(trimmed)
    }

    /// Return a StringRef with trailing whitespace removed.
    #[inline]
    pub fn rtrim(&self) -> StringRef<'a> {
        let trimmed = self.data.trim_end_matches(|c: char| {
            c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\x0b' || c == '\x0c'
        });
        StringRef::new(trimmed)
    }

    /// Return a StringRef with leading and trailing whitespace removed.
    #[inline]
    pub fn trim(&self) -> StringRef<'a> {
        self.ltrim().rtrim()
    }

    // === Splitting ===

    /// Split into two StringRefs at the first occurrence of a character.
    /// The character itself is not included in either part.
    /// Returns (lhs, rhs) where rhs is empty if char not found.
    /// @llvm_behavior: split(C) — if C is not found, lhs = entire string, rhs = empty.
    #[inline]
    pub fn split_char(&self, c: char) -> (StringRef<'a>, StringRef<'a>) {
        match self.data.find(c) {
            Some(pos) => (
                StringRef::new(&self.data[..pos]),
                StringRef::new(&self.data[pos + 1..]),
            ),
            None => (*self, StringRef::empty()),
        }
    }

    /// Split into two StringRefs at the last occurrence of a character.
    #[inline]
    pub fn rsplit_char(&self, c: char) -> (StringRef<'a>, StringRef<'a>) {
        match self.data.rfind(c) {
            Some(pos) => (
                StringRef::new(&self.data[..pos]),
                StringRef::new(&self.data[pos + 1..]),
            ),
            None => (*self, StringRef::empty()),
        }
    }

    /// Split into pairs around a separator string.
    /// Returns (lhs, rhs) where rhs is empty if separator not found.
    #[inline]
    pub fn split_str(&self, separator: &str) -> (StringRef<'a>, StringRef<'a>) {
        match self.data.find(separator) {
            Some(pos) => (
                StringRef::new(&self.data[..pos]),
                StringRef::new(&self.data[pos + separator.len()..]),
            ),
            None => (*self, StringRef::empty()),
        }
    }

    /// Returns an iterator over the pieces when split by a character.
    #[inline]
    pub fn split_iter(&self, c: char) -> impl Iterator<Item = StringRef<'a>> + '_ {
        self.data.split(c).map(StringRef::new)
    }

    // === Numeric Conversion ===

    /// Parse this StringRef as an integer in the given radix.
    /// @llvm_behavior: getAsInteger(Radix, Result) — returns true on error.
    /// Supports radices 2, 8, 10, 16.
    #[inline]
    pub fn get_as_integer(&self, radix: u32) -> Result<i64, std::string::String> {
        if self.data.is_empty() {
            return Err("empty string".into());
        }
        let s = self.data.trim();
        let (radix, s) = match radix {
            0 => {
                if s.starts_with("0x") || s.starts_with("0X") {
                    (16, &s[2..])
                } else if s.starts_with('0') && s.len() > 1 {
                    (8, &s[1..])
                } else {
                    (10, s)
                }
            }
            r => {
                if r == 16 && (s.starts_with("0x") || s.starts_with("0X")) {
                    (r, &s[2..])
                } else {
                    (r, s)
                }
            }
        };
        i64::from_str_radix(s, radix).map_err(|e| format!("{}", e))
    }

    /// Parse this StringRef as an unsigned integer.
    #[inline]
    pub fn get_as_unsigned_integer(&self, radix: u32) -> Result<u64, std::string::String> {
        if self.data.is_empty() {
            return Err("empty string".into());
        }
        u64::from_str_radix(self.data.trim(), radix).map_err(|e| format!("{}", e))
    }

    // === Consume operations (mutable-like, but since we're &self-based, return new) ===

    /// Consume the first character if it matches, return the rest.
    /// Returns Some(rest) if matched, None if empty or doesn't match.
    #[inline]
    pub fn consume_front_char(&self, c: char) -> Option<StringRef<'a>> {
        if self.data.starts_with(c) {
            Some(StringRef::new(&self.data[c.len_utf8()..]))
        } else {
            None
        }
    }

    /// Consume the given prefix string if present, return the rest.
    #[inline]
    pub fn consume_front(&self, prefix: &str) -> Option<StringRef<'a>> {
        self.data.strip_prefix(prefix).map(StringRef::new)
    }

    /// Consume the given suffix string if present, return the rest.
    #[inline]
    pub fn consume_back(&self, suffix: &str) -> Option<StringRef<'a>> {
        self.data.strip_suffix(suffix).map(StringRef::new)
    }

    /// Count the number of occurrences of a character.
    #[inline]
    pub fn count_char(&self, c: char) -> usize {
        self.data.matches(c).count()
    }

    /// Count the number of occurrences of a substring.
    #[inline]
    pub fn count(&self, needle: &str) -> usize {
        self.data.matches(needle).count()
    }

    /// Convert to an owned String.
    #[inline]
    pub fn to_owned(&self) -> std::string::String {
        self.data.to_string()
    }
}

// === Trait Implementations ===

impl<'a> fmt::Display for StringRef<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.data)
    }
}

impl<'a> fmt::Debug for StringRef<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "StringRef(\"{}\")", self.data)
    }
}

impl<'a> PartialEq for StringRef<'a> {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

impl<'a> Eq for StringRef<'a> {}

impl<'a> PartialEq<str> for StringRef<'a> {
    fn eq(&self, other: &str) -> bool {
        self.data == other
    }
}

impl<'a> PartialEq<&str> for StringRef<'a> {
    fn eq(&self, other: &&str) -> bool {
        self.data == *other
    }
}

impl<'a> PartialOrd for StringRef<'a> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<'a> Ord for StringRef<'a> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.data.cmp(other.data)
    }
}

impl<'a> std::hash::Hash for StringRef<'a> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.data.hash(state);
    }
}

impl<'a> From<&'a str> for StringRef<'a> {
    fn from(s: &'a str) -> Self {
        StringRef::new(s)
    }
}

impl<'a> AsRef<str> for StringRef<'a> {
    fn as_ref(&self) -> &str {
        self.data
    }
}

/// Represents either an owned or borrowed string, returned from
/// operations like lower() and upper() that may create new strings.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum String<'a> {
    Owned(std::string::String),
    Borrowed(&'a str),
}

impl<'a> fmt::Display for String<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            String::Owned(s) => write!(f, "{}", s),
            String::Borrowed(s) => write!(f, "{}", s),
        }
    }
}