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 pathGLSLPreParser.cxx
1364 lines (1179 loc) · 45.8 KB
/
GLSLPreParser.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 "GLSLPreParser.hxx"
#include "MemoryStream.hxx"
#include "RefCounted.hxx"
#include "GLSLPreExpandBuffer.hxx"
#include "GLSLUnicodeConverter.hxx"
#include "GLSLTranslateOptions.hxx"
#include "WebGLConstants.hxx"
#pragma warning(disable:28718)
#define YY_HEADER_EXPORT_START_CONDITIONS
#include "lex.pre.h"
//+----------------------------------------------------------------------------
//
// Function: Constructor
//
//-----------------------------------------------------------------------------
CGLSLPreParser::CGLSLPreParser() :
_scanner(nullptr),
_realLine(1),
_logicalLine(1),
_logicalFile(0),
_column(1),
_fErrors(false),
_commentCondition(INITIAL),
_lineSymbol(-1),
_fProcessedStatement(false),
_fNonWhitespaceOnLine(false)
{
}
//+----------------------------------------------------------------------------
//
// Function: Initialize
//
// Synopsis: Initialize the tokenizer and make our copy of the input.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::Initialize(
__in IParserInput* pInput, // Input to preprocess
__in IErrorSink* pErrorSink, // Where to store errors if you have them
UINT uOptions, // Translation options
GLSLShaderType::Enum shaderType // Type of shader
)
{
CHK_START;
_spInput = pInput;
_spErrorSink = pErrorSink;
// Set up the symbol table
CHK(RefCounted<CGLSLSymbolTable>::Create(/*out*/_spSymbolTable));
// Create a line map object
CHK(RefCounted<CGLSLLineMap>::Create(/*out*/_spLineMap));
// Add builtin definitions
CHK(AddDefinition("GL_ES", "1", nullptr));
CHK(AddDefinition("__VERSION__", "100", nullptr));
CHK(AddDefinition("__LINE__", "0", &_lineSymbol));
CHK(AddDefinition("__FILE__", "0", &_fileSymbol));
CHK(AddDefinition("GL_FRAGMENT_PRECISION_HIGH", "1", nullptr));
// Add extension information
CHK(RefCounted<CGLSLExtensionState>::Create(/*out*/_spExtensionState));
CHK(_spExtensionState->AddEntry(
GLSLExtension::all,
true, // all as an entry is supported
GLSLExtensionBehavior::disable // Spec says that disable all is initial starting point
));
if (shaderType == GLSLShaderType::Fragment)
{
bool fEnabled = (uOptions & GLSLTranslateOptions::EnableStandardDerivatives) != 0;
// Derivatives only in fragment shader
CHK(_spExtensionState->AddEntry(
GLSLExtension::GL_OES_standard_derivatives,
fEnabled,
GLSLExtensionBehavior::notSet
));
if (fEnabled)
{
CHK(AddDefinition("GL_OES_standard_derivatives", "1", nullptr));
}
fEnabled = (uOptions & GLSLTranslateOptions::EnableFragDepth) != 0;
// Fragment depth only in fragment shader
CHK(_spExtensionState->AddEntry(
GLSLExtension::GL_EXT_frag_depth,
fEnabled,
GLSLExtensionBehavior::notSet
));
if (fEnabled)
{
CHK(AddDefinition("GL_EXT_frag_depth", "1", nullptr));
}
}
// Create our output stream
CHK(RefCounted<CMemoryStream>::Create(/*out*/_spOutput));
// Initialize our allow stack to the initial state, which is passing code through
_conditionState._fAllowOutput = true;
// Create and kick off the scanner
GLSLPrelex_init(&_scanner);
GLSLPreset_extra(this, _scanner);
GLSLPreparse(_scanner);
// If we have more than one buffer left, then we should delete it. The macro
// expansion did not unroll naturally and the extra created buffers should be
// deleted.
while (SUCCEEDED(PopBufferState())) {}
GLSLPrelex_destroy(_scanner);
_scanner = nullptr;
// No errors allowed
CHKB(!_fErrors);
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: LogError
//
// Synopsis: Called to log specific errors when found during preprocessing.
//
// We set a boolean and we add to a list, because if we hit
// an out of memory error logging the error, we don't want to
// think that we had no errors.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::LogError(
__in_opt const YYLTYPE *pLocation, // Where the error occured
HRESULT hrCode, // The code for the error
__in_z_opt const char* pszErrorData // Optional string data
)
{
_fErrors = true;
return _spErrorSink->AddError(pLocation->first_line, pLocation->first_column, hrCode, pszErrorData);
}
//+----------------------------------------------------------------------------
//
// Function: NotifyError
//
// Synopsis: Method called when yyerror happens. Used to log the error.
//
//-----------------------------------------------------------------------------
void CGLSLPreParser::NotifyError(__in YYLTYPE* pLocation, __in_z_opt const char* pszError)
{
if (pszError == nullptr)
{
pszError = "Internal preprocessor error";
}
LogError(pLocation, E_GLSLERROR_SYNTAXERROR, pszError);
}
//+----------------------------------------------------------------------------
//
// Function: UpdateLocation
//
// Synopsis: Called to pass along location information.
//
//-----------------------------------------------------------------------------
void CGLSLPreParser::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: ProcessTextToken
//
// Synopsis: Called to process tokens that have not been deemed to be part
// of directing the preprocessor of what to do - these will end
// up accumulating somewhere and eventually form part of the
// output.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::ProcessTextToken(
__in_z char* pszText, // Token to process
int length, // Length of token
__in YYLTYPE* pLocation // Location of token
)
{
CHK_START;
// Restrict token length
CHK(VerifyTokenLength(length, pLocation));
if (!_fNonWhitespaceOnLine)
{
// Check if any non-whitespace was added
for (int i = 0; i < length; i++)
{
if (!CGLSLUnicodeConverter::IsWhitespaceChar(pszText[i]))
{
_fNonWhitespaceOnLine = true;
break;
}
}
}
if (_conditionState._fAllowOutput)
{
if (_paramStack.Size() == 0)
{
CHK(_spOutput->WriteString(pszText));
}
else
{
ParamState topState;
CHK(_paramStack.Top(topState));
CHK(topState._spParamList->AddToken(pszText));
}
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: EnsureSymbolIndex
//
// Synopsis: Wrapper for symbol table function that checks length.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::EnsureSymbolIndex(
__in_z char* pszName, // Name of symbol
int length, // Length of symbol
__in YYLTYPE* pLocation, // Location of symbol
__out int* pIndex // Index of symbol in table
)
{
CHK_START;
// Restrict token length
CHK(VerifyTokenLength(length, pLocation));
CHK(_spSymbolTable->EnsureSymbolIndex(pszName, pIndex));
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: VerifyTokenLength
//
// Synopsis: Verify that the token is not too long.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::VerifyTokenLength(
int length, // Length of text
__in YYLTYPE* pLocation // Location of text
)
{
CHK_START;
// Restrict token length
if (length > MAX_GLSL_TOKEN_SIZE)
{
CHK(LogError(pLocation, E_GLSLERROR_PREMAXTOKEN, nullptr));
CHK(E_GLSLERROR_KNOWNERROR);
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: GetMacroDefinition
//
// Synopsis: When an identifier token is encountered outside of a directive,
// it needs to be expanded if it maps to a macro definition.
//
// This method tests if the given identifier text maps to a macro.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::GetMacroDefinition(
__in_z char* pszText, // Text to test for being a macro
__deref_out CGLSLPreMacroDefinition** ppDefinition // Definition of that macro
)
{
CHK_START;
// See if we have a symbol - no symbol means no definition
int symIndex;
CHK(_spSymbolTable->LookupSymbolIndex(pszText, &symIndex));
// See if we have a definition
TSmartPointer<CGLSLPreMacroDefinition> spDefinition;
CHK(_rgDefinitions.FindDefinition(symIndex, /*index*/nullptr, &spDefinition));
// The line macro might be stale - update it
int identifierIndex = spDefinition->GetIdentifierIndex();
if (identifierIndex == _lineSymbol || identifierIndex == _fileSymbol)
{
CHK(spDefinition->SetToNumber((identifierIndex == _lineSymbol) ? _logicalLine : _logicalFile));
}
// If this definition is the one we are expanding, then pretend we could
// not find it. We need to check all the way up the chain because if you
// are two definitions deep, neither should expand themselves.
for (UINT i = 0; i < _bufferStack.Size(); i++)
{
if (_bufferStack.ItemRef(i)._spDefinition->GetIdentifierIndex() == symIndex)
{
CHK(E_INVALIDARG);
}
}
(*ppDefinition) = spDefinition.Extract();
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: PreProcessNewline
//
// Synopsis: Called in all conditions when a newline is encountered. The
// column counter is reset and the output is kept in sync with
// regard to line count.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PreProcessNewline()
{
CHK_START;
CHK(_spOutput->WriteChar('\n'));
// Reset column counter and increment line counter
_realLine++;
_logicalLine++;
_column = 1;
// _commentCondition is the condition that the lexer will return to when
// a C comment (/* */) ends. If we are preprocessing a newline, it means
// that any directive that was being processed has finished and when the
// comment ends, processing must resume at the initial condition.
//
// We only reset the comment condition for the case where we started inside
// of a directive. If we start inside of any other kind of condition, we
// must not modify states when we are done because we have a stack to
// deal with.
if (IsDirectiveCondition(_commentCondition))
{
_commentCondition = INITIAL;
}
// Reset non-whitespace flag since it is a per line flag
_fNonWhitespaceOnLine = false;
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: IsDirectiveCondition
//
// Synopsis: Returns true if the given lexer condition is one of the
// directive conditions.
//
//-----------------------------------------------------------------------------
bool CGLSLPreParser::IsDirectiveCondition(int cond)
{
return (
cond == EXPAND_DIR_COND ||
cond == NOEXPAND_DIR_COND ||
cond == DEF_DIR_COND ||
cond == DEF_DIR_PARAM_P_COND ||
cond == DEF_DIR_PARAM_I_COND ||
cond == DEF_DIR_PARAM_S_COND ||
cond == NOOUTPUT
);
}
//+----------------------------------------------------------------------------
//
// Function: PreProcessCommentText
//
// Synopsis: Called when C style comments are processed - the length
// indicates how many spaces to output to the stream.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PreProcessCommentText(int length)
{
CHK_START;
// We eat spaces while collecting parameters for macro expansion
// since we only preserve spaces to have accurate error positions, and
// expanding a macro ruins the error positions anyway.
//
// If there is a parameter stack, then we are processing parameters
// and we can give up on doing anything about comments.
if (_paramStack.Size() == 0)
{
// Don't output replacement spaces on a directive line if a comment started
// there. We want directive lines to be blank lines in the output. If the
// comment started on a directive condition it means that a comment
// has started and it is still on a directive line, and therefore we can
// eat these spaces.
if (!IsDirectiveCondition(_commentCondition))
{
for (int i = 0; i < length; i++)
{
CHK(_spOutput->WriteChar(' '));
}
}
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: PreIfImpl
//
// Synopsis: Contains the meat of the work to do ifdef / ifndef / if
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PreIfImpl(bool fVal)
{
CHK_START;
// Set the flag that a statement is being processed - conditional statements
// set through this path rather than using ProcessStatement() because they
// recursively have other statements inside. If conditional statements were
// to use ProcessStatement(), then the code would run after they process and
// not before, and it would not work correctly. Hence it is done here.
_fProcessedStatement = true;
// Push the old allow state to the stack so that we can restore it on the #endif
// for this directive. Even if we are not currently allowing code, we still have
// to have matching ifdef / endif statements.
//
// This is needed because later on, if an #else directive is encountered, we
// need to know what the state was before the #ifdef was encountered.
CHK(_conditionStack.Push(_conditionState));
// Reset whether the condition is met until we see it met somewhere
_conditionState._fConditionMet = false;
// If we are allowing code right now, then this new ifdef can alter our ability
// to allow output and we process it. If we are not allowing output right now,
// then another define cannot change that.
if (_conditionState._fAllowOutput)
{
// Whether we allow code to flow through depends on if the entry is defined
_conditionState._fAllowOutput = fVal;
if (fVal)
{
// If the value is met, then we found a true condition
_conditionState._fConditionMet = true;
}
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: PreIf
//
// Synopsis: If directives have an expression after them. We evaluate the
// expression and change the output allow appropriately.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PreIf(bool fExpr)
{
// based on the value of the expression, do the logic
return PreIfImpl(fExpr);
}
//+----------------------------------------------------------------------------
//
// Function: IsPreviousOutputAllowed
//
// Synopsis: Returns if the output was allowed before the current state
// was pushed.
//
//-----------------------------------------------------------------------------
bool CGLSLPreParser::IsPreviousOutputAllowed() const
{
ConditionState previousState;
if (SUCCEEDED(_conditionStack.Top(/*out*/previousState)))
{
return previousState._fAllowOutput;
}
else
{
// Incorrect usage of directives (like just starting your file with
// #elif) can cause this path to be hit. We are not really accurate
// with our return value here, but there will be a syntax error
// anyway.
return false;
}
}
//+----------------------------------------------------------------------------
//
// Function: PreElif
//
// Synopsis: Elif does the same thing as else + if, with the obvious caveat
// that an extra endif is not required.
//
// This makes it very similar to else, except instead of looking
// at the previous allow value to determine what to do, it also
// looks at the expression.
//
// Care must be taken to not go into multiple blocks - for
// example, this code:
//
// #if 1
// Line1
// #elif 1
// Line2
// #endif
//
// Should not print both Line1 and Line2, even though the
// condition is met both times.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PreElif(bool fExpr)
{
CHK_START;
ConditionState previousState;
// Get the top of the stack - this will tell us what the value of
// _conditionState._fAllowOutput was when the ifdef was done.
//
// If previousState._fAllowOutput is true, then output was enabled when
// the ifdef statement was encountered. So we need to evaluate the
// expression and look at the current condition to set what we can do.
//
// If previousState._fAllowOutput is false, it means that the corresponding
// if for this else was itself inside of a disallowed code block and
// therefore the else block, just like the if block it is related to,
// should do nothing.
CHK(_conditionStack.Top(/*out*/previousState));
if (previousState._fAllowOutput)
{
// We 'go into the branch' if we did not go into a previous
// one and the expression evaluates to true.
bool fConditionMet = (!_conditionState._fConditionMet && fExpr);
// Allow output if the condition is met
_conditionState._fAllowOutput = fConditionMet;
if (fConditionMet)
{
// If the condition is met, then we found a true condition
_conditionState._fConditionMet = true;
}
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: PreIfDef
//
// Synopsis: Ifdef directives have a symbol after them. This symbol is
// checked for existing, and the allow stack pushes the
// appropriate flag.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PreIfDef(int iIdSymbol)
{
return PreIfImpl(IsDefined(iIdSymbol));
}
//+----------------------------------------------------------------------------
//
// Function: PreIfNDef
//
// Synopsis: Ifndef directives have a symbol after them. This symbol is
// checked for existing, and the allow stack pushes the
// appropriate flag.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PreIfNDef(int iIdSymbol)
{
return PreIfImpl(!IsDefined(iIdSymbol));
}
//+----------------------------------------------------------------------------
//
// Function: PreElse
//
// Synopsis: Reverses the condition of the allow stack. This should have the
// same effect as popping the stack and immediately pushing the
// reverse condition as before.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PreElse()
{
CHK_START;
ConditionState previousState;
// Get the top of the stack - this will tell us what the value of
// _conditionState._fAllowOutput was when the ifdef was done.
//
// If previousState._fAllowOutput is true, then output was enabled when
// the ifdef statement was encountered. So we either need to go from on to
// off or off to on.
//
// If previousState._fAllowOutput is false, it means that the corresponding
// if for this else was itself inside of a disallowed code block and
// therefore the elseblock, just like the if block it is related to, should
// do nothing.
CHK(_conditionStack.Top(/*out*/previousState));
if (previousState._fAllowOutput)
{
_conditionState._fAllowOutput = !_conditionState._fConditionMet;
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: PreEndDef
//
// Synopsis: Pops the allow stack.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PreEndIf()
{
// Restore the output allow state
_conditionStack.Pop(/*out*/_conditionState);
return S_OK;
}
//+----------------------------------------------------------------------------
//
// Function: PreDefine
//
// Synopsis: Adds a definition to the preprocessor, given a symbol table
// token index and a definition table index. All of the define
// statement generations end up calling this, so at the point
// that this is called, all of the information to do define
// or redefine a macro is there.
//
// The token index can be -1, which means that the macro name
// has already been set when the definition was created. This
// occurs for macros with parameters.
//
// The definition index can be -1, which means that a definition
// with no tokens is created. This is perfectly legal.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PreDefine(
int iToken, // Token that specifies the macro being defined
int defIndex, // Index of the definition of what this define is (what replaces the token)
const YYLTYPE& pLocation // Location of the define statement
)
{
CHK_START;
// Don't use the definition if the output is disabled
if (_conditionState._fAllowOutput)
{
TSmartPointer<CGLSLPreMacroDefinition> spDefinition;
if (iToken != -1)
{
// We have an identifier for the macro but we might not have a definition
if (defIndex == -1)
{
// Create a definition to set the token on
CHK(_rgDefinitions.CreateAndAddDefinition(this, /*index*/nullptr, &spDefinition));
// Make sure that at least a space is used in this case
CHK(spDefinition->AddToken(" "));
}
else
{
// Set the identifier on the existing definition
CHK(_rgDefinitions.GetDefinition(defIndex, &spDefinition));
}
spDefinition->SetIdentifierIndex(iToken);
}
else
{
// If there is no token, then the definition needs to be valid
CHKB(defIndex != -1);
CHK(_rgDefinitions.GetDefinition(defIndex, &spDefinition));
// The identifier index needs to be set on this definition by now
iToken = spDefinition->GetIdentifierIndex();
CHKB(iToken != -1);
}
// We should have a valid token by this point
Assert(iToken != -1);
// Now see if this macro was already defined
int existingIndex;
TSmartPointer<CGLSLPreMacroDefinition> spExisting;
if (SUCCEEDED(_rgDefinitions.FindDefinition(iToken, &existingIndex, &spExisting)))
{
// An existing finalized definition has been found - the new one
// has to have a matching definition.
if (!spExisting->IsEqual(spDefinition))
{
CHK(_spErrorSink->AddError(pLocation.first_line, pLocation.first_column, E_GLSLERROR_MACRODEFINITIONNOTEQUAL, nullptr));
CHK(E_GLSLERROR_KNOWNERROR);
}
// Remove the new one and leave the old one
_rgDefinitions.RemoveDefinitionFromIndex(existingIndex);
}
// Now we can finalize what we have
spDefinition->Finalize();
// Make sure the macro name is legal
if (FAILED(VerifyMacroName(iToken)))
{
CHK(_spErrorSink->AddError(pLocation.first_line, pLocation.first_column, E_GLSLERROR_INVALIDMACRONAME, nullptr));
CHK(E_GLSLERROR_KNOWNERROR);
}
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: PreUndefine
//
// Synopsis: Removes a definition from the preprocessor, given a symbol table
// token index.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PreUndefine(
int iToken, // Token that specifies the macro being undefined
const YYLTYPE& pLocation // Location of the undefine statement
)
{
// Don't remove the definition if the output is disabled
if (_conditionState._fAllowOutput)
{
// Undef of a thing that is not defined is perfectly legal, so no error condition here
_rgDefinitions.RemoveDefinitionFromIdentifier(iToken);
}
return S_OK;
}
//+----------------------------------------------------------------------------
//
// Function: SetCommentCondition
//
// Synopsis: Set the condition that a C comment started in. Since they can
// span lines, the condition that they return to might need to
// change. The preparser keeps track of that.
//
//-----------------------------------------------------------------------------
void CGLSLPreParser::SetCommentCondition(int condition)
{
_commentCondition = condition;
}
//+----------------------------------------------------------------------------
//
// Function: GetCommentCondition
//
// Synopsis: Get the condition that a C comment should return to. This will
// be the value that SetCommentCondition last set, unless there
// was a newline encountered, in which case it will return to
// INITIAL.
//
//-----------------------------------------------------------------------------
int CGLSLPreParser::GetCommentCondition()
{
return _commentCondition;
}
//+----------------------------------------------------------------------------
//
// Function: IsDefined
//
// Synopsis: Return true if the given token is defined.
//
//-----------------------------------------------------------------------------
bool CGLSLPreParser::IsDefined(int token)
{
return SUCCEEDED(_rgDefinitions.FindDefinition(token, nullptr, nullptr));
}
//+----------------------------------------------------------------------------
//
// Function: AddDefinition
//
// Synopsis: Add a definition from two strings - used to add builtin
// definitions.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::AddDefinition(
__in_z const char* pszToken, // Macro identifier
__in_z const char* pszValue, // First token in macro value
__out_opt int* pSymbolIndex // Symbol index of macro identifier
)
{
CHK_START;
TSmartPointer<CGLSLPreMacroDefinition> spDefinition;
CHK(_rgDefinitions.CreateAndAddDefinition(this, nullptr, &spDefinition));
CHK(spDefinition->AddToken(pszValue));
int token;
CHK(_spSymbolTable->EnsureSymbolIndex(pszToken, &token));
spDefinition->SetIdentifierIndex(token);
spDefinition->Finalize();
if (pSymbolIndex != nullptr)
{
(*pSymbolIndex) = token;
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: CreateDefinition
//
// Synopsis: Create a definition, and add the given text if it is not
// nullptr as the first token. This is the form called by
// the production in the grammar file.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::CreateDefinition(
__in_z_opt const char* pszText, // Optional token to start the definition
__out int& defIndex // Returned index of definition
)
{
CHK_START;
TSmartPointer<CGLSLPreMacroDefinition> spDefinition;
CHK(_rgDefinitions.CreateAndAddDefinition(this, &defIndex, &spDefinition));
// If somebody provided a starting token, then add it
if (pszText != nullptr)
{
CHK(spDefinition->AddToken(pszText));
}
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: AddDefinitionToken
//
// Synopsis: Add the given token to the given definition.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::AddDefinitionToken(int defIndex, __in_z const char* pszText)
{
CHK_START;
TSmartPointer<CGLSLPreMacroDefinition> spDefinition;
CHK(_rgDefinitions.GetDefinition(defIndex, &spDefinition));
CHK(spDefinition->AddToken(pszText));
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: PushBufferState
//
// Synopsis: Push the given scan buffer onto the stack, and use the currently
// loaded up macro parameters (if any) to create a buffer to
// recommence scanning with.
//
// This function needs to be declared with a void parameter
// because of a circular reference problem with headers.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PushBufferState(
__in YYLTYPE* pLocation, // Location of macro being expanded
__in_opt CGLSLPreMacroDefinition* pDefinition, // The macro being expanded
void* oldState // The buffer to push (YY_CURRENT_BUFFER)
)
{
CHK_START;
TSmartPointer<CGLSLPreMacroDefinition> spPopDefinition;
TSmartPointer<CGLSLPreParamList> spParamList;
// If we don't have a definition, it is because we are closing off the parameter
// list. We need to pop the parameter list off and get the definition from there
if (pDefinition == nullptr)
{
CHK(PopMacroParam(&spPopDefinition, nullptr, &spParamList));
pDefinition = spPopDefinition;
}
TSmartPointer<CGLSLPreExpandBuffer> spNewBuffer;
CHK(RefCounted<CGLSLPreExpandBuffer>::Create(pLocation, pDefinition, spParamList, /*out*/spNewBuffer));
YY_BUFFER_STATE newState = GLSLPre_scan_string(spNewBuffer->GetBufferString(), _scanner);
// Set up the new state
BufferState newEntry;
newEntry._oldState = oldState;
newEntry._newState = newState;
newEntry._spBuffer = spNewBuffer;
newEntry._spDefinition = pDefinition;
// Push it onto the stack
CHK(_bufferStack.Push(newEntry));
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: PopBufferState
//
// Synopsis: Pop the given buffer from the stack.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PopBufferState()
{
CHK_START;
BufferState popState;
CHK(_bufferStack.Pop(/*out*/popState));
GLSLPre_delete_buffer(static_cast<YY_BUFFER_STATE>(popState._newState), _scanner);
GLSLPre_switch_to_buffer(static_cast<YY_BUFFER_STATE>(popState._oldState), _scanner);
CHK_RETURN;
}
//+----------------------------------------------------------------------------
//
// Function: PushMacroParam
//
// Synopsis: Push a new macro parameter context for calling a macro and
// expanding it.
//
//-----------------------------------------------------------------------------
HRESULT CGLSLPreParser::PushMacroParam(__in CGLSLPreMacroDefinition* pDefinition)
{
CHK_START;