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
#![allow(dead_code)]
#![warn(clippy::all)]
#![warn(clippy::pedantic)]

use slang_sys::*;
use std::ffi::CStr;
use std::num::NonZeroU32;
use std::ptr;

mod result;

pub use slang_sys as ffi;

use result::into_result;
use result::Result;

/// Implementation details for `handle_wrapper_struct`.
macro_rules! handle_wrapper_struct_impl {
    ($wrapper_name:ident, $inner:ty) => {
        impl ::std::fmt::Debug for $wrapper_name<'_> {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                f.debug_tuple(stringify!($wrapper_name))
                    .field(&self.handle)
                    .finish()
            }
        }

        impl<'a> $wrapper_name<'a> {
            #[inline]
            pub fn wrap(inner: $inner) -> Self {
                Self {
                    handle: inner,
                    phantom: ::std::marker::PhantomData,
                }
            }

            #[inline]
            pub fn get(&self) -> $inner {
                self.handle
            }
        }

        impl From<$inner> for $wrapper_name<'_> {
            fn from(inner: $inner) -> Self {
                Self::wrap(inner)
            }
        }
    };
}

/// Generate a wrapper struct with a lifetime specifier.
///
/// Use `$wrapper_name::wrap($inner)` and `$wrapper_name::get() -> $inner` to wrap and access the value.
macro_rules! handle_wrapper_struct {
    ($wrapper_name:ident, $inner:ty) => {
        pub struct $wrapper_name<'a> {
            handle: $inner,
            phantom: ::std::marker::PhantomData<&'a $inner>,
        }
        handle_wrapper_struct_impl!($wrapper_name, $inner);
    };
}

/// `handle_wrapper_struct` for `Copy` types.
macro_rules! handle_wrapper_struct_copy {
    ($wrapper_name:ident, $inner:ty) => {
        #[derive(Copy, Clone)]
        pub struct $wrapper_name<'a> {
            handle: $inner,
            phantom: ::std::marker::PhantomData<&'a $inner>,
        }
        handle_wrapper_struct_impl!($wrapper_name, $inner);
    };
}

handle_wrapper_struct!(Session, *mut SlangSession);

impl Default for Session<'_> {
    fn default() -> Self {
        unsafe { spCreateSession(ptr::null()).into() }
    }
}

impl Session<'_> {
    pub fn new() -> Self {
        Self::default()
    }

    // fn set_shared_library_loader(&self, loader: ISlangSharedLibraryLoader) {
    //     unimplemented!()
    // }

    // fn get_shared_library_loader(&self) -> ISlangSharedLibraryLoader {
    //     unimplemented!()
    // }

    // bool?
    fn check_compile_target_support(&self, target: SlangCompileTarget) -> Result {
        unsafe { into_result(spSessionCheckCompileTargetSupport(self.get(), target)) }
    }

    // bool?
    fn check_pass_through_support(&self, pass_through: SlangPassThrough) -> Result {
        unsafe { into_result(spSessionCheckPassThroughSupport(self.get(), pass_through)) }
    }

    fn add_builtins(&self, source_path: impl AsRef<CStr>, source_string: impl AsRef<CStr>) {
        unsafe {
            spAddBuiltins(
                self.get(),
                source_path.as_ref().as_ptr(),
                source_string.as_ref().as_ptr(),
            )
        }
    }

    fn create_compile_request(&self) -> CompileRequest {
        unsafe { spCreateCompileRequest(self.get()).into() }
    }

    fn find_profile(&self, name: impl AsRef<CStr>) -> Option<ProfileId> {
        unsafe {
            let profile = spFindProfile(self.get(), name.as_ref().as_ptr());
            NonZeroU32::new(profile)
        }
    }
}

impl Drop for Session<'_> {
    fn drop(&mut self) {
        unsafe {
            spDestroySession(self.get());
        }
    }
}

handle_wrapper_struct_copy!(CodeGenTarget, i32);
handle_wrapper_struct_copy!(TranslationUnitIndex, i32);
handle_wrapper_struct_copy!(EntryPointIndex, i32);

handle_wrapper_struct!(CompileRequest, *mut SlangCompileRequest);

impl<'a> CompileRequest<'a> {
    // fn set_file_system(&self, ISlangFileSystem* fileSystem) {}
    // fn set_compile_flags(&self, SlangCompileFlags flags) {}
    // fn set_dump_intermediates(&self, int enable) {}
    // fn set_line_directive_mode(&self, SlangLineDirectiveMode mode) {}
    // fn set_code_gen_target(&self, SlangCompileTarget target) {}

    fn add_code_gen_target(&self, target: SlangCompileTarget) -> CodeGenTarget {
        unsafe { spAddCodeGenTarget(self.get(), target).into() }
    }

