summaryrefslogtreecommitdiffstats
path: root/source/slang/slang.cpp
blob: ce48f9032c57bcd90ed2651f8a437884f43fc006 (plain)
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
#include "../../slang.h"

#include "../core/slang-io.h"
#include "../slang/slang-stdlib.h"
#include "parameter-binding.h"
#include "../slang/parser.h"
#include "../slang/preprocessor.h"
#include "../slang/reflection.h"
#include "syntax-visitors.h"
#include "../slang/type-layout.h"

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#undef WIN32_LEAN_AND_MEAN
#undef NOMINMAX
#endif

namespace Slang {

static void stdlibDiagnosticCallback(
    char const* message,
    void*       userData)
{
    fputs(message, stderr);
    fflush(stderr);
#ifdef WIN32
    OutputDebugStringA(message);
#endif
}

class Session
{
public:
    bool useCache = false;
    String cacheDir;

    RefPtr<Scope>   slangLanguageScope;
    RefPtr<Scope>   hlslLanguageScope;
    RefPtr<Scope>   glslLanguageScope;

    List<RefPtr<ProgramSyntaxNode>> loadedModuleCode;


    Session(bool /*pUseCache*/, String /*pCacheDir*/)
    {
        // Initialize global state
        // TODO: move this into the session instead
        BasicExpressionType::Init();

        // Create scopes for various language builtins.
        //
        // TODO: load these on-demand to avoid parsing
        // stdlib code for languages the user won't use.

        slangLanguageScope = new Scope();

        hlslLanguageScope = new Scope();
        hlslLanguageScope->parent = slangLanguageScope;

        glslLanguageScope = new Scope();
        glslLanguageScope->parent = slangLanguageScope;

        addBuiltinSource(slangLanguageScope, "stdlib", SlangStdLib::GetCode());
        addBuiltinSource(glslLanguageScope, "glsl", getGLSLLibraryCode());
    }

    ~Session()
    {
        // We need to clean up the strings for the standard library
        // code that we might have allocated and loaded into static
        // variables (TODO: don't use `static` variables for this stuff)

        SlangStdLib::Finalize();

        // Ditto for our type represnetation stuff

        ExpressionType::Finalize();
    }

    CompileUnit createPredefUnit()
    {
        CompileUnit translationUnit;


        RefPtr<ProgramSyntaxNode> translationUnitSyntax = new ProgramSyntaxNode();

        TranslationUnitOptions translationUnitOptions;
        translationUnit.options = translationUnitOptions;
        translationUnit.SyntaxNode = translationUnitSyntax;

        return translationUnit;
    }

    void addBuiltinSource(
        RefPtr<Scope> const&    scope,
        String const&           path,
        String const&           source);
};

struct CompileRequest
{
    // Pointer to parent session
    Session* mSession;

    // Input options
    CompileOptions Options;

    // Output stuff
    DiagnosticSink mSink;
    String mDiagnosticOutput;

    RefPtr<CollectionOfTranslationUnits> mCollectionOfTranslationUnits;

    RefPtr<ProgramLayout> mReflectionData;

    CompileResult mResult;

    List<String> mDependencyFilePaths;

    CompileRequest(Session* session)
        : mSession(session)
    {}

    ~CompileRequest()
    {}

    struct IncludeHandlerImpl : IncludeHandler
    {
        CompileRequest* request;

        List<String> searchDirs;

        virtual bool TryToFindIncludeFile(
            String const& pathToInclude,
            String const& pathIncludedFrom,
            String* outFoundPath,
            String* outFoundSource) override
        {
            String path = Path::Combine(Path::GetDirectoryName(pathIncludedFrom), pathToInclude);
            if (File::Exists(path))
            {
                *outFoundPath = path;
                *outFoundSource = File::ReadAllText(path);

                request->mDependencyFilePaths.Add(path);

                return true;
            }

            for (auto & dir : searchDirs)
            {
                path = Path::Combine(dir, pathToInclude);
                if (File::Exists(path))
                {
                    *outFoundPath = path;
                    *outFoundSource = File::ReadAllText(path);

                    request->mDependencyFilePaths.Add(path);

                    return true;
                }
            }
            return false;
        }
    };


