summaryrefslogtreecommitdiff
path: root/source/slang/slang-serialize-ast.cpp
blob: 3a2d3818eca098bc10d73f2cee4b6fd05478af83 (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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
// slang-serialize-ast.cpp
#include "slang-serialize-ast.h"

#include "slang-ast-dispatch.h"
#include "slang-compiler.h"
#include "slang-diagnostics.h"
#include "slang-mangle.h"
#include "slang-serialize-riff.h"

namespace Slang
{
// TODO(tfoley): have the parser export this, or a utility function
// for initializing a `SyntaxDecl` in the common case.
//
NodeBase* parseSimpleSyntax(Parser* parser, void* userData);

//
// Many of the types used in the AST can be serialized using
// just the `Serializer` type, so we will handle all of those first.
//

void serialize(Serializer const& serializer, ASTNodeType& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, TypeTag& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, BaseType& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, TryClauseType& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, DeclVisibility& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, BuiltinRequirementKind& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, ImageFormat& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, PreferRecomputeAttribute::SideEffectBehavior& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, TreatAsDifferentiableExpr::Flavor& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, LogicOperatorShortCircuitExpr::Flavor& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, RequirementWitness::Flavor& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, CapabilityAtom& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, DeclAssociationKind& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, TokenType& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, ValNodeOperandKind& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, SPIRVAsmOperand::Flavor& value)
{
    serializeEnum(serializer, value);
}

void serialize(Serializer const& serializer, SlangLanguageVersion version)
{
    serializeEnum(serializer, version);
}

void serialize(Serializer const& serializer, MatrixCoord& value)
{
    SLANG_SCOPED_SERIALIZER_TUPLE(serializer);
    serialize(serializer, value.row);
    serialize(serializer, value.col);
}

void serializePtr(Serializer const& serializer, DiagnosticInfo const*& value, DiagnosticInfo const*)
{
    Int32 id = 0;
    if (isWriting(serializer))
    {
        id = value->id;
        serialize(serializer, id);
    }
    else
    {
        serialize(serializer, id);
        value = getDiagnosticsLookup()->getDiagnosticById(id);
    }
}

void serialize(Serializer const& serializer, SemanticVersion& value)
{
    auto raw = value.getRawValue();
    serialize(serializer, raw);
    value = SemanticVersion::fromRaw(raw);
}

void serialize(Serializer const& serializer, SyntaxClass<NodeBase>& value)
{
    ASTNodeType raw;
    if (isWriting(serializer))
    {
        raw = value.getTag();
    }
    serialize(serializer, raw);
    if (isReading(serializer))
    {
        value = SyntaxClass<NodeBase>(raw);
    }
}

//
// Many types in the AST need additional context (beyond
// what the `Serializer` has) in order to serialize
// themselves or their members.
//
// We define a custom serializer interface to capture
// the cases that can't be handled by a `Serializer`
// alone.
//

/// Interface for AST serialization
struct ASTSerializerImpl
{
public:
    virtual void handleASTNode(NodeBase*& value) = 0;
    virtual void handleASTNodeContents(NodeBase* value) = 0;
    virtual void handleName(Name*& value) = 0;
    virtual void handleSourceLoc(SourceLoc& value) = 0;
    virtual void handleToken(Token& value) = 0;

    // Note that this type does *not* inherit from `ISerializerImpl`.
    //
    // We want to decouple the AST-specific context information
    // from the lower-level details of the serialization format.
    //
    // Instead of using inheritance, we expect that any
    // `ASTSerializerImpl` will aggregate a lower-level
    // serializer, and the interface exposes access to
    // that base serializer implementation.

    virtual ISerializerImpl* getBaseSerializer() = 0;
};

/// Specialization of `Serializer_` for AST serialization.
template<>
struct Serializer_<ASTSerializerImpl> : SerializerBase<ASTSerializerImpl>
{
public:
    using SerializerBase::SerializerBase;

    //
    // In order to allow an `ASTSerializer` to be used with
    // functions that expect an ordinary `Serializer`, we
    // implement an implicit conversion operator.
    //

    operator Serializer() const { return Serializer(get()->getBaseSerializer()); }
};

/// Context type for AST serialization.
using ASTSerializer = Serializer_<ASTSerializerImpl>;

template<typename T>
void serializeObject(ASTSerializer const& serializer, T*& value, NodeBase*)
{
    SLANG_SCOPED_SERIALIZER_STRUCT(serializer);
    serializer->handleASTNode(*(NodeBase**)&value);
}

void serializeObjectContents(ASTSerializer const& serializer, NodeBase* value, NodeBase*)
{
    serializer->handleASTNodeContents(value);
}

template<typename T>
void serialize(ASTSerializer const& serializer, DeclRef<T>& value)
{
    serialize(serializer, value.declRefBase);
}

void serialize(ASTSerializer const& serializer, SourceLoc& value)
{
    serializer->handleSourceLoc(value);
}

void serialize(ASTSerializer const& serializer, RequirementWitness& value)
{
    SLANG_SCOPED_SERIALIZER_TAGGED_UNION(serializer);
    serialize(serializer, value.m_flavor);
    switch (value.m_flavor)
    {
    case RequirementWitness::Flavor::none:
        break;

    case RequirementWitness::Flavor::declRef:
        serialize(serializer, value.m_declRef);
        break;

    case RequirementWitness::Flavor::val:
        serialize(serializer, value.m_val);
        break;

    case RequirementWitness::Flavor::witnessTable:
        serialize(serializer, value.m_obj);
        break;
    }
}

void serialize(ASTSerializer const& serializer, WitnessTable& value)
{
    SLANG_SCOPED_SERIALIZER_STRUCT(serializer);
    serialize(serializer, value.baseType);
    serialize(serializer, value.witnessedType);
    serialize(serializer, value.isExtern);

    // TODO(tfoley): In theory we should be able to streamline
    // this so that we only encode the requirements that we
    // absolutely need to (which basically amounts to `associatedtype`
    // requirements where the satisfying type is part of the public
    // API of the type).
    //
    serialize(serializer, value.m_requirementDictionary);
}

void serialize(Serializer const& serializer, CapabilityAtomSet& value)
{
    SLANG_SCOPED_SERIALIZER_ARRAY(serializer);
    if (isWriting(serializer))
    {
        for (auto rawAtom : value)
        {
            auto atom = CapabilityAtom(rawAtom);
            serialize(serializer, atom);
        }
    }
    else
    {
        while (hasElements(serializer))
        {
            CapabilityAtom atom;
            serialize(serializer, atom);
            value.add(UInt(atom));
        }
    }
}

void serialize(Serializer const& serializer, CapabilityStageSet& value)
{
    serialize(serializer, value.atomSet);
}

void serialize(Serializer const& serializer, CapabilityTargetSet& value)
{
    serialize(serializer, value.shaderStageSets);

    // The value for each entry in `shaderStageSets` have
    // a `stage` field that is redundant with the key for
    // that entry. Rather than serialize the key as part
    // of the `CapabilityStageSet` type, we instead copy
    // it over from the key to the value in the case where
    // we are reading.
    //
    if (isReading(serializer))
    {
        for (auto& p : value.shaderStageSets)
            p.second.stage = p.first;
    }
}

void serialize(Serializer const& serializer, CapabilitySet& value)
{
    serialize(serializer, value.getCapabilityTargetSets());

    // The value for each entry in `getCapabilityTargetSets()` have
    // a `target` field that is redundant with the key for
    // that entry. Rather than serialize the key as part
    // of the `CapabilityTargetSet` type, we instead copy
    // it over from the key to the value in the case where
    // we are reading.
    //
    if (isReading(serializer))
    {
        for (auto& p : value.getCapabilityTargetSets())
            p.second.target = p.first;
    }
}

void serialize(ASTSerializer const& serializer, CandidateExtensionList& value)
{
    serialize(serializer, value.candidateExtensions);
}

void serialize(ASTSerializer const& serializer, DeclAssociation& value)
{
    SLANG_SCOPED_SERIALIZER_STRUCT(serializer);
    serialize(serializer, value.kind);
    serialize(serializer, value.decl);
}

void serialize(ASTSerializer const& serializer, DeclAssociationList& value)
{
    serialize(serializer, value.associations);
}

void serialize(ASTSerializer const& serializer, Modifiers& value)
{
    SLANG_SCOPED_SERIALIZER_ARRAY(serializer);
    if (isWriting(serializer))
    {
        for (auto modifier : value)
        {
            serialize(serializer, modifier);
        }
    }
    else
    {
        Modifier** link = &value.first;

        while (hasElements(serializer))
        {
            Modifier* modifier = nullptr;
            serialize(serializer, modifier);

            *link = modifier;
            link = &modifier->next;
        }
    }
}

void serialize(ASTSerializer const& serializer, TypeExp& value)
{
    serialize(serializer, value.type);
}

void serialize(ASTSerializer const& serializer, QualType& value)
{
    SLANG_SCOPED_SERIALIZER_STRUCT(serializer);
    serialize(serializer, value.type);
    serialize(serializer, value.isLeftValue);
    serialize(serializer, value.hasReadOnlyOnTarget);
    serialize(serializer, value.isWriteOnly);
}

void serialize(ASTSerializer const& serializer, Token& value)
{
    serializer->handleToken(value);
}

void serialize(ASTSerializer const& serializer, SPIRVAsmOperand& value)
{
    SLANG_SCOPED_SERIALIZER_STRUCT(serializer);
    serialize(serializer, value.flavor);
    serialize(serializer, value.token);
    serialize(serializer, value.expr);
    serialize(serializer, value.bitwiseOrWith);
    serialize(serializer, value.knownValue);
    serialize(serializer, value.wrapInId);
    serialize(serializer, value.type);
}

void serialize(ASTSerializer const& serializer, SPIRVAsmInst& value)
{
    SLANG_SCOPED_SERIALIZER_STRUCT(serializer);
    serialize(serializer, value.opcode);
    serialize(serializer, value.operands);
}

void serialize(ASTSerializer const& serializer, ValNodeOperand& value)
{
    SLANG_SCOPED_SERIALIZER_TAGGED_UNION(serializer);
    serialize(serializer, value.kind);
    switch (value.kind)
    {
    case ValNodeOperandKind::ConstantValue:
        serialize(serializer, value.values.intOperand);
        break;

    case ValNodeOperandKind::ValNode:
    case ValNodeOperandKind::ASTNode:
        serialize(serializer, value.values.nodeOperand);
        break;
    }
}

void serializeObject(ASTSerializer const& serializer, Name*& value, Name*)
{
    serializer->handleName(value);
}

void serialize(ASTSerializer const& serializer, NameLoc& value)
{
    SLANG_SCOPED_SERIALIZER_STRUCT(serializer);
    serialize(serializer, value.name);
    serialize(serializer, value.loc);
}

#if 0 // FIDDLE TEMPLATE:
%for _,T in ipairs(Slang.NodeBase.subclasses) do
void _serializeASTNodeContents(ASTSerializer const& serializer, $T* value)
{
    SLANG_UNUSED(serializer);
    SLANG_UNUSED(value);
%   if T.directSuperClass then
    _serializeASTNodeContents(serializer, static_cast<$(T.directSuperClass)*>(value));
%   end
%   for _,f in ipairs(T.directFields) do
    serialize(serializer, value->$f);
%   end
        }
%end
#else // FIDDLE OUTPUT:
#define FIDDLE_GENERATED_OUTPUT_ID 0
#include "slang-serialize-ast.cpp.fiddle"
#endif // FIDDLE END

void serializeASTNodeContents(ASTSerializer const& serializer, NodeBase* node)
{
    ASTNodeDispatcher<NodeBase, void>::dispatch(
        node,
        [&](auto n) { _serializeASTNodeContents(serializer, n); });
}

enum class PseudoASTNodeType
{
    None,
    ImportedModule,
    ImportedDecl,
};

static PseudoASTNodeType _getPseudoASTNodeType(ASTNodeType type)
{
    return int(type) < 0 ? PseudoASTNodeType(~int(type)) : PseudoASTNodeType::None;
}

static ASTNodeType _getAsASTNodeType(PseudoASTNodeType type)
{
    return ASTNodeType(~int(type));
}

struct ASTEncodingContext : ASTSerializerImpl
{
public:
    ASTEncodingContext(
        RIFF::BuildCursor& cursor,
        ModuleDecl* module,
        SerialSourceLocWriter* sourceLocWriter)
        : _writer(cursor.getCurrentChunk()), _module(module), _sourceLocWriter(sourceLocWriter)
    {
    }

private:
    RIFFSerialWriter _writer;
    ModuleDecl* _module = nullptr;
    SerialSourceLocWriter* _sourceLocWriter = nullptr;

    virtual ISerializerImpl* getBaseSerializer() override { return &_writer; }

    virtual void handleName(Name*& value) override;
    virtual void handleSourceLoc(SourceLoc& value) override;
    virtual void handleToken(Token& value) override;
    virtual void handleASTNode(NodeBase*& node) override;
    virtual void handleASTNodeContents(NodeBase* node) override;

    void _writeImportedModule(ModuleDecl* moduleDecl);
    void _writeImportedDecl(Decl* decl, ModuleDecl* importedFromModuleDecl);

    ModuleDecl* _findModuleForDecl(Decl* decl)
    {
        for (auto d = decl; d; d = d->parentDecl)
        {
            if (auto m = as<ModuleDecl>(d))
                return m;
        }
        return nullptr;
    }

    ModuleDecl* _findModuleDeclWasImportedFrom(Decl* decl)
    {
        auto declModule = _findModuleForDecl(decl);
        if (declModule == nullptr)
            return nullptr;
        if (declModule == _module)
            return nullptr;
        return declModule;
    }
};

struct ASTDecodingContext : ASTSerializerImpl
{
public:
    ASTDecodingContext(
        Linkage* linkage,
        ASTBuilder* astBuilder,
        DiagnosticSink* sink,
        RIFF::Chunk const* baseChunk,
        SerialSourceLocReader* sourceLocReader,
        SourceLoc requestingSourceLoc)
        : _linkage(linkage)
        , _astBuilder(astBuilder)
        , _sink(sink)
        , _sourceLocReader(sourceLocReader)
        , _requestingSourceLoc(requestingSourceLoc)
        , _riffReader(baseChunk)
    {
    }

private:
    Linkage* _linkage = nullptr;
    ASTBuilder* _astBuilder = nullptr;
    DiagnosticSink* _sink = nullptr;
    SerialSourceLocReader* _sourceLocReader = nullptr;
    SourceLoc _requestingSourceLoc;
    RIFFSerialReader _riffReader;

    virtual ISerializerImpl* getBaseSerializer() override { return &_riffReader; }

    virtual void handleName(Name*& value) override;
    virtual void handleSourceLoc(SourceLoc& value) override;
    virtual void handleToken(Token& value) override;
    virtual void handleASTNode(NodeBase*& outNode) override;
    virtual void handleASTNodeContents(NodeBase* node) override;

    ModuleDecl* _readImportedModule();
    NodeBase* _readImportedDecl();

    void _cleanUpASTNode(NodeBase* node)
    {
        if (auto expr = as<Expr>(node))
        {
            expr->checked = true;
        }
        else if (auto decl = as<Decl>(node))
        {
            decl->checkState = DeclCheckState::CapabilityChecked;

            if (auto genericDecl = as<GenericDecl>(node))
            {
                _assignGenericParameterIndices(genericDecl);
            }
            else if (auto syntaxDecl = as<SyntaxDecl>(node))
            {
                syntaxDecl->parseCallback = &parseSimpleSyntax;
                syntaxDecl->parseUserData = (void*)syntaxDecl->syntaxClass.getInfo();
            }
            else if (auto namespaceLikeDecl = as<NamespaceDeclBase>(node))
            {
                auto declScope = _astBuilder->create<Scope>();
                declScope->containerDecl = namespaceLikeDecl;
                namespaceLikeDecl->ownedScope = declScope;
            }
        }
    }

    void _assignGenericParameterIndices(GenericDecl* genericDecl)
    {
        int parameterCounter = 0;
        for (auto m : genericDecl->members)
        {
            if (auto typeParam = as<GenericTypeParamDeclBase>(m))
            {
                typeParam->parameterIndex = parameterCounter++;
            }
            else if (auto valParam = as<GenericValueParamDecl>(m))
            {
                valParam->parameterIndex = parameterCounter++;
            }
        }
    }
};

//
// We are matching up the corresponding `handle*()` operations from the
// `AST{Encoding|Decoding}Context` types here, so that it is easier
// to visually verify that they are serializing the same data with the
// same ordering.
//

//
// AST{Encoding|Decoding}Context::handleName()
//

void ASTEncodingContext::handleName(Name*& value)
{
    serialize(ASTSerializer(this), value->text);
}

void ASTDecodingContext::handleName(Name*& value)
{
    String text;
    serialize(ASTSerializer(this), text);
    value = _astBuilder->getNamePool()->getName(text);
}

//
// AST{Encoding|Decoding}Context::handleSourceLoc()
//

void ASTEncodingContext::handleSourceLoc(SourceLoc& value)
{
    ASTSerializer serializer(this);
    SLANG_SCOPED_SERIALIZER_OPTIONAL(serializer);
    if (_sourceLocWriter != nullptr)
    {
        auto rawValue = _sourceLocWriter->addSourceLoc(value);
        serialize(serializer, rawValue);
    }
}

void ASTDecodingContext::handleSourceLoc(SourceLoc& value)
{
    ASTSerializer serializer(this);
    SLANG_SCOPED_SERIALIZER_OPTIONAL(serializer);
    if (hasElements(serializer))
    {
        SerialSourceLocData::SourceLoc rawValue;
        serialize(serializer, rawValue);

        if (_sourceLocReader)
        {
            value = _sourceLocReader->getSourceLoc(rawValue);
        }
    }
}

//
// AST{Encoding|Decoding}Context::handleToken()
//

void ASTDecodingContext::handleToken(Token& value)
{
    ASTSerializer serializer(this);

    SLANG_SCOPED_SERIALIZER_STRUCT(serializer);
    serialize(serializer, value.type);
    serialize(serializer, value.loc);

    serialize(serializer, value.flags);

    {
        SLANG_SCOPED_SERIALIZER_OPTIONAL(serializer);
        if (hasElements(serializer))
        {
            String content;
            serialize(serializer, content);

            // An important note here is that we cannot just
            // call `value.setContent(...)` and pass in an
            // `UnownedStringSlice` of `content`, because the
            // `Token` will not take ownership of its own
            // textual content.
            //
            // Instead, we need to get the text we just loaded
            // into something that the `Token` can refer info,
            // and the easiest way to accomplish that is to
            // represent the text using a `Name`.
            //
            Name* name = _astBuilder->getNamePool()->getName(content);
            value.setName(name);
        }
    }
}

void ASTEncodingContext::handleToken(Token& value)
{
    ASTSerializer serializer(this);

    SLANG_SCOPED_SERIALIZER_STRUCT(serializer);
    serialize(serializer, value.type);
    serialize(serializer, value.loc);

    TokenFlags flags = TokenFlags(value.flags & ~TokenFlag::Name);
    serialize(serializer, flags);

    {
        SLANG_SCOPED_SERIALIZER_OPTIONAL(serializer);
        if (value.hasContent())
        {
            String content = value.getContent();
            serialize(serializer, content);
        }
    }
}

//
// AST{Encoding|Decoding}Context::handleASTNode()
//

void ASTEncodingContext::handleASTNode(NodeBase*& node)
{
    if (auto decl = as<Decl>(node))
    {
        if (auto importedFromModule = _findModuleDeclWasImportedFrom(decl))
        {
            if (decl == importedFromModule)
            {
                _writeImportedModule(importedFromModule);
                return;
            }
            else
            {
                _writeImportedDecl(decl, importedFromModule);
                return;
            }
        }
    }

    ASTSerializer serializer(this);

    if (auto val = as<Val>(node))
    {
        val = val->resolve();

        // On the reading side of things, sublcasses of `Val`
        // are deduplicated as part of creation, and will read the
        // operands out immediately, so we mirror that approach
        // on the writing side to make sure the code is consistent.
        //
        serialize(serializer, val->astNodeType);
        serialize(serializer, val->m_operands);
    }
    else
    {
        serialize(serializer, node->astNodeType);
        deferSerializeObjectContents(serializer, node);
    }
}

void ASTDecodingContext::handleASTNode(NodeBase*& outNode)
{
    ASTSerializer serializer(this);

    ASTNodeType typeTag;
    serialize(serializer, typeTag);
    switch (_getPseudoASTNodeType(typeTag))
    {
    default:
        break;

    case PseudoASTNodeType::ImportedModule:
        outNode = _readImportedModule();
        return;

    case PseudoASTNodeType::ImportedDecl:
        outNode = _readImportedDecl();
        return;
    }

    auto syntaxClass = SyntaxClass<NodeBase>(typeTag);
    if (syntaxClass.isSubClassOf<Val>())
    {
        // Subclasses of `Val` are deduplicated as part
        // of creation, so we need to read in their
        // operands before we can create them, rather
        // than allocating the object up front and
        // then deserializing its content into it later.

        ValNodeDesc desc;
        desc.type = syntaxClass;
        serialize(serializer, desc.operands);

        desc.init();

        auto node = _astBuilder->_getOrCreateImpl(std::move(desc));
        outNode = node;
    }
    else
    {
        auto node = syntaxClass.createInstance(_astBuilder);
        outNode = node;

        deferSerializeObjectContents(serializer, node);
    }
}

//
// AST{Encoding|Decoding}Context::handleASTNodeContents()
//

void ASTEncodingContext::handleASTNodeContents(NodeBase* node)
{
    ASTSerializer serializer(this);
    serializeASTNodeContents(serializer, node);
}

void ASTDecodingContext::handleASTNodeContents(NodeBase* node)
{
    ASTSerializer serializer(this);
    serializeASTNodeContents(serializer, node);

    _cleanUpASTNode(node);
}

//
// AST{Encoding|Decoding}Context::_{write|read}ImportedModule()
//

void ASTEncodingContext::_writeImportedModule(ModuleDecl* moduleDecl)
{
    ASTNodeType type = _getAsASTNodeType(PseudoASTNodeType::ImportedModule);
    auto moduleName = moduleDecl->getName();

    ASTSerializer serializer(this);
    serialize(serializer, type);
    serialize(serializer, moduleName);
}

ModuleDecl* ASTDecodingContext::_readImportedModule()
{
    ASTSerializer serializer(this);

    Name* moduleName = nullptr;
    serialize(serializer, moduleName);
    auto module = _linkage->findOrImportModule(moduleName, _requestingSourceLoc, _sink);
    if (!module)
    {
        SLANG_ABORT_COMPILATION("failed to load an imported module during AST deserialization");
    }
    return module->getModuleDecl();
}

//
// AST{Encoding|Decoding}Context::_{write|read}ImportedModule()
//

void ASTEncodingContext::_writeImportedDecl(Decl* decl, ModuleDecl* importedFromModuleDecl)
{
    ASTNodeType type = _getAsASTNodeType(PseudoASTNodeType::ImportedDecl);
    auto mangledName = getMangledName(getCurrentASTBuilder(), decl);

    ASTSerializer serializer(this);
    serialize(serializer, type);
    serialize(serializer, importedFromModuleDecl);
    serialize(serializer, mangledName);
}

NodeBase* ASTDecodingContext::_readImportedDecl()
{
    ASTSerializer serializer(this);

    ModuleDecl* importedFromModuleDecl = nullptr;
    String mangledName;

    serialize(serializer, importedFromModuleDecl);
    serialize(serializer, mangledName);

    auto importedFromModule = importedFromModuleDecl->module;
    if (!importedFromModule)
    {
        return nullptr;
    }

    auto importedDecl =
        importedFromModule->findExportFromMangledName(mangledName.getUnownedSlice());
    if (!importedDecl)
    {
        SLANG_ABORT_COMPILATION(
            "failed to load an imported declaration during AST deserialization");
    }
    return importedDecl;
}

//
// {write|read}SerializedModuleAST()
//

void writeSerializedModuleAST(
    RIFF::BuildCursor& cursor,
    ModuleDecl* moduleDecl,
    SerialSourceLocWriter* sourceLocWriter)
{
    // TODO: we might want to have a more careful pass here,
    // where we only encode the public declarations.

    ASTEncodingContext context(cursor, moduleDecl, sourceLocWriter);
    serialize(ASTSerializer(&context), moduleDecl);
}

ModuleDecl* readSerializedModuleAST(
    Linkage* linkage,
    ASTBuilder* astBuilder,
    DiagnosticSink* sink,
    RIFF::Chunk const* chunk,
    SerialSourceLocReader* sourceLocReader,
    SourceLoc requestingSourceLoc)
{
    ASTDecodingContext
        context(linkage, astBuilder, sink, chunk, sourceLocReader, requestingSourceLoc);

    ModuleDecl* moduleDecl = nullptr;
    serialize(ASTSerializer(&context), moduleDecl);
    return moduleDecl;
}

} // namespace Slang