    fn set_target_profile(&self, target_index: CodeGenTarget, profile: ProfileId) {
        unsafe { spSetTargetProfile(self.get(), target_index.get(), profile.get()) }
    }

    // fn set_target_flags(&self, target_index: CodeGenTarget, SlangTargetFlags flags) {}
    // fn set_target_floating_point_mode(&self, target_index: CodeGenTarget, SlangFloatingPointMode mode) {}
    // fn set_target_matrix_layout_mode(&self, target_index: CodeGenTarget, SlangMatrixLayoutMode mode) {}
    // fn set_matrix_layout_mode(&self, SlangMatrixLayoutMode mode) {}
    // fn set_output_container_format(&self, SlangContainerFormat format) {}
    // fn set_pass_through(&self, SlangPassThrough passThrough) {}
    // fn set_diagnostic_callback(&self, SlangDiagnosticCallback callback, void const* userData) {}
    // fn set_writer(&self, SlangWriterChannel channel, ISlangWriter* writer) {}
    // fn get_writer(&self, SlangWriterChannel channel) -> ISlangWriter*  {}
    // fn add_search_path(&self, const char* searchDir) {}
    // fn add_preprocessor_define(&self, const char* key, const char* value) {}
    // fn process_command_line_arguments(&self, cstr const* args, int argCount) -> SlangResult  {}

    fn add_translation_unit(
        &self,
        language: SlangSourceLanguage,
        name: impl AsRef<CStr>,
    ) -> TranslationUnitIndex {
        unsafe { spAddTranslationUnit(self.get(), language, name.as_ref().as_ptr()).into() }
    }

    // fn translation_unit_add_preprocessor_define(&self, translation_unit_index: TranslationUnitIndex, const char* key, const char* value) {}
    // fn add_translation_unit_source_file(&self, translation_unit_index: TranslationUnitIndex, cstr path) {}

    fn add_translation_unit_source_string(
        &self,
        translation_unit_index: TranslationUnitIndex,
        path: impl AsRef<CStr>,
        source: impl AsRef<CStr>,
    ) {
        unsafe {
            spAddTranslationUnitSourceString(
                self.get(),
                translation_unit_index.get(),
                path.as_ref().as_ptr(),
                source.as_ref().as_ptr(),
            )
        }
    }

    // fn add_translation_unit_source_string_span(&self, translation_unit_index: TranslationUnitIndex, cstr path, cstr sourceBegin, cstr sourceEnd) {}
    // fn add_translation_unit_source_blob(&self, translation_unit_index: TranslationUnitIndex, cstr path, ISlangBlob* sourceBlob) {}

    fn add_entry_point(
        &self,
        translation_unit_index: TranslationUnitIndex,
        name: impl AsRef<CStr>,
        stage: SlangStage,
    ) -> EntryPointIndex {
        unsafe {
            spAddEntryPoint(
                self.get(),
                translation_unit_index.get(),
                name.as_ref().as_ptr(),
                stage,
            )
            .into()
        }
    }

    // fn add_entry_point_ex(&self, translation_unit_index: TranslationUnitIndex, cstr name, SlangStage stage, int genericTypeNameCount, cstr* genericTypeNames) -> int  {}

    fn compile(&self) -> Result {
        unsafe { into_result(spCompile(self.get())) }
    }

    fn get_diagnostic_output(&self) -> &'a CStr {
        unsafe { CStr::from_ptr(spGetDiagnosticOutput(self.get())) }
    }

    // fn get_diagnostic_output_blob(&self, ISlangBlob** outBlob) -> SlangResult  {}
    // fn get_dependency_file_count(&self) -> int  {}
    // fn get_dependency_file_path(&self, int index) -> cstr  {}
    // fn get_translation_unit_count(&self) -> int  {}
    // fn get_entry_point_source(&self,  entry_point_index: EntryPointIndex) -> cstr  {}

    fn get_entry_point_code(&self, entry_point_index: EntryPointIndex) -> &'a [u8] {
        unsafe {
            let out_size = std::ptr::null_mut();
            let blob = spGetEntryPointCode(self.get(), entry_point_index.get(), out_size);

            std::slice::from_raw_parts(blob as *const u8, *out_size)
        }
    }

    // fn get_entry_point_code_blob(&self,  entry_point_index: EntryPointIndex, targetIndex: CodeGenTarget, ISlangBlob** outBlob) -> SlangResult  {}
    // fn get_compile_request_code(&self, size_t* outSize) -> void const*  {}
    // fn get_reflection(&self) -> SlangReflection*  {}
}

impl Drop for CompileRequest<'_> {
    fn drop(&mut self) {
        unsafe {
            spDestroyCompileRequest(self.get());
        }
    }
}

type ProfileId = NonZeroU32;