    CompileUnit parseTranslationUnit(
        TranslationUnitOptions const&   translationUnitOptions,
        CompileOptions&                 options)
    {
        IncludeHandlerImpl includeHandler;
        includeHandler.request = this;

        CompileUnit translationUnit;

        RefPtr<Scope> languageScope;
        switch (translationUnitOptions.sourceLanguage)
        {
        case SourceLanguage::HLSL:
            languageScope = mSession->hlslLanguageScope;
            break;

        case SourceLanguage::GLSL:
            languageScope = mSession->glslLanguageScope;
            break;

        case SourceLanguage::Slang:
        default:
            languageScope = mSession->slangLanguageScope;
            break;
        }

        Dictionary<String, String> preprocessorDefinitions;
        for(auto& def : options.preprocessorDefinitions)
            preprocessorDefinitions.Add(def.Key, def.Value);
        for(auto& def : translationUnitOptions.preprocessorDefinitions)
            preprocessorDefinitions.Add(def.Key, def.Value);

        RefPtr<ProgramSyntaxNode> translationUnitSyntax = new ProgramSyntaxNode();

        for (auto sourceFile : translationUnitOptions.sourceFiles)
        {
            auto sourceFilePath = sourceFile->path;

            auto searchDirs = options.SearchDirectories;
            searchDirs.Reverse();
            searchDirs.Add(Path::GetDirectoryName(sourceFilePath));
            searchDirs.Reverse();
            includeHandler.searchDirs = searchDirs;

            String source = sourceFile->content;

            auto tokens = preprocessSource(
                source,
                sourceFilePath,
                mResult.GetErrorWriter(),
                &includeHandler,
                preprocessorDefinitions,
                translationUnitSyntax.Ptr());

            parseSourceFile(
                translationUnitSyntax.Ptr(),
                options,
                tokens,
                mResult.GetErrorWriter(),
                sourceFilePath,
                languageScope);
        }

        translationUnit.options = translationUnitOptions;
        translationUnit.SyntaxNode = translationUnitSyntax;

        return translationUnit;
    }

    CompileUnit parseTranslationUnit(
        TranslationUnitOptions const&   translationUnitOptions)
    {
        return parseTranslationUnit(translationUnitOptions, Options);
    }

    void checkTranslationUnit(
        CompileUnit&            translationUnit,
        RefPtr<SyntaxVisitor>   visitor)
    {
        visitor->setSourceLanguage(translationUnit.options.sourceLanguage);
        translationUnit.SyntaxNode->Accept(visitor.Ptr());
    }

    void checkTranslationUnit(
        CompileUnit&    translationUnit,
        CompileOptions& options)
    {
        RefPtr<SyntaxVisitor> visitor = CreateSemanticsVisitor(
            mResult.GetErrorWriter(),
            options,
            this);

        checkTranslationUnit(translationUnit, visitor);
    }

    void checkCollectionOfTranslationUnits(
        RefPtr<CollectionOfTranslationUnits>    collectionOfTranslationUnits)
    {
        RefPtr<SyntaxVisitor> visitor = CreateSemanticsVisitor(
            mResult.GetErrorWriter(),
            Options,
            this);

        for( auto& translationUnit : collectionOfTranslationUnits->translationUnits )
        {
            checkTranslationUnit(translationUnit, visitor);
        }
    }

    void generateOutputForCollectionOfTranslationUnits(
        RefPtr<CollectionOfTranslationUnits>    collectionOfTranslationUnits)
    {
        // Do binding generation, and then reflection (globally)
        // before we move on to any code-generation activites.
        GenerateParameterBindings(collectionOfTranslationUnits.Ptr());


        // HACK(tfoley): for right now I just want to pretty-print an AST
        // into another language, so the whole compiler back-end is just
        // getting in the way.
        //
        // I'm going to bypass it for now and see what I can do:

        ExtraContext extra;
        extra.options = &Options;
        extra.programLayout = collectionOfTranslationUnits->layout.Ptr();
        extra.compileResult = &mResult;

        generateOutput(extra, collectionOfTranslationUnits.Ptr());
    }

