cutile-compiler 0.1.0

Crate for compiling kernels authored in cuTile Rust to executable kernels.
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
/*
 * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Type-alias normalization for the DSL front-end.
//!
//! This is intentionally syntax-local: Pass 1 indexes `type` items, and
//! consumers that need the underlying DSL type ask this module to expand those
//! aliases before doing Tensor/scalar/pointer classification.

use quote::ToTokens;
use std::collections::HashMap;
use syn::visit_mut::{self, VisitMut};
use syn::{
    Expr, ExprPath, FnArg, GenericArgument, GenericParam, Item, ItemConst, ItemFn, ItemType, Lit,
    PatType, PathArguments, Type, TypePath,
};

const MAX_ALIAS_EXPANSION_DEPTH: usize = 64;

#[derive(Default)]
struct AliasSubstitution {
    types: HashMap<String, Type>,
    consts: HashMap<String, Expr>,
}

/// Collect type aliases from an inline module item list.
///
/// Nested inline modules are intentionally not merged into the parent scope.
/// Callers that process a submodule should call this again for that submodule's
/// own item list.
pub fn collect_type_aliases(items: &[Item]) -> HashMap<String, ItemType> {
    items
        .iter()
        .filter_map(|item| {
            let Item::Type(alias) = item else {
                return None;
            };
            Some((alias.ident.to_string(), alias.clone()))
        })
        .collect()
}

/// Expand all known type aliases in a type.
pub fn normalize_type_aliases(
    ty: &Type,
    aliases: &HashMap<String, ItemType>,
) -> Result<Type, String> {
    normalize_type_aliases_inner(ty, aliases, &mut Vec::new())
}

/// Replace paths to module-level scalar consts inside a type with their
/// literal expression. This keeps type-level shapes such as
/// `Tensor<f32, {[BLOCK]}>` consumable by the existing generic machinery.
pub fn normalize_const_paths_in_type(
    ty: &Type,
    consts: &HashMap<String, ItemConst>,
) -> Result<Type, String> {
    let mut out = ty.clone();
    ConstPathNormalizer { consts }.visit_type_mut(&mut out);
    Ok(out)
}

/// Return a supported scalar const expression suitable for substituting into
/// a type-level const expression.
pub fn const_item_scalar_expr(item: &ItemConst) -> Option<Expr> {
    let Type::Path(type_path) = item.ty.as_ref() else {
        return None;
    };
    let ty_name = type_path.path.segments.last()?.ident.to_string();
    match ty_name.as_str() {
        "bool" => match item.expr.as_ref() {
            Expr::Lit(lit) if matches!(lit.lit, Lit::Bool(_)) => Some(item.expr.as_ref().clone()),
            _ => None,
        },
        "i32" | "i64" | "u32" | "u64" => match item.expr.as_ref() {
            Expr::Lit(lit) if matches!(lit.lit, Lit::Int(_)) => Some(item.expr.as_ref().clone()),
            Expr::Unary(unary) => match unary.expr.as_ref() {
                Expr::Lit(lit) if matches!(lit.lit, Lit::Int(_)) => {
                    Some(item.expr.as_ref().clone())
                }
                _ => None,
            },
            _ => None,
        },
        _ => None,
    }
}

pub fn const_item_i32_value(item: &ItemConst) -> Option<i32> {
    let Type::Path(type_path) = item.ty.as_ref() else {
        return None;
    };
    if type_path.path.segments.last()?.ident != "i32" {
        return None;
    }
    match item.expr.as_ref() {
        Expr::Lit(lit) => match &lit.lit {
            Lit::Int(int_lit) => int_lit.base10_parse::<i32>().ok(),
            _ => None,
        },
        Expr::Unary(unary) => {
            if !matches!(unary.op, syn::UnOp::Neg(_)) {
                return None;
            }
            let Expr::Lit(lit) = unary.expr.as_ref() else {
                return None;
            };
            let Lit::Int(int_lit) = &lit.lit else {
                return None;
            };
            int_lit.base10_parse::<i32>().ok().map(|value| -value)
        }
        _ => None,
    }
}

pub fn const_item_bool_value(item: &ItemConst) -> Option<bool> {
    let Type::Path(type_path) = item.ty.as_ref() else {
        return None;
    };
    if type_path.path.segments.last()?.ident != "bool" {
        return None;
    }
    let Expr::Lit(lit) = item.expr.as_ref() else {
        return None;
    };
    let Lit::Bool(bool_lit) = &lit.lit else {
        return None;
    };
    Some(bool_lit.value)
}

/// Return a copy of `item` whose parameter types have aliases expanded.
pub fn normalize_item_fn_param_type_aliases(
    item: &ItemFn,
    aliases: &HashMap<String, ItemType>,
) -> Result<ItemFn, String> {
    let mut item = item.clone();
    for arg in &mut item.sig.inputs {
        let FnArg::Typed(PatType { ty, .. }) = arg else {
            continue;
        };
        *ty = Box::new(normalize_type_aliases(ty, aliases)?);
    }
    Ok(item)
}

struct ConstPathNormalizer<'a> {
    consts: &'a HashMap<String, ItemConst>,
}

impl VisitMut for ConstPathNormalizer<'_> {
    fn visit_generic_argument_mut(&mut self, arg: &mut GenericArgument) {
        if let GenericArgument::Const(expr) = arg {
            self.visit_expr_mut(expr);
        } else {
            visit_mut::visit_generic_argument_mut(self, arg);
        }
    }

    fn visit_expr_mut(&mut self, expr: &mut Expr) {
        if let Expr::Path(path) = expr {
            if let Some(name) = single_segment_expr_ident(path) {
                if let Some(replacement) = self.consts.get(&name).and_then(const_item_scalar_expr) {
                    *expr = replacement;
                    return;
                }
            }
        }
        visit_mut::visit_expr_mut(self, expr);
    }
}

fn normalize_type_aliases_inner(
    ty: &Type,
    aliases: &HashMap<String, ItemType>,
    stack: &mut Vec<String>,
) -> Result<Type, String> {
    if stack.len() > MAX_ALIAS_EXPANSION_DEPTH {
        return Err("type alias expansion exceeded recursion limit".to_string());
    }

    match ty {
        Type::Path(type_path) => normalize_path_type(type_path, aliases, stack),
        Type::Reference(type_ref) => {
            let mut out = type_ref.clone();
            out.elem = Box::new(normalize_type_aliases_inner(&out.elem, aliases, stack)?);
            Ok(Type::Reference(out))
        }
        Type::Ptr(type_ptr) => {
            let mut out = type_ptr.clone();
            out.elem = Box::new(normalize_type_aliases_inner(&out.elem, aliases, stack)?);
            Ok(Type::Ptr(out))
        }
        Type::Tuple(tuple) => {
            let mut out = tuple.clone();
            for elem in &mut out.elems {
                *elem = normalize_type_aliases_inner(elem, aliases, stack)?;
            }
            Ok(Type::Tuple(out))
        }
        Type::Array(array) => {
            let mut out = array.clone();
            out.elem = Box::new(normalize_type_aliases_inner(&out.elem, aliases, stack)?);
            Ok(Type::Array(out))
        }
        Type::Slice(slice) => {
            let mut out = slice.clone();
            out.elem = Box::new(normalize_type_aliases_inner(&out.elem, aliases, stack)?);
            Ok(Type::Slice(out))
        }
        Type::Paren(paren) => {
            let mut out = paren.clone();
            out.elem = Box::new(normalize_type_aliases_inner(&out.elem, aliases, stack)?);
            Ok(Type::Paren(out))
        }
        Type::Group(group) => {
            let mut out = group.clone();
            out.elem = Box::new(normalize_type_aliases_inner(&out.elem, aliases, stack)?);
            Ok(Type::Group(out))
        }
        _ => Ok(ty.clone()),
    }
}

fn normalize_path_type(
    type_path: &TypePath,
    aliases: &HashMap<String, ItemType>,
    stack: &mut Vec<String>,
) -> Result<Type, String> {
    let Some(last_segment) = type_path.path.segments.last() else {
        return Ok(Type::Path(type_path.clone()));
    };
    let alias_name = last_segment.ident.to_string();

    if let Some(alias) = aliases.get(&alias_name) {
        if stack.contains(&alias_name) {
            return Err(format!(
                "recursive type alias expansion involving `{}`",
                alias_name
            ));
        }
        stack.push(alias_name.clone());
        let subst = build_alias_substitution(alias, &last_segment.arguments)?;
        let substituted = substitute_type(&alias.ty, &subst, aliases, stack)?;
        let expanded = normalize_type_aliases_inner(&substituted, aliases, stack)?;
        stack.pop();
        return Ok(expanded);
    }

    let mut out = type_path.clone();
    if let Some(last_segment) = out.path.segments.last_mut() {
        if let PathArguments::AngleBracketed(args) = &mut last_segment.arguments {
            for arg in &mut args.args {
                *arg = substitute_generic_arg(arg, &AliasSubstitution::default(), aliases, stack)?;
            }
        }
    }
    Ok(Type::Path(out))
}

fn build_alias_substitution(
    alias: &ItemType,
    args: &PathArguments,
) -> Result<AliasSubstitution, String> {
    let actual_args: Vec<GenericArgument> = match args {
        PathArguments::AngleBracketed(args) => args.args.iter().cloned().collect(),
        PathArguments::None => Vec::new(),
        PathArguments::Parenthesized(_) => {
            return Err(format!(
                "type alias `{}` uses unsupported parenthesized generic arguments",
                alias.ident
            ));
        }
    };
    let formals: Vec<&GenericParam> = alias
        .generics
        .params
        .iter()
        .filter(|param| !matches!(param, GenericParam::Lifetime(_)))
        .collect();

    if formals.len() != actual_args.len() {
        return Err(format!(
            "type alias `{}` expects {} generic argument(s), got {}",
            alias.ident,
            formals.len(),
            actual_args.len()
        ));
    }

    let mut subst = AliasSubstitution::default();
    for (formal, actual) in formals.into_iter().zip(actual_args.into_iter()) {
        match (formal, actual) {
            (GenericParam::Type(param), GenericArgument::Type(ty)) => {
                subst.types.insert(param.ident.to_string(), ty);
            }
            (GenericParam::Const(param), GenericArgument::Const(expr)) => {
                subst.consts.insert(param.ident.to_string(), expr);
            }
            (GenericParam::Const(param), GenericArgument::Type(Type::Path(path))) => {
                subst
                    .consts
                    .insert(param.ident.to_string(), expr_path_from_type_path(&path));
            }
            (GenericParam::Type(param), other) => {
                return Err(format!(
                    "type alias `{}` expected type argument for `{}`, got `{}`",
                    alias.ident,
                    param.ident,
                    other.to_token_stream()
                ));
            }
            (GenericParam::Const(param), other) => {
                return Err(format!(
                    "type alias `{}` expected const argument for `{}`, got `{}`",
                    alias.ident,
                    param.ident,
                    other.to_token_stream()
                ));
            }
            (GenericParam::Lifetime(_), _) => {}
        }
    }
    Ok(subst)
}

fn substitute_type(
    ty: &Type,
    subst: &AliasSubstitution,
    aliases: &HashMap<String, ItemType>,
    stack: &mut Vec<String>,
) -> Result<Type, String> {
    match ty {
        Type::Path(type_path) => {
            if let Some(name) = single_segment_ident(type_path) {
                if let Some(replacement) = subst.types.get(&name) {
                    return normalize_type_aliases_inner(replacement, aliases, stack);
                }
            }
            let mut out = type_path.clone();
            if let Some(last_segment) = out.path.segments.last_mut() {
                if let PathArguments::AngleBracketed(args) = &mut last_segment.arguments {
                    for arg in &mut args.args {
                        *arg = substitute_generic_arg(arg, subst, aliases, stack)?;
                    }
                }
            }
            normalize_type_aliases_inner(&Type::Path(out), aliases, stack)
        }
        Type::Reference(type_ref) => {
            let mut out = type_ref.clone();
            out.elem = Box::new(substitute_type(&out.elem, subst, aliases, stack)?);
            Ok(Type::Reference(out))
        }
        Type::Ptr(type_ptr) => {
            let mut out = type_ptr.clone();
            out.elem = Box::new(substitute_type(&out.elem, subst, aliases, stack)?);
            Ok(Type::Ptr(out))
        }
        Type::Tuple(tuple) => {
            let mut out = tuple.clone();
            for elem in &mut out.elems {
                *elem = substitute_type(elem, subst, aliases, stack)?;
            }
            Ok(Type::Tuple(out))
        }
        Type::Array(array) => {
            let mut out = array.clone();
            out.elem = Box::new(substitute_type(&out.elem, subst, aliases, stack)?);
            substitute_expr_in_place(&mut out.len, subst);
            Ok(Type::Array(out))
        }
        Type::Slice(slice) => {
            let mut out = slice.clone();
            out.elem = Box::new(substitute_type(&out.elem, subst, aliases, stack)?);
            Ok(Type::Slice(out))
        }
        Type::Paren(paren) => {
            let mut out = paren.clone();
            out.elem = Box::new(substitute_type(&out.elem, subst, aliases, stack)?);
            Ok(Type::Paren(out))
        }
        Type::Group(group) => {
            let mut out = group.clone();
            out.elem = Box::new(substitute_type(&out.elem, subst, aliases, stack)?);
            Ok(Type::Group(out))
        }
        _ => Ok(ty.clone()),
    }
}

fn substitute_generic_arg(
    arg: &GenericArgument,
    subst: &AliasSubstitution,
    aliases: &HashMap<String, ItemType>,
    stack: &mut Vec<String>,
) -> Result<GenericArgument, String> {
    match arg {
        GenericArgument::Type(Type::Path(path)) => {
            if let Some(name) = single_segment_ident(path) {
                if let Some(expr) = subst.consts.get(&name) {
                    return Ok(generic_arg_from_const_expr(expr));
                }
            }
            Ok(GenericArgument::Type(substitute_type(
                &Type::Path(path.clone()),
                subst,
                aliases,
                stack,
            )?))
        }
        GenericArgument::Type(ty) => Ok(GenericArgument::Type(substitute_type(
            ty, subst, aliases, stack,
        )?)),
        GenericArgument::Const(expr) => {
            let mut expr = expr.clone();
            substitute_expr_in_place(&mut expr, subst);
            Ok(GenericArgument::Const(expr))
        }
        _ => Ok(arg.clone()),
    }
}

fn substitute_expr_in_place(expr: &mut Expr, subst: &AliasSubstitution) {
    struct Substituter<'a> {
        consts: &'a HashMap<String, Expr>,
    }

    impl VisitMut for Substituter<'_> {
        fn visit_expr_mut(&mut self, expr: &mut Expr) {
            if let Expr::Path(path) = expr {
                if let Some(name) = single_segment_expr_ident(path) {
                    if let Some(replacement) = self.consts.get(&name) {
                        *expr = replacement.clone();
                        return;
                    }
                }
            }
            visit_mut::visit_expr_mut(self, expr);
        }
    }

    Substituter {
        consts: &subst.consts,
    }
    .visit_expr_mut(expr);
}

fn single_segment_ident(type_path: &TypePath) -> Option<String> {
    if type_path.qself.is_some() || type_path.path.segments.len() != 1 {
        return None;
    }
    Some(type_path.path.segments.first()?.ident.to_string())
}

fn single_segment_expr_ident(expr_path: &ExprPath) -> Option<String> {
    if expr_path.qself.is_some() || expr_path.path.segments.len() != 1 {
        return None;
    }
    Some(expr_path.path.segments.first()?.ident.to_string())
}

fn expr_path_from_type_path(type_path: &TypePath) -> Expr {
    let qself = type_path.qself.clone();
    let path = type_path.path.clone();
    Expr::Path(ExprPath {
        attrs: Vec::new(),
        qself,
        path,
    })
}

fn generic_arg_from_const_expr(expr: &Expr) -> GenericArgument {
    if let Expr::Path(path) = expr {
        return GenericArgument::Type(Type::Path(TypePath {
            qself: path.qself.clone(),
            path: path.path.clone(),
        }));
    }
    GenericArgument::Const(expr.clone())
}