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