yum-slop/modular_slang

write individual HLSL modules/libraries in slang

git clone https://git.yummers.dev/yum-slop/modular_slang

yumfix abseil build break6e937f0

v1.0.0
16.7 KiB592 linesraw
1#include <array>
2#include <filesystem>
3#include <cctype>
4#include <fstream>
5#include <iomanip>
6#include <iostream>
7#include <limits>
8#include <sstream>
9#include <string>
10#include <string_view>
11#include <unordered_set>
12#include <vector>
13#include <utility>
14
15#include "absl/status/status.h"
16#include "absl/status/statusor.h"
17
18#include <slang.h>
19#include <slang-com-ptr.h>
20
21namespace fs = std::filesystem;
22
23using ::slang::CompilerOptionEntry;
24using ::slang::CompilerOptionName;
25using ::slang::createGlobalSession;
26using ::slang::DeclReflection;
27using ::slang::FunctionReflection;
28using ::slang::IBlob;
29using ::slang::ICompileRequest;
30using ::slang::IGlobalSession;
31using ::slang::IModule;
32using ::slang::ISession;
33using ::slang::SessionDesc;
34using ::slang::TargetDesc;
35
36template <typename T>
37using ComPtr = ::Slang::ComPtr<T>;
38
39// Print any diagnostics carried by a Slang blob with optional context information.
40void printDiagnostics(const char* context, IBlob* diagnostics) {
41  if (!diagnostics) {
42    return;
43  }
44
45  std::size_t size = diagnostics->getBufferSize();
46  if (size == 0) {
47    return;
48  }
49
50  std::string_view text(static_cast<const char*>(diagnostics->getBufferPointer()), size);
51  if (!text.empty() && text.back() == '\0') {
52    text.remove_suffix(1);
53  }
54
55  if (text.empty()) {
56    return;
57  }
58
59  if (context && *context) {
60    std::cerr << context << " diagnostics:" << std::endl;
61  }
62
63  std::cerr.write(text.data(), text.size());
64  if (text.back() != '\n') {
65    std::cerr << std::endl;
66  }
67}
68
69// Helper to convert Slang API results into absl::Status values.
70absl::Status checkSlangResult(const char* context, SlangResult res, IBlob* diagnostics = nullptr) {
71  printDiagnostics(context, diagnostics);
72
73  if (SLANG_FAILED(res)) {
74    std::ostringstream message;
75    message << (context && *context ? context : "Slang call")
76    << " failed with SlangResult " << res
77    << " (0x" << std::hex << res << std::dec << ')';
78    return absl::InternalError(message.str());
79  }
80
81  return absl::OkStatus();
82}
83
84absl::Status writeTextFile(const fs::path& path, std::string_view contents) {
85  std::ofstream file(path, std::ios::binary);
86  if (!file) {
87    std::ostringstream msg;
88    msg << "Failed to open " << path << " for writing.";
89    return absl::InternalError(msg.str());
90  }
91
92  file.write(contents.data(), static_cast<std::streamsize>(contents.size()));
93  file.close();
94
95  if (!file) {
96    std::ostringstream msg;
97    msg << "Failed to write " << path;
98    return absl::InternalError(msg.str());
99  }
100
101  return absl::OkStatus();
102}
103
104void addCompilerOption(std::vector<CompilerOptionEntry>& options, CompilerOptionName name) {
105  CompilerOptionEntry entry = {};
106  entry.name = name;
107  entry.value.intValue0 = 1;
108  options.push_back(entry);
109}
110
111struct FunctionInfo {
112  std::string name;
113};
114
115struct IncludeGuardInfo {
116  bool present = false;
117  std::string macro;
118  std::string ifndefLine;
119  std::string defineLine;
120  std::string endifLine;
121};
122
123struct ModuleRequest {
124  fs::path modulePath;
125  std::string moduleName;
126  std::string searchPath;
127  fs::path outputPath;
128};
129
130std::string trim(std::string_view text) {
131  std::size_t start = 0;
132  std::size_t end = text.size();
133
134  while (start < end && std::isspace(static_cast<unsigned char>(text[start]))) {
135    ++start;
136  }
137
138  while (end > start && std::isspace(static_cast<unsigned char>(text[end - 1]))) {
139    --end;
140  }
141
142  return std::string(text.substr(start, end - start));
143}
144
145bool isTopLevelFunction(DeclReflection* functionDecl) {
146  if (!functionDecl) {
147    return false;
148  }
149
150  using Kind = DeclReflection::Kind;
151  for (DeclReflection* parent = functionDecl->getParent(); parent;
152      parent = parent->getParent()) {
153    switch (parent->getKind()) {
154    case Kind::Module:
155    case Kind::Namespace:
156      return true;
157    case Kind::Generic:
158      continue;
159    default:
160      return false;
161    }
162  }
163
164  return false;
165}
166
167// Recursively gather function declarations defined in the supplied Slang module.
168void collectFunctionInfos(
169    DeclReflection* decl,
170    std::vector<FunctionInfo>& functions,
171    std::unordered_set<std::string>& seenNames) {
172  if (!decl) {
173    return;
174  }
175
176  using Kind = DeclReflection::Kind;
177
178  switch (decl->getKind()) {
179  case Kind::Func:
180    if (auto* functionReflection = decl->asFunction()) {
181      if (const char* name = functionReflection->getName()) {
182        // Heuristic: functions that don't start with underscore are considered public
183        // (Slang convention: private/internal functions typically start with _)
184        bool isPublic = name[0] != '_';
185
186        if (*name && seenNames.insert(name).second && isTopLevelFunction(decl) && isPublic) {
187          std::cerr << "Discovered entry point: " << name << std::endl;
188          functions.push_back({name});
189        }
190      }
191    }
192    break;
193  case Kind::Generic:
194    if (auto* genericDecl = decl->asGeneric()) {
195      collectFunctionInfos(
196          genericDecl->getInnerDecl(),
197          functions,
198          seenNames);
199    }
200    break;
201  default:
202    break;
203  }
204
205  for (auto* child : decl->getChildren()) {
206    collectFunctionInfos(child, functions, seenNames);
207  }
208}
209
210IncludeGuardInfo detectIncludeGuard(const fs::path& sourcePath) {
211  IncludeGuardInfo info;
212
213  std::ifstream input(sourcePath);
214  if (!input) {
215    return info;
216  }
217
218  std::vector<std::string> lines;
219  std::string line;
220  while (std::getline(input, line)) {
221    lines.push_back(line);
222  }
223
224  std::size_t ifndefIndex = std::numeric_limits<std::size_t>::max();
225  for (std::size_t i = 0; i < lines.size(); ++i) {
226    std::string trimmed = trim(lines[i]);
227    if (trimmed.rfind("#ifndef", 0) == 0) {
228      std::istringstream stream(trimmed);
229      std::string directive;
230      std::string macro;
231      stream >> directive >> macro;
232      if (!macro.empty()) {
233        info.macro = macro;
234        info.ifndefLine = lines[i];
235        ifndefIndex = i;
236      }
237      break;
238    }
239  }
240
241  if (info.macro.empty()) {
242    return info;
243  }
244
245  for (std::size_t i = ifndefIndex + 1; i < lines.size(); ++i) {
246    std::string trimmed = trim(lines[i]);
247    if (trimmed.rfind("#define", 0) == 0) {
248      std::istringstream stream(trimmed);
249      std::string directive;
250      std::string macro;
251      stream >> directive >> macro;
252      if (macro == info.macro) {
253        info.defineLine = lines[i];
254        break;
255      }
256    }
257  }
258
259  if (info.defineLine.empty()) {
260    info = IncludeGuardInfo{};
261    return info;
262  }
263
264  for (std::size_t i = lines.size(); i-- > 0;) {
265    std::string trimmed = trim(lines[i]);
266    if (trimmed.rfind("#endif", 0) == 0) {
267      info.endifLine = lines[i];
268      break;
269    }
270  }
271
272  if (info.endifLine.empty()) {
273    info = IncludeGuardInfo{};
274    return info;
275  }
276
277  info.present = true;
278  return info;
279}
280
281absl::StatusOr<ModuleRequest> parseModuleRequest(int argc, char** argv) {
282  const char* programName = (argc > 0 && argv) ? argv[0] : "modular_slang";
283
284  if (argc < 2 || !argv) {
285    std::ostringstream usage;
286    usage << "Usage: " << programName << " <module.slang>";
287    return absl::InvalidArgumentError(usage.str());
288  }
289
290  ModuleRequest request;
291  request.modulePath = fs::absolute(argv[1]);
292
293  if (!fs::exists(request.modulePath)) {
294    std::ostringstream msg;
295    msg << "Module not found: " << request.modulePath;
296    return absl::NotFoundError(msg.str());
297  }
298
299  if (request.modulePath.extension() != ".slang") {
300    std::ostringstream msg;
301    msg << "Expected a .slang file: " << request.modulePath;
302    return absl::InvalidArgumentError(msg.str());
303  }
304
305  request.moduleName = request.modulePath.stem().string();
306  request.searchPath = request.modulePath.has_parent_path()
307  ? request.modulePath.parent_path().string()
308  : fs::current_path().string();
309  request.outputPath = request.modulePath;
310  request.outputPath.replace_extension(".hlsl");
311
312  return request;
313}
314
315std::vector<CompilerOptionEntry> makeCommonOptions() {
316  std::vector<CompilerOptionEntry> options;
317  addCompilerOption(options, CompilerOptionName::DisableNonEssentialValidations);
318  addCompilerOption(options, CompilerOptionName::NoHLSLBinding);
319  addCompilerOption(options, CompilerOptionName::NoMangle);
320  addCompilerOption(options, CompilerOptionName::NoHLSLPackConstantBufferElements);
321  addCompilerOption(options, CompilerOptionName::PlainFunctionEntryPoints);
322  return options;
323}
324
325void configureTargetDesc(
326    IGlobalSession* globalSession,
327    std::vector<CompilerOptionEntry>& targetOptions,
328    TargetDesc& outDesc) {
329  outDesc = {};
330  outDesc.format = SLANG_HLSL;
331  outDesc.profile = globalSession->findProfile("lib_6_6");
332  outDesc.flags = SLANG_TARGET_FLAG_GENERATE_WHOLE_PROGRAM;
333  outDesc.compilerOptionEntries = targetOptions.data();
334  outDesc.compilerOptionEntryCount = static_cast<uint32_t>(targetOptions.size());
335}
336
337void configureSessionDesc(
338    const TargetDesc& targetDesc,
339    const ModuleRequest& request,
340    std::vector<CompilerOptionEntry>& sessionOptions,
341    std::array<const char*, 1>& searchPathStorage,
342    SessionDesc& outDesc) {
343  searchPathStorage[0] = request.searchPath.c_str();
344
345  outDesc = {};
346  outDesc.targets = &targetDesc;
347  outDesc.targetCount = 1;
348  outDesc.searchPaths = searchPathStorage.data();
349  outDesc.searchPathCount = static_cast<uint32_t>(searchPathStorage.size());
350  outDesc.compilerOptionEntries = sessionOptions.data();
351  outDesc.compilerOptionEntryCount = static_cast<uint32_t>(sessionOptions.size());
352}
353
354absl::StatusOr<ComPtr<IModule>> loadSlangModule(ISession* session, const std::string& moduleName) {
355  ComPtr<IModule> module;
356  ComPtr<IBlob> diagnostics;
357  module = session->loadModule(moduleName.c_str(), diagnostics.writeRef());
358
359  const std::string context = "loadModule: " + moduleName;
360  printDiagnostics(context.c_str(), diagnostics);
361
362  if (!module) {
363    std::ostringstream msg;
364    msg << "Failed to load module '" << moduleName << "'.";
365    return absl::InternalError(msg.str());
366  }
367
368  return module;
369}
370
371absl::StatusOr<std::vector<FunctionInfo>> collectEntryPoints(
372    IModule* module,
373    const std::string& moduleName) {
374  std::vector<FunctionInfo> functions;
375  std::unordered_set<std::string> seenNames;
376
377  DeclReflection* moduleReflection = module ? module->getModuleReflection() : nullptr;
378  if (!moduleReflection) {
379    std::ostringstream msg;
380    msg << "Failed to retrieve reflection data for module '"
381    << moduleName << "'.";
382    return absl::InternalError(msg.str());
383  }
384
385  collectFunctionInfos(moduleReflection, functions, seenNames);
386
387  if (functions.empty()) {
388    std::ostringstream msg;
389    msg << "No functions found in module '" << moduleName << "'.";
390    return absl::NotFoundError(msg.str());
391  }
392
393  return functions;
394}
395
396absl::StatusOr<ComPtr<ICompileRequest>> createCompileRequest(
397    ISession* session,
398    const ModuleRequest& request,
399    const TargetDesc& targetDesc,
400    const std::vector<FunctionInfo>& functions) {
401  ComPtr<ICompileRequest> compileRequest;
402  if (absl::Status status = checkSlangResult(
403          "ISession::createCompileRequest",
404          session->createCompileRequest(compileRequest.writeRef()));
405      !status.ok()) {
406    return status;
407  }
408
409  compileRequest->setCodeGenTarget(SLANG_HLSL);
410  compileRequest->setTargetProfile(0, targetDesc.profile);
411  compileRequest->setTargetFlags(0, SLANG_TARGET_FLAG_GENERATE_WHOLE_PROGRAM);
412  compileRequest->setMatrixLayoutMode(SLANG_MATRIX_LAYOUT_ROW_MAJOR);
413  compileRequest->setLineDirectiveMode(SLANG_LINE_DIRECTIVE_MODE_NONE);
414
415  compileRequest->addSearchPath(request.searchPath.c_str());
416
417  const int translationUnitIndex = compileRequest->addTranslationUnit(
418      SLANG_SOURCE_LANGUAGE_SLANG,
419      request.moduleName.c_str());
420  compileRequest->addTranslationUnitSourceFile(
421      translationUnitIndex,
422      request.modulePath.string().c_str());
423
424  for (const FunctionInfo& func : functions) {
425    const int entryPointIndex = compileRequest->addEntryPoint(
426        translationUnitIndex,
427        func.name.c_str(),
428        SLANG_STAGE_DISPATCH);
429    if (entryPointIndex < 0) {
430      std::ostringstream msg;
431      msg << "Failed to register entry point '" << func.name << "'.";
432      return absl::InternalError(msg.str());
433    }
434  }
435
436  return compileRequest;
437}
438
439absl::StatusOr<std::string> collectGeneratedHlsl(ICompileRequest* compileRequest, const std::string& moduleName) {
440  SlangResult compileResult = compileRequest->compile();
441  ComPtr<IBlob> diagnostics;
442  compileRequest->getDiagnosticOutputBlob(diagnostics.writeRef());
443  if (absl::Status status = checkSlangResult(
444          "ICompileRequest::compile", compileResult, diagnostics.get());
445      !status.ok()) {
446    return status;
447  }
448
449  ComPtr<IBlob> targetCodeBlob;
450  if (absl::Status status = checkSlangResult(
451          "ICompileRequest::getTargetCodeBlob",
452          compileRequest->getTargetCodeBlob(0, targetCodeBlob.writeRef()));
453      !status.ok()) {
454    return status;
455  }
456
457  if (!targetCodeBlob || targetCodeBlob->getBufferSize() == 0) {
458    std::ostringstream msg;
459    msg << "No HLSL was generated for module '" << moduleName << "'.";
460    return absl::InternalError(msg.str());
461  }
462
463  return std::string(
464      static_cast<const char*>(targetCodeBlob->getBufferPointer()),
465      static_cast<std::size_t>(targetCodeBlob->getBufferSize()));
466}
467
468std::string applyIncludeGuard(const std::string& hlslSource, const IncludeGuardInfo& includeGuard) {
469  if (!includeGuard.present) {
470    return hlslSource;
471  }
472
473  const std::string guardIfndefToken = "#ifndef " + includeGuard.macro;
474  const std::string guardDefineToken = "#define " + includeGuard.macro;
475  const bool alreadyGuarded =
476  hlslSource.find(guardIfndefToken) != std::string::npos &&
477  hlslSource.find(guardDefineToken) != std::string::npos;
478
479  if (alreadyGuarded) {
480    return hlslSource;
481  }
482
483  std::string body = hlslSource;
484  if (!body.empty() && body.back() != '\n') {
485    body += '\n';
486  }
487
488  std::ostringstream wrapped;
489  wrapped << includeGuard.ifndefLine << '\n';
490  wrapped << includeGuard.defineLine << '\n';
491  wrapped << '\n';
492  wrapped << body;
493  if (!body.empty() && body.back() != '\n') {
494    wrapped << '\n';
495  }
496  wrapped << includeGuard.endifLine;
497  if (!includeGuard.endifLine.empty() && includeGuard.endifLine.back() != '\n') {
498    wrapped << '\n';
499  }
500
501  return wrapped.str();
502}
503
504absl::Status run(int argc, char** argv) {
505  absl::StatusOr<ModuleRequest> requestOr = parseModuleRequest(argc, argv);
506  if (!requestOr.ok()) {
507    return requestOr.status();
508  }
509  ModuleRequest request = std::move(requestOr).value();
510
511  ComPtr<IGlobalSession> globalSession;
512  if (absl::Status status = checkSlangResult(
513          "createGlobalSession",
514          createGlobalSession(globalSession.writeRef()));
515      !status.ok()) {
516    return status;
517  }
518
519  auto commonOptions = makeCommonOptions();
520
521  std::vector<CompilerOptionEntry> targetOptions = commonOptions;
522  TargetDesc targetDesc;
523  configureTargetDesc(globalSession.get(), targetOptions, targetDesc);
524
525  std::vector<CompilerOptionEntry> sessionOptions = commonOptions;
526  SessionDesc sessionDesc;
527  std::array<const char*, 1> searchPaths{};
528  configureSessionDesc(targetDesc, request, sessionOptions, searchPaths, sessionDesc);
529
530  ComPtr<ISession> session;
531  if (absl::Status status = checkSlangResult(
532          "IGlobalSession::createSession",
533          globalSession->createSession(sessionDesc, session.writeRef()));
534      !status.ok()) {
535    return status;
536  }
537
538  absl::StatusOr<ComPtr<IModule>> libraryModuleOr =
539      loadSlangModule(session.get(), request.moduleName);
540  if (!libraryModuleOr.ok()) {
541    return libraryModuleOr.status();
542  }
543  ComPtr<IModule> libraryModule = std::move(libraryModuleOr).value();
544
545  absl::StatusOr<std::vector<FunctionInfo>> functionsOr =
546      collectEntryPoints(libraryModule.get(), request.moduleName);
547  if (!functionsOr.ok()) {
548    return functionsOr.status();
549  }
550  std::vector<FunctionInfo> functions = std::move(functionsOr).value();
551
552  absl::StatusOr<ComPtr<ICompileRequest>> compileRequestOr =
553      createCompileRequest(session.get(), request, targetDesc, functions);
554  if (!compileRequestOr.ok()) {
555    return compileRequestOr.status();
556  }
557  ComPtr<ICompileRequest> compileRequest = std::move(compileRequestOr).value();
558
559  absl::StatusOr<std::string> hlslSourceOr =
560      collectGeneratedHlsl(compileRequest.get(), request.moduleName);
561  if (!hlslSourceOr.ok()) {
562    return hlslSourceOr.status();
563  }
564  std::string hlslSource = std::move(hlslSourceOr).value();
565
566  fs::path rawOutputPath = request.outputPath;
567  rawOutputPath.replace_extension(".raw.hlsl");
568  if (absl::Status status = writeTextFile(rawOutputPath, hlslSource);
569      !status.ok()) {
570    return status;
571  }
572
573  IncludeGuardInfo includeGuard = detectIncludeGuard(request.modulePath);
574  std::string finalHlsl = applyIncludeGuard(hlslSource, includeGuard);
575  if (absl::Status status = writeTextFile(request.outputPath, finalHlsl);
576      !status.ok()) {
577    return status;
578  }
579
580  std::cerr << "Generated HLSL written to " << request.outputPath << std::endl;
581  return absl::OkStatus();
582}
583
584int main(int argc, char** argv) {
585  absl::Status status = run(argc, argv);
586  if (!status.ok()) {
587    std::cerr << status.message() << std::endl;
588    return 1;
589  }
590
591  return 0;
592}