    int executeCompilerDriverActions()
    {
        // If we are being asked to do pass-through, then we need to do that here...
        if (Options.passThrough != PassThroughMode::None)
        {
            for (auto& translationUnitOptions : Options.translationUnits)
            {
                switch (translationUnitOptions.sourceLanguage)
                {
                    // We can pass-through code written in a native shading language
                case SourceLanguage::GLSL:
                case SourceLanguage::HLSL:
                    break;

                    // All other translation units need to be skipped
                default:
                    continue;
                }

                auto sourceFile = translationUnitOptions.sourceFiles[0];
                auto sourceFilePath = sourceFile->path;
                String source = sourceFile->content;

                auto translationUnitResult = passThrough(
                    source,
                    sourceFilePath,
                    Options,
                    translationUnitOptions);

                mResult.translationUnits.Add(translationUnitResult);
            }
            return 0;
        }

        // TODO: load the stdlib

        mCollectionOfTranslationUnits = new CollectionOfTranslationUnits();

        // Parse everything from the input files requested
        //
        // TODO: this may trigger the loading and/or compilation of additional modules.
        for (auto& translationUnitOptions : Options.translationUnits)
        {
            auto translationUnit = parseTranslationUnit(translationUnitOptions);
            mCollectionOfTranslationUnits->translationUnits.Add(translationUnit);
        }
        if (mResult.GetErrorCount() != 0)
            return 1;

        // Perform semantic checking on the whole collection
        checkCollectionOfTranslationUnits(mCollectionOfTranslationUnits);
        if (mResult.GetErrorCount() != 0)
            return 1;

        // Generate output code, in whatever format was requested
        generateOutputForCollectionOfTranslationUnits(mCollectionOfTranslationUnits);
        if (mResult.GetErrorCount() != 0)
            return 1;

        // Extract the reflection layout information so that users
        // can easily query it.
        mReflectionData = mCollectionOfTranslationUnits->layout;

        return 0;
    }

    // Act as expected of the API-based compiler
    int executeAPIActions()
    {
        mResult.mSink = &mSink;

        int err = executeCompilerDriverActions();

        mDiagnosticOutput = mSink.outputBuffer.ProduceString();

        if (mSink.GetErrorCount() != 0)
            return mSink.GetErrorCount();

        return err;
    }

    int addTranslationUnit(SourceLanguage language, String const& name)
    {
        int result = Options.translationUnits.Count();

        TranslationUnitOptions translationUnit;
        translationUnit.sourceLanguage = SourceLanguage(language);

        Options.translationUnits.Add(translationUnit);

        return result;
    }

    void addTranslationUnitSourceString(
        int             translationUnitIndex,
        String const&   path,
        String const&   source)
    {
        RefPtr<SourceFile> sourceFile = new SourceFile();
        sourceFile->path = path;
        sourceFile->content = source;

        Options.translationUnits[translationUnitIndex].sourceFiles.Add(sourceFile);
    }

    void addTranslationUnitSourceFile(
        int             translationUnitIndex,
        String const&   path)
    {
        String source;
        try
        {
            source = File::ReadAllText(path);
        }
        catch (...)
        {
            // Emit a diagnostic!
            mSink.diagnose(
                CodePosition(0, 0, 0, path),
                Diagnostics::cannotOpenFile,
                path);
            return;
        }

        addTranslationUnitSourceString(
            translationUnitIndex,
            path,
            source);

        mDependencyFilePaths.Add(path);
    }

