This repository was archived by the owner on Sep 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathGLSLParser.cxx
2513 lines (2189 loc) · 116 KB
/
GLSLParser.cxx
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//--------------------------------------------------------------
//
// Microsoft Edge Implementation
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files(the ""Software""),
// to deal in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
// OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//--------------------------------------------------------------
#include "PreComp.hxx"
#include "GLSLParser.hxx"
#include "IStringStream.hxx"
#include "RefCounted.hxx"
#include "ParseTree.hxx"
#include "SamplerCollectionNode.hxx"
#include "GLSLUnicodeConverter.hxx"
#include "GLSLPreprocess.hxx"
#include "GLSLStreamParserInput.hxx"
#include "GLSLStringParserInput.hxx"
#include "KnownSymbols.hxx"
#include "FeatureControlHelper.hxx"
#include "WebGLConstants.hxx"
#include "DeclarationSamplerNodeWrapper.hxx"
#include "ParameterSamplerNodeWrapper.hxx"
#include "StructSpecifierCollectionNode.hxx"
#include "StructGLSLType.hxx"
#include "TypeNameIdentifierInfo.hxx"
#include "ArrayGLSLType.hxx"
#pragma warning(disable:28718)
#include "lex.GLSL.h"
#pragma warning(default:28718)
const UINT CGLSLParser::s_uMaxShaderSize = 131072; // Maximum size of input to GLSL parser
const char* CGLSLParser::s_pszMaxShaderSizeString = "131072"; // Max size as string
const YYLTYPE CGLSLParser::s_nullLocation = {0}; // Placeholder location for generated parse tree nodes
//+----------------------------------------------------------------------------
//
// Function: Constructor
//
//-----------------------------------------------------------------------------
CGLSLParser::CGLSLParser() :
_realLine(1),
_logicalLine(1),
_column(1),
_shaderType(GLSLShaderType::Vertex),
_currentScopeId(1), // Root scope is always has the 0 id
_generatedIdentifierId(0),
_fErrors(false),
_fWriteInputs(false),
_fWriteBoilerPlate(true),
_uFeaturesUsed(0),
_glFeatureLevel(WebGLFeatureLevel::Level_9_1),
_fHasNonConstGlobalInitializers(false)
{
}
//+----------------------------------------------------------------------------
//
// Function: Initialize
//
// Synopsis: Initialize the tokenizer and make our copy of the input.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLParser::Initialize(
__in BSTR bstrInput, // Input unicode text of shader
GLSLShaderType::Enum shaderType, // Type of shader to translate
UINT uOptions, // Translation options
WebGLFeatureLevel glFeatureLevel // Feature level to translate for
)
{
CHK_START;
_shaderType = shaderType;
_fWriteInputs = (uOptions & GLSLTranslateOptions::DisableWriteInputs) == 0;
_fWriteBoilerPlate = (uOptions & GLSLTranslateOptions::DisableBoilerPlate) == 0;
if ((uOptions & GLSLTranslateOptions::ForceFeatureLevel9) != 0)
{
_glFeatureLevel = WebGLFeatureLevel::Level_9_1;
}
else
{
_glFeatureLevel = glFeatureLevel;
}
CHK(RefCounted<CGLSLSymbolTable>::Create(/*out*/_spSymbolTable));
// Seed the symbol table with the known symbols so that the number of known symbols in
// the table is known. This is used to make the output of the variables more predictable.
for (int i = 0; i < GLSLSymbols::count; i++)
{
GLSLSymbols::Enum known = static_cast<GLSLSymbols::Enum>(i);
const GLSLSymbolInfo &info = GLSLKnownSymbols::GetKnownInfo<GLSLSymbolInfo>(known);
int symbolIndex;
CHK(_spSymbolTable->EnsureSymbolIndex(info._pGLSLName, &symbolIndex));
// Make sure that casting GLSL function enums to int gives its index, because we
// have code that makes use of this fact to do fast comparisons.
Assert(static_cast<int>(known) == symbolIndex);
}
// Create the object we will ultimately return back
CHK(RefCounted<CGLSLConvertedShader>::Create(/*out*/_spConverted));
// We need to convert to Ansi for our parser to work
TSmartPointer<CMemoryStream> spConvertedInput;
CHK(CGLSLUnicodeConverter::ConvertToAscii(bstrInput, &spConvertedInput));
// Preprocess the input - first make an input object from the converted input
TSmartPointer<CGLSLStreamParserInput> spPreprocessInput;
CHK(RefCounted<CGLSLStreamParserInput>::Create(spConvertedInput, /*out*/spPreprocessInput));
// Run the preprocessor
TSmartPointer<CMemoryStream> spPreprocessed;
if (SUCCEEDED(::GLSLPreprocess(spPreprocessInput, _spConverted, uOptions, shaderType, &spPreprocessed, &_spLineMap, &_spExtensionState)))
{
UINT uSize;
CHK(spPreprocessed->GetSize(&uSize));
if (uSize > s_uMaxShaderSize)
{
CHK(LogError(nullptr, E_GLSLERROR_SHADERTOOLONG, s_pszMaxShaderSizeString));
}
else
{
// Make an input object from the preprocessor output
CHK(RefCounted<CGLSLStreamParserInput>::Create(spPreprocessed, /*out*/_spInput));
// Before we start, check the line map so that a #line on the first line will have the right effect
_spLineMap->AdjustLogicalLine(_realLine, &_logicalLine);
// Kick off the parser
yyscan_t scanner;
GLSLlex_init(&scanner);
GLSLset_extra(this, scanner);
GLSLparse(scanner);
GLSLlex_destroy(scanner);
}
}
else
{
// The preprocessor should have tried to log errors for us
_fErrors = true;
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: NotifyError
//
// Synopsis: Method called when GLSLerror happens, which is essentially
// used for syntax errors or other rare errors that Bison will
// report.
//
// Verification failures will report directly to LogError.
//
//-----------------------------------------------------------------------------
void CGLSLParser::NotifyError(__in YYLTYPE* pLocation, __in_z const char* error)
{
if (strcmp(error, "memory exhausted") == 0)
{
// Report stack exhaustion as shader complexity error. This is the same
// error that we report if we detect the max depth of the parse tree
// has been exceeded.
LogError(pLocation, E_GLSLERROR_SHADERCOMPLEXITY, nullptr);
}
else
{
// Anything besides stack exhaustion will be reported as a syntax error.
LogError(pLocation, E_GLSLERROR_SYNTAXERROR, error);
}
}
//+----------------------------------------------------------------------------
//
// Function: UpdateLocation
//
// Synopsis: Called to pass along location information.
//
//-----------------------------------------------------------------------------
void CGLSLParser::UpdateLocation(__in YYLTYPE* pLocation, int lineNo, int tokenLength)
{
pLocation->first_line = pLocation->last_line = _logicalLine;
pLocation->first_column = _column;
pLocation->last_column = _column + tokenLength - 1;
_column += tokenLength;
}
//+----------------------------------------------------------------------------
//
// Function: RecordNewline
//
// Synopsis: Called when encountering a newline. This resets the column
// location counter, and increments the line counters.
//
//-----------------------------------------------------------------------------
void CGLSLParser::RecordNewline()
{
// Reset column counter and increment line counter
_realLine++;
_logicalLine++;
// Adjust the logical line based on the line map
_spLineMap->AdjustLogicalLine(_realLine, &_logicalLine);
_column = 1;
}
//+----------------------------------------------------------------------------
//
// Function: TranslateTree
//
// Synopsis: Function called on an assumed correctly built tree to do
// translation to HLSL.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLParser::TranslateTree(
bool fWriteInputs, // Flag used in testing to suppress input structures from output
__deref_out CMemoryStream** ppConverted // Stream with converted HLSL
)
{
CHK_START;
// We need to make sure we even have a root node - if not, then the parser failed in
// some fundamental way and we should not be here.
Assert(_spRootNode != nullptr);
CHKB(_spRootNode != nullptr);
TSmartPointer<CMemoryStream> spConvertedStream;
CHK(RefCounted<CMemoryStream>::Create(/*out*/spConvertedStream));
// Initialize the identifier table
CHK(RefCounted<CGLSLIdentifierTable>::Create(this, /*out*/_spIdTable));
// Give it to the converted shader
_spConverted->SetIdentifierTable(_spIdTable);
// Do the type verification pass
CHK(_spRootNode->VerifyNode());
// Verify the inputs
CHK(VerifyInputs());
// Now that everything has passed verification, we do various transformations. The order
// of these is important, because some of them transform stuff done in previous stages.
// For example, we move short-circuit initializer expressions before ensuring short-cirtuiting
// is respected and thus don't have to worry about doing so in the global scope.
if (_fHasNonConstGlobalInitializers)
{
CHK(TranslateGlobalDeclarations());
}
CHK(TranslateStructDeclarations());
CHK(TranslateShortCircuitExpressions());
// Translate the samplers
CHK(TranslateSamplers());
if (fWriteInputs)
{
// Output the HLSL inputs
CHK(TranslateInputs(spConvertedStream));
}
#if DBG
// Translation has been completed. At this point all nodes in the tree must be verified
_spRootNode->AssertSubtreeFullyVerified();
#endif
// Start at the root and work down...
CHK(_spRootNode->OutputHLSL(spConvertedStream));
(*ppConverted) = spConvertedStream.Extract();
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: TranslateGlobalDeclarations
//
// Synopsis: Global declarations that have initializer expressions can
// depend on shader input variables (GLSL: attribute/varying,
// HLSL: vsInput/psInput). In HLSL, vsInput and psInput are only
// accessible as passed parameters to the entry point function.
// We immediately assign these parameters to a static global as
// the first thing in main() (see WriteEntryPointBegin) but if
// global variables depend on these values, they must not be
// initialized until after this happens. In order to facilitate
// this we perform the following steps:
// 1.) generate a function that is declared just before the
// entry point and defined at the very end of the shader
// 2.) move all global initializer expressions into assignment
// statements inside that function definition
// 3.) call this initialization function as the first statement
// in main() which will then execute after the shader
// input variables are correctly initialized.
//
//+----------------------------------------------------------------------------
HRESULT CGLSLParser::TranslateGlobalDeclarations()
{
CHK_START;
// Before we do this translation, we need to figure out the entry point function
// where we're going to inject the function call statement. This could potentially
// be null if there are no functions, and will be the last function in the shader
// if main() is not defined (this is mainly for testability in our unit tests).
TSmartPointer<FunctionDefinitionNode> spEntryPoint;
CHK(DetermineEntryPoint(&spEntryPoint));
if (spEntryPoint != nullptr)
{
TSmartPointer<FunctionPrototypeDeclarationNode> spGlobalInitializerFunctionDeclaration;
TSmartPointer<FunctionDefinitionNode> spGlobalInitializerFunctionDefinition;
int iFunctionIdent;
TSmartPointer<CollectionNode> spFunctionDefinitionStatementList;
CHK(GenerateFunctionDeclarationAndDefinition(
&spGlobalInitializerFunctionDeclaration,
&spGlobalInitializerFunctionDefinition,
&iFunctionIdent,
&spFunctionDefinitionStatementList
));
CHK(MoveGlobalInitializersIntoStatementList(spFunctionDefinitionStatementList));
// Insert the init function declaration just before the entry point function definition;
CHK(_spRootNode->InsertBefore(spGlobalInitializerFunctionDeclaration, spEntryPoint));
// Insert the init function definition at the end of the shader (append as a child to root node)
CHK(_spRootNode->AppendChild(spGlobalInitializerFunctionDefinition));
// ...and verify the nodes once they are attached
requires(SUCCEEDED(spGlobalInitializerFunctionDeclaration->VerifyNode()));
requires(SUCCEEDED(spGlobalInitializerFunctionDefinition->VerifyNode()));
// Last step is to call the function at the beginning of the entry point.
CHK(AddFunctionCallToEntryPointBegin(spEntryPoint, iFunctionIdent));
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: MoveGlobalInitializersIntoStatementList
//
// Synopsis: Iterates through each declaration in the global scope and moves
// any non-const initializer expressions into the passed in
// statement list. Performs this move by cloning the identifier of
// the entry being intialized and constructing an assignment
// statement that is put into the statement list.
//
//+----------------------------------------------------------------------------
HRESULT CGLSLParser::MoveGlobalInitializersIntoStatementList(__in CollectionNode* pStatementList)
{
CHK_START;
requires(_fHasNonConstGlobalInitializers);
for (UINT i = 0; i < _spRootNode->GetChildCount(); i++)
{
ParseTreeNode* pChild = _spRootNode->GetChild(i);
if (pChild->GetParseNodeType() == ParseNodeType::initDeclaratorList)
{
InitDeclaratorListNode* pInitDeclList = pChild->GetAs<InitDeclaratorListNode>();
if (pInitDeclList->GetTypeQualifier() != CONST_TOK)
{
// For each non-const declaration, look at each decl entry for non-const initializer expressions
for (UINT j = 0; j < pInitDeclList->GetIdentifierCount(); j++)
{
InitDeclaratorListEntryNode* pEntry = pInitDeclList->GetEntry(j);
if (pEntry->GetDeclarationType() == DeclarationType::initialized)
{
TSmartPointer<ParseTreeNode> spInitializer(pEntry->GetInitializerNode());
bool fIsConstInitializer;
CHK(spInitializer->IsConstExpression(false, &fIsConstInitializer, nullptr));
if (!fIsConstInitializer)
{
// For each one that is initialized, clone the variable id node, and generate
// an assigment statement to append to the statement list.
TSmartPointer<ParseTreeNode> spClonedIdentifier;
CHK(pEntry->GetIdentifierNode()->Clone(&spClonedIdentifier));
pEntry->ExtractInitializer(spInitializer);
TSmartPointer<ParseTreeNode> spAssignStatement;
CHK(GenerateAssignmentStatement(spInitializer, spClonedIdentifier->GetAs<VariableIdentifierNode>(), &spAssignStatement));
CHK(pStatementList->AppendChild(spAssignStatement));
}
}
}
}
}
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: AddFunctionCallToEntryPointBegin
//
// Synopsis: Given an entry point function definition and a symbol of a
// function to call, adds a function call to that function as
// the first statement in the function body's statement list.
//
//+----------------------------------------------------------------------------
HRESULT CGLSLParser::AddFunctionCallToEntryPointBegin(
const FunctionDefinitionNode* pEntryPoint, // The entry point function definition where the function call statement should be added
int iFunctionIdent // The identifier of the function to call
)
{
CHK_START;
// Create the nodes that correspond with a function call
TSmartPointer<FunctionCallIdentifierNode> spFunctionCallIdentifier;
CHK(RefCounted<FunctionCallIdentifierNode>::Create(this, iFunctionIdent, s_nullLocation, /*out*/spFunctionCallIdentifier));
TSmartPointer<FunctionCallHeaderNode> spFunctionCallHeader;
CHK(RefCounted<FunctionCallHeaderNode>::Create(this, spFunctionCallIdentifier, /*out*/spFunctionCallHeader));
TSmartPointer<FunctionCallHeaderWithParametersNode> spFunctionCallHeaderWithParams;
CHK(RefCounted<FunctionCallHeaderWithParametersNode>::Create(this, spFunctionCallHeader, /*noargs*/nullptr, s_nullLocation, /*out*/spFunctionCallHeaderWithParams));
TSmartPointer<FunctionCallGenericNode> spFunctionCallGeneric;
CHK(RefCounted<FunctionCallGenericNode>::Create(this, spFunctionCallHeaderWithParams, /*out*/spFunctionCallGeneric));
// Merge the function call into a statement
TSmartPointer<ExpressionStatementNode> spFunctionCallStatement;
CHK(RefCounted<ExpressionStatementNode>::Create(this, spFunctionCallGeneric, /*out*/spFunctionCallStatement));
CompoundStatementNode* pFunctionBody = pEntryPoint->GetFunctionBody()->GetAs<CompoundStatementNode>();
StatementListNode* pEntryPointStatementList = pFunctionBody->GetChild(0)->GetAs<StatementListNode>();
CHK(pEntryPointStatementList->InsertChild(spFunctionCallStatement, 0));
// All nodes are required to be verified before outputting their HLSL.
requires(SUCCEEDED(spFunctionCallStatement->VerifyNode()));
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: DetermineEntryPoint
//
// Synopsis: Determines the entry point function. This could potentially
// be null if there are no functions in the shader, and will be
// the last function in the shader if main() is not defined.
// For our unit tests, many do not define main() as that brings in
// a certain amount of boilerplate. Using a different function as
// the entry point helps us keep testability without forcing
// the test to have main() defined.
//
//+----------------------------------------------------------------------------
HRESULT CGLSLParser::DetermineEntryPoint(__deref_out_opt FunctionDefinitionNode** ppEntryPoint)
{
TSmartPointer<FunctionDefinitionNode> spFoundEntryPoint;
if (_spEntryPoint == nullptr)
{
// Function definitions can only happen in the global scope; look for them there.
for (UINT i = _spRootNode->GetChildCount(); i > 0; i--)
{
ParseTreeNode* pChild = _spRootNode->GetChild(i - 1);
if (pChild->GetParseNodeType() == ParseNodeType::functionDefinition)
{
spFoundEntryPoint = pChild->GetAs<FunctionDefinitionNode>();
break;
}
}
}
else
{
spFoundEntryPoint = _spEntryPoint;
}
*ppEntryPoint = spFoundEntryPoint.Extract();
return S_OK;
}
//+----------------------------------------------------------------------------
//
// Function: Translate
//
// Synopsis: Outputs HLSL from the parsed tree into the member stream.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLParser::Translate(
__deref_out CGLSLConvertedShader** ppConvertedShader // Converted shader object
)
{
CHK_START;
// If no errors were found until now, then try to do conversion to HLSL
TSmartPointer<CMemoryStream> spConvertedStream;
if (!_fErrors)
{
hr = TranslateTree(_fWriteInputs, &spConvertedStream);
if (SUCCEEDED(hr))
{
// Conversion has succeeded - store the output to return
_spConverted->SetConverterOutput(spConvertedStream, _spVaryingStructInfo);
}
else
{
if (hr != E_GLSLERROR_KNOWNERROR)
{
// We hit an error, but it was not something that was known
// and logged. We want to make sure that something is still logged
// to be somewhat helpful. Over time we should minimize this message
// because it is not very helpful to people.
CHK(LogError(nullptr, E_GLSLERROR_INTERNALERROR, nullptr));
}
// Eat the error
hr = S_OK;
// Now we should be in a state where we have errors to report, because
// all known errors should be logging and unknown errors record an
// internal error.
Assert(_fErrors);
}
}
_spConverted.CopyTo(ppConvertedShader);
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: AddDeclaratorList
//
// Synopsis: Called when declarator lists are instantiated in the tree to
// collect them here.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLParser::AddDeclaratorList(
InitDeclaratorListNode* pNewDecl // The declarator to add
)
{
return _aryDeclarations.Add(pNewDecl);
}
//+----------------------------------------------------------------------------
//
// Function: AddShortCircuitExpression
//
// Synopsis: Add to the global list of short circuit expressions. The only
// callers should be ConditionalExpressionNode::PreVerifyChildren
// and BinaryOperatorNode::PreVerifyChildren which guarantee these
// are added in execution order.
//
//+----------------------------------------------------------------------------
HRESULT CGLSLParser::AddShortCircuitExpression(
__in ParseTreeNode* pExpr // The expression to add
)
{
Assert(pExpr->IsShortCircuitExpression());
return _aryShortCircuitExprs.Add(pExpr);
}
//+----------------------------------------------------------------------------
//
// Function: SetEntryPointNode
//
// Synopsis: Sets a pointer to the definition of 'main()' on parser for
// quick access during translation.
//
//+----------------------------------------------------------------------------
void CGLSLParser::SetEntryPointNode(__in FunctionDefinitionNode* pEntryPoint)
{
Assert(_spEntryPoint == nullptr);
_spEntryPoint = pEntryPoint;
}
//+----------------------------------------------------------------------------
//
// Function: GenerateIdentifierNode
//
// Synopsis: Generates a Node of type T, assuming that T derives from
// IdentifierNodeBase and is initialized with a symbol index
// and location. We generate a reserved symbol (leading __) that
// ensures we don't have name collisions with existing GLSL
// identifiers.
//
//+----------------------------------------------------------------------------
template <typename T>
HRESULT CGLSLParser::GenerateIdentifierNode(__deref_out T** ppIdentifier)
{
CHK_START;
int iSymbolIndex;
CHK(GenerateIdentifierSymbol(&iSymbolIndex));
CHK(GenerateIdentifierNodeFromSymbol(iSymbolIndex, ppIdentifier));
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: GenerateIdentifierNodeFromSymbol
//
// Synopsis: Given a symbol index, generates an identifier node
//
//+----------------------------------------------------------------------------
template <typename T>
HRESULT CGLSLParser::GenerateIdentifierNodeFromSymbol(int iSymbolIndex, __deref_out T** ppIdentifier)
{
CHK_START;
TSmartPointer<T> spIdentifierNode;
CHK(RefCounted<T>::Create(this, iSymbolIndex, s_nullLocation, /*out*/spIdentifierNode));
// Mark the new identifier as being generated so verification code allows the leading
// underscores - this is normally rejected, which is why we can use it internally.
spIdentifierNode->SetIsGenerated();
*ppIdentifier = spIdentifierNode.Extract();
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: GenerateIdentifierSymbol
//
// Synopsis: Generates a glsl symbol index using our unique identifier id
// counter combined with the reserved "__tmp_" prefix.
//
//+----------------------------------------------------------------------------
HRESULT CGLSLParser::GenerateIdentifierSymbol(__out int* piIdentifier)
{
CHK_START;
CMutableString<char> spszReservedName;
CHK(spszReservedName.Format(20, "__tmp_%d", GenerateIdentifierId()));
CHK(_spSymbolTable->EnsureSymbolIndex(static_cast<const char*>(spszReservedName), piIdentifier));
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: GeneratePlaceholderDeclaration
//
// Synopsis: Generates a declaration for a placeholder variable that has the
// same type as the given expression. It performs this by creating
// the necessary bits to have a fully formed InitDeclaratorListNode.
// Use this method if you are moving an expression, and need to sub back
// in the result of the expression in the original location.
//
//+----------------------------------------------------------------------------
HRESULT CGLSLParser::GeneratePlaceholderDeclaration(
__in GLSLType* pExprType, // Type of an expression for which a placeholder variable needs to be generated
__in_opt ParseTreeNode* pInitializer, // Optional initializer to init the placeholder variable with
__deref_out InitDeclaratorListNode** ppInitDeclaratorListNode // The generated declaration. Must be verified after attaching to the tree for the variable to be considered as declared and in scope
)
{
CHK_START;
// Generate a reserved identifier node; this identifier will be used to declare the placeholder variable.
TSmartPointer<VariableIdentifierNode> spVariableIdent;
CHK(GenerateIdentifierNode(&spVariableIdent));
// Generate a fully specified type - the type is the type of the expression passed in, potentially with
// the arrayness stripped off (we handle the arrayness separately by creating an IntConstant for the array specification)
TSmartPointer<TypeSpecifierNode> spTypeSpecifierNode;
CHK(TypeSpecifierNode::CreateNodeFromType(this, pExprType, &spTypeSpecifierNode));
// The fully specified type has no qualifier - it is just a local variable.
TSmartPointer<ParseTreeNode> spFullySpecifiedType;
CHK(RefCounted<FullySpecifiedTypeNode>::Create(this, NO_QUALIFIER, spTypeSpecifierNode, /*out*/spFullySpecifiedType));
// If the type is an array type, we'll need an extra node to specify this in the InitDeclaratorListNode.
TSmartPointer<IntConstantNode> spIntConstant;
const bool fIsArrayType = pExprType->IsArrayType();
if (fIsArrayType)
{
CHK(RefCounted<IntConstantNode>::Create(this, pExprType->AsArrayType()->GetElementCount(), /*out*/spIntConstant));
}
// Generated nodes do not need a location for error reporting; we're past the point of verification now.
TSmartPointer<InitDeclaratorListNode> spInitDecl;
CHK(RefCounted<InitDeclaratorListNode>::Create(
this,
spFullySpecifiedType,
spVariableIdent,
s_nullLocation,
pInitializer,
spIntConstant,
/*out*/spInitDecl
));
*ppInitDeclaratorListNode = spInitDecl.Extract();
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: GenerateAssignmentStatement
//
// Synopsis: Given variable identifier info and an expression, generates
// a binaryoperator (with the assignment operator) that assigns
// to a VariableIdentifierNode (LHS) from the expression (RHS).
// The binaryoperator node is then used as an expression statement
// in a statement list node of a single statement.
//
//+----------------------------------------------------------------------------
HRESULT CGLSLParser::GenerateAssignmentStatement(
__in ParseTreeNode* pExpr, // Expression to assign from
__in VariableIdentifierNode* pPlaceholderVariable, // Variable used to assign the result of the expression into
__deref_out ParseTreeNode** ppAssignStatement // Generated assignment statement
)
{
CHK_START;
TSmartPointer<ParseTreeNode> spVariableIdent;
CHK(pPlaceholderVariable->Clone(&spVariableIdent));
TSmartPointer<BinaryOperatorNode> spBinaryOperator;
CHK(RefCounted<BinaryOperatorNode>::Create(this, spVariableIdent, pExpr, s_nullLocation, EQUAL, /*out*/spBinaryOperator));
// The type of this assignment may be an array type, which is normally rejected by
// BinaryOperatorNode at verification time. However, this must be allowed if we're
// translating ternary operators with expression array type and the translated HLSL
// will compile - tell the operator to allow this.
spBinaryOperator->SetAllowArrayAssignment();
TSmartPointer<ExpressionStatementNode> spExprStmt;
CHK(RefCounted<ExpressionStatementNode>::Create(this, spBinaryOperator, /*out*/spExprStmt));
*ppAssignStatement = spExprStmt.Extract();
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: ConvertShortCircuitToSelection
//
// Synopsis: Converts expressions that need to short circuit to selection
// statement (i.e. if/else). Used to ensure HLSL only executes
// the 'taken' branch of an expression.
//
// Conditional expressions (i.e. ternary) are converted as thus:
//
// (test) ? true : false
//
// is converted to
//
// if (test) { tmp = true; } else { tmp = false; }
//
// where tmp is described by pInfo.
//
// Logical expressions (&& and ||) are converted as using the
// following equivalences:
//
// A && B -> if (A) { tmp = B; } else { tmp = false; }
// A || B -> if (A) { tmp = true; } else { tmp = B; }
//
//+----------------------------------------------------------------------------
HRESULT CGLSLParser::ConvertShortCircuitToSelection(
__in ParseTreeNode* pExpr, // Short circuit expression to convert
__in VariableIdentifierNode* pPlaceholderVariable, // Variable used to assign the result of the expression into
__deref_out ParseTreeNode** ppSelectionConverted // Created SelectionStatement node
)
{
CHK_START;
TSmartPointer<ParseTreeNode> spTestExpr;
TSmartPointer<ParseTreeNode> spTrueExpr;
TSmartPointer<ParseTreeNode> spFalseExpr;
if (pExpr->GetParseNodeType() == ParseNodeType::conditionalExpression)
{
ConditionalExpressionNode* pCondExpr = pExpr->GetAs<ConditionalExpressionNode>();
// Extract the false and true branches, and the test expression in backwards order
// (extracting is a destructive operation which moves the indices).
CHK_VERIFY(SUCCEEDED(pCondExpr->ExtractChild(2, &spFalseExpr)));
CHK_VERIFY(SUCCEEDED(pCondExpr->ExtractChild(1, &spTrueExpr)));
CHK_VERIFY(SUCCEEDED(pCondExpr->ExtractChild(0, &spTestExpr)));
}
else if (pExpr->GetParseNodeType() == ParseNodeType::binaryOperator)
{
BinaryOperatorNode* pBinaryExpr = pExpr->GetAs<BinaryOperatorNode>();
// We only support these two operators here
Assert(pBinaryExpr->GetOperator() == AND_OP || pBinaryExpr->GetOperator() == OR_OP);
// Pull the left and right side out - use the left side of the expression as the test
TSmartPointer<ParseTreeNode> spRight;
CHK_VERIFY(SUCCEEDED(pBinaryExpr->ExtractChild(1, &spRight)));
CHK_VERIFY(SUCCEEDED(pBinaryExpr->ExtractChild(0, &spTestExpr)));
// Per the function header comment && and || are converted as using the
// following equivalences:
// A && B -> if (A) { tmp = B; } else { tmp = false; }
// A || B -> if (A) { tmp = true; } else { tmp = B; }
// Here we need to generate the bool constant for the simple
// 'tmp' assignments above. This constant value is 'true' for || and
// 'false' for &&.
const bool fBoolConstantValue = (pBinaryExpr->GetOperator() == OR_OP);
TSmartPointer<BoolConstantNode> spConstantNode;
CHK(RefCounted<BoolConstantNode>::Create(
this,
fBoolConstantValue,
/*out*/spConstantNode
));
if (pBinaryExpr->GetOperator() == AND_OP)
{
spTrueExpr = spRight;
spFalseExpr = spConstantNode;
}
else
{
spTrueExpr = spConstantNode;
spFalseExpr = spRight;
}
}
CHK(CreateSelectionFromParts(spTestExpr, spTrueExpr, spFalseExpr, pPlaceholderVariable, ppSelectionConverted));
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: CreateSelectionFromParts
//
// Synopsis: Create a selection (if / else) from three expressions and
// a temporary variable.
//
//+----------------------------------------------------------------------------
HRESULT CGLSLParser::CreateSelectionFromParts(
__in ParseTreeNode* pTestExpr, // Expression to test in if
__in ParseTreeNode* pTrueExpr, // What to do if true
__in ParseTreeNode* pFalseExpr, // What to do if false
__in VariableIdentifierNode* pPlaceholderVariable, // Variable used to assign the result of the expression into
__deref_out ParseTreeNode** ppSelectionConverted // Created SelectionStatement node
)
{
CHK_START;
// Next, assign both the true and false expressions to the passed in placeholder variable,
// and put the statements into a statement list. If there's a ternary inside either branch
// of this ternary we'll need an insertion point.
TSmartPointer<ParseTreeNode> spTrueStmt;
CHK(GenerateAssignmentStatement(pTrueExpr, pPlaceholderVariable, &spTrueStmt));
TSmartPointer<StatementListNode> spTrueStmtList;
CHK(RefCounted<StatementListNode>::Create(this, spTrueStmt, /*out*/spTrueStmtList));
TSmartPointer<ParseTreeNode> spFalseStmt;
CHK(GenerateAssignmentStatement(pFalseExpr, pPlaceholderVariable, &spFalseStmt));
TSmartPointer<StatementListNode> spFalseStmtList;
CHK(RefCounted<StatementListNode>::Create(this, spFalseStmt, /*out*/spFalseStmtList));
// For both true/false statements created above, create a scope around them
// which is required by the structure of SelectionRestStatementNode
TSmartPointer<ParseTreeNode> spTrueScopeStmt;
CHK(RefCounted<ScopeStatementNode>::Create(this, spTrueStmtList, /*out*/spTrueScopeStmt));
TSmartPointer<ParseTreeNode> spFalseScopeStmt;
CHK(RefCounted<ScopeStatementNode>::Create(this, spFalseStmtList, /*out*/spFalseScopeStmt));
TSmartPointer<ParseTreeNode> spSelectionRest;
CHK(RefCounted<SelectionRestStatementNode>::Create(this, spTrueScopeStmt, spFalseScopeStmt, /*out*/spSelectionRest));
TSmartPointer<ParseTreeNode> spSelectionStatement;
CHK(RefCounted<SelectionStatementNode>::Create(this, pTestExpr, spSelectionRest, s_nullLocation, /*out*/spSelectionStatement));
*ppSelectionConverted = spSelectionStatement.Extract();
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: TranslateShortCircuitExpressions
//
// Synopsis: Iterates through all the short circuit expressions
// that were verified and translates them to selection statements
// (if else). Along the way it will lift expressions that
// must execute before the ternary into expression statements of
// their own.
//
// Also handles the case where the expression is in a
// declaration (splits each declarator entry into it's own
// declaration). Potentially inserts the expressions into a
// function is the ternary is in a global declaration since we
// cannot execute code directly.
//
//+----------------------------------------------------------------------------
HRESULT CGLSLParser::TranslateShortCircuitExpressions()
{
CHK_START;
while (_aryShortCircuitExprs.GetCount() > 0)
{
TSmartPointer<ParseTreeNode> spCondExpr = _aryShortCircuitExprs[0];
_aryShortCircuitExprs.RemoveAt(0);
// This array will hold every expression that occurs 'before' (i.e. must be executed
// prior to) the current short circuit expression. This is in reverse order to simplify
// adding to it while walking up the tree.
CModernArray<TSmartPointer<ParseTreeNode>> aryOrderedExpressionsToMove;
// Add the short circuit expression as the last expression to be moved.
CHK(aryOrderedExpressionsToMove.Add(spCondExpr));
ParseTreeNode* pChild = spCondExpr;
CollectionNode* pParent = pChild->GetParent();
while (pParent != nullptr)
{
if (IsValidExpressionInsertionPoint(pParent))
{
// At this point we've gathered all the nodes that must be executed before the
// short circuit expression we're concerned with. We want to have the gathered
// ordered expressions execute before the branch of the short circuit expression
// so that they executed before it.
CHK(MoveExpressionsToInsertionPoint(pParent, pChild, aryOrderedExpressionsToMove));
// Once the expressions have successfully been moved, we're done with this
break;
}
// As we're walking up the tree, some GLSL nodes require their expression
// children to be executed in order, left-to-right. If we encounter one of
// these nodes, we'll ensure that we either modify the parse tree to keep
// that invariant, or we'll gather the expressions so that we can ensure they
// execute before the ternary expression that we are planning on moving.
if (ParseTreeNode::RequiresOrderedExpressionExecution(pParent))
{
// Variable declarations are handled separately - each entry has
// the effect of declaring the variable identifier (along with whatever
// side effects are caused by the initializer expression). Because of this
// we will actually split the declaration into multiple statements.
if (pParent->GetParseNodeType() == ParseNodeType::initDeclaratorList)
{
CHK(FixupDeclarationForShortCircuiting(pParent->GetAs<InitDeclaratorListNode>(), pChild));
}
else
{
// Non-declarations requiring ordered execution are added to our list of expressions to move
CHK(ParseTreeNode::GatherPreviousSiblingExpressions(pParent, pChild, aryOrderedExpressionsToMove));
}
}
pChild = pParent;
pParent = pParent->GetParent();
}
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: IsValidExpressionInsertionPoint
//
// Synopsis: Returns true when we've encountered a parent node that we
// can determine an insertion point from. Because we move all
// non-const global initializers into a statement list inside
// a function, only statementLists are valid insertion points.
//
//+----------------------------------------------------------------------------
bool CGLSLParser::IsValidExpressionInsertionPoint(__in CollectionNode* pParent)
{
return pParent->GetParseNodeType() == ParseNodeType::statementList;
}