Skip to main content

cubecl_ir/
non_semantic.rs

1use core::fmt::Display;
2
3use alloc::{borrow::Cow, string::String, vec::Vec};
4
5use crate::TypeHash;
6
7use crate::{OperationCode, OperationReflect, fmt_vararg};
8
9use super::Value;
10
11/// Operations that don't change the semantics of the kernel. In other words, operations that do not
12/// perform any computation, if they run at all. i.e. `println`, comments and debug symbols.
13///
14/// Can be safely removed or ignored without changing the kernel result.
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16#[derive(Debug, Clone, TypeHash, PartialEq, Eq, Hash, OperationCode)]
17#[operation(opcode_name = NonSemanticOpCode)]
18pub enum NonSemantic {
19    /// Enter a new debug scope, this happens recursively when a cube function is called and
20    /// inlined into the kernel. Should push a new frame onto the debug call stack.
21    EnterDebugScope,
22    /// Exit a debug scope and resume execution at the previous stack frame.
23    ExitDebugScope,
24    /// Print a formatted string with arguments to the backend's debugging facilit
25    /// (i.e. validation layer). The syntax of the format string depends on the backend, but tends
26    /// to follow C++ convention.
27    Print {
28        format_string: String,
29        args: Vec<Value>,
30    },
31    /// Insert a comment into the compiled source
32    Comment { content: String },
33}
34
35impl OperationReflect for NonSemantic {
36    type OpCode = NonSemanticOpCode;
37
38    fn op_code(&self) -> Self::OpCode {
39        self.__match_opcode()
40    }
41
42    fn sanitize_args(&mut self, _: &crate::Scope) {}
43}
44
45impl Display for NonSemantic {
46    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
47        match self {
48            NonSemantic::Print {
49                format_string,
50                args,
51            } => {
52                write!(f, "print({format_string:?}{})", fmt_vararg(args))
53            }
54            NonSemantic::Comment { content } => write!(f, "//{content}"),
55            // Scopes don't have meaning to the user
56            _ => Ok(()),
57        }
58    }
59}
60
61/// A Rust source location, including the file, line and column
62#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
63#[derive(Debug, Clone, PartialEq, Eq, Hash, TypeHash)]
64pub struct SourceLoc {
65    pub line: u32,
66    pub column: u32,
67    pub source: CubeFnSource,
68}
69
70/// A cube function's source
71#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
72#[derive(Debug, Clone, PartialEq, Eq, Hash, TypeHash)]
73pub struct CubeFnSource {
74    pub function_name: Cow<'static, str>,
75    pub file: Cow<'static, str>,
76    pub source_text: Cow<'static, str>,
77    pub line: u32,
78    pub column: u32,
79}