    int addTranslationUnitEntryPoint(
        int                     translationUnitIndex,
        String const&           name,
        Profile                 profile)
    {
        EntryPointOption entryPoint;
        entryPoint.name = name;
        entryPoint.profile = profile;

        // TODO: realistically want this to be global across all TUs...
        int result = Options.translationUnits[translationUnitIndex].entryPoints.Count();

        Options.translationUnits[translationUnitIndex].entryPoints.Add(entryPoint);
        return result;
    }

    Dictionary<String, RefPtr<ProgramSyntaxNode>> loadedModules;

    RefPtr<ProgramSyntaxNode> findOrImportModule(
        String const&       name,
        CodePosition const& loc)
    {
        // Have we already loaded a module matching this name?
        // If so, return it.
        RefPtr<ProgramSyntaxNode> moduleDecl;
        if (loadedModules.TryGetValue(name, moduleDecl))
            return moduleDecl;

        // Derive a file name for the module, by taking the given
        // identifier, replacing all occurences of `_` with `-`,
        // and then appending `.slang`.
        //
        // For example, `foo_bar` becomes `foo-bar.slang`.

        StringBuilder sb;
        for (auto c : name)
        {
            if (c == '_')
                c = '-';

            sb.Append(c);
        }
        sb.Append(".slang");

        String fileName = sb.ProduceString();

        // Next, try to find the file of the given name,
        // using our ordinary include-handling logic.

        IncludeHandlerImpl includeHandler;
        includeHandler.request = this;

        String pathIncludedFrom = loc.FileName;

        String foundPath;
        String foundSource;
        bool found = includeHandler.TryToFindIncludeFile(fileName, pathIncludedFrom, &foundPath, &foundSource);
        if (!found)
        {
            this->mSink.diagnose(loc, Diagnostics::cannotFindFile, fileName);

            loadedModules[name] = nullptr;
            return nullptr;
        }

        // We've found a file that we can load for the given module, so
        // now we need to try compiling it, etc.

        // We don't want to use the same options that the user specified
        // for loading modules on-demand. In particular, we always want
        // semantic checking to be enabled.
        CompileOptions moduleOptions;
        moduleOptions.SearchDirectories = Options.SearchDirectories;
        moduleOptions.profile = Options.profile;

        RefPtr<SourceFile> sourceFile = new SourceFile();
        sourceFile->path = foundPath;
        sourceFile->content = foundSource;

        TranslationUnitOptions translationUnitOptions;
        translationUnitOptions.sourceFiles.Add(sourceFile);

        CompileUnit translationUnit = parseTranslationUnit(translationUnitOptions, moduleOptions);

        // TODO: handle errors

        checkTranslationUnit(translationUnit, moduleOptions);

        // Skip code generation

        //

        moduleDecl = translationUnit.SyntaxNode;

        loadedModules.Add(name, moduleDecl);

        return moduleDecl;
    }

};

RefPtr<ProgramSyntaxNode> findOrImportModule(
    CompileRequest*     request,
    String const&       name,
    CodePosition const& loc)
{
    return request->findOrImportModule(name, loc);
}

void Session::addBuiltinSource(
    RefPtr<Scope> const&    scope,
    String const&           path,
    String const&           source)
{
    CompileRequest compileRequest(this);

    auto translationUnitIndex = compileRequest.addTranslationUnit(SourceLanguage::Slang, path);

    compileRequest.addTranslationUnitSourceString(
        translationUnitIndex,
        path,
        source);

    int err = compileRequest.executeAPIActions();
    if (err)
    {
        fprintf(stderr, "%s", compileRequest.mDiagnosticOutput.Buffer());

#ifdef _WIN32
        OutputDebugStringA(compileRequest.mDiagnosticOutput.Buffer());
#endif

        assert(!"error in stdlib");
    }

    // Extract the AST for the code we just parsed
    auto syntax = compileRequest.mCollectionOfTranslationUnits->translationUnits[translationUnitIndex].SyntaxNode;

    // HACK(tfoley): mark all declarations in the "stdlib" so
    // that we can detect them later (e.g., so we don't emit them)
    for (auto m : syntax->Members)
    {
        auto fromStdLibModifier = new FromStdLibModifier();

        fromStdLibModifier->next = m->modifiers.first;
        m->modifiers.first = fromStdLibModifier;
    }

    // Add the resulting code to the appropriate scope
    if (!scope->containerDecl)
    {
        // We are the first chunk of code to be loaded for this scope
        scope->containerDecl = syntax.Ptr();
    }
    else
    {
        // We need to create a new scope to link into the whole thing
        auto subScope = new Scope();
        subScope->containerDecl = syntax.Ptr();
        subScope->nextSibling = scope->nextSibling;
        scope->nextSibling = subScope;
    }

    // We need to retain this AST so that we can use it in other code
    // (Note that the `Scope` type does not retain the AST it points to)
    loadedModuleCode.Add(syntax);
}

}

