4cc6c2f48898feda23622bde595e979117ff478a
[platform/upstream/glslang.git] / glslang / Public / ShaderLang.h
1 //
2 // Copyright (C) 2002-2005  3Dlabs Inc. Ltd.
3 // Copyright (C) 2013-2016 LunarG, Inc.
4 // Copyright (C) 2015-2018 Google, Inc.
5 //
6 // All rights reserved.
7 //
8 // Redistribution and use in source and binary forms, with or without
9 // modification, are permitted provided that the following conditions
10 // are met:
11 //
12 //    Redistributions of source code must retain the above copyright
13 //    notice, this list of conditions and the following disclaimer.
14 //
15 //    Redistributions in binary form must reproduce the above
16 //    copyright notice, this list of conditions and the following
17 //    disclaimer in the documentation and/or other materials provided
18 //    with the distribution.
19 //
20 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21 //    contributors may be used to endorse or promote products derived
22 //    from this software without specific prior written permission.
23 //
24 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 // POSSIBILITY OF SUCH DAMAGE.
36 //
37 #ifndef _COMPILER_INTERFACE_INCLUDED_
38 #define _COMPILER_INTERFACE_INCLUDED_
39
40 #include "../Include/ResourceLimits.h"
41 #include "../MachineIndependent/Versions.h"
42
43 #include <cstring>
44 #include <vector>
45
46 #ifdef _WIN32
47 #define C_DECL __cdecl
48 //#ifdef SH_EXPORTING
49 //    #define SH_IMPORT_EXPORT __declspec(dllexport)
50 //#else
51 //    #define SH_IMPORT_EXPORT __declspec(dllimport)
52 //#endif
53 #define SH_IMPORT_EXPORT
54 #else
55 #define SH_IMPORT_EXPORT
56 #define C_DECL
57 #endif
58
59 //
60 // This is the platform independent interface between an OGL driver
61 // and the shading language compiler/linker.
62 //
63
64 #ifdef __cplusplus
65     extern "C" {
66 #endif
67
68 // This should always increase, as some paths to do not consume
69 // a more major number.
70 // It should increment by one when new functionality is added.
71 #define GLSLANG_MINOR_VERSION 13
72
73 //
74 // Call before doing any other compiler/linker operations.
75 //
76 // (Call once per process, not once per thread.)
77 //
78 SH_IMPORT_EXPORT int ShInitialize();
79
80 //
81 // Call this at process shutdown to clean up memory.
82 //
83 SH_IMPORT_EXPORT int ShFinalize();
84
85 //
86 // Types of languages the compiler can consume.
87 //
88 typedef enum {
89     EShLangVertex,
90     EShLangTessControl,
91     EShLangTessEvaluation,
92     EShLangGeometry,
93     EShLangFragment,
94     EShLangCompute,
95     EShLangRayGenNV,
96     EShLangIntersectNV,
97     EShLangAnyHitNV,
98     EShLangClosestHitNV,
99     EShLangMissNV,
100     EShLangCallableNV,
101     EShLangTaskNV,
102     EShLangMeshNV,
103     EShLangCount,
104 } EShLanguage;         // would be better as stage, but this is ancient now
105
106 typedef enum {
107     EShLangVertexMask         = (1 << EShLangVertex),
108     EShLangTessControlMask    = (1 << EShLangTessControl),
109     EShLangTessEvaluationMask = (1 << EShLangTessEvaluation),
110     EShLangGeometryMask       = (1 << EShLangGeometry),
111     EShLangFragmentMask       = (1 << EShLangFragment),
112     EShLangComputeMask        = (1 << EShLangCompute),
113     EShLangRayGenNVMask       = (1 << EShLangRayGenNV),
114     EShLangIntersectNVMask    = (1 << EShLangIntersectNV),
115     EShLangAnyHitNVMask       = (1 << EShLangAnyHitNV),
116     EShLangClosestHitNVMask   = (1 << EShLangClosestHitNV),
117     EShLangMissNVMask         = (1 << EShLangMissNV),
118     EShLangCallableNVMask     = (1 << EShLangCallableNV),
119     EShLangTaskNVMask         = (1 << EShLangTaskNV),
120     EShLangMeshNVMask         = (1 << EShLangMeshNV),
121 } EShLanguageMask;
122
123 namespace glslang {
124
125 class TType;
126
127 typedef enum {
128     EShSourceNone,
129     EShSourceGlsl,               // GLSL, includes ESSL (OpenGL ES GLSL)
130     EShSourceHlsl,               // HLSL
131 } EShSource;                     // if EShLanguage were EShStage, this could be EShLanguage instead
132
133 typedef enum {
134     EShClientNone,               // use when there is no client, e.g. for validation
135     EShClientVulkan,
136     EShClientOpenGL,
137 } EShClient;
138
139 typedef enum {
140     EShTargetNone,
141     EShTargetSpv,                 // SPIR-V (preferred spelling)
142     EshTargetSpv = EShTargetSpv,  // legacy spelling
143 } EShTargetLanguage;
144
145 typedef enum {
146     EShTargetVulkan_1_0 = (1 << 22),                  // Vulkan 1.0
147     EShTargetVulkan_1_1 = (1 << 22) | (1 << 12),      // Vulkan 1.1
148     EShTargetOpenGL_450 = 450,                        // OpenGL
149 } EShTargetClientVersion;
150
151 typedef EShTargetClientVersion EshTargetClientVersion;
152
153 typedef enum {
154     EShTargetSpv_1_0 = (1 << 16),                     // SPIR-V 1.0
155     EShTargetSpv_1_1 = (1 << 16) | (1 << 8),          // SPIR-V 1.1
156     EShTargetSpv_1_2 = (1 << 16) | (2 << 8),          // SPIR-V 1.2
157     EShTargetSpv_1_3 = (1 << 16) | (3 << 8),          // SPIR-V 1.3
158     EShTargetSpv_1_4 = (1 << 16) | (4 << 8),          // SPIR-V 1.4
159     EShTargetSpv_1_5 = (1 << 16) | (5 << 8),          // SPIR-V 1.5
160 } EShTargetLanguageVersion;
161
162 struct TInputLanguage {
163     EShSource languageFamily; // redundant information with other input, this one overrides when not EShSourceNone
164     EShLanguage stage;        // redundant information with other input, this one overrides when not EShSourceNone
165     EShClient dialect;
166     int dialectVersion;       // version of client's language definition, not the client (when not EShClientNone)
167 };
168
169 struct TClient {
170     EShClient client;
171     EShTargetClientVersion version;   // version of client itself (not the client's input dialect)
172 };
173
174 struct TTarget {
175     EShTargetLanguage language;
176     EShTargetLanguageVersion version; // version to target, if SPIR-V, defined by "word 1" of the SPIR-V header
177     bool hlslFunctionality1;          // can target hlsl_functionality1 extension(s)
178 };
179
180 // All source/client/target versions and settings.
181 // Can override previous methods of setting, when items are set here.
182 // Expected to grow, as more are added, rather than growing parameter lists.
183 struct TEnvironment {
184     TInputLanguage input;     // definition of the input language
185     TClient client;           // what client is the overall compilation being done for?
186     TTarget target;           // what to generate
187 };
188
189 const char* StageName(EShLanguage);
190
191 } // end namespace glslang
192
193 //
194 // Types of output the linker will create.
195 //
196 typedef enum {
197     EShExVertexFragment,
198     EShExFragment
199 } EShExecutable;
200
201 //
202 // Optimization level for the compiler.
203 //
204 typedef enum {
205     EShOptNoGeneration,
206     EShOptNone,
207     EShOptSimple,       // Optimizations that can be done quickly
208     EShOptFull,         // Optimizations that will take more time
209 } EShOptimizationLevel;
210
211 //
212 // Texture and Sampler transformation mode.
213 //
214 typedef enum {
215     EShTexSampTransKeep,   // keep textures and samplers as is (default)
216     EShTexSampTransUpgradeTextureRemoveSampler,  // change texture w/o embeded sampler into sampled texture and throw away all samplers
217 } EShTextureSamplerTransformMode;
218
219 //
220 // Message choices for what errors and warnings are given.
221 //
222 enum EShMessages {
223     EShMsgDefault          = 0,         // default is to give all required errors and extra warnings
224     EShMsgRelaxedErrors    = (1 << 0),  // be liberal in accepting input
225     EShMsgSuppressWarnings = (1 << 1),  // suppress all warnings, except those required by the specification
226     EShMsgAST              = (1 << 2),  // print the AST intermediate representation
227     EShMsgSpvRules         = (1 << 3),  // issue messages for SPIR-V generation
228     EShMsgVulkanRules      = (1 << 4),  // issue messages for Vulkan-requirements of GLSL for SPIR-V
229     EShMsgOnlyPreprocessor = (1 << 5),  // only print out errors produced by the preprocessor
230     EShMsgReadHlsl         = (1 << 6),  // use HLSL parsing rules and semantics
231     EShMsgCascadingErrors  = (1 << 7),  // get cascading errors; risks error-recovery issues, instead of an early exit
232     EShMsgKeepUncalled     = (1 << 8),  // for testing, don't eliminate uncalled functions
233     EShMsgHlslOffsets      = (1 << 9),  // allow block offsets to follow HLSL rules instead of GLSL rules
234     EShMsgDebugInfo        = (1 << 10), // save debug information
235     EShMsgHlslEnable16BitTypes  = (1 << 11), // enable use of 16-bit types in SPIR-V for HLSL
236     EShMsgHlslLegalization  = (1 << 12), // enable HLSL Legalization messages
237     EShMsgHlslDX9Compatible = (1 << 13), // enable HLSL DX9 compatible mode (right now only for samplers)
238     EShMsgBuiltinSymbolTable = (1 << 14), // print the builtin symbol table
239 };
240
241 //
242 // Options for building reflection
243 //
244 typedef enum {
245     EShReflectionDefault           = 0,        // default is original behaviour before options were added
246     EShReflectionStrictArraySuffix = (1 << 0), // reflection will follow stricter rules for array-of-structs suffixes
247     EShReflectionBasicArraySuffix  = (1 << 1), // arrays of basic types will be appended with [0] as in GL reflection
248     EShReflectionIntermediateIO    = (1 << 2), // reflect inputs and outputs to program, even with no vertex shader
249     EShReflectionSeparateBuffers   = (1 << 3), // buffer variables and buffer blocks are reflected separately
250     EShReflectionAllBlockVariables = (1 << 4), // reflect all variables in blocks, even if they are inactive
251     EShReflectionUnwrapIOBlocks    = (1 << 5), // unwrap input/output blocks the same as with uniform blocks
252 } EShReflectionOptions;
253
254 //
255 // Build a table for bindings.  This can be used for locating
256 // attributes, uniforms, globals, etc., as needed.
257 //
258 typedef struct {
259     const char* name;
260     int binding;
261 } ShBinding;
262
263 typedef struct {
264     int numBindings;
265     ShBinding* bindings;  // array of bindings
266 } ShBindingTable;
267
268 //
269 // ShHandle held by but opaque to the driver.  It is allocated,
270 // managed, and de-allocated by the compiler/linker. It's contents
271 // are defined by and used by the compiler and linker.  For example,
272 // symbol table information and object code passed from the compiler
273 // to the linker can be stored where ShHandle points.
274 //
275 // If handle creation fails, 0 will be returned.
276 //
277 typedef void* ShHandle;
278
279 //
280 // Driver calls these to create and destroy compiler/linker
281 // objects.
282 //
283 SH_IMPORT_EXPORT ShHandle ShConstructCompiler(const EShLanguage, int debugOptions);  // one per shader
284 SH_IMPORT_EXPORT ShHandle ShConstructLinker(const EShExecutable, int debugOptions);  // one per shader pair
285 SH_IMPORT_EXPORT ShHandle ShConstructUniformMap();                 // one per uniform namespace (currently entire program object)
286 SH_IMPORT_EXPORT void ShDestruct(ShHandle);
287
288 //
289 // The return value of ShCompile is boolean, non-zero indicating
290 // success.
291 //
292 // The info-log should be written by ShCompile into
293 // ShHandle, so it can answer future queries.
294 //
295 SH_IMPORT_EXPORT int ShCompile(
296     const ShHandle,
297     const char* const shaderStrings[],
298     const int numStrings,
299     const int* lengths,
300     const EShOptimizationLevel,
301     const TBuiltInResource *resources,
302     int debugOptions,
303     int defaultVersion = 110,            // use 100 for ES environment, overridden by #version in shader
304     bool forwardCompatible = false,      // give errors for use of deprecated features
305     EShMessages messages = EShMsgDefault // warnings and errors
306     );
307
308 SH_IMPORT_EXPORT int ShLinkExt(
309     const ShHandle,               // linker object
310     const ShHandle h[],           // compiler objects to link together
311     const int numHandles);
312
313 //
314 // ShSetEncrpytionMethod is a place-holder for specifying
315 // how source code is encrypted.
316 //
317 SH_IMPORT_EXPORT void ShSetEncryptionMethod(ShHandle);
318
319 //
320 // All the following return 0 if the information is not
321 // available in the object passed down, or the object is bad.
322 //
323 SH_IMPORT_EXPORT const char* ShGetInfoLog(const ShHandle);
324 SH_IMPORT_EXPORT const void* ShGetExecutable(const ShHandle);
325 SH_IMPORT_EXPORT int ShSetVirtualAttributeBindings(const ShHandle, const ShBindingTable*);   // to detect user aliasing
326 SH_IMPORT_EXPORT int ShSetFixedAttributeBindings(const ShHandle, const ShBindingTable*);     // to force any physical mappings
327 //
328 // Tell the linker to never assign a vertex attribute to this list of physical attributes
329 //
330 SH_IMPORT_EXPORT int ShExcludeAttributes(const ShHandle, int *attributes, int count);
331
332 //
333 // Returns the location ID of the named uniform.
334 // Returns -1 if error.
335 //
336 SH_IMPORT_EXPORT int ShGetUniformLocation(const ShHandle uniformMap, const char* name);
337
338 #ifdef __cplusplus
339     }  // end extern "C"
340 #endif
341
342 ////////////////////////////////////////////////////////////////////////////////////////////
343 //
344 // Deferred-Lowering C++ Interface
345 // -----------------------------------
346 //
347 // Below is a new alternate C++ interface, which deprecates the above
348 // opaque handle-based interface.
349 //
350 // The below is further designed to handle multiple compilation units per stage, where
351 // the intermediate results, including the parse tree, are preserved until link time,
352 // rather than the above interface which is designed to have each compilation unit
353 // lowered at compile time.  In the above model, linking occurs on the lowered results,
354 // whereas in this model intra-stage linking can occur at the parse tree
355 // (treeRoot in TIntermediate) level, and then a full stage can be lowered.
356 //
357
358 #include <list>
359 #include <string>
360 #include <utility>
361
362 class TCompiler;
363 class TInfoSink;
364
365 namespace glslang {
366
367 const char* GetEsslVersionString();
368 const char* GetGlslVersionString();
369 int GetKhronosToolId();
370
371 class TIntermediate;
372 class TProgram;
373 class TPoolAllocator;
374
375 // Call this exactly once per process before using anything else
376 bool InitializeProcess();
377
378 // Call once per process to tear down everything
379 void FinalizeProcess();
380
381 // Resource type for IO resolver
382 enum TResourceType {
383     EResSampler,
384     EResTexture,
385     EResImage,
386     EResUbo,
387     EResSsbo,
388     EResUav,
389     EResCount
390 };
391
392 // Make one TShader per shader that you will link into a program. Then
393 //  - provide the shader through setStrings() or setStringsWithLengths()
394 //  - optionally call setEnv*(), see below for more detail
395 //  - optionally use setPreamble() to set a special shader string that will be
396 //    processed before all others but won't affect the validity of #version
397 //  - call parse(): source language and target environment must be selected
398 //    either by correct setting of EShMessages sent to parse(), or by
399 //    explicitly calling setEnv*()
400 //  - query the info logs
401 //
402 // N.B.: Does not yet support having the same TShader instance being linked into
403 // multiple programs.
404 //
405 // N.B.: Destruct a linked program *before* destructing the shaders linked into it.
406 //
407 class TShader {
408 public:
409     explicit TShader(EShLanguage);
410     virtual ~TShader();
411     void setStrings(const char* const* s, int n);
412     void setStringsWithLengths(const char* const* s, const int* l, int n);
413     void setStringsWithLengthsAndNames(
414         const char* const* s, const int* l, const char* const* names, int n);
415     void setPreamble(const char* s) { preamble = s; }
416     void setEntryPoint(const char* entryPoint);
417     void setSourceEntryPoint(const char* sourceEntryPointName);
418     void addProcesses(const std::vector<std::string>&);
419
420     // IO resolver binding data: see comments in ShaderLang.cpp
421     void setShiftBinding(TResourceType res, unsigned int base);
422     void setShiftSamplerBinding(unsigned int base);  // DEPRECATED: use setShiftBinding
423     void setShiftTextureBinding(unsigned int base);  // DEPRECATED: use setShiftBinding
424     void setShiftImageBinding(unsigned int base);    // DEPRECATED: use setShiftBinding
425     void setShiftUboBinding(unsigned int base);      // DEPRECATED: use setShiftBinding
426     void setShiftUavBinding(unsigned int base);      // DEPRECATED: use setShiftBinding
427     void setShiftCbufferBinding(unsigned int base);  // synonym for setShiftUboBinding
428     void setShiftSsboBinding(unsigned int base);     // DEPRECATED: use setShiftBinding
429     void setShiftBindingForSet(TResourceType res, unsigned int base, unsigned int set);
430     void setResourceSetBinding(const std::vector<std::string>& base);
431     void setAutoMapBindings(bool map);
432     void setAutoMapLocations(bool map);
433     void addUniformLocationOverride(const char* name, int loc);
434     void setUniformLocationBase(int base);
435     void setInvertY(bool invert);
436 #ifdef ENABLE_HLSL
437     void setHlslIoMapping(bool hlslIoMap);
438     void setFlattenUniformArrays(bool flatten);
439 #endif
440     void setNoStorageFormat(bool useUnknownFormat);
441     void setNanMinMaxClamp(bool nanMinMaxClamp);
442     void setTextureSamplerTransformMode(EShTextureSamplerTransformMode mode);
443
444     // For setting up the environment (cleared to nothingness in the constructor).
445     // These must be called so that parsing is done for the right source language and
446     // target environment, either indirectly through TranslateEnvironment() based on
447     // EShMessages et. al., or directly by the user.
448     //
449     // setEnvInput:    The input source language and stage. If generating code for a
450     //                 specific client, the input client semantics to use and the
451     //                 version of the that client's input semantics to use, otherwise
452     //                 use EShClientNone and version of 0, e.g. for validation mode.
453     //                 Note 'version' does not describe the target environment,
454     //                 just the version of the source dialect to compile under.
455     //
456     //                 See the definitions of TEnvironment, EShSource, EShLanguage,
457     //                 and EShClient for choices and more detail.
458     //
459     // setEnvClient:   The client that will be hosting the execution, and it's version.
460     //                 Note 'version' is not the version of the languages involved, but
461     //                 the version of the client environment.
462     //                 Use EShClientNone and version of 0 if there is no client, e.g.
463     //                 for validation mode.
464     //
465     //                 See EShTargetClientVersion for choices.
466     //
467     // setEnvTarget:   The language to translate to when generating code, and that
468     //                 language's version.
469     //                 Use EShTargetNone and version of 0 if there is no client, e.g.
470     //                 for validation mode.
471     //
472     void setEnvInput(EShSource lang, EShLanguage envStage, EShClient client, int version)
473     {
474         environment.input.languageFamily = lang;
475         environment.input.stage = envStage;
476         environment.input.dialect = client;
477         environment.input.dialectVersion = version;
478     }
479     void setEnvClient(EShClient client, EShTargetClientVersion version)
480     {
481         environment.client.client = client;
482         environment.client.version = version;
483     }
484     void setEnvTarget(EShTargetLanguage lang, EShTargetLanguageVersion version)
485     {
486         environment.target.language = lang;
487         environment.target.version = version;
488     }
489
490     void getStrings(const char* const* &s, int& n) { s = strings; n = numStrings; }
491
492 #ifdef ENABLE_HLSL
493     void setEnvTargetHlslFunctionality1() { environment.target.hlslFunctionality1 = true; }
494     bool getEnvTargetHlslFunctionality1() const { return environment.target.hlslFunctionality1; }
495 #else
496     bool getEnvTargetHlslFunctionality1() const { return false; }
497 #endif
498
499     // Interface to #include handlers.
500     //
501     // To support #include, a client of Glslang does the following:
502     // 1. Call setStringsWithNames to set the source strings and associated
503     //    names.  For example, the names could be the names of the files
504     //    containing the shader sources.
505     // 2. Call parse with an Includer.
506     //
507     // When the Glslang parser encounters an #include directive, it calls
508     // the Includer's include method with the requested include name
509     // together with the current string name.  The returned IncludeResult
510     // contains the fully resolved name of the included source, together
511     // with the source text that should replace the #include directive
512     // in the source stream.  After parsing that source, Glslang will
513     // release the IncludeResult object.
514     class Includer {
515     public:
516         // An IncludeResult contains the resolved name and content of a source
517         // inclusion.
518         struct IncludeResult {
519             IncludeResult(const std::string& headerName, const char* const headerData, const size_t headerLength, void* userData) :
520                 headerName(headerName), headerData(headerData), headerLength(headerLength), userData(userData) { }
521             // For a successful inclusion, the fully resolved name of the requested
522             // include.  For example, in a file system-based includer, full resolution
523             // should convert a relative path name into an absolute path name.
524             // For a failed inclusion, this is an empty string.
525             const std::string headerName;
526             // The content and byte length of the requested inclusion.  The
527             // Includer producing this IncludeResult retains ownership of the
528             // storage.
529             // For a failed inclusion, the header
530             // field points to a string containing error details.
531             const char* const headerData;
532             const size_t headerLength;
533             // Include resolver's context.
534             void* userData;
535         protected:
536             IncludeResult& operator=(const IncludeResult&);
537             IncludeResult();
538         };
539
540         // For both include methods below:
541         //
542         // Resolves an inclusion request by name, current source name,
543         // and include depth.
544         // On success, returns an IncludeResult containing the resolved name
545         // and content of the include.
546         // On failure, returns a nullptr, or an IncludeResult
547         // with an empty string for the headerName and error details in the
548         // header field.
549         // The Includer retains ownership of the contents
550         // of the returned IncludeResult value, and those contents must
551         // remain valid until the releaseInclude method is called on that
552         // IncludeResult object.
553         //
554         // Note "local" vs. "system" is not an "either/or": "local" is an
555         // extra thing to do over "system". Both might get called, as per
556         // the C++ specification.
557
558         // For the "system" or <>-style includes; search the "system" paths.
559         virtual IncludeResult* includeSystem(const char* /*headerName*/,
560                                              const char* /*includerName*/,
561                                              size_t /*inclusionDepth*/) { return nullptr; }
562
563         // For the "local"-only aspect of a "" include. Should not search in the
564         // "system" paths, because on returning a failure, the parser will
565         // call includeSystem() to look in the "system" locations.
566         virtual IncludeResult* includeLocal(const char* /*headerName*/,
567                                             const char* /*includerName*/,
568                                             size_t /*inclusionDepth*/) { return nullptr; }
569
570         // Signals that the parser will no longer use the contents of the
571         // specified IncludeResult.
572         virtual void releaseInclude(IncludeResult*) = 0;
573         virtual ~Includer() {}
574     };
575
576     // Fail all Includer searches
577     class ForbidIncluder : public Includer {
578     public:
579         virtual void releaseInclude(IncludeResult*) override { }
580     };
581
582     bool parse(const TBuiltInResource*, int defaultVersion, EProfile defaultProfile, bool forceDefaultVersionAndProfile,
583                bool forwardCompatible, EShMessages, Includer&);
584
585     bool parse(const TBuiltInResource* res, int defaultVersion, EProfile defaultProfile, bool forceDefaultVersionAndProfile,
586                bool forwardCompatible, EShMessages messages)
587     {
588         TShader::ForbidIncluder includer;
589         return parse(res, defaultVersion, defaultProfile, forceDefaultVersionAndProfile, forwardCompatible, messages, includer);
590     }
591
592     // Equivalent to parse() without a default profile and without forcing defaults.
593     bool parse(const TBuiltInResource* builtInResources, int defaultVersion, bool forwardCompatible, EShMessages messages)
594     {
595         return parse(builtInResources, defaultVersion, ENoProfile, false, forwardCompatible, messages);
596     }
597
598     bool parse(const TBuiltInResource* builtInResources, int defaultVersion, bool forwardCompatible, EShMessages messages,
599                Includer& includer)
600     {
601         return parse(builtInResources, defaultVersion, ENoProfile, false, forwardCompatible, messages, includer);
602     }
603
604     // NOTE: Doing just preprocessing to obtain a correct preprocessed shader string
605     // is not an officially supported or fully working path.
606     bool preprocess(const TBuiltInResource* builtInResources,
607                     int defaultVersion, EProfile defaultProfile, bool forceDefaultVersionAndProfile,
608                     bool forwardCompatible, EShMessages message, std::string* outputString,
609                     Includer& includer);
610
611     const char* getInfoLog();
612     const char* getInfoDebugLog();
613     EShLanguage getStage() const { return stage; }
614     TIntermediate* getIntermediate() const { return intermediate; }
615
616 protected:
617     TPoolAllocator* pool;
618     EShLanguage stage;
619     TCompiler* compiler;
620     TIntermediate* intermediate;
621     TInfoSink* infoSink;
622     // strings and lengths follow the standard for glShaderSource:
623     //     strings is an array of numStrings pointers to string data.
624     //     lengths can be null, but if not it is an array of numStrings
625     //         integers containing the length of the associated strings.
626     //         if lengths is null or lengths[n] < 0  the associated strings[n] is
627     //         assumed to be null-terminated.
628     // stringNames is the optional names for all the strings. If stringNames
629     // is null, then none of the strings has name. If a certain element in
630     // stringNames is null, then the corresponding string does not have name.
631     const char* const* strings;
632     const int* lengths;
633     const char* const* stringNames;
634     const char* preamble;
635     int numStrings;
636
637     // a function in the source string can be renamed FROM this TO the name given in setEntryPoint.
638     std::string sourceEntryPointName;
639
640     TEnvironment environment;
641
642     friend class TProgram;
643
644 private:
645     TShader& operator=(TShader&);
646 };
647
648 #ifndef GLSLANG_WEB
649
650 //
651 // A reflection database and its interface, consistent with the OpenGL API reflection queries.
652 //
653
654 // Data needed for just a single object at the granularity exchanged by the reflection API
655 class TObjectReflection {
656 public:
657     TObjectReflection(const std::string& pName, const TType& pType, int pOffset, int pGLDefineType, int pSize, int pIndex);
658
659     const TType* getType() const { return type; }
660     int getBinding() const;
661     void dump() const;
662     static TObjectReflection badReflection() { return TObjectReflection(); }
663
664     std::string name;
665     int offset;
666     int glDefineType;
667     int size;                   // data size in bytes for a block, array size for a (non-block) object that's an array
668     int index;
669     int counterIndex;
670     int numMembers;
671     int arrayStride;            // stride of an array variable
672     int topLevelArrayStride;    // stride of the top-level variable in a storage buffer member
673     EShLanguageMask stages;
674
675 protected:
676     TObjectReflection()
677         : offset(-1), glDefineType(-1), size(-1), index(-1), counterIndex(-1), numMembers(-1), arrayStride(0),
678           topLevelArrayStride(0), stages(EShLanguageMask(0)), type(nullptr)
679     {
680     }
681
682     const TType* type;
683 };
684
685 class  TReflection;
686 class  TIoMapper;
687 struct TVarEntryInfo;
688
689 // Allows to customize the binding layout after linking.
690 // All used uniform variables will invoke at least validateBinding.
691 // If validateBinding returned true then the other resolveBinding,
692 // resolveSet, and resolveLocation are invoked to resolve the binding
693 // and descriptor set index respectively.
694 //
695 // Invocations happen in a particular order:
696 // 1) all shader inputs
697 // 2) all shader outputs
698 // 3) all uniforms with binding and set already defined
699 // 4) all uniforms with binding but no set defined
700 // 5) all uniforms with set but no binding defined
701 // 6) all uniforms with no binding and no set defined
702 //
703 // mapIO will use this resolver in two phases. The first
704 // phase is a notification phase, calling the corresponging
705 // notifiy callbacks, this phase ends with a call to endNotifications.
706 // Phase two starts directly after the call to endNotifications
707 // and calls all other callbacks to validate and to get the
708 // bindings, sets, locations, component and color indices.
709 //
710 // NOTE: that still limit checks are applied to bindings and sets
711 // and may result in an error.
712 class TIoMapResolver
713 {
714 public:
715     virtual ~TIoMapResolver() {}
716
717     // Should return true if the resulting/current binding would be okay.
718     // Basic idea is to do aliasing binding checks with this.
719     virtual bool validateBinding(EShLanguage stage, TVarEntryInfo& ent) = 0;
720     // Should return a value >= 0 if the current binding should be overridden.
721     // Return -1 if the current binding (including no binding) should be kept.
722     virtual int resolveBinding(EShLanguage stage, TVarEntryInfo& ent) = 0;
723     // Should return a value >= 0 if the current set should be overridden.
724     // Return -1 if the current set (including no set) should be kept.
725     virtual int resolveSet(EShLanguage stage, TVarEntryInfo& ent) = 0;
726     // Should return a value >= 0 if the current location should be overridden.
727     // Return -1 if the current location (including no location) should be kept.
728     virtual int resolveUniformLocation(EShLanguage stage, TVarEntryInfo& ent) = 0;
729     // Should return true if the resulting/current setup would be okay.
730     // Basic idea is to do aliasing checks and reject invalid semantic names.
731     virtual bool validateInOut(EShLanguage stage, TVarEntryInfo& ent) = 0;
732     // Should return a value >= 0 if the current location should be overridden.
733     // Return -1 if the current location (including no location) should be kept.
734     virtual int resolveInOutLocation(EShLanguage stage, TVarEntryInfo& ent) = 0;
735     // Should return a value >= 0 if the current component index should be overridden.
736     // Return -1 if the current component index (including no index) should be kept.
737     virtual int resolveInOutComponent(EShLanguage stage, TVarEntryInfo& ent) = 0;
738     // Should return a value >= 0 if the current color index should be overridden.
739     // Return -1 if the current color index (including no index) should be kept.
740     virtual int resolveInOutIndex(EShLanguage stage, TVarEntryInfo& ent) = 0;
741     // Notification of a uniform variable
742     virtual void notifyBinding(EShLanguage stage, TVarEntryInfo& ent) = 0;
743     // Notification of a in or out variable
744     virtual void notifyInOut(EShLanguage stage, TVarEntryInfo& ent) = 0;
745     // Called by mapIO when it starts its notify pass for the given stage
746     virtual void beginNotifications(EShLanguage stage) = 0;
747     // Called by mapIO when it has finished the notify pass
748     virtual void endNotifications(EShLanguage stage) = 0;
749     // Called by mipIO when it starts its resolve pass for the given stage
750     virtual void beginResolve(EShLanguage stage) = 0;
751     // Called by mapIO when it has finished the resolve pass
752     virtual void endResolve(EShLanguage stage) = 0;
753     // Called by mapIO when it starts its symbol collect for teh given stage
754     virtual void beginCollect(EShLanguage stage) = 0;
755     // Called by mapIO when it has finished the symbol collect
756     virtual void endCollect(EShLanguage stage) = 0;
757     // Called by TSlotCollector to resolve storage locations or bindings
758     virtual void reserverStorageSlot(TVarEntryInfo& ent, TInfoSink& infoSink) = 0;
759     // Called by TSlotCollector to resolve resource locations or bindings
760     virtual void reserverResourceSlot(TVarEntryInfo& ent, TInfoSink& infoSink) = 0;
761     // Called by mapIO.addStage to set shader stage mask to mark a stage be added to this pipeline
762     virtual void addStage(EShLanguage stage) = 0;
763 };
764
765 #endif // GLSLANG_WEB
766
767 // Make one TProgram per set of shaders that will get linked together.  Add all
768 // the shaders that are to be linked together.  After calling shader.parse()
769 // for all shaders, call link().
770 //
771 // N.B.: Destruct a linked program *before* destructing the shaders linked into it.
772 //
773 class TProgram {
774 public:
775     TProgram();
776     virtual ~TProgram();
777     void addShader(TShader* shader) { stages[shader->stage].push_back(shader); }
778     std::list<TShader*>& getShaders(EShLanguage stage) { return stages[stage]; }
779     // Link Validation interface
780     bool link(EShMessages);
781     const char* getInfoLog();
782     const char* getInfoDebugLog();
783
784     TIntermediate* getIntermediate(EShLanguage stage) const { return intermediate[stage]; }
785
786 #ifndef GLSLANG_WEB
787
788     // Reflection Interface
789
790     // call first, to do liveness analysis, index mapping, etc.; returns false on failure
791     bool buildReflection(int opts = EShReflectionDefault);
792     unsigned getLocalSize(int dim) const;                  // return dim'th local size
793     int getReflectionIndex(const char *name) const;
794     int getReflectionPipeIOIndex(const char* name, const bool inOrOut) const;
795     int getNumUniformVariables() const;
796     const TObjectReflection& getUniform(int index) const;
797     int getNumUniformBlocks() const;
798     const TObjectReflection& getUniformBlock(int index) const;
799     int getNumPipeInputs() const;
800     const TObjectReflection& getPipeInput(int index) const;
801     int getNumPipeOutputs() const;
802     const TObjectReflection& getPipeOutput(int index) const;
803     int getNumBufferVariables() const;
804     const TObjectReflection& getBufferVariable(int index) const;
805     int getNumBufferBlocks() const;
806     const TObjectReflection& getBufferBlock(int index) const;
807     int getNumAtomicCounters() const;
808     const TObjectReflection& getAtomicCounter(int index) const;
809
810     // Legacy Reflection Interface - expressed in terms of above interface
811
812     // can be used for glGetProgramiv(GL_ACTIVE_UNIFORMS)
813     int getNumLiveUniformVariables() const             { return getNumUniformVariables(); }
814
815     // can be used for glGetProgramiv(GL_ACTIVE_UNIFORM_BLOCKS)
816     int getNumLiveUniformBlocks() const                { return getNumUniformBlocks(); }
817
818     // can be used for glGetProgramiv(GL_ACTIVE_ATTRIBUTES)
819     int getNumLiveAttributes() const                   { return getNumPipeInputs(); }
820
821     // can be used for glGetUniformIndices()
822     int getUniformIndex(const char *name) const        { return getReflectionIndex(name); }
823
824     int getPipeIOIndex(const char *name, const bool inOrOut) const
825                                                        { return getReflectionPipeIOIndex(name, inOrOut); }
826
827     // can be used for "name" part of glGetActiveUniform()
828     const char *getUniformName(int index) const        { return getUniform(index).name.c_str(); }
829
830     // returns the binding number
831     int getUniformBinding(int index) const             { return getUniform(index).getBinding(); }
832
833     // returns Shaders Stages where a Uniform is present
834     EShLanguageMask getUniformStages(int index) const  { return getUniform(index).stages; }
835
836     // can be used for glGetActiveUniformsiv(GL_UNIFORM_BLOCK_INDEX)
837     int getUniformBlockIndex(int index) const          { return getUniform(index).index; }
838
839     // can be used for glGetActiveUniformsiv(GL_UNIFORM_TYPE)
840     int getUniformType(int index) const                { return getUniform(index).glDefineType; }
841
842     // can be used for glGetActiveUniformsiv(GL_UNIFORM_OFFSET)
843     int getUniformBufferOffset(int index) const        { return getUniform(index).offset; }
844
845     // can be used for glGetActiveUniformsiv(GL_UNIFORM_SIZE)
846     int getUniformArraySize(int index) const           { return getUniform(index).size; }
847
848     // returns a TType*
849     const TType *getUniformTType(int index) const      { return getUniform(index).getType(); }
850
851     // can be used for glGetActiveUniformBlockName()
852     const char *getUniformBlockName(int index) const   { return getUniformBlock(index).name.c_str(); }
853
854     // can be used for glGetActiveUniformBlockiv(UNIFORM_BLOCK_DATA_SIZE)
855     int getUniformBlockSize(int index) const           { return getUniformBlock(index).size; }
856
857     // returns the block binding number
858     int getUniformBlockBinding(int index) const        { return getUniformBlock(index).getBinding(); }
859
860     // returns block index of associated counter.
861     int getUniformBlockCounterIndex(int index) const   { return getUniformBlock(index).counterIndex; }
862
863     // returns a TType*
864     const TType *getUniformBlockTType(int index) const { return getUniformBlock(index).getType(); }
865
866     // can be used for glGetActiveAttrib()
867     const char *getAttributeName(int index) const      { return getPipeInput(index).name.c_str(); }
868
869     // can be used for glGetActiveAttrib()
870     int getAttributeType(int index) const              { return getPipeInput(index).glDefineType; }
871
872     // returns a TType*
873     const TType *getAttributeTType(int index) const    { return getPipeInput(index).getType(); }
874
875     void dumpReflection();
876     // I/O mapping: apply base offsets and map live unbound variables
877     // If resolver is not provided it uses the previous approach
878     // and respects auto assignment and offsets.
879     bool mapIO(TIoMapResolver* pResolver = nullptr, TIoMapper* pIoMapper = nullptr);
880 #endif
881
882 protected:
883     bool linkStage(EShLanguage, EShMessages);
884
885     TPoolAllocator* pool;
886     std::list<TShader*> stages[EShLangCount];
887     TIntermediate* intermediate[EShLangCount];
888     bool newedIntermediate[EShLangCount];      // track which intermediate were "new" versus reusing a singleton unit in a stage
889     TInfoSink* infoSink;
890 #ifndef GLSLANG_WEB
891     TReflection* reflection;
892 #endif
893     bool linked;
894
895 private:
896     TProgram(TProgram&);
897     TProgram& operator=(TProgram&);
898 };
899
900 } // end namespace glslang
901
902 #endif // _COMPILER_INTERFACE_INCLUDED_