libperl-macrogen 0.1.5

Generate Rust FFI bindings from C macro functions in Perl headers
Documentation
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
//! Preprocessor integration tests

use std::io::Write;
use tempfile::NamedTempFile;
use libperl_macrogen::{PPConfig, Preprocessor, TokenKind};

/// Helper to create a preprocessor from source string
fn preprocess(source: &str) -> Preprocessor {
    let mut file = NamedTempFile::new().unwrap();
    file.write_all(source.as_bytes()).unwrap();
    file.flush().unwrap();

    let config = PPConfig {
        include_paths: vec![],
        predefined: vec![],
        debug_pp: false,
        target_dir: None,
        ..Default::default()
    };

    let mut pp = Preprocessor::new(config);
    pp.add_source_file(file.path()).unwrap();
    pp
}

/// Helper to collect all tokens from preprocessor (excluding Newline tokens)
fn collect_tokens(pp: &mut Preprocessor) -> Vec<(TokenKind, String)> {
    let mut tokens = Vec::new();
    loop {
        let token = pp.next_token().unwrap();
        if matches!(token.kind, TokenKind::Eof) {
            break;
        }
        // Skip newline tokens for easier test assertions
        if matches!(token.kind, TokenKind::Newline) {
            continue;
        }
        let text = token.kind.format(pp.interner());
        tokens.push((token.kind, text));
    }
    tokens
}

/// Helper to get token kinds only
fn token_kinds(pp: &mut Preprocessor) -> Vec<TokenKind> {
    collect_tokens(pp).into_iter().map(|(k, _)| k).collect()
}

#[test]
fn test_simple_tokens() {
    let mut pp = preprocess("int x;");
    let tokens = collect_tokens(&mut pp);

    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "int");
    assert_eq!(tokens[1].1, "x");
    assert!(matches!(tokens[2].0, TokenKind::Semi));
}

#[test]
fn test_object_macro() {
    let mut pp = preprocess("#define VALUE 42\nint x = VALUE;");
    let tokens = collect_tokens(&mut pp);

    // int x = 42 ;
    assert_eq!(tokens.len(), 5);
    assert_eq!(tokens[0].1, "int");
    assert_eq!(tokens[1].1, "x");
    assert!(matches!(tokens[2].0, TokenKind::Eq));
    assert!(matches!(tokens[3].0, TokenKind::IntLit(42)));
    assert!(matches!(tokens[4].0, TokenKind::Semi));
}

#[test]
fn test_function_macro() {
    let mut pp = preprocess("#define ADD(a, b) ((a) + (b))\nint x = ADD(1, 2);");
    let tokens = collect_tokens(&mut pp);

    // int x = ( ( 1 ) + ( 2 ) ) ;
    // 13 tokens: int, x, =, (, (, 1, ), +, (, 2, ), ), ;
    assert_eq!(tokens.len(), 13);
    assert_eq!(tokens[0].1, "int");
    assert!(matches!(tokens[3].0, TokenKind::LParen)); // (
    assert!(matches!(tokens[4].0, TokenKind::LParen)); // (
    assert!(matches!(tokens[5].0, TokenKind::IntLit(1)));
    assert!(matches!(tokens[7].0, TokenKind::Plus));
    assert!(matches!(tokens[9].0, TokenKind::IntLit(2)));
}

#[test]
fn test_ifdef_true() {
    let mut pp = preprocess("#define FOO\n#ifdef FOO\nint x;\n#endif");
    let tokens = collect_tokens(&mut pp);

    // int x ;
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "int");
}

#[test]
fn test_ifdef_false() {
    let mut pp = preprocess("#ifdef FOO\nint x;\n#endif\nint y;");
    let tokens = collect_tokens(&mut pp);

    // int y ;
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "int");
    assert_eq!(tokens[1].1, "y");
}

#[test]
fn test_ifndef() {
    let mut pp = preprocess("#ifndef FOO\nint x;\n#endif");
    let tokens = collect_tokens(&mut pp);

    // int x ;
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "int");
    assert_eq!(tokens[1].1, "x");
}

#[test]
fn test_if_else() {
    let mut pp = preprocess("#define FOO 1\n#if FOO\nint x;\n#else\nint y;\n#endif");
    let tokens = collect_tokens(&mut pp);

    // int x ;
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[1].1, "x");
}

#[test]
fn test_elif() {
    let mut pp = preprocess("#define FOO 0\n#define BAR 1\n#if FOO\nint x;\n#elif BAR\nint y;\n#else\nint z;\n#endif");
    let tokens = collect_tokens(&mut pp);

    // int y ;
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[1].1, "y");
}