// implementation of C interface

#define SESSION(x) reinterpret_cast<Slang::Session *>(x)
#define REQ(x) reinterpret_cast<Slang::CompileRequest*>(x)

SLANG_API SlangSession* spCreateSession(const char * cacheDir)
{
    return reinterpret_cast<SlangSession *>(new Slang::Session((cacheDir ? true : false), cacheDir));
}

SLANG_API void spDestroySession(
    SlangSession*   session)
{
    if(!session) return;
    delete SESSION(session);
}

SLANG_API void spAddBuiltins(
    SlangSession*   session,
    char const*     sourcePath,
    char const*     sourceString)
{
    auto s = SESSION(session);
    s->addBuiltinSource(

        // TODO(tfoley): Add ability to directly new builtins to the approriate scope
        s->slangLanguageScope,

        sourcePath,
        sourceString);
}


SLANG_API SlangCompileRequest* spCreateCompileRequest(
    SlangSession* session)
{
    auto s = SESSION(session);
    auto req = new Slang::CompileRequest(s);
    return reinterpret_cast<SlangCompileRequest*>(req);
}

/*!
@brief Destroy a compile request.
*/
SLANG_API void spDestroyCompileRequest(
    SlangCompileRequest*    request)
{
    if(!request) return;
    auto req = REQ(request);
    delete req;
}

SLANG_API void spSetCompileFlags(
    SlangCompileRequest*    request,
    SlangCompileFlags       flags)
{
    REQ(request)->Options.flags = flags;
}

SLANG_API void spSetCodeGenTarget(
        SlangCompileRequest*    request,
        int target)
{
    REQ(request)->Options.Target = (Slang::CodeGenTarget)target;
}

SLANG_API void spSetPassThrough(
    SlangCompileRequest*    request,
    SlangPassThrough        passThrough)
{
    REQ(request)->Options.passThrough = Slang::PassThroughMode(passThrough);
}

SLANG_API void spSetDiagnosticCallback(
    SlangCompileRequest*    request,
    SlangDiagnosticCallback callback,
    void const*             userData)
{
    if(!request) return;
    auto req = REQ(request);

    req->mSink.callback = callback;
    req->mSink.callbackUserData = (void*) userData;
}

SLANG_API void spAddSearchPath(
        SlangCompileRequest*    request,
        const char*             searchDir)
{
    REQ(request)->Options.SearchDirectories.Add(searchDir);
}

SLANG_API void spAddPreprocessorDefine(
    SlangCompileRequest*    request,
    const char*             key,
    const char*             value)
{
    REQ(request)->Options.preprocessorDefinitions[key] = value;
}

SLANG_API char const* spGetDiagnosticOutput(
    SlangCompileRequest*    request)
{
    if(!request) return 0;
    auto req = REQ(request);
    return req->mDiagnosticOutput.begin();
}

// New-fangled compilation API

SLANG_API int spAddTranslationUnit(
    SlangCompileRequest*    request,
    SlangSourceLanguage     language,
    char const*             name)
{
    auto req = REQ(request);

    return req->addTranslationUnit(
        Slang::SourceLanguage(language),
        name ? name : "");
}

