Why GLSL Disallows Nested Block Comments

The OpenGL Shading Language (GLSL) disallows the nesting of multiline C-style block comments (/* ... */) primarily due to its architectural inheritance from the ISO C language specification and the technical constraints of its lexical analyzer. This article examines why the GLSL grammar treats block comments as flat tokens, the computational difference between regular and context-free lexing, and the standard alternatives developers should use when commenting out blocks of shader code.

Heritage from the C Specification

GLSL was intentionally designed to be familiar to C and C++ developers. Rather than inventing a new lexical grammar, the creators of GLSL adopted the preprocessing and tokenization rules of ISO C (specifically C99).

In C and GLSL alike, multiline comments are defined by the opening delimiter /* and the closing delimiter */. The grammar dictates that once the lexer detects /*, it discards all subsequent characters until it encounters the very first */ sequence. The lexer does not treat an internal /* as a special token; it simply treats it as arbitrary text inside the active comment. Consequently, the first */ encountered terminates the comment entirely, leaving any remaining trailing text—including what was intended to be the outer closing tag—exposed to the compiler as invalid syntax.

Lexical Simplicity and Finite Automata

From a compiler design standpoint, tokenizing comments that do not nest requires only a simple Deterministic Finite Automaton (DFA), which can be matched using standard regular expressions. The state machine merely needs to toggle a "comment mode" on and off.

Allowing nested comments would require the lexical analyzer to keep track of nesting depth. Tracking depth requires a counter or a stack, turning the lexical specification from a regular grammar into a context-free grammar (equivalent to a Pushdown Automaton). Compilers typically reserve context-free parsing for the syntax phase (abstract syntax tree generation) rather than the lexical tokenization phase. Disallowing nested comments keeps the lexer lightweight, fast, and simple to implement across diverse GPU driver platforms.

Proper Alternatives in GLSL

Because block comments cannot be nested, placing /* ... */ around a section of code that already contains block comments will trigger a compilation error. To comment out blocks of code safely in GLSL, use these alternative approaches:

  1. Preprocessor Directives: Wrap the target code with #if 0 and #endif. The GLSL preprocessor properly skips code blocks enclosed in false conditional directives, regardless of any internal /* ... */ or // comments.
  2. Single-Line Comments: Use line comments (//) for each line. Modern code editors provide keybindings to comment out large selections using single-line delimiters, which do not interfere with multiline comment syntax.