#[test]
fn test_nested_ifdef() {
    let mut pp = preprocess("#define A\n#define B\n#ifdef A\n#ifdef B\nint x;\n#endif\n#endif");
    let tokens = collect_tokens(&mut pp);

    // int x ;
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[1].1, "x");
}

#[test]
fn test_undef() {
    let mut pp = preprocess("#define FOO 1\n#undef FOO\n#ifdef FOO\nint x;\n#endif\nint y;");
    let tokens = collect_tokens(&mut pp);

    // int y ;
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[1].1, "y");
}

#[test]
fn test_defined_operator() {
    let mut pp = preprocess("#define FOO\n#if defined(FOO)\nint x;\n#endif");
    let tokens = collect_tokens(&mut pp);

    // int x ;
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[1].1, "x");
}

#[test]
fn test_defined_without_parens() {
    let mut pp = preprocess("#define FOO\n#if defined FOO\nint x;\n#endif");
    let tokens = collect_tokens(&mut pp);

    // int x ;
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[1].1, "x");
}

#[test]
fn test_stringification() {
    let mut pp = preprocess("#define STR(x) #x\nchar *s = STR(hello);");
    let tokens = collect_tokens(&mut pp);

    // char * s = "hello" ;
    assert_eq!(tokens.len(), 6);
    assert!(matches!(&tokens[4].0, TokenKind::StringLit(s) if s == b"hello"));
}

#[test]
fn test_token_pasting() {
    let mut pp = preprocess("#define PASTE(a, b) a##b\nint PASTE(foo, bar);");
    let tokens = collect_tokens(&mut pp);

    // int foobar ;
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[1].1, "foobar");
}

#[test]
fn test_variadic_macro() {
    let mut pp = preprocess("#define CALL(fn, ...) fn(__VA_ARGS__)\nCALL(foo, 1, 2, 3);");
    let tokens = collect_tokens(&mut pp);

    // Verify that the output contains the expected elements
    // Note: exact token count may vary due to macro expansion behavior
    assert!(tokens.iter().any(|(_, text)| text == "foo"));
    assert!(tokens.iter().any(|(kind, _)| matches!(kind, TokenKind::LParen)));
    assert!(tokens.iter().any(|(kind, _)| matches!(kind, TokenKind::IntLit(1))));
    assert!(tokens.iter().any(|(kind, _)| matches!(kind, TokenKind::IntLit(2))));
    assert!(tokens.iter().any(|(kind, _)| matches!(kind, TokenKind::IntLit(3))));
    assert!(tokens.iter().any(|(kind, _)| matches!(kind, TokenKind::Semi)));
}

#[test]
fn test_predefined_macros() {
    let config = PPConfig {
        include_paths: vec![],
        predefined: vec![("TEST_MACRO".to_string(), Some("123".to_string()))],
        debug_pp: false,
        target_dir: None,
        ..Default::default()
    };

    let mut file = NamedTempFile::new().unwrap();
    file.write_all(b"int x = TEST_MACRO;").unwrap();
    file.flush().unwrap();

    let mut pp = Preprocessor::new(config);
    pp.add_source_file(file.path()).unwrap();

    let tokens = collect_tokens(&mut pp);

    // int x = 123 ;
    assert_eq!(tokens.len(), 5);
    assert!(matches!(tokens[3].0, TokenKind::IntLit(123)));
}

#[test]
#[ignore = "__FILE__ macro not yet implemented"]
fn test_file_macro() {
    let mut pp = preprocess("const char *f = __FILE__;");
    let tokens = collect_tokens(&mut pp);

    // const char * f = "..." ;
    assert_eq!(tokens.len(), 7);
    assert!(matches!(&tokens[5].0, TokenKind::StringLit(_)));
}

#[test]
#[ignore = "__LINE__ macro not yet implemented"]
fn test_line_macro() {
    let mut pp = preprocess("int line = __LINE__;");
    let tokens = collect_tokens(&mut pp);

    // int line = <number> ;
    assert_eq!(tokens.len(), 5);
    assert!(matches!(tokens[3].0, TokenKind::IntLit(_)));
}

#[test]
fn test_multiline_macro() {
    let mut pp = preprocess("#define MULTI(x) \\\n    ((x) + 1)\nint y = MULTI(5);");
    let tokens = collect_tokens(&mut pp);

    // int y = ( ( 5 ) + 1 ) ;
    assert!(tokens.len() >= 5);
    assert_eq!(tokens[0].1, "int");
    assert_eq!(tokens[1].1, "y");
}

#[test]
fn test_empty_macro() {
    let mut pp = preprocess("#define EMPTY\nint EMPTY x;");
    let tokens = collect_tokens(&mut pp);

    // int x ;
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "int");
    assert_eq!(tokens[1].1, "x");
}