SLANG_API void spTranslationUnit_addPreprocessorDefine(
    SlangCompileRequest*    request,
    int                     translationUnitIndex,
    const char*             key,
    const char*             value)
{
    auto req = REQ(request);

    req->Options.translationUnits[translationUnitIndex].preprocessorDefinitions[key] = value;

}

SLANG_API void spAddTranslationUnitSourceFile(
    SlangCompileRequest*    request,
    int                     translationUnitIndex,
    char const*             path)
{
    if(!request) return;
    auto req = REQ(request);
    if(!path) return;
    if(translationUnitIndex < 0) return;
    if(translationUnitIndex >= req->Options.translationUnits.Count()) return;

    req->addTranslationUnitSourceFile(
        translationUnitIndex,
        path);
}

// Add a source string to the given translation unit
SLANG_API void spAddTranslationUnitSourceString(
    SlangCompileRequest*    request,
    int                     translationUnitIndex,
    char const*             path,
    char const*             source)
{
    if(!request) return;
    auto req = REQ(request);
    if(!source) return;
    if(translationUnitIndex < 0) return;
    if(translationUnitIndex >= req->Options.translationUnits.Count()) return;

    if(!path) path = "";

    req->addTranslationUnitSourceString(
        translationUnitIndex,
        path,
        source);

}

SLANG_API SlangProfileID spFindProfile(
    SlangSession*   session,
    char const*     name)
{
    return Slang::Profile::LookUp(name).raw;
}

SLANG_API int spAddTranslationUnitEntryPoint(
    SlangCompileRequest*    request,
    int                     translationUnitIndex,
    char const*             name,
    SlangProfileID          profile)
{
    if(!request) return -1;
    auto req = REQ(request);
    if(!name) return -1;
    if(translationUnitIndex < 0) return -1;
    if(translationUnitIndex >= req->Options.translationUnits.Count()) return -1;


    return req->addTranslationUnitEntryPoint(
        translationUnitIndex,
        name,
        Slang::Profile(Slang::Profile::RawVal(profile)));
}


// Compile in a context that already has its translation units specified
SLANG_API int spCompile(
    SlangCompileRequest*    request)
{
    auto req = REQ(request);

    int anyErrors = req->executeAPIActions();
    return anyErrors;
}

SLANG_API int
spGetDependencyFileCount(
    SlangCompileRequest*    request)
{
    if(!request) return 0;
    auto req = REQ(request);
    return req->mDependencyFilePaths.Count();
}

/** Get the path to a file this compilation dependend on.
*/
SLANG_API char const*
spGetDependencyFilePath(
    SlangCompileRequest*    request,
    int                     index)
{
    if(!request) return 0;
    auto req = REQ(request);
    return req->mDependencyFilePaths[index].begin();
}

SLANG_API int
spGetTranslationUnitCount(
    SlangCompileRequest*    request)
{
    auto req = REQ(request);
    return req->mResult.translationUnits.Count();
}

// Get the output code associated with a specific translation unit
SLANG_API char const* spGetTranslationUnitSource(
    SlangCompileRequest*    request,
    int                     translationUnitIndex)
{
    auto req = REQ(request);
    return req->mResult.translationUnits[translationUnitIndex].outputSource.Buffer();
}

SLANG_API char const* spGetEntryPointSource(
    SlangCompileRequest*    request,
    int                     translationUnitIndex,
    int                     entryPointIndex)
{
    auto req = REQ(request);
    return req->mResult.translationUnits[translationUnitIndex].entryPoints[entryPointIndex].outputSource.Buffer();

}

// Reflection API

SLANG_API SlangReflection* spGetReflection(
    SlangCompileRequest*    request)
{
    if( !request ) return 0;

    auto req = REQ(request);
    return (SlangReflection*) req->mReflectionData.Ptr();
}


// ... rest of reflection API implementation is in `Reflection.cpp`