@galacean/engine-shader-analyzer 0.0.0-stage → 2.0.0-alpha.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,2722 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var node_fs = require('node:fs');
5
+ var node_path = require('node:path');
6
+ var analyzer = require('@galacean/engine-shader-parser/internal/analyzer');
7
+
8
+ function _instanceof(left, right) {
9
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
10
+ return !!right[Symbol.hasInstance](left);
11
+ } else return left instanceof right;
12
+ }
13
+
14
+ function _array_like_to_array(arr, len) {
15
+ if (len == null || len > arr.length) len = arr.length;
16
+
17
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
18
+
19
+ return arr2;
20
+ }
21
+
22
+ function _unsupported_iterable_to_array(o, minLen) {
23
+ if (!o) return;
24
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
25
+
26
+ var n = Object.prototype.toString.call(o).slice(8, -1);
27
+
28
+ if (n === "Object" && o.constructor) n = o.constructor.name;
29
+ if (n === "Map" || n === "Set") return Array.from(n);
30
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
31
+ }
32
+
33
+ function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
34
+ var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
35
+
36
+ if (it) return (it = it.call(o)).next.bind(it);
37
+ // Fallback for engines without symbol support
38
+ if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike && o && typeof o.length === "number") {
39
+ if (it) o = it;
40
+
41
+ var i = 0;
42
+
43
+ return function() {
44
+ if (i >= o.length) return { done: true };
45
+
46
+ return { done: false, value: o[i++] };
47
+ };
48
+ }
49
+
50
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
51
+ }
52
+
53
+ /**
54
+ * Semantic classification of a shader diagnostic.
55
+ *
56
+ * Severity is reported separately.
57
+ */ var DiagnosticType = /*#__PURE__*/ function(DiagnosticType) {
58
+ DiagnosticType["SyntaxError"] = "SyntaxError";
59
+ DiagnosticType["PreprocessorError"] = "PreprocessorError";
60
+ DiagnosticType["NoMatchingOverload"] = "NoMatchingOverload";
61
+ DiagnosticType["Redefinition"] = "Redefinition";
62
+ DiagnosticType["UseBeforeDeclaration"] = "UseBeforeDeclaration";
63
+ DiagnosticType["LocalFunctionPrototype"] = "LocalFunctionPrototype";
64
+ DiagnosticType["AmbiguousMacroBranchResolution"] = "AmbiguousMacroBranchResolution";
65
+ DiagnosticType["InvalidSwizzle"] = "InvalidSwizzle";
66
+ DiagnosticType["UndeclaredStructMember"] = "UndeclaredStructMember";
67
+ DiagnosticType["AssignTypeMismatch"] = "AssignTypeMismatch";
68
+ DiagnosticType["InvalidAssignmentTarget"] = "InvalidAssignmentTarget";
69
+ DiagnosticType["ConstDivideByZero"] = "ConstDivideByZero";
70
+ DiagnosticType["ShiftOutOfRange"] = "ShiftOutOfRange";
71
+ DiagnosticType["IndexOutOfBounds"] = "IndexOutOfBounds";
72
+ DiagnosticType["NonIntegerIndex"] = "NonIntegerIndex";
73
+ DiagnosticType["NonIndexableType"] = "NonIndexableType";
74
+ DiagnosticType["ExpectedSampler"] = "ExpectedSampler";
75
+ DiagnosticType["InvalidUnaryOperand"] = "InvalidUnaryOperand";
76
+ DiagnosticType["InvalidBinaryOperands"] = "InvalidBinaryOperands";
77
+ DiagnosticType["ConstructorArgType"] = "ConstructorArgType";
78
+ DiagnosticType["ConstructorArgCount"] = "ConstructorArgCount";
79
+ DiagnosticType["NonConstInitializer"] = "NonConstInitializer";
80
+ DiagnosticType["NonConstArraySize"] = "NonConstArraySize";
81
+ DiagnosticType["EmptyStruct"] = "EmptyStruct";
82
+ DiagnosticType["InvalidArraySize"] = "InvalidArraySize";
83
+ DiagnosticType["InvalidVoidVariable"] = "InvalidVoidVariable";
84
+ DiagnosticType["NonFloatDerivativeArg"] = "NonFloatDerivativeArg";
85
+ DiagnosticType["InvalidReturnType"] = "InvalidReturnType";
86
+ DiagnosticType["MissingReturn"] = "MissingReturn";
87
+ DiagnosticType["NonBoolCondition"] = "NonBoolCondition";
88
+ DiagnosticType["RecursiveFunction"] = "RecursiveFunction";
89
+ DiagnosticType["NonConstructibleReturnType"] = "NonConstructibleReturnType";
90
+ DiagnosticType["MisplacedControlFlow"] = "MisplacedControlFlow";
91
+ DiagnosticType["DerivativeInVertexShader"] = "DerivativeInVertexShader";
92
+ DiagnosticType["InvalidBuiltinStage"] = "InvalidBuiltinStage";
93
+ DiagnosticType["InvalidIOStruct"] = "InvalidIOStruct";
94
+ DiagnosticType["InvalidEntryReturnType"] = "InvalidEntryReturnType";
95
+ DiagnosticType["StructRoleConflict"] = "StructRoleConflict";
96
+ DiagnosticType["DuplicateEntryAssignment"] = "DuplicateEntryAssignment";
97
+ DiagnosticType["MissingEntry"] = "MissingEntry";
98
+ DiagnosticType["EntryNotFound"] = "EntryNotFound";
99
+ DiagnosticType["AmbiguousEntryPoint"] = "AmbiguousEntryPoint";
100
+ DiagnosticType["GlFragColorWithMrt"] = "GlFragColorWithMrt";
101
+ DiagnosticType["LegacyFragmentOutputConflict"] = "LegacyFragmentOutputConflict";
102
+ DiagnosticType["InvalidMrtOutput"] = "InvalidMrtOutput";
103
+ DiagnosticType["BareGlFragData"] = "BareGlFragData";
104
+ DiagnosticType["NonConstFragmentOutputIndex"] = "NonConstFragmentOutputIndex";
105
+ DiagnosticType["NestedIOStruct"] = "NestedIOStruct";
106
+ DiagnosticType["MissingVertexPosition"] = "MissingVertexPosition";
107
+ DiagnosticType["NonFlatIntegerVarying"] = "NonFlatIntegerVarying";
108
+ DiagnosticType["InvalidRenderStateProperty"] = "InvalidRenderStateProperty";
109
+ DiagnosticType["InvalidEnumValue"] = "InvalidEnumValue";
110
+ DiagnosticType["BitwiseOrOnNonBitmask"] = "BitwiseOrOnNonBitmask";
111
+ DiagnosticType["MixedEnumTypes"] = "MixedEnumTypes";
112
+ DiagnosticType["InvalidRenderStateVariable"] = "InvalidRenderStateVariable";
113
+ DiagnosticType["InvalidRenderQueueVariable"] = "InvalidRenderQueueVariable";
114
+ return DiagnosticType;
115
+ }({});
116
+
117
+ /** Severity assigned to a shader diagnostic. */ var DiagnosticSeverity = /*#__PURE__*/ function(DiagnosticSeverity) {
118
+ DiagnosticSeverity["Error"] = "error";
119
+ DiagnosticSeverity["Warning"] = "warning";
120
+ return DiagnosticSeverity;
121
+ }({});
122
+ /**
123
+ * Formats a diagnostic with a source excerpt and caret markers.
124
+ * @param diagnostic - Diagnostic to format.
125
+ * @returns Formatted diagnostic text.
126
+ */ function formatDiagnostic(diagnostic) {
127
+ var _diagnostic_range = diagnostic.range, start = _diagnostic_range.start, end = _diagnostic_range.end;
128
+ return analyzer.formatDiagnosticSource(diagnostic.relatedSource, {
129
+ start: {
130
+ line: start.line - 1,
131
+ column: start.column - 1
132
+ },
133
+ end: {
134
+ line: end.line - 1,
135
+ column: end.column - 1
136
+ }
137
+ }, diagnostic.code + ": " + diagnostic.message);
138
+ }
139
+
140
+ var diagnosticTypes = new Set(Object.values(DiagnosticType));
141
+ /**
142
+ * Converts a parser error to a structured diagnostic.
143
+ * @param error - Error reported while parsing or analyzing shader source.
144
+ * @returns Structured diagnostic for the error.
145
+ */ function gseErrorToDiagnostic(error) {
146
+ if (!_instanceof(error, analyzer.GSError)) {
147
+ // Non-GSError (e.g. thrown from lexer/preprocess) — best-effort
148
+ return {
149
+ severity: DiagnosticSeverity.Error,
150
+ code: DiagnosticType.SyntaxError,
151
+ message: error.message,
152
+ range: {
153
+ start: {
154
+ line: 1,
155
+ column: 1,
156
+ offset: 0
157
+ },
158
+ end: {
159
+ line: 1,
160
+ column: 1,
161
+ offset: 0
162
+ }
163
+ }
164
+ };
165
+ }
166
+ var severity = error.name === analyzer.GSErrorName.CompilationWarn ? DiagnosticSeverity.Warning : DiagnosticSeverity.Error;
167
+ var code = isDiagnosticType(error.code) ? error.code : error.name === analyzer.GSErrorName.PreprocessorError ? DiagnosticType.PreprocessorError : DiagnosticType.SyntaxError;
168
+ return {
169
+ severity: severity,
170
+ code: code,
171
+ message: error.message,
172
+ sourceFile: error.file,
173
+ range: gSErrorLocationToRange(error.location),
174
+ relatedSource: error.source || undefined
175
+ };
176
+ }
177
+ function isDiagnosticType(code) {
178
+ return code !== undefined && diagnosticTypes.has(code);
179
+ }
180
+ function gSErrorLocationToRange(location) {
181
+ if ("start" in location && "end" in location) {
182
+ // ShaderRange
183
+ return {
184
+ start: {
185
+ line: location.start.line + 1,
186
+ column: location.start.column + 1,
187
+ offset: location.start.index
188
+ },
189
+ end: {
190
+ line: location.end.line + 1,
191
+ column: location.end.column + 1,
192
+ offset: location.end.index
193
+ }
194
+ };
195
+ }
196
+ // ShaderPosition
197
+ return {
198
+ start: {
199
+ line: location.line + 1,
200
+ column: location.column + 1,
201
+ offset: location.index
202
+ },
203
+ end: {
204
+ line: location.line + 1,
205
+ column: location.column + 1,
206
+ offset: location.index
207
+ }
208
+ };
209
+ }
210
+
211
+ var INTEGER_MINIMUM = -0x80000000;
212
+ var INTEGER_END = 0x80000000;
213
+ var TERMINAL_NODE = {
214
+ variable: Infinity,
215
+ ends: [],
216
+ children: []
217
+ };
218
+ // Let ordinary large shaders scale linearly without admitting exponential proof work
219
+ var MIN_DIAGRAM_WORK = 65536;
220
+ var WORK_PER_CONSTRAINT = 128;
221
+ /**
222
+ * Request-owned symbolic macro conditions shared by call-graph reachability and coverage.
223
+ * @internal
224
+ */ var ShaderConditionDiagram = /*#__PURE__*/ function() {
225
+ function ShaderConditionDiagram(branches) {
226
+ this._variables = [];
227
+ this._variableIds = new Map();
228
+ this._nodes = [
229
+ TERMINAL_NODE,
230
+ TERMINAL_NODE,
231
+ TERMINAL_NODE
232
+ ];
233
+ this._unique = new Map();
234
+ this._operations = new Map();
235
+ this._negations = new Map([
236
+ [
237
+ 0,
238
+ 1
239
+ ],
240
+ [
241
+ 1,
242
+ 0
243
+ ],
244
+ [
245
+ 2,
246
+ 2
247
+ ]
248
+ ]);
249
+ this._knownConditions = new Map([
250
+ [
251
+ 0,
252
+ 0
253
+ ],
254
+ [
255
+ 1,
256
+ 1
257
+ ],
258
+ [
259
+ 2,
260
+ 0
261
+ ]
262
+ ]);
263
+ this._conditions = new WeakMap();
264
+ this._sources = new WeakMap();
265
+ this._sourceFacts = new Map();
266
+ this._sourceKeys = new Map();
267
+ this._constraints = new Map();
268
+ this._groups = new Map();
269
+ this._groupRoots = new Map();
270
+ this._branches = [
271
+ new WeakMap(),
272
+ new WeakMap()
273
+ ];
274
+ for(var _iterator = _create_for_of_iterator_helper_loose(branches), _step; !(_step = _iterator()).done;){
275
+ var branch = _step.value;
276
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(branch), _step1; !(_step1 = _iterator1()).done;){
277
+ var constraint = _step1.value;
278
+ var _sourceArm_predicates;
279
+ if (this._constraints.has(constraint)) continue;
280
+ this._constraints.set(constraint, this._constraints.size);
281
+ var condition = constraint.condition, sourceArm = constraint.sourceArm, conditionalGroup = constraint.conditionalGroup, conditionalArm = constraint.conditionalArm;
282
+ var current = sourceArm == null ? void 0 : (_sourceArm_predicates = sourceArm.predicates) == null ? void 0 : _sourceArm_predicates[sourceArm.predicates.length - 1];
283
+ if (condition && condition.kind !== "constant" && current && !current.negated) {
284
+ this._sourceFacts.set(current.condition, condition);
285
+ }
286
+ if (conditionalGroup !== undefined && conditionalArm !== undefined) {
287
+ var arms = this._groups.get(conditionalGroup);
288
+ if (!arms) this._groups.set(conditionalGroup, arms = new Map());
289
+ var previous = arms.get(conditionalArm);
290
+ if (!previous || !previous.sourceArm && sourceArm) arms.set(conditionalArm, constraint);
291
+ }
292
+ }
293
+ }
294
+ var domains = new Map();
295
+ var register = function(key, opaque) {
296
+ var domain = domains.get(key);
297
+ if (!domain) domains.set(key, domain = {
298
+ opaque: opaque,
299
+ points: new Set([
300
+ INTEGER_MINIMUM,
301
+ INTEGER_END
302
+ ])
303
+ });
304
+ return domain;
305
+ };
306
+ var collect = function(condition) {
307
+ if (condition.kind === "constant") return;
308
+ if (condition.kind === "expression" && !condition.opaque) {
309
+ condition.operands.forEach(collect);
310
+ } else if (condition.kind === "expression" || !isExactCondition(condition)) {
311
+ register(opaqueConditionKey(condition), true);
312
+ } else {
313
+ var domain = register(macroKey(condition), false);
314
+ if (condition.kind === "comparison") {
315
+ domain.points.add(condition.value);
316
+ domain.points.add(condition.value + 1);
317
+ }
318
+ }
319
+ };
320
+ for(var _iterator2 = _create_for_of_iterator_helper_loose(this._constraints.keys()), _step2; !(_step2 = _iterator2()).done;){
321
+ var constraint1 = _step2.value;
322
+ var _constraint_precedingConditions, _constraint_sourceArm;
323
+ if (constraint1.condition) collect(constraint1.condition);
324
+ (_constraint_precedingConditions = constraint1.precedingConditions) == null ? void 0 : _constraint_precedingConditions.forEach(collect);
325
+ var _constraint_sourceArm_predicates;
326
+ for(var _iterator3 = _create_for_of_iterator_helper_loose((_constraint_sourceArm_predicates = (_constraint_sourceArm = constraint1.sourceArm) == null ? void 0 : _constraint_sourceArm.predicates) != null ? _constraint_sourceArm_predicates : []), _step3; !(_step3 = _iterator3()).done;){
327
+ var condition1 = _step3.value.condition;
328
+ var known = this._sourceFacts.get(condition1);
329
+ if (known) collect(known);
330
+ else register(this._sourceKey(condition1), true);
331
+ }
332
+ register(this._unknownConstraintKey(constraint1), true);
333
+ }
334
+ for(var _iterator4 = _create_for_of_iterator_helper_loose(this._groups), _step4; !(_step4 = _iterator4()).done;){
335
+ var _step_value = _step4.value, group = _step_value[0], arms1 = _step_value[1];
336
+ var count = groupArmCount(arms1);
337
+ for(var arm = 0; arm < count; arm++)register(groupArmKey(group, arm), true);
338
+ }
339
+ for(var _iterator5 = _create_for_of_iterator_helper_loose(domains), _step5; !(_step5 = _iterator5()).done;){
340
+ var _step_value1 = _step5.value, key = _step_value1[0], domain = _step_value1[1];
341
+ var points = Array.from(domain.points).sort(function(left, right) {
342
+ return left - right;
343
+ });
344
+ this._variableIds.set(key, this._variables.length);
345
+ this._variables.push({
346
+ opaque: domain.opaque,
347
+ points: points,
348
+ indices: new Map(points.map(function(point, index) {
349
+ return [
350
+ point,
351
+ index
352
+ ];
353
+ })),
354
+ size: domain.opaque ? 2 : points.length
355
+ });
356
+ }
357
+ this._remainingWork = Math.max(MIN_DIAGRAM_WORK, this._constraints.size * WORK_PER_CONSTRAINT);
358
+ }
359
+ var _proto = ShaderConditionDiagram.prototype;
360
+ /**
361
+ * Projects source branch constraints into one shared graph root.
362
+ * @param signature - A branch registered when this diagram was constructed.
363
+ * @param ignoreSelfGuarding - Omits canonical include guards for declaration/write coverage.
364
+ * @returns The canonical condition node ID.
365
+ */ _proto.branch = function branch(signature, ignoreSelfGuarding) {
366
+ if (ignoreSelfGuarding === void 0) ignoreSelfGuarding = false;
367
+ var cache = this._branches[Number(ignoreSelfGuarding)];
368
+ var cached = cache.get(signature);
369
+ if (cached !== undefined) return cached;
370
+ var root = ShaderConditionDiagram.TRUE;
371
+ for(var _iterator = _create_for_of_iterator_helper_loose(signature), _step; !(_step = _iterator()).done;){
372
+ var constraint = _step.value;
373
+ if (ignoreSelfGuarding && constraint.selfGuarding) continue;
374
+ root = this.and(root, this._constraint(constraint));
375
+ }
376
+ cache.set(signature, root);
377
+ return root;
378
+ };
379
+ /**
380
+ * Intersects two represented sets of macro configurations.
381
+ * @param left - First condition node ID.
382
+ * @param right - Second condition node ID.
383
+ * @returns Their canonical conjunction.
384
+ */ _proto.and = function and(left, right) {
385
+ return this._apply("and", left, right);
386
+ };
387
+ /**
388
+ * Unions two represented sets of macro configurations.
389
+ * @param left - First condition node ID.
390
+ * @param right - Second condition node ID.
391
+ * @returns Their canonical disjunction.
392
+ */ _proto.or = function or(left, right) {
393
+ return this._apply("or", left, right);
394
+ };
395
+ /**
396
+ * Unions alternatives without retaining every successively longer prefix of the result.
397
+ * @param roots - Alternative condition node IDs.
398
+ * @returns Their canonical disjunction, or FALSE for no alternatives.
399
+ */ _proto.orAll = function orAll(roots) {
400
+ var pending = roots.slice();
401
+ while(pending.length > 1){
402
+ var count = 0;
403
+ for(var index = 0; index < pending.length; index += 2){
404
+ pending[count++] = index + 1 < pending.length ? this.or(pending[index], pending[index + 1]) : pending[index];
405
+ }
406
+ pending.length = count;
407
+ }
408
+ var _pending_;
409
+ return (_pending_ = pending[0]) != null ? _pending_ : ShaderConditionDiagram.FALSE;
410
+ };
411
+ /**
412
+ * Complements a represented set of macro configurations.
413
+ * @param root - Condition node ID.
414
+ * @returns Its canonical negation.
415
+ */ _proto.not = function not(root) {
416
+ return this._transform(root, "not");
417
+ };
418
+ /**
419
+ * Classifies existence of a configuration without guessing unresolved predicates.
420
+ * @param root - Condition node ID.
421
+ * @returns Proven reachability, proven absence, or dependence on unresolved predicates.
422
+ */ _proto.reachability = function reachability(root) {
423
+ return root === 0 ? "unreachable" : this._transform(root, "known") !== 0 ? "reachable" : "unknown";
424
+ };
425
+ /**
426
+ * Classifies whether writes cover every configuration that reaches a reference.
427
+ * @param writes - Union of all writing conditions.
428
+ * @param reference - Condition under which coverage is required.
429
+ * @returns Proven coverage, a concrete missing configuration, or unresolved coverage.
430
+ */ _proto.coverage = function coverage(writes, reference) {
431
+ if (reference === void 0) reference = ShaderConditionDiagram.TRUE;
432
+ var missing = this.and(reference, this.not(writes));
433
+ return missing === 0 ? "covered" : this._transform(missing, "known") !== 0 ? "uncovered" : "unknown";
434
+ };
435
+ /**
436
+ * Selects one known macro assignment that satisfies the condition for every unresolved predicate.
437
+ * @param root - Condition for which a concrete witness is required.
438
+ * @returns A cube fixing known macro variables, or FALSE when no definite witness exists.
439
+ */ _proto.knownWitness = function knownWitness(root) {
440
+ var known = this._transform(root, "known");
441
+ if (known === 0) return 0;
442
+ var choices = [];
443
+ for(var variable = 0; variable < this._variables.length; variable++){
444
+ if (this._variables[variable].opaque) continue;
445
+ var node = this._nodes[known];
446
+ var choice = 0;
447
+ if (node.variable === variable) {
448
+ var edge = node.children.findIndex(function(child) {
449
+ return child !== 0;
450
+ });
451
+ choice = edge ? node.ends[edge - 1] : 0;
452
+ known = node.children[edge];
453
+ }
454
+ choices.push([
455
+ variable,
456
+ choice
457
+ ]);
458
+ }
459
+ var cube = 1;
460
+ for(var index = choices.length - 1; index >= 0; index--){
461
+ var _choices_index = choices[index], variable1 = _choices_index[0], choice1 = _choices_index[1];
462
+ var size = this._variables[variable1].size;
463
+ var ends = [], children = [];
464
+ if (choice1) {
465
+ ends.push(choice1);
466
+ children.push(0);
467
+ }
468
+ ends.push(choice1 + 1);
469
+ children.push(cube);
470
+ if (choice1 + 1 < size) {
471
+ ends.push(size);
472
+ children.push(0);
473
+ }
474
+ cube = this._node(variable1, ends, children);
475
+ if (cube === ShaderConditionDiagram.UNKNOWN) return ShaderConditionDiagram.FALSE;
476
+ }
477
+ return cube;
478
+ };
479
+ _proto._constraint = function _constraint(constraint) {
480
+ if (hasSourceFacts(constraint.sourceArm)) return this._sourceArm(constraint.sourceArm);
481
+ var group = constraint.conditionalGroup;
482
+ var arm = constraint.conditionalArm;
483
+ if (group !== undefined && arm !== undefined) {
484
+ var roots = this._groupRoots.get(group);
485
+ if (!roots) this._groupRoots.set(group, roots = this._group(group));
486
+ return roots.get(arm);
487
+ }
488
+ var _constraint_precedingConditions;
489
+ var conditions = (_constraint_precedingConditions = constraint.precedingConditions) != null ? _constraint_precedingConditions : [];
490
+ var root = constraint.condition ? this._condition(constraint.condition) : conditions.length ? 1 : this._opaque(this._unknownConstraintKey(constraint));
491
+ for(var _iterator = _create_for_of_iterator_helper_loose(conditions), _step; !(_step = _iterator()).done;){
492
+ var condition = _step.value;
493
+ root = this.and(root, this._condition(condition));
494
+ }
495
+ return root;
496
+ };
497
+ _proto._sourceArm = function _sourceArm(arm) {
498
+ if (arm.value !== undefined) return Number(arm.value);
499
+ var root = 1;
500
+ var _arm_predicates;
501
+ for(var _iterator = _create_for_of_iterator_helper_loose((_arm_predicates = arm.predicates) != null ? _arm_predicates : []), _step; !(_step = _iterator()).done;){
502
+ var term = _step.value;
503
+ var condition = this._sources.get(term.condition);
504
+ if (condition === undefined) {
505
+ var known = this._sourceFacts.get(term.condition);
506
+ condition = known ? this._condition(known) : this._opaque(this._sourceKey(term.condition));
507
+ this._sources.set(term.condition, condition);
508
+ }
509
+ root = this.and(root, term.negated ? this.not(condition) : condition);
510
+ }
511
+ return root;
512
+ };
513
+ _proto._group = function _group(group) {
514
+ var arms = this._groups.get(group);
515
+ var count = groupArmCount(arms);
516
+ var representative = arms.values().next().value;
517
+ var roots = new Map();
518
+ var remaining = 1;
519
+ for(var arm = 0; arm < count; arm++){
520
+ var _representative_conditionalReachableArms;
521
+ var constraint = arms.get(arm);
522
+ if (((_representative_conditionalReachableArms = representative.conditionalReachableArms) == null ? void 0 : _representative_conditionalReachableArms[arm]) === false) {
523
+ roots.set(arm, 0);
524
+ continue;
525
+ }
526
+ var last = representative.conditionalComplete && arm === count - 1;
527
+ var condition = last ? 1 : hasSourceFacts(constraint == null ? void 0 : constraint.sourceArm) ? this._sourceArm(constraint.sourceArm) : (constraint == null ? void 0 : constraint.condition) ? this._condition(constraint.condition) : this._opaque(groupArmKey(group, arm));
528
+ var _constraint_precedingConditions;
529
+ for(var _iterator = _create_for_of_iterator_helper_loose((_constraint_precedingConditions = constraint == null ? void 0 : constraint.precedingConditions) != null ? _constraint_precedingConditions : []), _step; !(_step = _iterator()).done;){
530
+ var preceding = _step.value;
531
+ condition = this.and(condition, this._condition(preceding));
532
+ }
533
+ roots.set(arm, this.and(remaining, condition));
534
+ remaining = this.and(remaining, this.not(condition));
535
+ }
536
+ return roots;
537
+ };
538
+ _proto._condition = function _condition(condition) {
539
+ var cached = this._conditions.get(condition);
540
+ if (cached !== undefined) return cached;
541
+ var result;
542
+ if (condition.kind === "constant") result = Number(condition.value);
543
+ else if (condition.kind === "expression" && !condition.opaque) {
544
+ var conjunction = condition.operator === "&&";
545
+ result = Number(conjunction);
546
+ for(var _iterator = _create_for_of_iterator_helper_loose(condition.operands), _step; !(_step = _iterator()).done;){
547
+ var operand = _step.value;
548
+ result = this._apply(conjunction ? "and" : "or", result, this._condition(operand));
549
+ }
550
+ if (condition.negated) result = this.not(result);
551
+ } else if (condition.kind === "expression" || !isExactCondition(condition)) {
552
+ result = this._opaque(opaqueConditionKey(condition));
553
+ if (condition.kind === "expression" && condition.negated) result = this.not(result);
554
+ } else {
555
+ var variable = this._variableIds.get(macroKey(condition));
556
+ var domain = this._variables[variable];
557
+ var ranges;
558
+ if (condition.kind === "defined") ranges = condition.defined ? [
559
+ [
560
+ 1,
561
+ domain.size
562
+ ]
563
+ ] : [
564
+ [
565
+ 0,
566
+ 1
567
+ ]
568
+ ];
569
+ else {
570
+ var start = domain.indices.get(condition.value) + 1;
571
+ var end = domain.indices.get(condition.value + 1) + 1;
572
+ switch(condition.operator){
573
+ case "==":
574
+ ranges = [
575
+ [
576
+ start,
577
+ end
578
+ ]
579
+ ];
580
+ break;
581
+ case "!=":
582
+ ranges = [
583
+ [
584
+ 1,
585
+ start
586
+ ],
587
+ [
588
+ end,
589
+ domain.size
590
+ ]
591
+ ];
592
+ break;
593
+ case "<":
594
+ ranges = [
595
+ [
596
+ 1,
597
+ start
598
+ ]
599
+ ];
600
+ break;
601
+ case "<=":
602
+ ranges = [
603
+ [
604
+ 1,
605
+ end
606
+ ]
607
+ ];
608
+ break;
609
+ case ">":
610
+ ranges = [
611
+ [
612
+ end,
613
+ domain.size
614
+ ]
615
+ ];
616
+ break;
617
+ case ">=":
618
+ ranges = [
619
+ [
620
+ start,
621
+ domain.size
622
+ ]
623
+ ];
624
+ break;
625
+ }
626
+ if (compareZero(condition.operator, condition.value)) ranges.push([
627
+ 0,
628
+ 1
629
+ ]);
630
+ }
631
+ result = this._ranges(variable, ranges);
632
+ }
633
+ this._conditions.set(condition, result);
634
+ return result;
635
+ };
636
+ _proto._sourceKey = function _sourceKey(condition) {
637
+ var key = this._sourceKeys.get(condition);
638
+ if (key === undefined) {
639
+ key = condition.kind === "opaque" ? "source-opaque:" + condition.identity : "source-expression:" + JSON.stringify([
640
+ condition.expression,
641
+ condition.versions
642
+ ]);
643
+ this._sourceKeys.set(condition, key);
644
+ }
645
+ return key;
646
+ };
647
+ _proto._unknownConstraintKey = function _unknownConstraintKey(constraint) {
648
+ return "constraint:" + this._constraints.get(constraint);
649
+ };
650
+ _proto._opaque = function _opaque(key) {
651
+ return this._ranges(this._variableIds.get(key), [
652
+ [
653
+ 1,
654
+ 2
655
+ ]
656
+ ]);
657
+ };
658
+ _proto._ranges = function _ranges(variable, ranges) {
659
+ var _loop = function(index) {
660
+ var start = boundaries[index];
661
+ ends.push(boundaries[index + 1]);
662
+ children.push(Number(ranges.some(function(param) {
663
+ var left = param[0], right = param[1];
664
+ return left <= start && start < right;
665
+ })));
666
+ };
667
+ var size = this._variables[variable].size;
668
+ var boundaries = Array.from(new Set([].concat([
669
+ 0,
670
+ size
671
+ ], ranges.flat()))).sort(function(left, right) {
672
+ return left - right;
673
+ });
674
+ var ends = [], children = [];
675
+ for(var index = 0; index < boundaries.length - 1; index++)_loop(index);
676
+ return this._node(variable, ends, children);
677
+ };
678
+ _proto._node = function _node(variable, ends, children) {
679
+ if ((this._remainingWork -= children.length) < 0) return ShaderConditionDiagram.UNKNOWN;
680
+ var compactEnds = [], compactChildren = [];
681
+ for(var index = 0; index < children.length; index++){
682
+ if (compactChildren[compactChildren.length - 1] === children[index]) compactEnds[compactEnds.length - 1] = ends[index];
683
+ else {
684
+ compactEnds.push(ends[index]);
685
+ compactChildren.push(children[index]);
686
+ }
687
+ }
688
+ if (compactChildren.length === 1) return compactChildren[0];
689
+ var key = variable + "|" + compactEnds.join(",") + "|" + compactChildren.join(",");
690
+ var result = this._unique.get(key);
691
+ if (result === undefined) {
692
+ result = this._nodes.length;
693
+ this._nodes.push({
694
+ variable: variable,
695
+ ends: compactEnds,
696
+ children: compactChildren
697
+ });
698
+ this._unique.set(key, result);
699
+ }
700
+ return result;
701
+ };
702
+ _proto._apply = function _apply(operator, left, right) {
703
+ var cached = this._operationResult(operator, left, right);
704
+ if (cached !== undefined) return cached;
705
+ var pending = [
706
+ [
707
+ left,
708
+ right
709
+ ]
710
+ ];
711
+ while(pending.length){
712
+ if (--this._remainingWork < 0) return ShaderConditionDiagram.UNKNOWN;
713
+ var _pending_ = pending[pending.length - 1], _$left = _pending_[0], _$right = _pending_[1];
714
+ if (this._operationResult(operator, _$left, _$right) !== undefined) {
715
+ pending.pop();
716
+ continue;
717
+ }
718
+ var a = this._nodes[_$left], b = this._nodes[_$right];
719
+ var variable = Math.min(a.variable, b.variable), size = this._variables[variable].size;
720
+ var aEnds = a.variable === variable ? a.ends : [
721
+ size
722
+ ], aChildren = a.variable === variable ? a.children : [
723
+ _$left
724
+ ];
725
+ var bEnds = b.variable === variable ? b.ends : [
726
+ size
727
+ ], bChildren = b.variable === variable ? b.children : [
728
+ _$right
729
+ ];
730
+ if ((this._remainingWork -= aEnds.length + bEnds.length) < 0) return ShaderConditionDiagram.UNKNOWN;
731
+ var ends = [], children = [];
732
+ var ready = true, i = 0, j = 0;
733
+ while(i < aEnds.length && j < bEnds.length){
734
+ var end = Math.min(aEnds[i], bEnds[j]);
735
+ var child = this._operationResult(operator, aChildren[i], bChildren[j]);
736
+ if (child === undefined) {
737
+ pending.push([
738
+ aChildren[i],
739
+ bChildren[j]
740
+ ]);
741
+ ready = false;
742
+ }
743
+ ends.push(end);
744
+ children.push(child);
745
+ if (aEnds[i] === end) i++;
746
+ if (bEnds[j] === end) j++;
747
+ }
748
+ if (!ready) continue;
749
+ this._operations.set(operationKey(operator, _$left, _$right), this._node(variable, ends, children));
750
+ pending.pop();
751
+ }
752
+ return this._operationResult(operator, left, right);
753
+ };
754
+ _proto._operationResult = function _operationResult(operator, left, right) {
755
+ if (left === right) return left;
756
+ if (operator === "and") {
757
+ if (!left || !right) return 0;
758
+ if (left === 1) return right;
759
+ if (right === 1) return left;
760
+ } else {
761
+ if (left === 1 || right === 1) return 1;
762
+ if (!left) return right;
763
+ if (!right) return left;
764
+ }
765
+ return this._operations.get(operationKey(operator, left, right));
766
+ };
767
+ _proto._transform = function _transform(root, mode) {
768
+ var _this = this;
769
+ var cache = mode === "not" ? this._negations : this._knownConditions;
770
+ var cached = cache.get(root);
771
+ if (cached !== undefined) return cached;
772
+ var pending = [
773
+ root
774
+ ];
775
+ while(pending.length){
776
+ var current = pending[pending.length - 1];
777
+ if (cache.has(current)) {
778
+ pending.pop();
779
+ continue;
780
+ }
781
+ var node = this._nodes[current];
782
+ if ((this._remainingWork -= node.children.length + 1) < 0) {
783
+ return mode === "known" ? ShaderConditionDiagram.FALSE : ShaderConditionDiagram.UNKNOWN;
784
+ }
785
+ var ready = true;
786
+ for(var _iterator = _create_for_of_iterator_helper_loose(node.children), _step; !(_step = _iterator()).done;){
787
+ var child = _step.value;
788
+ if (cache.has(child)) continue;
789
+ pending.push(child);
790
+ ready = false;
791
+ }
792
+ if (!ready) continue;
793
+ var children = node.children.map(function(child) {
794
+ return cache.get(child);
795
+ });
796
+ var result = mode === "known" && this._variables[node.variable].opaque ? children.reduce(function(left, right) {
797
+ return _this.and(left, right);
798
+ }, 1) : this._node(node.variable, node.ends, children);
799
+ // Only configurations proven true may survive the witness transform
800
+ if (mode === "known" && result === ShaderConditionDiagram.UNKNOWN) result = ShaderConditionDiagram.FALSE;
801
+ cache.set(current, result);
802
+ if (mode === "not" && this._remainingWork >= 0) cache.set(result, current);
803
+ pending.pop();
804
+ }
805
+ return cache.get(root);
806
+ };
807
+ return ShaderConditionDiagram;
808
+ }();
809
+ ShaderConditionDiagram.FALSE = 0;
810
+ ShaderConditionDiagram.TRUE = 1;
811
+ // An unknown terminal must not correlate independent incomplete proofs
812
+ ShaderConditionDiagram.UNKNOWN = 2;
813
+ function operationKey(operator, left, right) {
814
+ return left < right ? operator + ":" + left + ":" + right : operator + ":" + right + ":" + left;
815
+ }
816
+ function macroKey(condition) {
817
+ return "macro:" + condition.name + ":" + condition.version;
818
+ }
819
+ function hasSourceFacts(arm) {
820
+ return arm !== undefined && (arm.value !== undefined || arm.predicates !== undefined);
821
+ }
822
+ function groupArmKey(group, arm) {
823
+ return "group:" + group + ":" + arm;
824
+ }
825
+ function groupArmCount(arms) {
826
+ var count = 0;
827
+ var _constraint_conditionalArmCount;
828
+ for(var _iterator = _create_for_of_iterator_helper_loose(arms), _step; !(_step = _iterator()).done;){
829
+ var _step_value = _step.value, arm = _step_value[0], constraint = _step_value[1];
830
+ count = Math.max(count, arm + 1, (_constraint_conditionalArmCount = constraint.conditionalArmCount) != null ? _constraint_conditionalArmCount : 0);
831
+ }
832
+ return count;
833
+ }
834
+ function isExactCondition(condition) {
835
+ return condition.kind === "defined" || Number.isInteger(condition.value) && condition.value >= INTEGER_MINIMUM && condition.value < INTEGER_END;
836
+ }
837
+ function opaqueConditionKey(condition) {
838
+ return condition.kind === "expression" ? "expression:" + JSON.stringify([
839
+ condition.expression,
840
+ condition.names,
841
+ condition.versions
842
+ ]) : "invalid:" + condition.name + ":" + condition.version + ":" + (condition.kind === "comparison" ? condition.operator + ":" + condition.value : condition.defined);
843
+ }
844
+ function compareZero(operator, value) {
845
+ switch(operator){
846
+ case "==":
847
+ return value === 0;
848
+ case "!=":
849
+ return value !== 0;
850
+ case "<":
851
+ return value > 0;
852
+ case "<=":
853
+ return value >= 0;
854
+ case ">":
855
+ return value < 0;
856
+ case ">=":
857
+ return value <= 0;
858
+ }
859
+ }
860
+
861
+ /**
862
+ * Analyzer-only graph and reachability information derived from neutral shader IR.
863
+ * @internal
864
+ */ var ShaderAnalysisInfo = /*#__PURE__*/ function() {
865
+ function ShaderAnalysisInfo(ir, coreInfo) {
866
+ this.ir = ir;
867
+ this.coreInfo = coreInfo;
868
+ this._glFragColorReferences = [];
869
+ this._glFragDataConditionalReferences = [];
870
+ this.glFragDataReferences = [];
871
+ this._callFacts = new Map();
872
+ this._writes = new Map();
873
+ this._unknownEffects = new Map();
874
+ this._indexedMacroReferences = new Set();
875
+ this._indexedMacroArguments = new Map();
876
+ this._functionsByName = new Map();
877
+ this._branches = new Set();
878
+ this._reachableByEntry = new Map();
879
+ this._reachableByFunction = new Map();
880
+ this._writeReachableByFunction = new Map();
881
+ this._indexFunctions(ir.program);
882
+ this._indexFunctionBodies();
883
+ for(var _i = 0, _iter = [
884
+ coreInfo.vertexEntry,
885
+ coreInfo.fragmentEntry
886
+ ]; _i < _iter.length; _i++){
887
+ var entry = _iter[_i];
888
+ var _fn_branchSignature;
889
+ for(var _iterator = _create_for_of_iterator_helper_loose(entry.functions), _step; !(_step = _iterator()).done;){
890
+ var fn = _step.value;
891
+ this._branches.add((_fn_branchSignature = fn.branchSignature) != null ? _fn_branchSignature : fn.astNode.protoType.ident.branch);
892
+ }
893
+ }
894
+ this._conditions = new ShaderConditionDiagram(this._branches);
895
+ this._branches.clear();
896
+ }
897
+ var _proto = ShaderAnalysisInfo.prototype;
898
+ /**
899
+ * Finds every function reachable from an entry, including the entry declarations themselves.
900
+ * @param entry - Entry point to traverse.
901
+ * @returns Reachable function identities.
902
+ */ _proto.reachableFunctions = function reachableFunctions(entry) {
903
+ return new Set(this._getReachableConditions(entry).keys());
904
+ };
905
+ /**
906
+ * Determines whether a branch inside a function is reachable from an entry under one consistent
907
+ * macro configuration. An unresolved proof is not treated as evidence for a diagnostic.
908
+ * @param entry - Entry point from which calls originate.
909
+ * @param functionNode - Function containing the branch.
910
+ * @param branch - Branch at the diagnostic site.
911
+ * @returns Whether at least one macro configuration is proven to reach the site.
912
+ */ _proto.isFunctionBranchReachable = function isFunctionBranchReachable(entry, functionNode, branch) {
913
+ var _this__getReachableConditions_get;
914
+ var reachable = (_this__getReachableConditions_get = this._getReachableConditions(entry).get(functionNode)) != null ? _this__getReachableConditions_get : ShaderConditionDiagram.FALSE;
915
+ return this._conditions.reachability(this._conditions.and(reachable, this._conditions.branch(branch))) === "reachable";
916
+ };
917
+ /**
918
+ * Classifies whether every reachable entry configuration writes a source identifier or builtin semantic.
919
+ * @param entry - Entry point whose call graph is inspected.
920
+ * @param target - Leftmost source identifier or builtin semantic of the assignment target.
921
+ * @returns Proven coverage, a proven missing-write configuration, or an unresolved complex condition.
922
+ */ _proto.getReachableWriteCoverage = function getReachableWriteCoverage(entry, target) {
923
+ if (!entry.functions.length) return "unknown";
924
+ var diagram = this._conditions;
925
+ var result = "covered";
926
+ for(var _iterator = _create_for_of_iterator_helper_loose(entry.functions), _step; !(_step = _iterator()).done;){
927
+ var entryFunction = _step.value;
928
+ var writes = [];
929
+ var unknownEffects = [];
930
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(this._getFunctionReachableConditions(entryFunction, true)), _step1; !(_step1 = _iterator1()).done;){
931
+ var _step_value = _step1.value, functionNode = _step_value[0], reachable = _step_value[1];
932
+ var _this__unknownEffects_get;
933
+ for(var _iterator2 = _create_for_of_iterator_helper_loose((_this__unknownEffects_get = this._unknownEffects.get(functionNode)) != null ? _this__unknownEffects_get : []), _step2; !(_step2 = _iterator2()).done;){
934
+ var effect = _step2.value;
935
+ unknownEffects.push(diagram.and(reachable, diagram.branch(effect, true)));
936
+ }
937
+ var _this__writes_get;
938
+ for(var _iterator3 = _create_for_of_iterator_helper_loose((_this__writes_get = this._writes.get(functionNode)) != null ? _this__writes_get : []), _step3; !(_step3 = _iterator3()).done;){
939
+ var write = _step3.value;
940
+ if (write.target !== target) continue;
941
+ writes.push(diagram.and(reachable, diagram.branch(write.branch, true)));
942
+ }
943
+ }
944
+ var _entryFunction_branchSignature;
945
+ var entryCondition = diagram.branch((_entryFunction_branchSignature = entryFunction.branchSignature) != null ? _entryFunction_branchSignature : entryFunction.astNode.protoType.ident.branch, true);
946
+ var missing = diagram.and(entryCondition, diagram.not(diagram.orAll(writes)));
947
+ if (missing === ShaderConditionDiagram.FALSE) continue;
948
+ if (diagram.reachability(diagram.and(missing, diagram.not(diagram.orAll(unknownEffects)))) === "reachable") {
949
+ return "uncovered";
950
+ }
951
+ result = "unknown";
952
+ }
953
+ return result;
954
+ };
955
+ /**
956
+ * Classifies whether a function returns under every macro configuration reaching its declaration.
957
+ * @param functionNode - Function whose body is inspected.
958
+ * @returns Proven return coverage, a missing-return configuration, or unresolved coverage.
959
+ */ _proto.getReturnCoverage = function getReturnCoverage(functionNode) {
960
+ var returns = this._returnCondition(functionNode.statements);
961
+ // A body with no possible return is invalid whenever its declaration is selected.
962
+ return returns === ShaderConditionDiagram.FALSE ? "uncovered" : this._conditions.coverage(returns, this._conditions.branch(functionNode.protoType.ident.branch, true));
963
+ };
964
+ /**
965
+ * Finds references to the legacy fragment output that a fragment entry can actually reach.
966
+ * @param entry - Fragment entry whose conditional call paths are inspected.
967
+ * @returns Source ranges proven reachable under at least one consistent macro configuration.
968
+ */ _proto.reachableFragmentOutput0References = function reachableFragmentOutput0References(entry) {
969
+ var locations = [];
970
+ for(var _iterator = _create_for_of_iterator_helper_loose(this._glFragColorReferences), _step; !(_step = _iterator()).done;){
971
+ var reference = _step.value;
972
+ if (this.isFunctionBranchReachable(entry, reference.functionNode, reference.branch)) {
973
+ locations.push(reference.location);
974
+ }
975
+ }
976
+ return locations;
977
+ };
978
+ /**
979
+ * Finds legacy fragment-output references reachable from one exact entry declaration.
980
+ * @param entryFunction - Exact macro-alternative function selected as the fragment entry.
981
+ * @returns Source ranges proven reachable under the entry declaration's macro constraints.
982
+ */ _proto.reachableFragmentOutput0ReferencesFrom = function reachableFragmentOutput0ReferencesFrom(entryFunction) {
983
+ var reachable = this._getFunctionReachableConditions(entryFunction);
984
+ var diagram = this._conditions;
985
+ return this._glFragColorReferences.filter(function(reference) {
986
+ var _reachable_get;
987
+ return diagram.reachability(diagram.and((_reachable_get = reachable.get(reference.functionNode)) != null ? _reachable_get : ShaderConditionDiagram.FALSE, diagram.branch(reference.branch))) === "reachable";
988
+ }).map(function(reference) {
989
+ return reference.location;
990
+ });
991
+ };
992
+ /**
993
+ * Finds a macro configuration in which one fragment entry can reach both legacy output forms.
994
+ * @param entryFunction - Exact macro-alternative function selected as the fragment entry.
995
+ * @returns The conflicting output ranges, or `undefined` when coexistence is disproven or unknown.
996
+ */ _proto.coexistingLegacyFragmentOutputsFrom = function coexistingLegacyFragmentOutputsFrom(entryFunction) {
997
+ var reachable = this._getFunctionReachableConditions(entryFunction);
998
+ var diagram = this._conditions;
999
+ var at = function(reference) {
1000
+ var _reachable_get;
1001
+ return diagram.and((_reachable_get = reachable.get(reference.functionNode)) != null ? _reachable_get : ShaderConditionDiagram.FALSE, diagram.branch(reference.branch));
1002
+ };
1003
+ for(var _iterator = _create_for_of_iterator_helper_loose(this._glFragColorReferences), _step; !(_step = _iterator()).done;){
1004
+ var output0 = _step.value;
1005
+ var output0Condition = at(output0);
1006
+ if (output0Condition === ShaderConditionDiagram.FALSE) continue;
1007
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(this._glFragDataConditionalReferences), _step1; !(_step1 = _iterator1()).done;){
1008
+ var outputArray = _step1.value;
1009
+ if (diagram.reachability(diagram.and(output0Condition, at(outputArray))) === "reachable") {
1010
+ return {
1011
+ output0: output0.location,
1012
+ outputArray: outputArray.location
1013
+ };
1014
+ }
1015
+ }
1016
+ }
1017
+ return;
1018
+ };
1019
+ /**
1020
+ * Returns every parsed function declaration.
1021
+ * @returns Function identities retained by the neutral IR.
1022
+ */ _proto.functions = function functions() {
1023
+ var _result;
1024
+ var result = [];
1025
+ this._functionsByName.forEach(function(functions) {
1026
+ return (_result = result).push.apply(_result, [].concat(functions));
1027
+ });
1028
+ return result;
1029
+ };
1030
+ /**
1031
+ * Finds satisfiable mutual recursion without enumerating conditional call paths or all simple cycles.
1032
+ * @returns One witness per canonical minimum participant; an opaque-dependent cycle has no fixed chain.
1033
+ */ _proto.mutualRecursionWitnesses = function mutualRecursionWitnesses() {
1034
+ var _this, _loop = function() {
1035
+ var _this2, _loop = function() {
1036
+ var marker = _step1.value;
1037
+ var name = marker.protoType.ident.lexeme;
1038
+ var allowed = new Set(Array.from(component).filter(function(fn) {
1039
+ return fn.protoType.ident.lexeme > name || fn.protoType.ident.lexeme === name && order.get(fn) >= order.get(marker);
1040
+ }));
1041
+ if (allowed.size < 2) return "continue";
1042
+ var declaration = diagram.branch(marker.protoType.ident.branch);
1043
+ var seeds = [];
1044
+ var _this__callFacts_get;
1045
+ for(var _iterator = _create_for_of_iterator_helper_loose((_this__callFacts_get = _this2._callFacts.get(marker)) != null ? _this__callFacts_get : []), _step; !(_step = _iterator()).done;){
1046
+ var call = _step.value;
1047
+ if (call.callee === marker || !allowed.has(call.callee)) continue;
1048
+ seeds.push([
1049
+ call.callee,
1050
+ diagram.and(declaration, _this2._callCondition(call, false))
1051
+ ]);
1052
+ }
1053
+ var _this__propagateConditions_get;
1054
+ var cycleCondition = (_this__propagateConditions_get = _this2._propagateConditions(seeds, false, allowed, marker).get(marker)) != null ? _this__propagateConditions_get : ShaderConditionDiagram.FALSE;
1055
+ if (diagram.reachability(cycleCondition) !== "reachable") return "continue";
1056
+ var witness = diagram.knownWitness(cycleCondition);
1057
+ witnesses.push({
1058
+ marker: marker,
1059
+ cycle: _this2._findCycleWitness(marker, allowed, witness)
1060
+ });
1061
+ };
1062
+ var component = _step.value;
1063
+ var members = functions.filter(function(fn) {
1064
+ return component.has(fn);
1065
+ });
1066
+ var simple = members.every(function(fn) {
1067
+ var _this__callFacts_get;
1068
+ return new Set(((_this__callFacts_get = _this1._callFacts.get(fn)) != null ? _this__callFacts_get : []).filter(function(call) {
1069
+ return call.callee !== fn && component.has(call.callee);
1070
+ }).map(function(call) {
1071
+ return call.callee;
1072
+ })).size === 1;
1073
+ });
1074
+ var minimum = members.reduce(function(left, right) {
1075
+ return right.protoType.ident.lexeme < left.protoType.ident.lexeme ? right : left;
1076
+ });
1077
+ // A simple component has only one non-self cycle, regardless of its conditional edge alternatives.
1078
+ for(var _iterator = _create_for_of_iterator_helper_loose(simple ? [
1079
+ minimum
1080
+ ] : members), _step1; !(_step1 = _iterator()).done;)_this2 = _this, _loop();
1081
+ };
1082
+ var _this1 = this;
1083
+ var witnesses = [];
1084
+ var functions = this.functions();
1085
+ var order = new Map(functions.map(function(fn, index) {
1086
+ return [
1087
+ fn,
1088
+ index
1089
+ ];
1090
+ }));
1091
+ var diagram = this._conditions;
1092
+ for(var _iterator = _create_for_of_iterator_helper_loose(this._cyclicComponents()), _step; !(_step = _iterator()).done;)_this = this, _loop();
1093
+ return witnesses;
1094
+ };
1095
+ _proto._indexFunctions = function _indexFunctions(root) {
1096
+ var pending = [
1097
+ root
1098
+ ];
1099
+ while(pending.length){
1100
+ var node = pending.pop();
1101
+ if (_instanceof(node, analyzer.BaseToken)) {
1102
+ this._branches.add(node.branch);
1103
+ continue;
1104
+ }
1105
+ this._branches.add(node._branch);
1106
+ if (_instanceof(node, analyzer.ASTNode.FunctionDefinition)) {
1107
+ var name = node.protoType.ident.lexeme;
1108
+ var _this__functionsByName_get;
1109
+ var functions = (_this__functionsByName_get = this._functionsByName.get(name)) != null ? _this__functionsByName_get : [];
1110
+ functions.push(node);
1111
+ this._functionsByName.set(name, functions);
1112
+ }
1113
+ for(var index = node.children.length - 1; index >= 0; index--){
1114
+ var child = node.children[index];
1115
+ if (_instanceof(child, analyzer.TreeNode) || _instanceof(child, analyzer.BaseToken)) pending.push(child);
1116
+ }
1117
+ }
1118
+ };
1119
+ _proto._indexFunctionBodies = function _indexFunctionBodies() {
1120
+ var _this = this;
1121
+ this._functionsByName.forEach(function(functions) {
1122
+ for(var _iterator = _create_for_of_iterator_helper_loose(functions), _step; !(_step = _iterator()).done;){
1123
+ var functionNode = _step.value;
1124
+ _this._walkFunction(functionNode, functionNode.statements);
1125
+ }
1126
+ });
1127
+ for(var _iterator = _create_for_of_iterator_helper_loose(this._callFacts), _step; !(_step = _iterator()).done;){
1128
+ var _loop = function() {
1129
+ var call = _step1.value;
1130
+ var _branchesByCallee_get;
1131
+ var branches = (_branchesByCallee_get = branchesByCallee.get(call.callee)) != null ? _branchesByCallee_get : [];
1132
+ if (branches.some(function(branch) {
1133
+ return analyzer.sameBranch(branch, call.branch);
1134
+ })) return "continue";
1135
+ branches.push(call.branch);
1136
+ branchesByCallee.set(call.callee, branches);
1137
+ unique.push(call);
1138
+ };
1139
+ var _step_value = _step.value, caller = _step_value[0], calls = _step_value[1];
1140
+ var unique = [];
1141
+ var branchesByCallee = new Map();
1142
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(calls), _step1; !(_step1 = _iterator1()).done;)_loop();
1143
+ this._callFacts.set(caller, unique);
1144
+ }
1145
+ };
1146
+ _proto._walkFunction = function _walkFunction(functionNode, node) {
1147
+ var _this = this;
1148
+ walkEffectiveShaderSyntax(node, function(node, branch, location) {
1149
+ _this._branches.add(branch);
1150
+ if (_instanceof(node, analyzer.ASTNode.PostfixExpression) && node.children.length === 4) {
1151
+ var base = node.children[0];
1152
+ if (_instanceof(base, analyzer.TreeNode)) {
1153
+ var target = assignmentTargetBase(base);
1154
+ if (_instanceof(target, analyzer.ASTNode.MacroCallSymbol) || _instanceof(target, analyzer.ASTNode.MacroCallFunction)) {
1155
+ _this._indexedMacroReferences.add(target.location.start.index);
1156
+ }
1157
+ }
1158
+ }
1159
+ if (_instanceof(node, analyzer.ASTNode.FunctionCallGeneric)) _this._recordCall(functionNode, node, branch);
1160
+ if (_instanceof(node, analyzer.ASTNode.VariableIdentifier)) {
1161
+ if (node.builtinSemantic === analyzer.ShaderBuiltinSemantic.FragmentOutput0) {
1162
+ _this._glFragColorReferences.push({
1163
+ functionNode: functionNode,
1164
+ location: location,
1165
+ branch: branch
1166
+ });
1167
+ } else if (node.builtinSemantic === analyzer.ShaderBuiltinSemantic.FragmentOutputArray) {
1168
+ var _this__indexedMacroArguments_get;
1169
+ if (!((_this__indexedMacroArguments_get = _this._indexedMacroArguments.get(node)) != null ? _this__indexedMacroArguments_get : []).some(function(indexedBranch) {
1170
+ return analyzer.sameBranch(indexedBranch, branch);
1171
+ })) {
1172
+ _this.glFragDataReferences.push(location);
1173
+ }
1174
+ _this._glFragDataConditionalReferences.push({
1175
+ functionNode: functionNode,
1176
+ location: location,
1177
+ branch: branch
1178
+ });
1179
+ }
1180
+ }
1181
+ if (_instanceof(node, analyzer.ASTNode.AssignmentExpression) && node.children.length === 3) {
1182
+ var lhs = node.children[0];
1183
+ if (_instanceof(lhs, analyzer.TreeNode)) {
1184
+ _this._recordAssignmentTarget(functionNode, lhs, branch);
1185
+ }
1186
+ }
1187
+ }, function(syntax, branch, location) {
1188
+ _this._branches.add(branch);
1189
+ var indexedAlias = _this._indexedMacroReferences.has(location.start.index);
1190
+ if (indexedAlias && _instanceof(syntax.valueTarget, analyzer.TreeNode)) {
1191
+ var argument = assignmentTargetBase(syntax.valueTarget);
1192
+ if (_instanceof(argument, analyzer.ASTNode.VariableIdentifier)) {
1193
+ var _this__indexedMacroArguments_get;
1194
+ var branches = (_this__indexedMacroArguments_get = _this._indexedMacroArguments.get(argument)) != null ? _this__indexedMacroArguments_get : [];
1195
+ branches.push(branch);
1196
+ _this._indexedMacroArguments.set(argument, branches);
1197
+ }
1198
+ }
1199
+ var _syntax_writtenTargets;
1200
+ for(var _iterator = _create_for_of_iterator_helper_loose((_syntax_writtenTargets = syntax.writtenTargets) != null ? _syntax_writtenTargets : []), _step; !(_step = _iterator()).done;){
1201
+ var target = _step.value;
1202
+ _this._recordAssignmentTarget(functionNode, target, branch);
1203
+ }
1204
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(syntax.references), _step1; !(_step1 = _iterator1()).done;){
1205
+ var reference = _step1.value;
1206
+ if (reference.builtinSemantic === analyzer.ShaderBuiltinSemantic.FragmentOutput0) {
1207
+ _this._glFragColorReferences.push({
1208
+ functionNode: functionNode,
1209
+ location: location,
1210
+ branch: branch
1211
+ });
1212
+ } else if (reference.builtinSemantic === analyzer.ShaderBuiltinSemantic.FragmentOutputArray) {
1213
+ if (!reference.indexed && !(indexedAlias && syntax.valueTarget === analyzer.ShaderBuiltinSemantic.FragmentOutputArray)) {
1214
+ _this.glFragDataReferences.push(location);
1215
+ }
1216
+ _this._glFragDataConditionalReferences.push({
1217
+ functionNode: functionNode,
1218
+ location: location,
1219
+ branch: branch
1220
+ });
1221
+ }
1222
+ for(var _iterator2 = _create_for_of_iterator_helper_loose(reference.functions), _step2; !(_step2 = _iterator2()).done;){
1223
+ var candidate = _step2.value;
1224
+ var _this__callFacts_get;
1225
+ var facts = (_this__callFacts_get = _this._callFacts.get(functionNode)) != null ? _this__callFacts_get : [];
1226
+ facts.push({
1227
+ callee: candidate.astNode,
1228
+ branch: branch
1229
+ });
1230
+ _this._callFacts.set(functionNode, facts);
1231
+ }
1232
+ }
1233
+ }, analyzer.EMPTY_BRANCH, undefined, function(branch) {
1234
+ _this._branches.add(branch);
1235
+ var _this__unknownEffects_get;
1236
+ var effects = (_this__unknownEffects_get = _this._unknownEffects.get(functionNode)) != null ? _this__unknownEffects_get : [];
1237
+ effects.push(branch);
1238
+ _this._unknownEffects.set(functionNode, effects);
1239
+ });
1240
+ };
1241
+ _proto._recordCall = function _recordCall(caller, call, branch) {
1242
+ if (branch === void 0) branch = call._branch;
1243
+ var _call_fnSymbols;
1244
+ var candidates = (_call_fnSymbols = call.fnSymbols) != null ? _call_fnSymbols : _instanceof(call.fnSymbol, analyzer.FnSymbol) ? [
1245
+ call.fnSymbol
1246
+ ] : [];
1247
+ if (!candidates.length) return;
1248
+ var _this__callFacts_get;
1249
+ var facts = (_this__callFacts_get = this._callFacts.get(caller)) != null ? _this__callFacts_get : [];
1250
+ for(var _iterator = _create_for_of_iterator_helper_loose(candidates), _step; !(_step = _iterator()).done;){
1251
+ var candidate = _step.value;
1252
+ facts.push({
1253
+ callee: candidate.astNode,
1254
+ branch: branch
1255
+ });
1256
+ this._recordOutputParameterWrites(caller, call, candidate, branch);
1257
+ }
1258
+ this._callFacts.set(caller, facts);
1259
+ };
1260
+ _proto._returnCondition = function _returnCondition(root) {
1261
+ var diagram = this._conditions;
1262
+ var returns = [];
1263
+ var pending = [
1264
+ {
1265
+ node: root,
1266
+ returns: returns
1267
+ }
1268
+ ];
1269
+ while(pending.length){
1270
+ var current = pending.pop();
1271
+ if ("left" in current) {
1272
+ // A runtime if/else guarantees a return only where both arms terminate.
1273
+ current.returns.push(diagram.and(diagram.orAll(current.left), diagram.orAll(current.right)));
1274
+ continue;
1275
+ }
1276
+ var node = current.node, returns1 = current.returns;
1277
+ var branch = diagram.branch(node._branch, true);
1278
+ if (branch === ShaderConditionDiagram.FALSE) continue;
1279
+ if (_instanceof(node, analyzer.ASTNode.JumpStatement)) {
1280
+ var keyword = node.children[0];
1281
+ if (_instanceof(keyword, analyzer.BaseToken) && keyword.type === analyzer.Keyword.RETURN) returns1.push(branch);
1282
+ } else if (_instanceof(node, analyzer.ASTNode.SelectionStatement)) {
1283
+ if (node.children.length !== 7) continue;
1284
+ var left = [], right = [];
1285
+ pending.push({
1286
+ left: left,
1287
+ right: right,
1288
+ returns: returns1
1289
+ });
1290
+ pending.push({
1291
+ node: node.children[6],
1292
+ returns: right
1293
+ });
1294
+ pending.push({
1295
+ node: node.children[4],
1296
+ returns: left
1297
+ });
1298
+ } else if (_instanceof(node, analyzer.ASTNode.IterationStatement)) {
1299
+ // Loop termination is not proven here, so missing return coverage remains unknown
1300
+ returns1.push(diagram.and(branch, ShaderConditionDiagram.UNKNOWN));
1301
+ } else if (_instanceof(node, analyzer.ASTNode.Statement) || _instanceof(node, analyzer.ASTNode.SimpleStatement) || _instanceof(node, analyzer.ASTNode.CompoundStatement) || _instanceof(node, analyzer.ASTNode.CompoundStatementNoScope) || _instanceof(node, analyzer.ASTNode.StatementList) || _instanceof(node, analyzer.ASTNode.MacroIfStatement) || _instanceof(node, analyzer.ASTNode.MacroBranch)) {
1302
+ // Flatten sequential containers before unioning, including left-recursive statement lists.
1303
+ for(var index = node.children.length - 1; index >= 0; index--){
1304
+ var child = node.children[index];
1305
+ if (_instanceof(child, analyzer.TreeNode)) pending.push({
1306
+ node: child,
1307
+ returns: returns1
1308
+ });
1309
+ }
1310
+ }
1311
+ }
1312
+ return diagram.orAll(returns);
1313
+ };
1314
+ _proto._getReachableConditions = function _getReachableConditions(entry) {
1315
+ var _this = this;
1316
+ var cached = this._reachableByEntry.get(entry);
1317
+ if (cached) return cached;
1318
+ var reachable = entry.functions.length === 1 ? this._getFunctionReachableConditions(entry.functions[0]) : this._propagateConditions(entry.functions.map(function(fn) {
1319
+ var _fn_branchSignature;
1320
+ return [
1321
+ fn.astNode,
1322
+ _this._conditions.branch((_fn_branchSignature = fn.branchSignature) != null ? _fn_branchSignature : fn.astNode.protoType.ident.branch)
1323
+ ];
1324
+ }), false);
1325
+ this._reachableByEntry.set(entry, reachable);
1326
+ return reachable;
1327
+ };
1328
+ _proto._getFunctionReachableConditions = function _getFunctionReachableConditions(entry, forWrites) {
1329
+ if (forWrites === void 0) forWrites = false;
1330
+ var cache = forWrites ? this._writeReachableByFunction : this._reachableByFunction;
1331
+ var cached = cache.get(entry);
1332
+ if (cached) return cached;
1333
+ var _entry_branchSignature;
1334
+ var reachable = this._propagateConditions([
1335
+ [
1336
+ entry.astNode,
1337
+ this._conditions.branch((_entry_branchSignature = entry.branchSignature) != null ? _entry_branchSignature : entry.astNode.protoType.ident.branch, forWrites)
1338
+ ]
1339
+ ], forWrites);
1340
+ cache.set(entry, reachable);
1341
+ return reachable;
1342
+ };
1343
+ _proto._callCondition = function _callCondition(call, forWrites) {
1344
+ return this._conditions.and(this._conditions.branch(call.branch, forWrites), this._conditions.branch(call.callee.protoType.ident.branch, forWrites));
1345
+ };
1346
+ _proto._propagateConditions = function _propagateConditions(seeds, forWrites, allowed, terminal) {
1347
+ var diagram = this._conditions;
1348
+ var reachable = new Map();
1349
+ var queued = new Map();
1350
+ var pending = [];
1351
+ var enqueue = function(fn, condition) {
1352
+ if (condition === ShaderConditionDiagram.FALSE || allowed && !allowed.has(fn)) return;
1353
+ var incoming = queued.get(fn);
1354
+ if (incoming) {
1355
+ incoming.push(condition);
1356
+ } else {
1357
+ queued.set(fn, [
1358
+ condition
1359
+ ]);
1360
+ pending.push(fn);
1361
+ }
1362
+ };
1363
+ for(var _iterator = _create_for_of_iterator_helper_loose(seeds), _step; !(_step = _iterator()).done;){
1364
+ var _step_value = _step.value, fn = _step_value[0], condition = _step_value[1];
1365
+ enqueue(fn, condition);
1366
+ }
1367
+ for(var index = 0; index < pending.length; index++){
1368
+ var fn1 = pending[index];
1369
+ var incoming = queued.get(fn1);
1370
+ queued.delete(fn1);
1371
+ var _reachable_get;
1372
+ var previous = (_reachable_get = reachable.get(fn1)) != null ? _reachable_get : ShaderConditionDiagram.FALSE;
1373
+ incoming.push(previous);
1374
+ // Batch incoming edges so high fan-in does not build every prefix of the same union.
1375
+ var condition1 = diagram.orAll(incoming);
1376
+ if (condition1 === previous) continue;
1377
+ reachable.set(fn1, condition1);
1378
+ if (fn1 === terminal) continue;
1379
+ var _this__callFacts_get;
1380
+ for(var _iterator1 = _create_for_of_iterator_helper_loose((_this__callFacts_get = this._callFacts.get(fn1)) != null ? _this__callFacts_get : []), _step1; !(_step1 = _iterator1()).done;){
1381
+ var call = _step1.value;
1382
+ enqueue(call.callee, diagram.and(condition1, this._callCondition(call, forWrites)));
1383
+ }
1384
+ }
1385
+ return reachable;
1386
+ };
1387
+ _proto._cyclicComponents = function _cyclicComponents() {
1388
+ var functions = this.functions();
1389
+ var reverse = new Map();
1390
+ for(var _iterator = _create_for_of_iterator_helper_loose(this._callFacts), _step; !(_step = _iterator()).done;){
1391
+ var _step_value = _step.value, caller = _step_value[0], calls = _step_value[1];
1392
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(calls), _step1; !(_step1 = _iterator1()).done;){
1393
+ var callee = _step1.value.callee;
1394
+ var _reverse_get;
1395
+ var incoming = (_reverse_get = reverse.get(callee)) != null ? _reverse_get : [];
1396
+ incoming.push(caller);
1397
+ reverse.set(callee, incoming);
1398
+ }
1399
+ }
1400
+ var visited = new Set();
1401
+ var finished = [];
1402
+ for(var _iterator2 = _create_for_of_iterator_helper_loose(functions), _step2; !(_step2 = _iterator2()).done;){
1403
+ var start = _step2.value;
1404
+ if (visited.has(start)) continue;
1405
+ var pending = [
1406
+ {
1407
+ node: start,
1408
+ finish: false
1409
+ }
1410
+ ];
1411
+ while(pending.length){
1412
+ var _pending_pop = pending.pop(), node = _pending_pop.node, finish = _pending_pop.finish;
1413
+ if (finish) {
1414
+ finished.push(node);
1415
+ continue;
1416
+ }
1417
+ if (visited.has(node)) continue;
1418
+ visited.add(node);
1419
+ pending.push({
1420
+ node: node,
1421
+ finish: true
1422
+ });
1423
+ var _this__callFacts_get;
1424
+ for(var _iterator3 = _create_for_of_iterator_helper_loose((_this__callFacts_get = this._callFacts.get(node)) != null ? _this__callFacts_get : []), _step3; !(_step3 = _iterator3()).done;){
1425
+ var callee1 = _step3.value.callee;
1426
+ pending.push({
1427
+ node: callee1,
1428
+ finish: false
1429
+ });
1430
+ }
1431
+ }
1432
+ }
1433
+ visited.clear();
1434
+ var components = [];
1435
+ while(finished.length){
1436
+ var start1 = finished.pop();
1437
+ if (visited.has(start1)) continue;
1438
+ var component = new Set();
1439
+ var pending1 = [
1440
+ start1
1441
+ ];
1442
+ while(pending1.length){
1443
+ var _pending;
1444
+ var node1 = pending1.pop();
1445
+ if (visited.has(node1)) continue;
1446
+ visited.add(node1);
1447
+ component.add(node1);
1448
+ var _reverse_get1;
1449
+ (_pending = pending1).push.apply(_pending, [].concat((_reverse_get1 = reverse.get(node1)) != null ? _reverse_get1 : []));
1450
+ }
1451
+ if (component.size > 1) components.push(component);
1452
+ }
1453
+ return components;
1454
+ };
1455
+ _proto._findCycleWitness = function _findCycleWitness(marker, allowed, witness) {
1456
+ if (witness === ShaderConditionDiagram.FALSE) return;
1457
+ var visited = new Set([
1458
+ marker
1459
+ ]);
1460
+ var stack = [
1461
+ {
1462
+ node: marker,
1463
+ next: 0
1464
+ }
1465
+ ];
1466
+ while(stack.length){
1467
+ var frame = stack[stack.length - 1];
1468
+ var _this__callFacts_get;
1469
+ var calls = (_this__callFacts_get = this._callFacts.get(frame.node)) != null ? _this__callFacts_get : [];
1470
+ if (frame.next === calls.length) {
1471
+ stack.pop();
1472
+ continue;
1473
+ }
1474
+ var call = calls[frame.next++];
1475
+ if (!allowed.has(call.callee) || call.callee === frame.node || this._conditions.coverage(this._callCondition(call, false), witness) !== "covered") continue;
1476
+ if (call.callee === marker && stack.length > 1) return stack.map(function(item) {
1477
+ return item.node;
1478
+ });
1479
+ if (!visited.has(call.callee)) {
1480
+ visited.add(call.callee);
1481
+ stack.push({
1482
+ node: call.callee,
1483
+ next: 0
1484
+ });
1485
+ }
1486
+ }
1487
+ };
1488
+ _proto._recordOutputParameterWrites = function _recordOutputParameterWrites(caller, call, callee, callBranch) {
1489
+ var argumentList = call.children[2];
1490
+ if (!_instanceof(argumentList, analyzer.ASTNode.FunctionCallParameterList)) return;
1491
+ var _callee_astNode_protoType_parameterList;
1492
+ var parameters = (_callee_astNode_protoType_parameterList = callee.astNode.protoType.parameterList) != null ? _callee_astNode_protoType_parameterList : [];
1493
+ for(var i = 0, n = Math.min(parameters.length, argumentList.paramNodes.length); i < n; i++){
1494
+ var parameter = parameters[i].astNode;
1495
+ if (!_instanceof(parameter, analyzer.ASTNode.ParameterDeclaration)) continue;
1496
+ if (!analyzer.ParserUtils.hasQualifier(parameter, analyzer.Keyword.OUT) && !analyzer.ParserUtils.hasQualifier(parameter, analyzer.Keyword.INOUT)) {
1497
+ continue;
1498
+ }
1499
+ var argument = argumentList.paramNodes[i];
1500
+ if (!_instanceof(argument, analyzer.TreeNode)) continue;
1501
+ var _callee_branchSignature;
1502
+ var branch = combineBranches(callBranch, (_callee_branchSignature = callee.branchSignature) != null ? _callee_branchSignature : analyzer.EMPTY_BRANCH);
1503
+ if (branch) this._recordAssignmentTarget(caller, argument, branch);
1504
+ }
1505
+ };
1506
+ _proto._recordAssignmentTarget = function _recordAssignmentTarget(functionNode, target, branch) {
1507
+ if (typeof target === "string") {
1508
+ this._recordWrite(functionNode, target, branch);
1509
+ return;
1510
+ }
1511
+ var current = assignmentTargetBase(target);
1512
+ if (_instanceof(current, analyzer.ASTNode.MacroCallSymbol) || _instanceof(current, analyzer.ASTNode.MacroCallFunction)) {
1513
+ var _current_expandedSyntax;
1514
+ for(var _iterator = _create_for_of_iterator_helper_loose((_current_expandedSyntax = current.expandedSyntax) != null ? _current_expandedSyntax : []), _step; !(_step = _iterator()).done;){
1515
+ var syntax = _step.value;
1516
+ if (syntax.valueTarget === undefined) continue;
1517
+ var targetBranch = combineBranches(branch, syntax.branch);
1518
+ if (targetBranch) this._recordAssignmentTarget(functionNode, syntax.valueTarget, targetBranch);
1519
+ }
1520
+ return;
1521
+ }
1522
+ if (_instanceof(current, analyzer.ASTNode.VariableIdentifier)) {
1523
+ var child = current.children[0];
1524
+ var _current_builtinSemantic;
1525
+ var name = (_current_builtinSemantic = current.builtinSemantic) != null ? _current_builtinSemantic : _instanceof(child, analyzer.BaseToken) ? child.lexeme : undefined;
1526
+ if (name !== undefined) this._recordWrite(functionNode, name, branch);
1527
+ }
1528
+ };
1529
+ _proto._recordWrite = function _recordWrite(functionNode, target, branch) {
1530
+ this._branches.add(branch);
1531
+ var _this__writes_get;
1532
+ var writes = (_this__writes_get = this._writes.get(functionNode)) != null ? _this__writes_get : [];
1533
+ writes.push({
1534
+ target: target,
1535
+ branch: branch
1536
+ });
1537
+ this._writes.set(functionNode, writes);
1538
+ };
1539
+ return ShaderAnalysisInfo;
1540
+ }();
1541
+ /**
1542
+ * Visits effective source syntax while leaving unresolved macro arguments unproven.
1543
+ * @param node - Source syntax to inspect.
1544
+ * @param visit - Receives ordinary syntax and its effective branch and location.
1545
+ * @param visitMacro - Receives proven macro expansion facts at the invocation location.
1546
+ * @param incoming - Additional constraints from a containing macro expansion.
1547
+ * @param mappedLocation - Invocation location for syntax projected from a macro argument.
1548
+ * @param visitUnknown - Receives branches where macro execution effects cannot be proven.
1549
+ * @internal
1550
+ */ function walkEffectiveShaderSyntax(node, visit, visitMacro, incoming, mappedLocation, visitUnknown) {
1551
+ if (incoming === void 0) incoming = analyzer.EMPTY_BRANCH;
1552
+ var pending = [
1553
+ {
1554
+ node: node,
1555
+ incoming: incoming,
1556
+ mappedLocation: mappedLocation
1557
+ }
1558
+ ];
1559
+ while(pending.length){
1560
+ var current = pending.pop();
1561
+ if ("syntax" in current) {
1562
+ var syntax = current.syntax, branch = current.branch, location = current.location;
1563
+ visitMacro(syntax, branch, location);
1564
+ if (syntax.hasUnknownEffects) visitUnknown == null ? void 0 : visitUnknown(branch);
1565
+ for(var index = syntax.arguments.length - 1; index >= 0; index--){
1566
+ pending.push({
1567
+ node: syntax.arguments[index],
1568
+ incoming: branch,
1569
+ mappedLocation: location
1570
+ });
1571
+ }
1572
+ continue;
1573
+ }
1574
+ var _$node = current.node, _$incoming = current.incoming, _$mappedLocation = current.mappedLocation;
1575
+ var branch1 = combineBranches(_$incoming, _$node._branch);
1576
+ if (!branch1 || !analyzer.isBranchReachable(branch1) || _instanceof(_$node, analyzer.ASTNode.MacroDefine)) continue;
1577
+ var location1 = _$mappedLocation != null ? _$mappedLocation : _$node.location;
1578
+ if (_instanceof(_$node, analyzer.ASTNode.MacroCallSymbol) || _instanceof(_$node, analyzer.ASTNode.MacroCallFunction)) {
1579
+ var _node_expandedSyntax, _node_expandedSyntax1;
1580
+ if (!((_node_expandedSyntax = _$node.expandedSyntax) == null ? void 0 : _node_expandedSyntax.length)) visitUnknown == null ? void 0 : visitUnknown(branch1);
1581
+ var _node_expandedSyntax_length;
1582
+ for(var index1 = ((_node_expandedSyntax_length = (_node_expandedSyntax1 = _$node.expandedSyntax) == null ? void 0 : _node_expandedSyntax1.length) != null ? _node_expandedSyntax_length : 0) - 1; index1 >= 0; index1--){
1583
+ var syntax1 = _$node.expandedSyntax[index1];
1584
+ var expandedBranch = combineBranches(branch1, syntax1.branch);
1585
+ if (expandedBranch) pending.push({
1586
+ syntax: syntax1,
1587
+ branch: expandedBranch,
1588
+ location: location1
1589
+ });
1590
+ }
1591
+ continue;
1592
+ }
1593
+ visit(_$node, branch1, location1);
1594
+ if (_instanceof(_$node, analyzer.ASTNode.FunctionCallGeneric)) {
1595
+ var _node_fnSymbols;
1596
+ var identifier = _$node.children[0];
1597
+ if (!identifier.isBuiltin && !analyzer.BuiltinFunction.isExist(identifier.lexeme) && !(((_node_fnSymbols = _$node.fnSymbols) == null ? void 0 : _node_fnSymbols.length) || _instanceof(_$node.fnSymbol, analyzer.FnSymbol))) {
1598
+ visitUnknown == null ? void 0 : visitUnknown(branch1);
1599
+ continue;
1600
+ }
1601
+ }
1602
+ for(var index2 = _$node.children.length - 1; index2 >= 0; index2--){
1603
+ var child = _$node.children[index2];
1604
+ // Container branches describe their first token, not every following sibling statement.
1605
+ if (_instanceof(child, analyzer.TreeNode)) pending.push({
1606
+ node: child,
1607
+ incoming: _$incoming,
1608
+ mappedLocation: _$mappedLocation
1609
+ });
1610
+ }
1611
+ }
1612
+ }
1613
+ function combineBranches(left, right) {
1614
+ var _loop = function() {
1615
+ var constraint = _step.value;
1616
+ if (combined.includes(constraint)) return "continue";
1617
+ if (constraint.conditionalGroup !== undefined && combined.some(function(existing) {
1618
+ return existing.conditionalGroup === constraint.conditionalGroup && existing.conditionalArm === constraint.conditionalArm;
1619
+ })) {
1620
+ return "continue";
1621
+ }
1622
+ combined.push(constraint);
1623
+ };
1624
+ if (!analyzer.canBranchesOverlap(left, right)) return;
1625
+ if (!left.length) return right;
1626
+ if (!right.length) return left;
1627
+ var combined = left.slice();
1628
+ for(var _iterator = _create_for_of_iterator_helper_loose(right), _step; !(_step = _iterator()).done;)_loop();
1629
+ return combined;
1630
+ }
1631
+ function assignmentTargetBase(node) {
1632
+ var current = node;
1633
+ while(true){
1634
+ if (_instanceof(current, analyzer.ASTNode.PostfixExpression) || _instanceof(current, analyzer.ASTNode.VariableIdentifier) || _instanceof(current, analyzer.ASTNode.ExpressionAstNode) && current.children.length === 1) {
1635
+ var child = current.children[0];
1636
+ if (_instanceof(child, analyzer.TreeNode)) {
1637
+ current = child;
1638
+ continue;
1639
+ }
1640
+ } else if (_instanceof(current, analyzer.ASTNode.PrimaryExpression) && current.children.length === 3) {
1641
+ var child1 = current.children[1];
1642
+ if (_instanceof(child1, analyzer.TreeNode)) {
1643
+ current = child1;
1644
+ continue;
1645
+ }
1646
+ }
1647
+ return current;
1648
+ }
1649
+ }
1650
+
1651
+ /** Fragment-only derivative builtins (GLSL ES 3.00 §8.9) — illegal in the vertex stage. */ var DERIVATIVE_BUILTINS = new Set([
1652
+ "dFdx",
1653
+ "dFdy",
1654
+ "fwidth"
1655
+ ]);
1656
+ /**
1657
+ * Post-parse validation pass. Walks the already-typed AST (the parser built the symbol table and
1658
+ * inferred `.type` inline; only validation moved here) and collects diagnostics. The parsed pass
1659
+ * source is retained by the neutral IR and attached to diagnostics emitted by this pass.
1660
+ */ var ShaderValidator = /*#__PURE__*/ function() {
1661
+ function ShaderValidator(_analysis) {
1662
+ this._analysis = _analysis;
1663
+ this._typeLookup = new analyzer.SymbolInfo("", analyzer.ESymbolType.STRUCT);
1664
+ this._errors = [];
1665
+ this._indexedGlFragDataStarts = new Set();
1666
+ this._stageRestrictedSites = new Map();
1667
+ this._source = _analysis.ir.source;
1668
+ this._shaderData = _analysis.ir.shaderData;
1669
+ }
1670
+ var _proto = ShaderValidator.prototype;
1671
+ _proto._walk = function _walk(root, context) {
1672
+ var pending = [
1673
+ {
1674
+ node: root,
1675
+ ctx: context
1676
+ }
1677
+ ];
1678
+ while(pending.length){
1679
+ var _pending_pop = pending.pop(), node = _pending_pop.node, ctx = _pending_pop.ctx;
1680
+ if (!analyzer.isBranchReachable(node._branch)) continue;
1681
+ if (_instanceof(node, analyzer.ASTNode.MacroDefine)) continue;
1682
+ // A FunctionDefinition becomes the enclosing function for its subtree (GLSL has no nested
1683
+ // functions, so it always replaces rather than nests); an iteration statement (for/while/do)
1684
+ // raises the loop depth for its subtree.
1685
+ var childCtx = ctx;
1686
+ if (_instanceof(node, analyzer.ASTNode.FunctionDefinition)) {
1687
+ this._checkFunctionReturn(node);
1688
+ childCtx = {
1689
+ currentFunction: node,
1690
+ loopDepth: ctx.loopDepth
1691
+ };
1692
+ } else if (_instanceof(node, analyzer.ASTNode.IterationStatement)) {
1693
+ childCtx = {
1694
+ currentFunction: ctx.currentFunction,
1695
+ loopDepth: ctx.loopDepth + 1
1696
+ };
1697
+ } else if (_instanceof(node, analyzer.ASTNode.JumpStatement)) {
1698
+ this._checkJump(node, ctx);
1699
+ } else if (_instanceof(node, analyzer.ASTNode.FunctionCallGeneric)) {
1700
+ this._checkRecursiveCall(node, ctx);
1701
+ this._checkDerivativeCall(node);
1702
+ } else if (_instanceof(node, analyzer.ASTNode.UnaryExpression)) {
1703
+ this._checkUnaryOperand(node);
1704
+ } else if (_instanceof(node, analyzer.ASTNode.MultiplicativeExpression)) {
1705
+ if (!this._checkArithmeticOperation(node)) {
1706
+ this._checkConstDivideByZero(node);
1707
+ }
1708
+ } else if (_instanceof(node, analyzer.ASTNode.AdditiveExpression)) {
1709
+ this._checkArithmeticOperation(node);
1710
+ } else if (_instanceof(node, analyzer.ASTNode.ShiftExpression)) {
1711
+ this._checkShiftRange(node);
1712
+ this._checkIntegerBinaryOperands(node);
1713
+ } else if (_instanceof(node, analyzer.ASTNode.AndExpression) || _instanceof(node, analyzer.ASTNode.ExclusiveOrExpression) || _instanceof(node, analyzer.ASTNode.InclusiveOrExpression)) {
1714
+ this._checkIntegerBinaryOperands(node);
1715
+ } else if (_instanceof(node, analyzer.ASTNode.LogicalAndExpression) || _instanceof(node, analyzer.ASTNode.LogicalXorExpression) || _instanceof(node, analyzer.ASTNode.LogicalOrExpression)) {
1716
+ this._checkScalarBoolBinaryOperands(node);
1717
+ } else if (_instanceof(node, analyzer.ASTNode.PostfixExpression)) {
1718
+ this._checkPostfix(node);
1719
+ } else if (_instanceof(node, analyzer.ASTNode.FunctionProtoType)) {
1720
+ this._checkLocalFunctionPrototype(node, ctx);
1721
+ } else if (_instanceof(node, analyzer.ASTNode.StructSpecifier)) {
1722
+ this._checkStructSpecifier(node);
1723
+ } else if (_instanceof(node, analyzer.ASTNode.TypeSpecifier) && !_instanceof(node.parent, analyzer.ASTNode.FunctionIdentifier)) {
1724
+ this._checkCustomTypeReference(node);
1725
+ } else if (_instanceof(node, analyzer.ASTNode.SingleDeclaration) || _instanceof(node, analyzer.ASTNode.VariableDeclaration)) {
1726
+ this._checkVariableDeclarator(node.declarator);
1727
+ } else if (_instanceof(node, analyzer.ASTNode.InitDeclaratorList) && node.declarator) {
1728
+ this._checkVariableDeclarator(node.declarator);
1729
+ } else if (_instanceof(node, analyzer.ASTNode.ArraySpecifier)) {
1730
+ this._checkArraySpecifier(node);
1731
+ }
1732
+ for(var index = node.children.length - 1; index >= 0; index--){
1733
+ var child = node.children[index];
1734
+ if (_instanceof(child, analyzer.TreeNode)) pending.push({
1735
+ node: child,
1736
+ ctx: childCtx
1737
+ });
1738
+ }
1739
+ }
1740
+ };
1741
+ /**
1742
+ * `gl_FragData` is a fragment-output *array* — legal only when indexed (`gl_FragData[i] = ...`).
1743
+ * A bare reference (r-value, l-value, swizzle, function arg) is invalid GLSL. `ShaderAnalysisInfo`
1744
+ * collects every `gl_FragData` location; `_checkPostfix`
1745
+ * records the base of every `gl_FragData[i]` shape in `_indexedGlFragDataStarts`. Anything left
1746
+ * over — first occurrence only — is reported here.
1747
+ */ _proto._reportBareGlFragData = function _reportBareGlFragData() {
1748
+ for(var _iterator = _create_for_of_iterator_helper_loose(this._analysis.glFragDataReferences), _step; !(_step = _iterator()).done;){
1749
+ var loc = _step.value;
1750
+ if (this._indexedGlFragDataStarts.has(loc.start.index)) continue;
1751
+ this._push("'gl_FragData' must be indexed — write to `gl_FragData[i]` or return an MRT struct.", loc, DiagnosticType.BareGlFragData);
1752
+ return;
1753
+ }
1754
+ };
1755
+ _proto._push = function _push(message, location, code) {
1756
+ this._errors.push(analyzer.ShaderCompilerUtils.createGSError(message, analyzer.GSErrorName.CompilationError, this._source, location, code));
1757
+ };
1758
+ _proto._checkCustomTypeReference = function _checkCustomTypeReference(node) {
1759
+ if (!node.isCustom) return;
1760
+ var typeName = node.children[0].children[0];
1761
+ if (!_instanceof(typeName, analyzer.BaseToken)) return;
1762
+ // Later inherited overrides can remove a declaration from the final table without changing its earlier visibility.
1763
+ var structs = node.structDeclarations;
1764
+ if (!structs.length) {
1765
+ var lookup = this._typeLookup;
1766
+ lookup.set(typeName.lexeme, analyzer.ESymbolType.STRUCT);
1767
+ if (this._shaderData.symbolTable.hasSymbol(lookup)) {
1768
+ this._push("Type '" + typeName.lexeme + "' is declared only after this reference or in an unavailable macro branch.", typeName.location, DiagnosticType.UseBeforeDeclaration);
1769
+ }
1770
+ return;
1771
+ }
1772
+ var coverage = analyzer.getBranchCoverage(structs.map(function(struct) {
1773
+ return struct._branch;
1774
+ }), node._branch);
1775
+ if (coverage === "uncovered") {
1776
+ this._push("Type '" + typeName.lexeme + "' is unavailable under at least one macro configuration reaching this reference.", typeName.location, DiagnosticType.UseBeforeDeclaration);
1777
+ }
1778
+ };
1779
+ _proto._checkVariableDeclarator = function _checkVariableDeclarator(declarator) {
1780
+ var identifier = declarator.identifier, initializer = declarator.initializer, isConst = declarator.isConst, typeInfo = declarator.typeInfo;
1781
+ if (typeInfo.type === analyzer.Keyword.VOID) {
1782
+ this._push("Illegal use of type 'void' — '" + identifier.lexeme + "' cannot be declared as void.", identifier.location, DiagnosticType.InvalidVoidVariable);
1783
+ }
1784
+ if (initializer && !typeInfo.arraySpecifier && !analyzer.TypeSystem.isAssignable(typeInfo.type, initializer.type)) {
1785
+ this._push("Cannot initialize '" + identifier.lexeme + "' of type '" + analyzer.TypeSystem.typeName(typeInfo.type) + "' from '" + analyzer.TypeSystem.typeName(initializer.type) + "'.", initializer.location, DiagnosticType.AssignTypeMismatch);
1786
+ }
1787
+ if (initializer && isConst && !analyzer.ParserUtils.isConstExpr(initializer)) {
1788
+ this._push("'" + identifier.lexeme + "': const initializer must be a constant expression.", initializer.location, DiagnosticType.NonConstInitializer);
1789
+ }
1790
+ };
1791
+ _proto._checkArraySpecifier = function _checkArraySpecifier(node) {
1792
+ if (typeof node.size !== "number" || node.size > 0) return;
1793
+ var expression = node.children[1];
1794
+ if (!_instanceof(expression, analyzer.TreeNode)) return;
1795
+ this._push("Array size " + node.size + " must be greater than zero.", expression.location, DiagnosticType.InvalidArraySize);
1796
+ };
1797
+ /**
1798
+ * Unary operand-type rules: `!` needs bool, `~` needs integer, `-`/`+` need numeric. The operand
1799
+ * type is read directly (not the deduced result), so this fires for known operands and skips
1800
+ * TypeAny (continue-with-unknown); `++`/`--` reduce with a raw token child and are not handled here.
1801
+ */ _proto._checkUnaryOperand = function _checkUnaryOperand(node) {
1802
+ if (node.children.length !== 2) return;
1803
+ var firstChild = node.children[0];
1804
+ if (!_instanceof(firstChild, analyzer.ASTNode.UnaryOperator)) return;
1805
+ var opToken = firstChild.children[0];
1806
+ var operand = node.children[1];
1807
+ var t = operand.type;
1808
+ if (!_instanceof(opToken, analyzer.BaseToken) || t === analyzer.TypeAny) return;
1809
+ var bad = false;
1810
+ switch(opToken.type){
1811
+ case analyzer.ETokenType.BANG:
1812
+ bad = t !== analyzer.Keyword.BOOL;
1813
+ break;
1814
+ case analyzer.ETokenType.TILDE:
1815
+ bad = !analyzer.TypeSystem.isIntegerType(t);
1816
+ break;
1817
+ case analyzer.ETokenType.DASH:
1818
+ case analyzer.ETokenType.PLUS:
1819
+ bad = analyzer.TypeSystem.isBoolType(t) || analyzer.TypeSystem.isSamplerType(t) || typeof t === "string";
1820
+ break;
1821
+ }
1822
+ if (bad) {
1823
+ this._push("Operator '" + opToken.lexeme + "' cannot be applied to operand of type '" + analyzer.TypeSystem.typeName(t) + "'.", node.location, DiagnosticType.InvalidUnaryOperand);
1824
+ }
1825
+ };
1826
+ /** Validate and infer arithmetic from the same TypeSystem operation result used by the parser. */ _proto._checkArithmeticOperation = function _checkArithmeticOperation(node) {
1827
+ if (node.children.length !== 3) return false;
1828
+ var left = node.children[0];
1829
+ var right = node.children[2];
1830
+ var operator = node.children[1];
1831
+ if (!_instanceof(left, analyzer.ASTNode.ExpressionAstNode) || !_instanceof(right, analyzer.ASTNode.ExpressionAstNode)) return false;
1832
+ var operatorLexeme = _instanceof(operator, analyzer.BaseToken) ? operator.lexeme : "op";
1833
+ var result = analyzer.TypeSystem.arithmeticOperation(left.type, right.type, operatorLexeme);
1834
+ if (result.valid !== false) return false;
1835
+ this._push("Operator '" + operatorLexeme + "' cannot combine '" + analyzer.TypeSystem.typeName(left.type) + "' and '" + analyzer.TypeSystem.typeName(right.type) + "'.", node.location, DiagnosticType.InvalidBinaryOperands);
1836
+ return true;
1837
+ };
1838
+ /**
1839
+ * GLSL ES §6.1: function declarations (prototypes) may only appear at global scope. The grammar
1840
+ * accepts `int g();` inside a function body, so without this check the parser cascades into a
1841
+ * misleading `EntryNotFound`. A `FunctionProtoType` wrapped in a `FunctionDefinition` is the
1842
+ * body path — that's a legal definition, not a prototype declaration.
1843
+ */ _proto._checkLocalFunctionPrototype = function _checkLocalFunctionPrototype(node, ctx) {
1844
+ if (!ctx.currentFunction) return;
1845
+ if (_instanceof(node.parent, analyzer.ASTNode.FunctionDefinition)) return;
1846
+ this._push("Function prototype '" + node.ident.lexeme + "' cannot be declared inside a function body — declare it at global scope.", node.location, DiagnosticType.LocalFunctionPrototype);
1847
+ };
1848
+ /**
1849
+ * `<<` `>>` `&` `|` `^` all take integer scalar-or-vector operands per §5.9.
1850
+ */ _proto._checkIntegerBinaryOperands = function _checkIntegerBinaryOperands(node) {
1851
+ if (node.children.length !== 3) return;
1852
+ var op = node.children[1];
1853
+ var opLexeme = _instanceof(op, analyzer.BaseToken) ? op.lexeme : "op";
1854
+ var bad = this._firstNonIntegerOperand(node.children[0], node.children[2]);
1855
+ if (bad) {
1856
+ this._push("Operator '" + opLexeme + "' requires integer operands, got '" + analyzer.TypeSystem.typeName(bad.type) + "'.", bad.location, DiagnosticType.InvalidBinaryOperands);
1857
+ }
1858
+ };
1859
+ /**
1860
+ * `&&` `||` `^^` — each operand must be `bool` scalar per §5.9. GLSL ES rejects `bvecN` operands
1861
+ * (desktop-GL 4.x does allow it; ES 3.00 does not).
1862
+ */ _proto._checkScalarBoolBinaryOperands = function _checkScalarBoolBinaryOperands(node) {
1863
+ if (node.children.length !== 3) return;
1864
+ var op = node.children[1];
1865
+ var opLexeme = _instanceof(op, analyzer.BaseToken) ? op.lexeme : "op";
1866
+ var bad = this._firstNonScalarBoolOperand(node.children[0], node.children[2]);
1867
+ if (bad) {
1868
+ this._push("Operator '" + opLexeme + "' requires scalar bool operands, got '" + analyzer.TypeSystem.typeName(bad.type) + "'.", bad.location, DiagnosticType.InvalidBinaryOperands);
1869
+ }
1870
+ };
1871
+ /** First operand whose direct type is neither integer nor `TypeAny`. */ _proto._firstNonIntegerOperand = function _firstNonIntegerOperand(a, b) {
1872
+ if (_instanceof(a, analyzer.ASTNode.ExpressionAstNode) && a.type !== analyzer.TypeAny && !analyzer.TypeSystem.isIntegerType(a.type)) return a;
1873
+ if (_instanceof(b, analyzer.ASTNode.ExpressionAstNode) && b.type !== analyzer.TypeAny && !analyzer.TypeSystem.isIntegerType(b.type)) return b;
1874
+ return undefined;
1875
+ };
1876
+ /** First operand whose direct type is neither `bool` nor `TypeAny`. */ _proto._firstNonScalarBoolOperand = function _firstNonScalarBoolOperand(a, b) {
1877
+ if (_instanceof(a, analyzer.ASTNode.ExpressionAstNode) && a.type !== analyzer.TypeAny && a.type !== analyzer.Keyword.BOOL) return a;
1878
+ if (_instanceof(b, analyzer.ASTNode.ExpressionAstNode) && b.type !== analyzer.TypeAny && b.type !== analyzer.Keyword.BOOL) return b;
1879
+ return undefined;
1880
+ };
1881
+ /**
1882
+ * Integer division/modulo by a compile-time constant zero is an error; float `1.0/0.0` yields Inf
1883
+ * (unspecified, not an error). `%` is integer-only in GLSL ES; `/` qualifies only when the result
1884
+ * type deduced to an integer (int/int) — FLOAT or TypeAny don't flag. Only reached with clean
1885
+ * operands (the arithmetic-operand check already suppressed bad ones), so it scans operands once.
1886
+ */ _proto._checkConstDivideByZero = function _checkConstDivideByZero(node) {
1887
+ if (node.children.length !== 3) return;
1888
+ var op = node.children[1];
1889
+ // Gate on the operator before touching operands: only `/` and `%` can divide by zero.
1890
+ if (!_instanceof(op, analyzer.BaseToken) || op.type !== analyzer.ETokenType.PERCENT && op.type !== analyzer.ETokenType.SLASH) return;
1891
+ if (op.type === analyzer.ETokenType.SLASH && !analyzer.TypeSystem.isIntegerType(node.type)) return;
1892
+ var divisor = node.children[2];
1893
+ if (_instanceof(divisor, analyzer.TreeNode) && analyzer.ParserUtils.constNumericValue(divisor) === 0) {
1894
+ this._push(op.type === analyzer.ETokenType.PERCENT ? "Modulo by constant zero." : "Division by constant zero.", divisor.location, DiagnosticType.ConstDivideByZero);
1895
+ }
1896
+ };
1897
+ /** A shift by a constant amount outside [0, 32) is out of range — GLSL ES int/uint are 32-bit. */ _proto._checkShiftRange = function _checkShiftRange(node) {
1898
+ if (node.children.length !== 3) return;
1899
+ var amount = node.children[2];
1900
+ if (!_instanceof(amount, analyzer.TreeNode)) return;
1901
+ var n = analyzer.ParserUtils.constNumericValue(amount);
1902
+ if (n !== undefined && (n < 0 || n >= 32)) {
1903
+ this._push("Shift amount " + n + " is out of range; must be in [0, 32).", amount.location, DiagnosticType.ShiftOutOfRange);
1904
+ }
1905
+ };
1906
+ /**
1907
+ * Stateless postfix checks: an invalid swizzle on a known vector (`InvalidSwizzle`), and the
1908
+ * `base[index]` family — `gl_FragData[i]` (`GlFragData`), a scalar non-array base (`NonIndexableType`),
1909
+ * a non-integer index (`NonIntegerIndex`), and a constant index past a known vector/array size
1910
+ * (`IndexOutOfBounds`). The struct-field (`else if`) path stays inline in the parser since it reads the
1911
+ * symbol table; preserve the original control flow here (early returns, gl_FragData-vs-index branching).
1912
+ */ _proto._checkPostfix = function _checkPostfix(node) {
1913
+ var children = node.children;
1914
+ if (children.length === 2) return;
1915
+ if (children.length === 3 && _instanceof(children[2], analyzer.BaseToken)) {
1916
+ var base = children[0];
1917
+ var field = children[2];
1918
+ // GLSL ES §5.5: `.field` on a receiver that is not a struct, scalar, or vector is invalid.
1919
+ // The driver rejects `s.rr` (sampler) or `f().xx` (void return) with "field selection requires
1920
+ // structure, vector, or interface block on left hand side". Skip TypeAny — unknown types keep
1921
+ // the wiggle room. Struct types are strings; `ParserUtils.swizzleError` already returns null
1922
+ // for them and the parser's inline UndeclaredStructMember path takes over.
1923
+ var baseType = base.type;
1924
+ if (baseType !== undefined && baseType !== analyzer.TypeAny && typeof baseType !== "string" && analyzer.TypeSystem.vectorComponentCount(baseType) === 0 && !analyzer.TypeSystem.isScalarType(baseType)) {
1925
+ this._push("Field selection '." + field.lexeme + "' requires a structure, vector, or scalar receiver — got '" + analyzer.TypeSystem.typeName(baseType) + "'.", field.location, DiagnosticType.InvalidSwizzle);
1926
+ return;
1927
+ }
1928
+ var swizzleError = analyzer.ParserUtils.swizzleError(base.type, field.lexeme);
1929
+ if (swizzleError) {
1930
+ this._push(swizzleError, field.location, DiagnosticType.InvalidSwizzle);
1931
+ }
1932
+ } else if (children.length === 4) {
1933
+ // `base [ index ]`.
1934
+ var base1 = children[0];
1935
+ var index = children[2];
1936
+ // `gl_FragData[i]` — record the base's location so `_reportBareGlFragData` treats this
1937
+ // occurrence as legal rather than reporting it as a bare use.
1938
+ var baseIdentifier = analyzer.ParserUtils.unwrapBareIdentifier(base1, {
1939
+ allowParens: true
1940
+ });
1941
+ var isFragmentOutputArray = (baseIdentifier == null ? void 0 : baseIdentifier.builtinSemantic) === analyzer.ShaderBuiltinSemantic.FragmentOutputArray;
1942
+ if (isFragmentOutputArray) {
1943
+ this._indexedGlFragDataStarts.add(baseIdentifier.location.start.index);
1944
+ }
1945
+ // A scalar (non-array) base can't be indexed at all. Resolve the base to a bare variable so an
1946
+ // array (`a[3]`) or a vector (`v[0]`) is excluded; non-variable/compound bases stay unknown.
1947
+ if (analyzer.TypeSystem.isScalarType(base1.type)) {
1948
+ var baseIdent = analyzer.ParserUtils.unwrapBareIdentifier(base1, {
1949
+ allowParens: true
1950
+ });
1951
+ if (baseIdent && !baseIdent.isArray) {
1952
+ var m = "Type '" + analyzer.TypeSystem.typeName(base1.type) + "' is not indexable.";
1953
+ this._push(m, base1.location, DiagnosticType.NonIndexableType);
1954
+ }
1955
+ }
1956
+ if (!_instanceof(index, analyzer.ASTNode.ExpressionAstNode)) return;
1957
+ // The index must be an integer; a constant integer index past a known vector's size is out of bounds.
1958
+ var indexType = index.type;
1959
+ if (indexType !== analyzer.TypeAny && indexType !== analyzer.Keyword.INT && indexType !== analyzer.Keyword.UINT) {
1960
+ var m1 = "Index must be an integer, got '" + analyzer.TypeSystem.typeName(indexType) + "'.";
1961
+ this._push(m1, index.location, DiagnosticType.NonIntegerIndex);
1962
+ return;
1963
+ }
1964
+ if (isFragmentOutputArray && !analyzer.ParserUtils.isConstExpr(index)) {
1965
+ this._push("Fragment output array index must be a constant integral expression.", index.location, DiagnosticType.NonConstFragmentOutputIndex);
1966
+ }
1967
+ if (isFragmentOutputArray) {
1968
+ var outputIndex = analyzer.ParserUtils.constIntegerValue(index);
1969
+ if (outputIndex !== undefined && outputIndex < 0) {
1970
+ this._push("Fragment output index " + outputIndex + " is out of bounds.", index.location, DiagnosticType.IndexOutOfBounds);
1971
+ }
1972
+ }
1973
+ // Array-of-vector base like `ivec2 arr[N]` — a[i] indexes the outer array, not the inner
1974
+ // vec2. Skip the vector-bounds check when the base is an array; the array-size check
1975
+ // still runs below when the array size is known at compile time.
1976
+ var baseArrayIdent = analyzer.ParserUtils.unwrapBareIdentifier(base1, {
1977
+ allowParens: true
1978
+ });
1979
+ var baseIsArray = !!(baseArrayIdent == null ? void 0 : baseArrayIdent.isArray);
1980
+ var size = baseIsArray ? 0 : analyzer.TypeSystem.vectorComponentCount(base1.type);
1981
+ if (size > 0) {
1982
+ var n = analyzer.ParserUtils.constNumericValue(index);
1983
+ if (n !== undefined && (n < 0 || n >= size)) {
1984
+ var m2 = "Index " + n + " is out of bounds for a " + size + "-component vector.";
1985
+ this._push(m2, index.location, DiagnosticType.IndexOutOfBounds);
1986
+ }
1987
+ } else {
1988
+ // A constant index past a fixed-size array's bounds is out of bounds — the spec
1989
+ // requires bounds-checking fixed-size arrays as well as vectors. Unsized / non-array
1990
+ // bases keep arraySize undefined.
1991
+ var baseIdent1 = analyzer.ParserUtils.unwrapBareIdentifier(base1, {
1992
+ allowParens: true
1993
+ });
1994
+ var arraySize = baseIdent1 == null ? void 0 : baseIdent1.arraySize;
1995
+ if (arraySize !== undefined) {
1996
+ var n1 = analyzer.ParserUtils.constNumericValue(index);
1997
+ if (n1 !== undefined && (n1 < 0 || n1 >= arraySize)) {
1998
+ var m3 = "Index " + n1 + " is out of bounds for an array of size " + arraySize + ".";
1999
+ this._push(m3, index.location, DiagnosticType.IndexOutOfBounds);
2000
+ }
2001
+ }
2002
+ }
2003
+ }
2004
+ };
2005
+ /** Diagnose only a proven fallthrough; unresolved macro conditions remain inconclusive. */ _proto._checkFunctionReturn = function _checkFunctionReturn(node) {
2006
+ var returnType = node.protoType.returnType;
2007
+ if (returnType.type === analyzer.Keyword.VOID) return;
2008
+ if (this._analysis.getReturnCoverage(node) === "uncovered") {
2009
+ this._push("No return statement found.", returnType.location, DiagnosticType.MissingReturn);
2010
+ }
2011
+ };
2012
+ /**
2013
+ * Jump-statement checks needing walk-local context: `InvalidReturnType` fires per-jump — a value
2014
+ * return in a `void` function, or a `return value;` whose value isn't assignable to the declared
2015
+ * non-void return type. A `break`/`continue` at loop depth 0 (outside any loop) is
2016
+ * `MisplacedControlFlow`. A discard site is checked against stage reachability after the walk.
2017
+ */ _proto._checkJump = function _checkJump(node, ctx) {
2018
+ var children = node.children;
2019
+ var keyword = analyzer.ASTNode._unwrapToken(children[0]).type;
2020
+ if (keyword === analyzer.Keyword.RETURN) {
2021
+ if (!ctx.currentFunction) return;
2022
+ var declared = ctx.currentFunction.protoType.returnType.type;
2023
+ if (declared === analyzer.Keyword.VOID) {
2024
+ // `void f() { return value; }` — the value at children[1] is illegal.
2025
+ if (children.length === 3) {
2026
+ this._push("Return in void function.", children[1].location, DiagnosticType.InvalidReturnType);
2027
+ }
2028
+ } else if (children.length !== 3) {
2029
+ this._push("Return in a non-void function must provide a value.", node.location, DiagnosticType.InvalidReturnType);
2030
+ } else {
2031
+ var returned = children[1].type;
2032
+ if (declared != undefined && !analyzer.TypeSystem.isAssignable(declared, returned)) {
2033
+ this._push("Cannot return a value of type '" + analyzer.TypeSystem.typeName(returned) + "' from a function returning '" + analyzer.TypeSystem.typeName(declared) + "'.", children[1].location, DiagnosticType.InvalidReturnType);
2034
+ }
2035
+ }
2036
+ } else if ((keyword === analyzer.Keyword.BREAK || keyword === analyzer.Keyword.CONTINUE) && ctx.loopDepth === 0) {
2037
+ this._push("'" + (keyword === analyzer.Keyword.BREAK ? "break" : "continue") + "' is only allowed inside a loop.", node.location, DiagnosticType.MisplacedControlFlow);
2038
+ }
2039
+ };
2040
+ /**
2041
+ * GLSL forbids recursion: a call whose callee name AND parameter signature match the enclosing
2042
+ * function (the same overload) is `RecursiveFunction`. The parser short-circuits this same case
2043
+ * during overload resolution (so it isn't mis-reported as Undefined/NoMatchingOverload); the
2044
+ * exact-signature match avoids flagging a call to a different overload of the same name.
2045
+ */ _proto._checkRecursiveCall = function _checkRecursiveCall(node, ctx) {
2046
+ var currentFunction = ctx.currentFunction;
2047
+ if (!currentFunction) return;
2048
+ var functionIdentifier = node.children[0];
2049
+ if (functionIdentifier.isBuiltin) return;
2050
+ var fnIdent = functionIdentifier.ident;
2051
+ var proto = currentFunction.protoType;
2052
+ var _node_fnSymbols;
2053
+ var callees = (_node_fnSymbols = node.fnSymbols) != null ? _node_fnSymbols : _instanceof(node.fnSymbol, analyzer.FnSymbol) ? [
2054
+ node.fnSymbol
2055
+ ] : [];
2056
+ if (callees.length) {
2057
+ if (!callees.some(function(callee) {
2058
+ return callee.astNode === currentFunction;
2059
+ })) return;
2060
+ this._push("Recursive call to '" + fnIdent + "' is not allowed (GLSL forbids recursion).", functionIdentifier.location, DiagnosticType.RecursiveFunction);
2061
+ return;
2062
+ }
2063
+ if (proto.ident.lexeme !== fnIdent) return;
2064
+ var callSig;
2065
+ if (node.children.length === 4 && _instanceof(node.children[2], analyzer.ASTNode.FunctionCallParameterList)) {
2066
+ callSig = node.children[2].paramSig;
2067
+ }
2068
+ var _proto_paramSig;
2069
+ var headerSig = (_proto_paramSig = proto.paramSig) != null ? _proto_paramSig : [];
2070
+ var cSig = callSig != null ? callSig : [];
2071
+ if (headerSig.length === cSig.length && headerSig.every(function(t, i) {
2072
+ return t === cSig[i];
2073
+ })) {
2074
+ this._push("Recursive call to '" + fnIdent + "' is not allowed (GLSL forbids recursion).", node.location, DiagnosticType.RecursiveFunction);
2075
+ }
2076
+ };
2077
+ /**
2078
+ * Reports one mutual-recursion witness per canonical participant. Direct self-recursion is
2079
+ * already reported at the call site by `_checkRecursiveCall`.
2080
+ */ _proto._reportMutualRecursion = function _reportMutualRecursion() {
2081
+ for(var _iterator = _create_for_of_iterator_helper_loose(this._analysis.mutualRecursionWitnesses()), _step; !(_step = _iterator()).done;){
2082
+ var _step_value = _step.value, marker = _step_value.marker, cycle = _step_value.cycle;
2083
+ this._push(cycle ? "Mutual recursion detected in call chain: " + cycle.map(function(fn) {
2084
+ return fn.protoType.ident.lexeme;
2085
+ }).join(" → ") + " → " + cycle[0].protoType.ident.lexeme + " (GLSL forbids recursion)." : "Mutual recursion detected involving function '" + marker.protoType.ident.lexeme + "' (GLSL forbids recursion).", marker.protoType.ident.location, DiagnosticType.RecursiveFunction);
2086
+ }
2087
+ };
2088
+ /**
2089
+ * Resolves stage restrictions through the shared branch-aware call graph, including entry bodies.
2090
+ * Uncalled helpers and incompatible macro paths do not establish a stage violation.
2091
+ */ _proto._reportStageRestrictions = function _reportStageRestrictions() {
2092
+ if (!this._stageRestrictedSites.size) return;
2093
+ var _this__analysis_coreInfo = this._analysis.coreInfo, vertexEntry = _this__analysis_coreInfo.vertexEntry, fragmentEntry = _this__analysis_coreInfo.fragmentEntry;
2094
+ for(var _i = 0, _iter = [
2095
+ vertexEntry,
2096
+ fragmentEntry
2097
+ ]; _i < _iter.length; _i++){
2098
+ var entry = _iter[_i];
2099
+ var reported = new Set();
2100
+ var stage = entry.stage === analyzer.EShaderStage.VERTEX ? "vertex" : "fragment";
2101
+ for(var _iterator = _create_for_of_iterator_helper_loose(this._analysis.reachableFunctions(entry)), _step; !(_step = _iterator()).done;){
2102
+ var fn = _step.value;
2103
+ var _this__stageRestrictedSites_get;
2104
+ for(var _iterator1 = _create_for_of_iterator_helper_loose((_this__stageRestrictedSites_get = this._stageRestrictedSites.get(fn)) != null ? _this__stageRestrictedSites_get : []), _step1; !(_step1 = _iterator1()).done;){
2105
+ var site = _step1.value;
2106
+ if (site.scope === entry.stage || !this._analysis.isFunctionBranchReachable(entry, fn, site.branch)) continue;
2107
+ var key = site.type + ":" + site.location.start.index + ":" + site.location.end.index + ":" + site.description;
2108
+ if (reported.has(key)) continue;
2109
+ reported.add(key);
2110
+ var allowed = site.scope === analyzer.EShaderStage.VERTEX ? "vertex" : "fragment";
2111
+ this._push(site.description + " is only allowed in the " + allowed + " shader, but is reachable from the " + stage + " entry via '" + fn.protoType.ident.lexeme + "'.", site.location, site.type);
2112
+ }
2113
+ }
2114
+ }
2115
+ };
2116
+ _proto._recordStageRestriction = function _recordStageRestriction(ctx, site) {
2117
+ if (!ctx.currentFunction) return;
2118
+ var sites = this._stageRestrictedSites.get(ctx.currentFunction);
2119
+ if (!sites) this._stageRestrictedSites.set(ctx.currentFunction, sites = []);
2120
+ sites.push(site);
2121
+ };
2122
+ _proto._collectStageRestrictions = function _collectStageRestrictions() {
2123
+ var _loop = function() {
2124
+ var fn = _step.value;
2125
+ var ctx = {
2126
+ currentFunction: fn,
2127
+ loopDepth: 0
2128
+ };
2129
+ var record = function(name, call, branch, location) {
2130
+ if (call) {
2131
+ if (DERIVATIVE_BUILTINS.has(name)) _this._recordStageRestriction(ctx, {
2132
+ description: "Derivative function '" + name + "'",
2133
+ scope: analyzer.EShaderStage.FRAGMENT,
2134
+ type: DiagnosticType.DerivativeInVertexShader,
2135
+ location: location,
2136
+ branch: branch
2137
+ });
2138
+ return;
2139
+ }
2140
+ var builtin = analyzer.BuiltinVariable.getVar(name);
2141
+ if (!builtin || builtin.scope === analyzer.EShaderStage.ALL) return;
2142
+ _this._recordStageRestriction(ctx, {
2143
+ description: "Builtin variable '" + name + "'",
2144
+ scope: builtin.scope,
2145
+ type: DiagnosticType.InvalidBuiltinStage,
2146
+ location: location,
2147
+ branch: branch
2148
+ });
2149
+ };
2150
+ var discard = function(branch, location) {
2151
+ return _this._recordStageRestriction(ctx, {
2152
+ description: "'discard'",
2153
+ scope: analyzer.EShaderStage.FRAGMENT,
2154
+ type: DiagnosticType.MisplacedControlFlow,
2155
+ location: location,
2156
+ branch: branch
2157
+ });
2158
+ };
2159
+ walkEffectiveShaderSyntax(fn.statements, function(node, branch, location) {
2160
+ if (_instanceof(node, analyzer.ASTNode.JumpStatement) && analyzer.ASTNode._unwrapToken(node.children[0]).type === analyzer.Keyword.DISCARD) {
2161
+ discard(branch, location);
2162
+ } else if (_instanceof(node, analyzer.ASTNode.FunctionCallGeneric)) {
2163
+ var identifier = node.children[0];
2164
+ if (!identifier.isBuiltin) record(identifier.lexeme, true, branch, location);
2165
+ } else if (_instanceof(node, analyzer.ASTNode.VariableIdentifier)) {
2166
+ var _BuiltinVariable_getVar;
2167
+ var child = node.children[0];
2168
+ if (_instanceof(child, analyzer.BaseToken) && !node.resolvedSymbols().length && node.typeInfo === ((_BuiltinVariable_getVar = analyzer.BuiltinVariable.getVar(child.lexeme)) == null ? void 0 : _BuiltinVariable_getVar.type)) {
2169
+ record(child.lexeme, false, branch, location);
2170
+ }
2171
+ }
2172
+ }, function(syntax, branch, location) {
2173
+ if (syntax.keywords.includes(analyzer.Keyword.DISCARD)) discard(branch, location);
2174
+ for(var _iterator = _create_for_of_iterator_helper_loose(syntax.references), _step; !(_step = _iterator()).done;){
2175
+ var reference = _step.value;
2176
+ record(reference.name, reference.call, branch, location);
2177
+ }
2178
+ });
2179
+ };
2180
+ var _this = this;
2181
+ for(var _iterator = _create_for_of_iterator_helper_loose(this._analysis.functions()), _step; !(_step = _iterator()).done;)_loop();
2182
+ };
2183
+ /**
2184
+ * Fragment-only derivative builtins (`dFdx`/`dFdy`/`fwidth`) — illegal in the vertex shader
2185
+ * (`DerivativeInVertexShader`) and require a float/floatN argument (`NonFloatDerivativeArg`).
2186
+ * Only user-callable functions reach here (isBuiltin=false, since the identifier is a string name,
2187
+ * not a type keyword); constructors like `vec3(...)` never match a derivative name.
2188
+ */ _proto._checkDerivativeCall = function _checkDerivativeCall(node) {
2189
+ var functionIdentifier = node.children[0];
2190
+ if (functionIdentifier.isBuiltin) return;
2191
+ var name = functionIdentifier.lexeme;
2192
+ if (!DERIVATIVE_BUILTINS.has(name)) return;
2193
+ // Spec: derivative builtins take `genType` (float/vec2/vec3/vec4); anything else is a type error.
2194
+ if (node.children.length === 4 && _instanceof(node.children[2], analyzer.ASTNode.FunctionCallParameterList)) {
2195
+ var list = node.children[2];
2196
+ var paramSig = list.paramSig;
2197
+ if (paramSig.length === 1) {
2198
+ var t = paramSig[0];
2199
+ if (t !== analyzer.TypeAny && !ShaderValidator._isFloatOrFloatVector(t)) {
2200
+ var argNode = list.paramNodes[0];
2201
+ var _argNode_location;
2202
+ this._push("'" + name + "' expects a float or floatN argument, got '" + analyzer.TypeSystem.typeName(t) + "'.", (_argNode_location = argNode == null ? void 0 : argNode.location) != null ? _argNode_location : list.location, DiagnosticType.NonFloatDerivativeArg);
2203
+ }
2204
+ }
2205
+ }
2206
+ };
2207
+ /**
2208
+ * `struct Foo { ... }` — flags an empty body (`EmptyStruct`). An empty body is unreachable via
2209
+ * the plain grammar (`struct_declaration_list` requires ≥1 declaration → SyntaxError first), but a
2210
+ * fully-macro-guarded body can reduce to zero collected props; the check catches that shape rather
2211
+ * than the surface form.
2212
+ */ _proto._checkStructSpecifier = function _checkStructSpecifier(node) {
2213
+ var propList = node.propList;
2214
+ if (!propList || propList.length === 0) {
2215
+ var _node_ident;
2216
+ var _node_ident_location;
2217
+ var location = (_node_ident_location = (_node_ident = node.ident) == null ? void 0 : _node_ident.location) != null ? _node_ident_location : node.location;
2218
+ this._push("Struct declaration must contain at least one member.", location, DiagnosticType.EmptyStruct);
2219
+ }
2220
+ };
2221
+ /**
2222
+ * Validate an already-parsed program and return collected diagnostics.
2223
+ * @param analysis neutral IR plus analyzer-only graph information
2224
+ * @returns diagnostics as `GSError[]`
2225
+ */ ShaderValidator.validate = function validate(analysis) {
2226
+ var v = new ShaderValidator(analysis);
2227
+ v._walk(analysis.ir.program, {
2228
+ currentFunction: null,
2229
+ loopDepth: 0
2230
+ });
2231
+ v._collectStageRestrictions();
2232
+ v._reportMutualRecursion();
2233
+ v._reportStageRestrictions();
2234
+ v._reportBareGlFragData();
2235
+ return v._errors;
2236
+ };
2237
+ /** float / vec2 / vec3 / vec4 — the `genType` family derivative builtins accept. */ ShaderValidator._isFloatOrFloatVector = function _isFloatOrFloatVector(t) {
2238
+ return t === analyzer.Keyword.FLOAT || t === analyzer.Keyword.VEC2 || t === analyzer.Keyword.VEC3 || t === analyzer.Keyword.VEC4;
2239
+ };
2240
+ return ShaderValidator;
2241
+ }();
2242
+
2243
+ var zeroPosition = new analyzer.ShaderPosition();
2244
+ zeroPosition.set(0, 0, 0);
2245
+ Object.freeze(zeroPosition);
2246
+ /**
2247
+ * Validates pipeline IO facts produced by `ShaderCoreInfo`.
2248
+ * @internal
2249
+ */ var ShaderIOValidator = /*#__PURE__*/ function() {
2250
+ function ShaderIOValidator() {}
2251
+ /**
2252
+ * Validates stage entries and IO without participating in backend generation.
2253
+ * @param analysis - Analyzer-only facts and their neutral/core backing data.
2254
+ * @param vertexEntryLocation - ShaderLab source range of the vertex entry binding.
2255
+ * @param fragmentEntryLocation - ShaderLab source range of the fragment entry binding.
2256
+ * @param entrySource - Complete ShaderLab source containing the entry bindings.
2257
+ * @returns Analyzer errors for invalid pipeline IO.
2258
+ */ ShaderIOValidator.validate = function validate(analysis, vertexEntryLocation, fragmentEntryLocation, entrySource) {
2259
+ var ir = analysis.ir, coreInfo = analysis.coreInfo;
2260
+ var source = ir.source;
2261
+ var glesInfo = new analyzer.GLESShaderInfo(ir, coreInfo);
2262
+ var errors = [];
2263
+ if (coreInfo.vertexEntry.name && !coreInfo.vertexEntry.functions.length) {
2264
+ this._entryNotFound(errors, coreInfo.vertexEntry.name, vertexEntryLocation, entrySource != null ? entrySource : source);
2265
+ }
2266
+ if (coreInfo.fragmentEntry.name && !coreInfo.fragmentEntry.functions.length) {
2267
+ this._entryNotFound(errors, coreInfo.fragmentEntry.name, fragmentEntryLocation, entrySource != null ? entrySource : source);
2268
+ }
2269
+ if (coreInfo.vertexEntry.hasDefiniteAmbiguity) {
2270
+ this._ambiguousEntry(errors, coreInfo.vertexEntry.name, vertexEntryLocation, entrySource, coreInfo.vertexEntry.functions[1].astNode.protoType.ident.location, source);
2271
+ }
2272
+ if (coreInfo.fragmentEntry.hasDefiniteAmbiguity) {
2273
+ this._ambiguousEntry(errors, coreInfo.fragmentEntry.name, fragmentEntryLocation, entrySource, coreInfo.fragmentEntry.functions[1].astNode.protoType.ident.location, source);
2274
+ }
2275
+ this._validateVertex(analysis, errors);
2276
+ this._validateFragment(analysis, errors);
2277
+ this._validateRoleConflicts(analysis, errors);
2278
+ this._validateStructMembers(analysis, errors);
2279
+ this._validateMrtOutputs(analysis, glesInfo, errors);
2280
+ for(var _iterator = _create_for_of_iterator_helper_loose(glesInfo.invalidMrtReturnLocations), _step; !(_step = _iterator()).done;){
2281
+ var location = _step.value;
2282
+ this._error(errors, DiagnosticType.InvalidMrtOutput, "MRT fragment entries must return a struct variable after assigning its members.", location, source);
2283
+ }
2284
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(glesInfo.invalidVaryingReturnLocations), _step1; !(_step1 = _iterator1()).done;){
2285
+ var location1 = _step1.value;
2286
+ this._error(errors, DiagnosticType.InvalidEntryReturnType, "Vertex entries returning varyings must return a struct variable or a function result of the same type.", location1, source);
2287
+ }
2288
+ for(var _iterator2 = _create_for_of_iterator_helper_loose(glesInfo.structMemberOwnerIssues), _step2; !(_step2 = _iterator2()).done;){
2289
+ var issue = _step2.value;
2290
+ if (issue.certainty !== "definite") continue;
2291
+ this._error(errors, DiagnosticType.AmbiguousMacroBranchResolution, issue.kind === "runtime-expanded-io-owner" ? "This macro member owner resolves to stage IO only after runtime substitution and cannot be lowered safely." : issue.kind === "incompatible-io-member" ? "This member is not available on every stage IO owner selected by the macro configuration." : "This member reference may resolve to stage IO or an ordinary variable across runtime macro configurations.", issue.location, source);
2292
+ }
2293
+ for(var _iterator3 = _create_for_of_iterator_helper_loose(coreInfo.fragmentEntry.functions), _step3; !(_step3 = _iterator3()).done;){
2294
+ var fragmentFunction = _step3.value;
2295
+ var returnStructs = fragmentFunction.astNode.protoType.returnType.typeSpecifier.structDeclarations;
2296
+ var returnsMrt = returnStructs.some(function(struct) {
2297
+ return coreInfo.io.mrtStructs.includes(struct);
2298
+ });
2299
+ if (!returnsMrt) continue;
2300
+ var reachableFragmentOutputs = analysis.reachableFragmentOutput0ReferencesFrom(fragmentFunction);
2301
+ if (reachableFragmentOutputs.length) {
2302
+ this._error(errors, DiagnosticType.GlFragColorWithMrt, "gl_FragColor cannot be used with MRT (Multiple Render Targets).", reachableFragmentOutputs[0], source);
2303
+ break;
2304
+ }
2305
+ }
2306
+ for(var _iterator4 = _create_for_of_iterator_helper_loose(coreInfo.fragmentEntry.functions), _step4; !(_step4 = _iterator4()).done;){
2307
+ var fragmentFunction1 = _step4.value;
2308
+ var conflict = analysis.coexistingLegacyFragmentOutputsFrom(fragmentFunction1);
2309
+ if (!conflict) continue;
2310
+ this._error(errors, DiagnosticType.LegacyFragmentOutputConflict, "gl_FragColor and gl_FragData cannot be used in the same fragment shader configuration.", conflict.outputArray, source);
2311
+ break;
2312
+ }
2313
+ if (coreInfo.vertexEntry.functions.length && analysis.getReachableWriteCoverage(coreInfo.vertexEntry, analyzer.ShaderBuiltinSemantic.VertexPosition) === "uncovered") {
2314
+ this._error(errors, DiagnosticType.MissingVertexPosition, "Vertex shader must write gl_Position.", coreInfo.vertexEntry.functions[0].astNode.protoType.returnType.location, source);
2315
+ }
2316
+ return errors;
2317
+ };
2318
+ ShaderIOValidator._validateVertex = function _validateVertex(analysis, errors) {
2319
+ var coreInfo = analysis.coreInfo, ir = analysis.ir;
2320
+ for(var _iterator = _create_for_of_iterator_helper_loose(coreInfo.vertexEntry.functions), _step; !(_step = _iterator()).done;){
2321
+ var functionSymbol = _step.value;
2322
+ var _proto_parameterList;
2323
+ var proto = functionSymbol.astNode.protoType;
2324
+ var returnType = proto.returnType;
2325
+ if (typeof returnType.type === "string") {
2326
+ if (!returnType.typeSpecifier.structDeclarations.length) {
2327
+ this._error(errors, DiagnosticType.InvalidIOStruct, 'Invalid varying struct: "' + returnType.type + '".', returnType.location, ir.source);
2328
+ }
2329
+ } else if (returnType.type !== analyzer.Keyword.VOID) {
2330
+ this._error(errors, DiagnosticType.InvalidEntryReturnType, "vertex main entry can only return struct or void.", returnType.location, ir.source);
2331
+ }
2332
+ var attribute = (_proto_parameterList = proto.parameterList) == null ? void 0 : _proto_parameterList[0];
2333
+ if (attribute && typeof attribute.typeInfo.type === "string") {
2334
+ if (!attribute.typeInfo.structDeclarations.length) {
2335
+ this._error(errors, DiagnosticType.InvalidIOStruct, 'Invalid attribute struct: "' + attribute.typeInfo.type + '".', attribute.astNode.location, ir.source);
2336
+ }
2337
+ }
2338
+ }
2339
+ };
2340
+ ShaderIOValidator._validateFragment = function _validateFragment(analysis, errors) {
2341
+ var coreInfo = analysis.coreInfo, ir = analysis.ir;
2342
+ for(var _iterator = _create_for_of_iterator_helper_loose(coreInfo.fragmentEntry.functions), _step; !(_step = _iterator()).done;){
2343
+ var functionSymbol = _step.value;
2344
+ var returnType = functionSymbol.astNode.protoType.returnType;
2345
+ if (typeof returnType.type === "string") {
2346
+ if (!returnType.typeSpecifier.structDeclarations.length) {
2347
+ this._error(errors, DiagnosticType.InvalidIOStruct, "Invalid MRT struct: " + returnType.type, returnType.location, ir.source);
2348
+ }
2349
+ } else if (returnType.type !== analyzer.Keyword.VOID && returnType.type !== analyzer.Keyword.VEC4) {
2350
+ this._error(errors, DiagnosticType.InvalidEntryReturnType, "fragment main entry can only return struct, vec4, or void.", returnType.location, ir.source);
2351
+ }
2352
+ }
2353
+ };
2354
+ ShaderIOValidator._validateRoleConflicts = function _validateRoleConflicts(analysis, errors) {
2355
+ for(var _iterator = _create_for_of_iterator_helper_loose(analysis.coreInfo.roleConflicts), _step; !(_step = _iterator()).done;){
2356
+ var conflict = _step.value;
2357
+ this._error(errors, DiagnosticType.StructRoleConflict, "Cannot use the same struct as " + conflict.roles.join(" and ") + ".", conflict.struct.location, analysis.ir.source);
2358
+ }
2359
+ };
2360
+ ShaderIOValidator._validateStructMembers = function _validateStructMembers(analysis, errors) {
2361
+ var _this = this;
2362
+ var io = analysis.coreInfo.io;
2363
+ var inspect = function(structs, role) {
2364
+ for(var _iterator = _create_for_of_iterator_helper_loose(structs), _step; !(_step = _iterator()).done;){
2365
+ var struct = _step.value;
2366
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(struct.propList), _step1; !(_step1 = _iterator1()).done;){
2367
+ var prop = _step1.value;
2368
+ if (typeof prop.typeInfo.type === "string") {
2369
+ _this._error(errors, DiagnosticType.NestedIOStruct, "IO struct member '" + prop.ident.lexeme + "' cannot be a struct ('" + prop.typeInfo.type + "'); nested IO structs are not allowed.", prop.ident.location, analysis.ir.source);
2370
+ } else if (role === analyzer.ShaderStructRole.Varying && !prop.isFlat && analyzer.TypeSystem.isIntegerType(prop.typeInfo.type)) {
2371
+ _this._error(errors, DiagnosticType.NonFlatIntegerVarying, "Integer varying '" + prop.ident.lexeme + "' must be declared 'flat'.", prop.ident.location, analysis.ir.source);
2372
+ }
2373
+ }
2374
+ }
2375
+ };
2376
+ inspect(io.attributeStructs, analyzer.ShaderStructRole.Attribute);
2377
+ inspect(io.varyingStructs, analyzer.ShaderStructRole.Varying);
2378
+ inspect(io.mrtStructs, analyzer.ShaderStructRole.Mrt);
2379
+ };
2380
+ ShaderIOValidator._validateMrtOutputs = function _validateMrtOutputs(analysis, glesInfo, errors) {
2381
+ for(var _iterator = _create_for_of_iterator_helper_loose(glesInfo.mrtOutputIssues), _step; !(_step = _iterator()).done;){
2382
+ var issue = _step.value;
2383
+ var prop = issue.prop;
2384
+ var message = void 0;
2385
+ switch(issue.kind){
2386
+ case "missing-location":
2387
+ message = "MRT output '" + prop.ident.lexeme + "' requires layout(location = N).";
2388
+ break;
2389
+ case "invalid-location":
2390
+ message = "MRT output '" + prop.ident.lexeme + "' requires a non-negative integer location.";
2391
+ break;
2392
+ case "duplicate-location":
2393
+ message = "MRT output location " + prop.mrtIndex + " is already used by another member.";
2394
+ break;
2395
+ default:
2396
+ message = "MRT output '" + prop.ident.lexeme + "' must have type vec4 for GLES portability.";
2397
+ break;
2398
+ }
2399
+ this._error(errors, DiagnosticType.InvalidMrtOutput, message, prop.ident.location, analysis.ir.source);
2400
+ }
2401
+ };
2402
+ ShaderIOValidator._entryNotFound = function _entryNotFound(errors, entry, location, source) {
2403
+ this._error(errors, DiagnosticType.EntryNotFound, "Entry function '" + entry + "' not found.", location != null ? location : zeroPosition, source);
2404
+ };
2405
+ ShaderIOValidator._ambiguousEntry = function _ambiguousEntry(errors, entry, bindingLocation, entrySource, declarationLocation, passSource) {
2406
+ this._error(errors, DiagnosticType.AmbiguousEntryPoint, "Entry function '" + entry + "' resolves to multiple declarations in the same macro configuration.", bindingLocation != null ? bindingLocation : declarationLocation, bindingLocation && entrySource ? entrySource : passSource);
2407
+ };
2408
+ ShaderIOValidator._error = function _error(errors, code, message, location, source) {
2409
+ errors.push(analyzer.ShaderCompilerUtils.createGSError(message, analyzer.GSErrorName.CompilationError, source, location, code));
2410
+ };
2411
+ return ShaderIOValidator;
2412
+ }();
2413
+
2414
+ /**
2415
+ * Converts a source offset to the analyzer's one-based diagnostic position.
2416
+ * @param source - Source text containing the offset.
2417
+ * @param offset - Zero-based UTF-16 offset into the source.
2418
+ * @returns One-based line and column plus the original offset.
2419
+ * @internal
2420
+ */ function positionAt(source, offset) {
2421
+ var line = 1;
2422
+ var column = 1;
2423
+ for(var index = 0; index < offset; index++){
2424
+ if (source.charCodeAt(index) === 10) {
2425
+ line++;
2426
+ column = 1;
2427
+ } else {
2428
+ column++;
2429
+ }
2430
+ }
2431
+ return {
2432
+ line: line,
2433
+ column: column,
2434
+ offset: offset
2435
+ };
2436
+ }
2437
+
2438
+ /**
2439
+ * Analyzes ShaderLab source and GLSL semantics without generating backend source.
2440
+ *
2441
+ * Parser-owned definite failures remain attached to reusable pass handles so backend admission reaches the same
2442
+ * conclusion. Analyzer-only validation stays independent from GLES code generation.
2443
+ */ var ShaderAnalyzer = /*#__PURE__*/ function() {
2444
+ function ShaderAnalyzer() {}
2445
+ /**
2446
+ * Analyzes shader source.
2447
+ * @param source - ShaderLab source to analyze.
2448
+ * @param options - Analysis options.
2449
+ * @returns Structured diagnostics and reusable parsed-pass handles.
2450
+ * @throws Error when include keys collide after normalization or `sourceFile` is not a valid absolute URL.
2451
+ */ ShaderAnalyzer.analyze = function analyze(source, options) {
2452
+ var passes = [];
2453
+ var diagnostics = ShaderAnalyzer._analyzeSource(source, passes, options);
2454
+ return Object.freeze({
2455
+ diagnostics: diagnostics,
2456
+ passes: Object.freeze(passes)
2457
+ });
2458
+ };
2459
+ ShaderAnalyzer._analyzeSource = function _analyzeSource(source, parsedPasses, options) {
2460
+ var _diagnostics;
2461
+ var includeMap = analyzer.normalizeShaderIncludeMap(options == null ? void 0 : options.includeMap);
2462
+ var sourceFile = analyzer.normalizeShaderSourceFile(options == null ? void 0 : options.sourceFile);
2463
+ var chunkOutputCache = new Map();
2464
+ var diagnostics = [];
2465
+ var sourceResult = analyzer.ShaderSourceParser.parseWithErrors(source);
2466
+ var shaderSource = sourceResult.shaderSource;
2467
+ var retainParsedPasses = sourceResult.errors.length === 0;
2468
+ (_diagnostics = diagnostics).push.apply(_diagnostics, [].concat(sourceResult.errors.map(function(error) {
2469
+ return gseErrorToDiagnostic(error);
2470
+ })));
2471
+ for(var _iterator = _create_for_of_iterator_helper_loose(shaderSource.subShaders), _step; !(_step = _iterator()).done;){
2472
+ var subShader = _step.value;
2473
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(subShader.passes), _step1; !(_step1 = _iterator1()).done;){
2474
+ var pass = _step1.value;
2475
+ if (pass.isUsePass) continue;
2476
+ var statements = shaderSource.pendingContents.concat(subShader.pendingContents, pass.pendingContents);
2477
+ ShaderAnalyzer._analyzePass(pass, statements, source, diagnostics, includeMap, chunkOutputCache, sourceFile, retainParsedPasses ? parsedPasses : undefined);
2478
+ }
2479
+ }
2480
+ if (sourceFile) {
2481
+ var _diagnostic;
2482
+ var _sourceFile;
2483
+ for(var _iterator2 = _create_for_of_iterator_helper_loose(diagnostics), _step2; !(_step2 = _iterator2()).done;){
2484
+ var diagnostic = _step2.value;
2485
+ (_sourceFile = (_diagnostic = diagnostic).sourceFile) != null ? _sourceFile : _diagnostic.sourceFile = sourceFile;
2486
+ }
2487
+ }
2488
+ return Object.freeze(diagnostics);
2489
+ };
2490
+ ShaderAnalyzer._analyzePass = function _analyzePass(pass, statements, source, diagnostics, includeMap, chunkOutputCache, sourceFile, parsedPasses) {
2491
+ if (pass.contents.trim().length === 0 && (!pass.vertexEntry || !pass.fragmentEntry)) return;
2492
+ var vertexEntry = pass.vertexEntry, fragmentEntry = pass.fragmentEntry;
2493
+ var passDiagnostics = [];
2494
+ var shouldSkipSemanticValidation = false;
2495
+ var parsed = analyzer.parseShaderPass(pass.contents, includeMap, chunkOutputCache, sourceFile, pass.contentScopeStarts);
2496
+ var ir = parsed.ir, errors = parsed.errors;
2497
+ var coreInfo = ir ? analyzer.ShaderCoreInfo.create(ir, vertexEntry, fragmentEntry, analyzer.branchAnalysis.getDeclarationCoexistence, analyzer.branchAnalysis.getBranchCoverage) : undefined;
2498
+ parsedPasses == null ? void 0 : parsedPasses.push(analyzer.createParsedShaderPass(parsed, vertexEntry, fragmentEntry, coreInfo));
2499
+ for(var _iterator = _create_for_of_iterator_helper_loose(errors), _step; !(_step = _iterator()).done;){
2500
+ var error = _step.value;
2501
+ var diagnostic = gseErrorToDiagnostic(error);
2502
+ if (diagnostic.code === DiagnosticType.PreprocessorError) shouldSkipSemanticValidation = true;
2503
+ if (!shouldSkipSemanticValidation || diagnostic.code === DiagnosticType.SyntaxError || diagnostic.code === DiagnosticType.PreprocessorError) {
2504
+ passDiagnostics.push(diagnostic);
2505
+ }
2506
+ }
2507
+ if (ir && coreInfo && !shouldSkipSemanticValidation) {
2508
+ var _passDiagnostics, _passDiagnostics1;
2509
+ var analysisInfo = new ShaderAnalysisInfo(ir, coreInfo);
2510
+ (_passDiagnostics = passDiagnostics).push.apply(_passDiagnostics, [].concat(ShaderValidator.validate(analysisInfo).map(function(error) {
2511
+ return gseErrorToDiagnostic(error);
2512
+ })));
2513
+ (_passDiagnostics1 = passDiagnostics).push.apply(_passDiagnostics1, [].concat(ShaderIOValidator.validate(analysisInfo, pass.vertexEntryLocation, pass.fragmentEntryLocation, source).map(function(error) {
2514
+ return gseErrorToDiagnostic(error);
2515
+ })));
2516
+ }
2517
+ var sourceMap = createPassSourceMap(statements);
2518
+ for(var _iterator1 = _create_for_of_iterator_helper_loose(passDiagnostics), _step1; !(_step1 = _iterator1()).done;){
2519
+ var diagnostic1 = _step1.value;
2520
+ var _diagnostic;
2521
+ if (diagnostic1.relatedSource === parsed.expandedSource) {
2522
+ remapExpandedDiagnostic(diagnostic1, parsed.sourceMap);
2523
+ }
2524
+ if (sourceMap.generatedSource === pass.contents && diagnostic1.relatedSource === pass.contents) {
2525
+ remapDiagnostic(diagnostic1, sourceMap.segments, source);
2526
+ }
2527
+ var _sourceFile;
2528
+ (_sourceFile = (_diagnostic = diagnostic1).sourceFile) != null ? _sourceFile : _diagnostic.sourceFile = sourceFile;
2529
+ diagnostics.push(diagnostic1);
2530
+ }
2531
+ };
2532
+ return ShaderAnalyzer;
2533
+ }();
2534
+ function remapExpandedDiagnostic(diagnostic, segments) {
2535
+ var mapped = analyzer.mapExpandedShaderRange(diagnostic.range.start.offset, diagnostic.range.end.offset, segments);
2536
+ if (!mapped) return;
2537
+ diagnostic.range = {
2538
+ start: {
2539
+ offset: mapped.start.index,
2540
+ line: mapped.start.line + 1,
2541
+ column: mapped.start.column + 1
2542
+ },
2543
+ end: {
2544
+ offset: mapped.end.index,
2545
+ line: mapped.end.line + 1,
2546
+ column: mapped.end.column + 1
2547
+ }
2548
+ };
2549
+ diagnostic.relatedSource = mapped.source;
2550
+ var _mapped_sourceFile;
2551
+ diagnostic.sourceFile = (_mapped_sourceFile = mapped.sourceFile) != null ? _mapped_sourceFile : diagnostic.sourceFile;
2552
+ }
2553
+ function createPassSourceMap(statements) {
2554
+ var segments = [];
2555
+ var generatedSource = "";
2556
+ for(var index = 0; index < statements.length; index++){
2557
+ if (index > 0) generatedSource += "\n";
2558
+ var statement = statements[index];
2559
+ var generatedStart = generatedSource.length;
2560
+ generatedSource += statement.content;
2561
+ segments.push({
2562
+ generatedStart: generatedStart,
2563
+ generatedEnd: generatedSource.length,
2564
+ sourceStart: statement.range.start.index
2565
+ });
2566
+ }
2567
+ return {
2568
+ generatedSource: generatedSource,
2569
+ segments: segments
2570
+ };
2571
+ }
2572
+ function remapDiagnostic(diagnostic, segments, source) {
2573
+ var start = remapOffset(diagnostic.range.start.offset, segments);
2574
+ if (start === undefined) return;
2575
+ var _remapOffset;
2576
+ var end = (_remapOffset = remapOffset(diagnostic.range.end.offset, segments)) != null ? _remapOffset : start;
2577
+ diagnostic.range = {
2578
+ start: positionAt(source, start),
2579
+ end: positionAt(source, end)
2580
+ };
2581
+ diagnostic.relatedSource = source;
2582
+ }
2583
+ function remapOffset(offset, segments) {
2584
+ for(var index = 0; index < segments.length; index++){
2585
+ var segment = segments[index];
2586
+ if (offset >= segment.generatedStart && offset <= segment.generatedEnd) {
2587
+ return segment.sourceStart + offset - segment.generatedStart;
2588
+ }
2589
+ }
2590
+ }
2591
+
2592
+ var USAGE = "Usage: galacean-shader-analyzer [--json] [--include-root directory] [file|-]";
2593
+ var HELP = "" + USAGE + "\n\nOptions:\n --json Print machine-readable diagnostics.\n --include-root directory Resolve shader includes below this directory.\n -h, --help Show this help.\n\nInput:\n file Analyze one ShaderLab file.\n - or omitted Read ShaderLab source from stdin.\n\nExit codes:\n 0 No error diagnostics (warnings may be present).\n 1 At least one error diagnostic.\n 2 Invalid command-line usage.\n\nExamples:\n galacean-shader-analyzer Assets/Shaders/PBR.shader\n galacean-shader-analyzer --json --include-root Assets/Shaders Assets/Shaders/PBR.shader\n galacean-shader-analyzer --json -";
2594
+ try {
2595
+ var options = parseArgs(process.argv.slice(2));
2596
+ if (options.help) {
2597
+ console.log(HELP);
2598
+ } else {
2599
+ run(options);
2600
+ }
2601
+ } catch (error) {
2602
+ console.error(_instanceof(error, Error) ? error.message : String(error));
2603
+ console.error(USAGE);
2604
+ process.exitCode = 2;
2605
+ }
2606
+ function run(options) {
2607
+ var source = node_fs.readFileSync(options.file === "-" ? 0 : options.file, "utf8");
2608
+ var includeRoot = options.includeRoot ? node_path.resolve(options.includeRoot) : options.file === "-" ? undefined : node_path.dirname(node_path.resolve(options.file));
2609
+ var includeMap = includeRoot ? createLazyIncludeMap(includeRoot) : undefined;
2610
+ var sourceFile = includeRoot && options.file !== "-" ? sourceFilePath(options.file, includeRoot) : undefined;
2611
+ var diagnostics = ShaderAnalyzer.analyze(source, {
2612
+ sourceFile: sourceFile,
2613
+ includeMap: includeMap
2614
+ }).diagnostics;
2615
+ if (options.json) {
2616
+ console.log(JSON.stringify({
2617
+ file: options.file,
2618
+ diagnostics: diagnostics
2619
+ }, null, 2));
2620
+ } else {
2621
+ for(var _iterator = _create_for_of_iterator_helper_loose(diagnostics), _step; !(_step = _iterator()).done;){
2622
+ var diagnostic = _step.value;
2623
+ var _diagnostic_range_start = diagnostic.range.start, line = _diagnostic_range_start.line, column = _diagnostic_range_start.column;
2624
+ var _diagnostic_sourceFile;
2625
+ console.log(((_diagnostic_sourceFile = diagnostic.sourceFile) != null ? _diagnostic_sourceFile : options.file) + ":" + line + ":" + column + " " + diagnostic.severity + " " + formatDiagnostic(diagnostic));
2626
+ }
2627
+ }
2628
+ if (diagnostics.some(function(diagnostic) {
2629
+ return diagnostic.severity === DiagnosticSeverity.Error;
2630
+ })) process.exitCode = 1;
2631
+ }
2632
+ function parseArgs(args) {
2633
+ var file = "-";
2634
+ var includeRoot;
2635
+ var json = false;
2636
+ var help = false;
2637
+ var hasFile = false;
2638
+ for(var i = 0; i < args.length; i++){
2639
+ var arg = args[i];
2640
+ if (arg === "--json") {
2641
+ json = true;
2642
+ } else if (arg === "--include-root") {
2643
+ includeRoot = args[++i];
2644
+ if (!includeRoot) throw new Error("--include-root requires a directory.");
2645
+ } else if (arg === "--help" || arg === "-h") {
2646
+ help = true;
2647
+ } else if (arg.startsWith("-") && arg !== "-") {
2648
+ throw new Error("Unknown option '" + arg + "'.");
2649
+ } else if (hasFile) {
2650
+ throw new Error("Only one shader file may be analyzed at a time.");
2651
+ } else {
2652
+ file = arg;
2653
+ hasFile = true;
2654
+ }
2655
+ }
2656
+ return {
2657
+ file: file,
2658
+ includeRoot: includeRoot,
2659
+ json: json,
2660
+ help: help
2661
+ };
2662
+ }
2663
+ function createLazyIncludeMap(root) {
2664
+ var cache = Object.create(null);
2665
+ return new Proxy(cache, {
2666
+ get: function get(target, includeName) {
2667
+ if (typeof includeName !== "string") return undefined;
2668
+ if (Object.prototype.hasOwnProperty.call(target, includeName)) return target[includeName];
2669
+ var path = root;
2670
+ try {
2671
+ var stats;
2672
+ for(var _iterator = _create_for_of_iterator_helper_loose(includeName.split("/")), _step; !(_step = _iterator()).done;){
2673
+ var encodedSegment = _step.value;
2674
+ var segment = decodeIncludePathSegment(encodedSegment);
2675
+ if (segment === undefined) {
2676
+ target[includeName] = undefined;
2677
+ return undefined;
2678
+ }
2679
+ path = node_path.join(path, segment);
2680
+ var relativePath = node_path.relative(root, path);
2681
+ if (relativePath === ".." || relativePath.startsWith(".." + node_path.sep)) {
2682
+ target[includeName] = undefined;
2683
+ return undefined;
2684
+ }
2685
+ stats = node_fs.lstatSync(path);
2686
+ if (stats.isSymbolicLink()) {
2687
+ target[includeName] = undefined;
2688
+ return undefined;
2689
+ }
2690
+ }
2691
+ var source = (stats == null ? void 0 : stats.isFile()) ? node_fs.readFileSync(path, "utf8") : undefined;
2692
+ target[includeName] = source;
2693
+ return source;
2694
+ } catch (error) {
2695
+ var code = error.code;
2696
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
2697
+ target[includeName] = undefined;
2698
+ return undefined;
2699
+ }
2700
+ }
2701
+ });
2702
+ }
2703
+ function decodeIncludePathSegment(segment) {
2704
+ var decoded;
2705
+ try {
2706
+ decoded = decodeURIComponent(segment);
2707
+ } catch (e) {
2708
+ return;
2709
+ }
2710
+ if (!decoded || decoded === "." || decoded === ".." || /[\\/\0]/.test(decoded)) return;
2711
+ return decoded;
2712
+ }
2713
+ function sourceFilePath(file, includeRoot) {
2714
+ var sourceFile = node_path.relative(includeRoot, node_path.resolve(file));
2715
+ if (sourceFile === ".." || sourceFile.startsWith(".." + node_path.sep)) {
2716
+ throw new Error("Shader file must be inside the include root '" + includeRoot + "'.");
2717
+ }
2718
+ return toIncludeKey(sourceFile);
2719
+ }
2720
+ function toIncludeKey(path) {
2721
+ return path.split(node_path.sep).map(encodeURIComponent).join("/");
2722
+ }