#[test]
fn test_macro_redefine() {
    let mut pp = preprocess("#define X 1\n#define X 2\nint a = X;");
    let tokens = collect_tokens(&mut pp);

    // int a = 2 ;
    assert_eq!(tokens.len(), 5);
    assert!(matches!(tokens[3].0, TokenKind::IntLit(2)));
}

#[test]
fn test_if_expression_arithmetic() {
    let mut pp = preprocess("#if 2 + 3 == 5\nint x;\n#endif");
    let tokens = collect_tokens(&mut pp);

    // int x ;
    assert_eq!(tokens.len(), 3);
}

#[test]
fn test_if_expression_logical() {
    let mut pp = preprocess("#if 1 && 1\nint x;\n#endif");
    let tokens = collect_tokens(&mut pp);

    // int x ;
    assert_eq!(tokens.len(), 3);
}

#[test]
fn test_recursive_macro_prevention() {
    let mut pp = preprocess("#define X X\nint y = X;");
    let tokens = collect_tokens(&mut pp);

    // int y = X ;  (X is not expanded recursively)
    assert_eq!(tokens.len(), 5);
    assert_eq!(tokens[3].1, "X");
}

// =============================================================================
// キーワード相当のトークンを #define / #undef / #ifdef の名前として受理する
// (TinyCC 流: tccpp.c parse_define / process_ifdef は v < TOK_IDENT のみ弾く)
// 直接の動機: <stdbool.h> の `#define bool _Bool` で落ちていた CI を通す。
// =============================================================================

#[test]
fn test_define_keyword_name_does_not_error() {
    // #define bool _Bool が処理できること(preprocess() 内 add_source_file が
    // エラーを返さない時点で OK。さらに後続トークンが取り出せることも確認)。
    let mut pp = preprocess("#define bool _Bool\nbool x;");
    let tokens = collect_tokens(&mut pp);
    // トークン展開は keyword token 経路では行われないので、bool x ; がそのまま出る
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "bool");
    assert_eq!(tokens[1].1, "x");
}

#[test]
fn test_ifdef_keyword_after_define() {
    // #define bool に続けて #ifdef bool が真分岐を選ぶ
    let mut pp = preprocess("#define bool\n#ifdef bool\nint x;\n#endif");
    let tokens = collect_tokens(&mut pp);
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "int");
    assert_eq!(tokens[1].1, "x");
}

#[test]
fn test_ifdef_keyword_no_define() {
    // #define が無いとき #ifdef bool は偽(bool キーワードは未定義扱い)
    let mut pp = preprocess("#ifdef bool\nint x;\n#endif\nint y;");
    let tokens = collect_tokens(&mut pp);
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "int");
    assert_eq!(tokens[1].1, "y");
}

#[test]
fn test_ifndef_keyword_no_define() {
    // #ifndef bool は #define が無いとき真分岐
    let mut pp = preprocess("#ifndef bool\nint x;\n#endif");
    let tokens = collect_tokens(&mut pp);
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "int");
    assert_eq!(tokens[1].1, "x");
}

#[test]
fn test_undef_keyword_clears_define() {
    // #define bool したあと #undef bool すると #ifdef bool は偽
    let mut pp = preprocess(
        "#define bool\n#undef bool\n#ifdef bool\nint x;\n#endif\nint y;"
    );
    let tokens = collect_tokens(&mut pp);
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "int");
    assert_eq!(tokens[1].1, "y");
}

#[test]
fn test_define_inline_alias_does_not_error() {
    // 互換ヘッダで頻出のパターン: #define inline __inline
    let mut pp = preprocess("#define inline __inline\nint x;");
    let tokens = collect_tokens(&mut pp);
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "int");
}

#[test]
fn test_defined_operator_with_keyword_regression() {
    // pp_expr.rs の parse_defined は既にキーワード対応済み。
    // 今回の修正で壊れていないことの回帰テスト。
    let mut pp = preprocess("#define bool\n#if defined(bool)\nint x;\n#endif");
    let tokens = collect_tokens(&mut pp);
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "int");
    assert_eq!(tokens[1].1, "x");
}

#[test]
fn test_macro_param_keyword_does_not_error() {
    // 仮引数名にキーワードを使う `#define FOO(bool) ...` がエラーにならない。
    // expansion 側はまだ keyword token 経路を扱わないので、本テストは
    // 「directive 自体が処理できる」ことのみ確認する。
    let mut pp = preprocess("#define FOO(bool) 1\nint x;");
    let tokens = collect_tokens(&mut pp);
    assert_eq!(tokens.len(), 3);
    assert_eq!(tokens[0].1, "int");
}