Blender V5.3
diagnostic.hh
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#pragma once
10
11#include "ast.hh"
12#include "token.hh"
13
14#include <sstream>
15
16namespace bsl {
17
19
20using namespace blender::gpu::shader::parser;
21using namespace std;
22
23/* TODO using fmt directly.
24 * Using std::format is not possible on macos because of our minimum target. */
25namespace mini_fmt {
26
27namespace detail {
28// Convert any streamable argument into a std::string
29template<typename T> std::string to_string_arg(T &&arg)
30{
31 std::ostringstream ss;
32 ss << std::forward<T>(arg);
33 return ss.str();
34}
35
36// Expand variadic arguments into a vector of strings
37template<typename... Args> std::vector<std::string> args_to_strings(Args &&...args)
38{
39 return {to_string_arg(std::forward<Args>(args))...};
40}
41} // namespace detail
42
43template<typename... Args> std::string format(const std::string &fmt, Args &&...args)
44{
45 std::vector<std::string> str_args = detail::args_to_strings(std::forward<Args>(args)...);
46 std::string result;
47 result.reserve(fmt.size() + 16 * sizeof...(args));
48
49 size_t auto_idx = 0;
50 size_t i = 0;
51 size_t len = fmt.size();
52
53 while (i < len) {
54 if (fmt[i] == '{' && i + 1 < len) {
55 // Case 1: Sequential placeholder "{}"
56 if (fmt[i + 1] == '}') {
57 if (auto_idx < str_args.size()) {
58 result += str_args[auto_idx++];
59 }
60 i += 2;
61 continue;
62 }
63
64 // Case 2: Positional placeholder "{N}"
65 size_t end_pos = fmt.find('}', i + 1);
66 if (end_pos != std::string::npos) {
67 std::string num_str = fmt.substr(i + 1, end_pos - (i + 1));
68
69 // Parse integer index manually to avoid std::stoi dependency
70 bool valid = !num_str.empty();
71 size_t idx = 0;
72 for (char c : num_str) {
73 if (c < '0' || c > '9') {
74 valid = false;
75 break;
76 }
77 idx = idx * 10 + (c - '0');
78 }
79
80 if (valid && idx < str_args.size()) {
81 result += str_args[idx];
82 i = end_pos + 1;
83 continue;
84 }
85 }
86 }
87
88 result += fmt[i++];
89 }
90
91 return result;
92}
93
94} // namespace mini_fmt
95
96enum class Diag {
100
102
109
113
117
123
126
132
135
146
148
151
161
166
170
173
176
178
183
185
194
196
201
204
206
215
217
219
223
230
236
238
243
246
248
259
263
265
267
276
286
288
290};
291
292static inline std::string_view diagnostic_message_get(Diag diag)
293{
294 switch (diag) {
296 return "Anonymous unions at namespace or global scope are not supported";
298 return "Multi-dimensional arrays cannot have implicit size";
300 return "Multi-dimensional arrays are not supported";
302 return "Definition of variable with array type needs an explicit size or an initializer";
304 return "Array size must be greater than zero";
306 return "Array size is not a constant expression";
308 return "Invalid operand of array type";
310 return "'{}' attribute is only allowed in vertex and fragment shaders";
312 return "Only entry points can use 'in' attribute";
314 return "Only entry points can use 'out' attribute";
316 return "Cannot deduce actual type for variable '{}' with type 'auto'";
318 return "Bit-field has non-integral type '{}'";
320 return "Width of bit-field ({} bits) is negative";
322 return "Width of bit-field ({} bits) exceeds the width of its type";
324 return "Width of bit-field is zero";
326 return "Bitfields must have single declarator";
328 return "Initializer for variable '{}' with type 'auto' contains multiple expressions";
330 return "Cannot deduce type for variable '{}' with type 'auto' from nested initializer list";
332 return "Runtime capacity can only be specified for one dimensional array";
334 return "Runtime capacity requires the array to be sized to its maximum size";
336 return "Cannot use ADL on types";
338 return "Compiler error: member function has no class";
340 return "Compiler error: non-existing child scope";
342 return "Division by zero during constexpr evaluation";
344 return "Non-static global variable cannot be constexpr; did you intend to make it static?";
346 return "Constexpr if condition is not a constant expression";
348 return "Non-static data member cannot be constexpr; did you intend to make it static?";
350 return "Negative shift count {}";
352 return "Shift count {} >= width of type 32";
354 return "Constexpr variable '{}' must be initialized by a constant expression";
356 return "Constexpr variable '{}' must be initialized by a constant expression of type '{}' "
357 "but got '{}'";
359 return "Constexpr variable must be scalar or vector of type 'int', 'uint', 'bool' or "
360 "'float'";
362 return "Array variables cannot be constexpr";
364 return "Empty classes are not supported in storage or uniform buffers";
366 return "Entry point functions must return 'void'";
368 return "Expected array member initializer but got designated initializer";
370 return "Expected colon ':'";
372 return "Expected compute shader entry point function";
374 return "Expected entry point resource attribute but got '{}'";
376 return "Expected fragment shader entry point function";
378 return "Expected image format";
380 return "Expected {} parameter(s) for attribute '{}'";
382 return "Expecting one typename";
384 return "Expected closing parenthesis";
386 return "Expected between 1 and {} parameter(s) for attribute '{}'";
388 return "Expected resource definition of type '{}' but got '{}'";
390 return "Expected resource of type '{}' or '{}' but got '{}'";
392 return "Expected resource of type '{}' but got '{}'";
394 return "Expected resource table initializer";
396 return "Excess elements in scalar initializer";
398 return "Expected vertex shader entry point function";
400 return "{} cannot contain function calls";
402 return "Expression is not an integral constant expression";
404 return "Field designator '{}' does not refer to any field in type '{}'";
406 return "Field designator '{}' needs to be specified in declaration order";
408 return "Function calls are not allowed in reference definition";
410 return "Implicit padding of 4 bytes per array element, do not use 12 bytes types in arrays";
412 return "Implicit padding of {} bytes per array element, use a 16 bytes type or use a "
413 "storage buffer";
415 return "Implicit {} bytes padding at the end of '{}', add manual padding";
417 return "Implicit {} bytes padding before '{}', add manual padding";
419 return "Initializer list requires explicit type";
421 return "Cannot inline recursive call";
423 return "Invalid operands to binary expression ('{}' {} '{}')";
425 return "Invalid expression in codegen";
427 return "Invalid expression in type checker";
429 return "Cannot inline function call inside a compound expression";
431 return "Unsupported literal";
433 return "Invalid resource of type '{}' for resource table class";
435 return "Subscripted value is not an array, pointer, or vector";
437 return "Invalid argument type '{0}' to unary expression ({0}'{1}')";
439 return "Missing parameter for call to '{}'";
441 return "Condition declared here";
443 return "Only one condition attribute is allowed";
445 return "Access to conditional resource '{}' is not guarded by any static check";
447 return "Condition attribute is only allowed on resources declaration";
449 return "Condition attribute is not compatible with resource type '{}'";
451 return "Redefinition of compilation constant '{}'";
453 return "Previous definition is here";
455 return "Read of non-const variable is not allowed in a {}";
457 return "In declaration of union '{}' requested here";
459 return "In declaration of '{}' of type '{}'";
461 return "In inlining of function '{}' requested here";
463 return "In this storage buffer declaration";
465 return "In this uniform buffer declaration";
467 return "In instantiation of class template specialization '{}' requested here";
469 return "In instantiation of function template specialization '{}' requested here";
471 return "Previous definition of '{}' is here";
473 return "Called object type '{}' is not a function";
475 return "Incompatible operand types ('{}' and '{}')";
477 return "Increment and decrement operators are not supported on bitfield";
479 return "Invalid operator token '{}'";
481 return "Call to '{}' is ambiguous for parameters '{}' with candidates: {}";
483 return "No matching function for call to '{}' for parameters {} with candidates: {}";
485 return "Trailing input";
487 return "Redefinition of '{}'";
489 return "Redefinition of entry point function '{}'";
491 return "Redefinition of template '{}'";
493 return "Reference cannot bind to expression of non-const subscript index";
495 return "Reference cannot bind to an expression with side effects";
497 return "Reference cannot bind to a temporary";
499 return "Variable declaration must declare either no reference or only reference";
501 return "Reference to type '{}' cannot bind to a value of unrelated type '{}'";
503 return "Declaration of reference variable '{}' requires an initializer";
505 return "Resource attributes are only supported on entry point arguments";
507 return "Out of class resource declaration";
509 return "Calling resource table constructor '{0}' is not allowed; use "
510 "'resource_table_get({0})' instead";
512 return "Declaration is already of type '{}'";
514 return "Resource table must be declared as reference";
516 return "Resources cannot be declared in an anonymous struct";
518 return "Return statement outside of a function";
520 return "'if' statement cannot be 'constexpr' inside a static branch";
522 return "Statement cannot be tagged as 'static_branch' because previous statement also isn't";
524 return "Statement must be tagged as 'static_branch' because previous statement is";
526 return "Static data member '{}' not allowed in {} {}";
528 return "Not enough names in structure binding";
530 return "Too many names in structure binding";
532 return "Array subscript is not an integer";
534 return "Invalid argument for template parameter '{}'";
536 return "Missing argument for template parameter '{}'";
538 return "Missing template definition";
540 return "Missing explicit template arguments";
542 return "Missing explicit instantiation of template '{}'";
544 return "Missing template parameters";
546 return "Missing template parameters for '{}'";
548 return "Missing instantiation of parent class for instantiation of '{}'";
550 return "Template parameter count must match declaration argument count";
552 return "Non-type template argument is not a constant expression";
554 return "Type '{}' is not allowed in storage buffer{}";
556 return "Type '{}' is not allowed in uniform and storage buffer{}";
558 return "Type '{}' is not allowed in uniform buffer because it contains implicit padding";
560 return "Value of type '{}' is not contextually convertible to 'bool'";
562 return "Unsupported array at union base scope; wrap it inside a named struct";
564 return "Unknown attribute '{}'";
566 return "Compiler error: Can't find class symbol";
568 return "Unknown function name '{}'";
570 return "Use of undeclared identifier '{}'";
572 return "Unknown member '{}'";
574 return "Unknown type name";
576 return "Unknown type name '{}'";
578 return "Unknown variable '{}'";
580 return "Comma operator is not allowed in unrolled loop statement";
582 return "Expected '++{0}', '--{0}', '{0}++', '{0}--' or '{0} = expr', '{0} += expr', '{0} -= "
583 "expr', '{0} /= expr', '{0} *= expr' for unrolled loop expression";
585 return "Loop variable needs to be assigned a value (using assignment) for unrolled loops";
587 return "Init statement needs to define the loop variable for unrolled loops";
589 return "Multiple variables declared in unrolled loop";
591 return "Unrolled loop expression must assign to '{}'";
593 return "Loop variable needs to be an integer type for unrolled loops";
595 return "Non-constant expression in unrolled loop control";
597 return "Loop unrolling generates too many iterations (over 64)";
599 return "Unsupported symbol '{}' inside {}";
601 return "Using namespace statements are not supported";
602 }
603 return "Compiler error: Invalid diagnostic value";
604}
605
609 string param1;
610 string param2;
611 string param3;
612
614 Diag diag,
615 const string &param1 = "",
616 const string &param2 = "",
617 const string &param3 = "")
619 {
620 }
621};
622
626 string param1;
627 string param2;
628 string param3;
629
631 Diag diag,
632 const string &param1 = "",
633 const string &param2 = "",
634 const string &param3 = "")
636 {
637 }
638};
639
642
644
645 void error(Token tok, const string &msg)
646 {
647 if (err_handler.err) {
648 return;
649 }
650 vector<pair<Token, string>> errors;
651 errors.emplace_back(tok, msg);
652
653 for (auto it = note_stack.rbegin(); it != note_stack.rend(); ++it) {
654 auto [note_node, note_msg] = *it;
655 errors.emplace_back(note_node, note_msg);
656 }
657 err_handler.report(errors);
658 }
659
660 void error(ast::Node node, const string &msg)
661 {
662 error(node.front(), msg);
663 }
664
665 /* Pipe error if existing. */
666 void error(std::optional<AstNodeException> &err)
667 {
668 if (err) {
669 error(err->node, err->diag, err->param1, err->param2, err->param3);
670 }
671 }
672 void error(std::optional<TokenException> &err)
673 {
674 if (err) {
675 error(err->tok, err->diag, err->param1, err->param2, err->param3);
676 }
677 }
678
679 template<typename... Args> void error(Token tok, Diag code, Args &&...args)
680 {
681 std::string_view format_str = diagnostic_message_get(code);
682 std::string message = mini_fmt::format(std::string(format_str), std::forward<Args>(args)...);
683 error(tok, message);
684 }
685 template<typename... Args> void error(ast::Node node, Diag code, Args &&...args)
686 {
687 error(node.front(), code, std::forward<Args>(args)...);
688 }
689
690 /* Stack of notes to add to the error. */
691 vector<tuple<Token, string>> note_stack = {};
692
693 struct ScopedNote {
694 vector<tuple<Token, string>> &note_stack;
695
696 ScopedNote(Token tok, const string &msg, vector<tuple<Token, string>> &note_stack)
698 {
699 note_stack.emplace_back(tok, msg);
700 }
701
703 {
704 note_stack.pop_back();
705 }
706 };
707
708 template<typename... Args> [[nodiscard]] ScopedNote note(Token tok, Diag code, Args &&...args)
709 {
710 std::string_view format_str = diagnostic_message_get(code);
711 std::string message = mini_fmt::format(std::string(format_str), std::forward<Args>(args)...);
712 return ScopedNote(tok, message, note_stack);
713 }
714
715 template<typename... Args>
716 [[nodiscard]] ScopedNote note(ast::Node node, Diag code, Args &&...args)
717 {
718 std::string_view format_str = diagnostic_message_get(code);
719 std::string message = mini_fmt::format(std::string(format_str), std::forward<Args>(args)...);
720 return ScopedNote(node.front(), message, note_stack);
721 }
722
723#define NOTE(node, diag, id) auto n = note(node, diag, id)
724};
725
726template<typename T, typename ExceptionT = AstNodeException> struct Result {
728 std::optional<ExceptionT> err;
729
731 {
732 handler->error(err);
733 return value;
734 }
735
736 /* Transfer error if not yet set. */
737 T unwrap(std::optional<AstNodeException> &other_err)
738 {
739 if (!other_err) {
740 other_err = err;
741 }
742 return value;
743 }
744};
745
746template<typename T, typename U, typename ExceptionT = AstNodeException> struct ResultPair {
749 std::optional<ExceptionT> err;
750
751 pair<T, U> unwrap(NodeErrorHandler *handler)
752 {
753 handler->error(err);
754 return {first, second};
755 }
756
757 /* Transfer error if not yet set. */
758 pair<T, U> unwrap(std::optional<AstNodeException> &other_err)
759 {
760 if (!other_err) {
761 other_err = err;
762 }
763 return {first, second};
764 }
765};
766
767} // namespace bsl
#define U
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
#define T
std::string to_string_arg(T &&arg)
Definition diagnostic.hh:29
std::vector< std::string > args_to_strings(Args &&...args)
Definition diagnostic.hh:37
std::string format(const std::string &fmt, Args &&...args)
Definition diagnostic.hh:43
Definition codegen.cc:18
static std::string_view diagnostic_message_get(Diag diag)
@ TemplateParameterNotConstexpr
@ CompilationConstantPreviousDecl
@ ConditionAttributeNotChecked
@ AutoTypeNestedInitializer
@ ConstexprShiftNegative
@ ArrayMultidimensionalNotSupported
@ InvalidNumberLiteral
@ UnrolledLoopMissingAssignment
@ ConstexprVarMustBeInitializedByConstantExpr
@ ConstexprShiftTooLarge
@ TemplateInvalidArg
@ ExpectedOneTypename
@ ReferenceCannotBindTemporary
@ InvalidExprTypeCodegen
@ StaticBranchConstexprIfNotAllowed
@ StructuredBindingTooManyNames
@ InliningRecursive
@ ExprNotIntegralConstant
@ AnonymousUnionNotSupportedAtNamespaceScope
@ InvalidBinaryOperands
@ NonConstVariableInExpr
@ InvalidUnaryArgumentType
@ ConstexprMemberNonStatic
@ UnknownIdentifier
@ CompilerErrorMemberFuncNoClass
Definition diagnostic.hh:98
@ ExpectedScalarInitializer
@ TypeNotConvertibleToBool
@ ConstexprGlobalNonStatic
@ CapacityArrayImplicitSize
@ OperatorBitfieldInvalid
@ TypeNotAllowedInStorageBuffer
@ TemplateMissingArgument
@ ResourceOutOfClassDeclaration
@ OperatorCalledIsNotFunction
@ FunctionCallNotAllowedInReferenceDefinition
@ CompilerErrorChildScopeNotFound
Definition diagnostic.hh:99
@ UnrolledLoopTooManyIterations
@ OperatorInvalidTernary
@ ExpectedResourceTableInitializer
@ ImplicitPaddingArrayElementStd140
@ NoteInStorageBufferDeclaration
@ ExpectedResourceDefinitionOfType
@ ResourceTableConstructorNotAllowed
@ OperatorTokenInvalid
@ RedefinitionOfEntryPointFunction
@ ArraySizeMustBeGreaterThanZero
@ ConditionAttributeMultiple
@ ConditionAttributeDeclaredHere
@ UnrolledLoopInvalidExpression
@ UnionArrayUnsupported
@ StaticDataMemberNotAllowed
@ ExpectedImageFormat
@ MissingParameterForCall
@ EmptyClassNotSupportedInBuffer
@ UnrolledLoopNonIntVar
@ ResourcesNotAllowedInAnonymousStruct
@ UnrolledLoopMissingInit
@ InvalidExprTypeChecker
@ TemplateParameterCountMismatch
@ ConditionAttributeUnsupported
@ BitFieldNotSingleDeclarator
@ CompilationConstantRedefinition
@ NoteInUniformBufferDeclaration
@ UnknownClassInstantiation
@ ExpectedFragmentShaderEntryPoint
@ ArrayMultidimensionalImplicitSize
@ ReferenceCannotBindSideEffect
@ ConstexprVarMustNotBeArray
@ NoteDeclarationUnionRequested
@ CompilerErrorADLOnTypesNotAllowed
Definition diagnostic.hh:97
@ NoteInstantiationClassTemplateRequested
@ ParserTrailingInput
@ ReturnOutsideFunction
@ AutoTypeMultipleExpressions
@ UnknownTypeNameWithArg
@ ExpectedEntryPointResourceAttribute
@ UnrolledLoopMustAssignToVar
@ AttributeNotAllowedInComp
@ ImplicitPaddingAtEndOfStruct
@ TemplateMissingExplicitArguments
@ ConstexprIfConditionNotConstexpr
@ ExprCannotContainFunctionCalls
@ TypeNotAllowedInUniformBufferImplicitPadding
@ ConstexprDivisionByZero
@ AttributeOnlyEntryPointsCanUseOut
@ TemplateMissingInstantiation
@ ImplicitPaddingBeforeMember
@ ImplicitPadding12BytesArrayElement
@ InvalidResourceTypeForResourceTableClass
@ UnrolledLoopCommaOperator
@ ReferenceMixedVarDecl
@ ArrayNeedsSizeOrInitializer
@ StaticBranchRequiredByPrevious
@ ExpectedVertexShaderEntryPoint
@ AttributeOnlyEntryPointsCanUseIn
@ NotePreviousDefinition
@ ReferenceCannotBindNonConstSubscript
@ InitializerListRequiresExplicitType
@ BitFieldSizeTooLarge
@ NoteInstantiationFuncTemplateRequested
@ BitFieldNotIntegral
@ AutoTypeCannotBeDeduced
@ ReferenceVariableRequiresInitializer
@ TemplateMissingParametersForType
@ TypeNotAllowedInUniformAndStorageBuffer
@ RedefinitionTemplate
@ StaticBranchMissingPrevious
@ UnrolledLoopMultipleVariables
@ ExpectedRangeParametersForAttribute
@ ResourceAttributesOnlyOnEntryPointArgs
@ ResourceTableDeclarationAlreadyOfType
@ ExpectedArrayMemberInitializer
@ TemplateMissingDefinition
@ UnsupportedSymbolInExpr
@ ConstexprVarMustBeValidType
@ InvalidInlinedFunctionLocation
@ ArraySizeNotConstantExpression
@ FieldDesignatorNotFound
@ EntryPointVoidReturn
@ TemplateMissingParameters
@ ExpectedNParametersForAttribute
@ StructuredBindingNotEnoughNames
@ OverloadAmbiguous
@ ExpectedComputeShaderEntryPoint
@ TemplateMissingParentClassInstantiation
@ ExpectedResourceOfType
@ FieldDesignatorOutOfOrder
@ UnrolledLoopNotConstexpr
@ ReferenceTypeMismatch
@ ExpectedResourceOfEitherType
@ CapacityArrayDimensionMismatch
@ ExpectedParenthesis
@ NoteInDeclarationOfVariable
@ ConditionAttributeNotOnResource
@ ResourceTableMustBeReference
@ BitFieldSizeNegative
@ UsingNamespaceNotSupported
@ ConstexprVarMustBeInitializedByCorrectType
void report(Token tok, std::string_view message)
AstNodeException(ast::Node node, Diag diag, const string &param1="", const string &param2="", const string &param3="")
vector< tuple< Token, string > > & note_stack
ScopedNote(Token tok, const string &msg, vector< tuple< Token, string > > &note_stack)
void error(std::optional< AstNodeException > &err)
void error(ast::Node node, const string &msg)
ScopedNote note(ast::Node node, Diag code, Args &&...args)
ScopedNote note(Token tok, Diag code, Args &&...args)
void error(Token tok, const string &msg)
void error(Token tok, Diag code, Args &&...args)
vector< tuple< Token, string > > note_stack
ErrorHandler & err_handler
void error(ast::Node node, Diag code, Args &&...args)
NodeErrorHandler(ErrorHandler &handler)
void error(std::optional< TokenException > &err)
pair< T, U > unwrap(std::optional< AstNodeException > &other_err)
std::optional< ExceptionT > err
pair< T, U > unwrap(NodeErrorHandler *handler)
std::optional< ExceptionT > err
T unwrap(std::optional< AstNodeException > &other_err)
T unwrap(NodeErrorHandler *handler)
TokenException(Token tok, Diag diag, const string &param1="", const string &param2="", const string &param3="")