LCOV - code coverage report
Current view: top level - source/graphics - PreprocessorWrapper.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 112 141 79.4 %
Date: 2026-12-03 01:19:39 Functions: 7 11 63.6 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "PreprocessorWrapper.h"
      21             : 
      22             : #include "graphics/ShaderDefines.h"
      23             : #include "lib/debug.h"
      24             : #include "ps/CLogger.h"
      25             : #include "ps/CStrIntern.h"
      26             : #include "ps/Profile.h"
      27             : 
      28             : #include <cctype>
      29             : #include <cstdlib>
      30             : #include <cstring>
      31             : #include <deque>
      32             : #include <map>
      33             : #include <string>
      34             : #include <string_view>
      35             : #include <utility>
      36             : #include <vector>
      37             : 
      38             : namespace
      39             : {
      40             : 
      41             : struct MatchIncludeResult
      42             : {
      43             :     bool found;
      44             :     bool error;
      45             :     size_t nextLineStart;
      46             :     size_t pathFirst, pathLast;
      47             : 
      48             :     static MatchIncludeResult MakeNotFound(const std::string_view& source, size_t pos)
      49             :     {
      50         441 :         while (pos < source.size() && source[pos] != '\n')
      51         384 :             ++pos;
      52          57 :         return MatchIncludeResult{
      53          57 :             false, false, pos < source.size() ? pos + 1 : source.size(), 0, 0};
      54             :     }
      55             : 
      56           1 :     static MatchIncludeResult MakeError(
      57             :         const char* message, const std::string_view& source, const size_t lineStart, const size_t currentPos)
      58             :     {
      59           1 :         ENSURE(currentPos >= lineStart);
      60             :         size_t lineEnd = currentPos;
      61           9 :         while (lineEnd < source.size() && source[lineEnd] != '\n' && source[lineEnd] != '\r')
      62           8 :             ++lineEnd;
      63           1 :         const std::string_view line = source.substr(lineStart, lineEnd - lineStart);
      64           1 :         while (lineEnd < source.size() && source[lineEnd] != '\n')
      65           0 :             ++lineEnd;
      66           1 :         const size_t nextLineStart = lineEnd < source.size() ? lineEnd + 1 : source.size();
      67           2 :         LOGERROR("Preprocessor error: {}: '{}'\n", message, line);
      68           1 :         return MatchIncludeResult{false, true, nextLineStart, 0, 0};
      69             :     }
      70             : };
      71             : 
      72          67 : MatchIncludeResult MatchIncludeUntilEOLorEOS(const std::string_view& source, const size_t lineStart)
      73             : {
      74             :     // We need to match a line like this:
      75             :     // ^[ \t]*#[ \t]*include[ \t]*"[^"]+".*$
      76             :     //  ^     ^^     ^      ^     ^^    ^
      77             :     //  1     23     4      5     67    8    <- steps
      78          67 :     const CStr INCLUDE = "include";
      79          67 :     size_t pos = lineStart;
      80             :     // Matching step #1.
      81         198 :     while (pos < source.size() && std::isblank(source[pos]))
      82         131 :         ++pos;
      83             :     // Matching step #2.
      84          67 :     if (pos == source.size() || source[pos] != '#')
      85          67 :         return MatchIncludeResult::MakeNotFound(source, pos);
      86          48 :     ++pos;
      87             :     // Matching step #3.
      88          48 :     while (pos < source.size() && std::isblank(source[pos]))
      89           0 :         ++pos;
      90             :     // Matching step #4.
      91          78 :     if (pos + INCLUDE.size() >= source.size() || source.substr(pos, INCLUDE.size()) != INCLUDE)
      92          67 :         return MatchIncludeResult::MakeNotFound(source, pos);
      93          10 :     pos += INCLUDE.size();
      94             :     // Matching step #5.
      95          20 :     while (pos < source.size() && std::isblank(source[pos]))
      96          10 :         ++pos;
      97             :     // Matching step #6.
      98          10 :     if (pos == source.size() || source[pos] != '"')
      99           1 :         return MatchIncludeResult::MakeError("#include should be followed by quote", source, lineStart, pos);
     100           9 :     ++pos;
     101             :     // Matching step #7.
     102           9 :     const size_t pathFirst = pos;
     103          70 :     while (pos < source.size() && source[pos] != '"' && source[pos] != '\n')
     104          61 :         ++pos;
     105           9 :     const size_t pathLast = pos;
     106             :     // Matching step #8.
     107           9 :     if (pos == source.size() || source[pos] != '"')
     108           0 :         return MatchIncludeResult::MakeError("#include has invalid quote pair", source, lineStart, pos);
     109           9 :     if (pathLast - pathFirst <= 1)
     110           0 :         return MatchIncludeResult::MakeError("#include path shouldn't be empty", source, lineStart, pos);
     111          41 :     while (pos < source.size() && source[pos] != '\n')
     112          32 :         ++pos;
     113           9 :     return MatchIncludeResult{true, false, pos < source.size() ? pos + 1 : source.size(), pathFirst, pathLast};
     114          67 : }
     115             : 
     116          14 : bool ResolveIncludesImpl(
     117             :     std::string_view currentPart,
     118             :     std::unordered_map<CStr, CStr>& includeCache, const CPreprocessorWrapper::IncludeRetrieverCallback& includeCallback,
     119             :     std::deque<std::string>& chunks, std::vector<std::string_view>& processedParts)
     120             : {
     121          14 :     static const CStr lineDirective = "#line ";
     122          79 :     for (size_t lineStart = 0, line = 1; lineStart < currentPart.size(); ++line)
     123             :     {
     124          67 :         MatchIncludeResult match = MatchIncludeUntilEOLorEOS(currentPart, lineStart);
     125          67 :         if (match.error)
     126           2 :             return {};
     127          66 :         else if (!match.found)
     128             :         {
     129          57 :             if (lineStart + lineDirective.size() < currentPart.size() &&
     130          92 :                 currentPart.substr(lineStart, lineDirective.size()) == lineDirective)
     131             :             {
     132          16 :                 size_t newLineNumber = 0;
     133          16 :                 size_t pos = lineStart + lineDirective.size();
     134          32 :                 while (pos < match.nextLineStart && std::isdigit(currentPart[pos]))
     135             :                 {
     136          16 :                     newLineNumber = newLineNumber * 10 + (currentPart[pos] - '0');
     137          16 :                     ++pos;
     138             :                 }
     139          16 :                 if (newLineNumber > 0)
     140          16 :                     line = newLineNumber - 1;
     141             :             }
     142             : 
     143          57 :             lineStart = match.nextLineStart;
     144          57 :             continue;
     145          57 :         }
     146          18 :         const std::string path(currentPart.substr(match.pathFirst, match.pathLast - match.pathFirst));
     147          18 :         auto it = includeCache.find(path);
     148           9 :         if (it == includeCache.end())
     149             :         {
     150           5 :             CStr includeContent;
     151          15 :             if (!includeCallback(path, includeContent))
     152             :             {
     153           2 :                 LOGERROR("Preprocessor error: line {}: Can't load #include file: '{}'", line,
     154             :                     path);
     155           1 :                 return false;
     156             :             }
     157           4 :             it = includeCache.emplace(path, std::move(includeContent)).first;
     158           5 :         }
     159             :         // We need to insert #line directives to have correct line numbers in errors.
     160           8 :         chunks.emplace_back(fmt::format("{}1\n{}\n{}{}\n", lineDirective, it->second, lineDirective,
     161           8 :             line + 1));
     162           8 :         processedParts.emplace_back(currentPart.substr(0, lineStart));
     163           8 :         if (!ResolveIncludesImpl(chunks.back(), includeCache, includeCallback, chunks, processedParts))
     164             :             return false;
     165           8 :         currentPart = currentPart.substr(match.nextLineStart);
     166           8 :         lineStart = 0;
     167          10 :     }
     168          12 :     if (!currentPart.empty())
     169          11 :         processedParts.emplace_back(currentPart);
     170             :     return true;
     171             : }
     172             : 
     173             : } // anonymous namespace
     174             : 
     175           2 : void CPreprocessorWrapper::PyrogenesisShaderError(int iLine, const char* iError, const Ogre::CPreprocessor::Token* iToken)
     176             : {
     177           2 :     if (iToken)
     178           0 :         LOGERROR("Preprocessor error: line {}: {}: '{}'\n", iLine, iError,
     179             :             std::string_view(iToken->String, iToken->Length));
     180             :     else
     181           6 :         LOGERROR("Preprocessor error: line {}: {}\n", iLine, iError);
     182           2 : }
     183             : 
     184           0 : CPreprocessorWrapper::CPreprocessorWrapper()
     185           0 :     : CPreprocessorWrapper(IncludeRetrieverCallback{})
     186             : {
     187           0 : }
     188             : 
     189           6 : CPreprocessorWrapper::CPreprocessorWrapper(const IncludeRetrieverCallback& includeCallback)
     190           6 :     : m_IncludeCallback(includeCallback)
     191             : {
     192           6 :     Ogre::CPreprocessor::ErrorHandler = CPreprocessorWrapper::PyrogenesisShaderError;
     193           6 : }
     194             : 
     195           0 : void CPreprocessorWrapper::AddDefine(const char* name, const char* value)
     196             : {
     197           0 :     m_Preprocessor.Define(name, strlen(name), value, strlen(value));
     198           0 : }
     199             : 
     200           0 : void CPreprocessorWrapper::AddDefines(const CShaderDefines& defines)
     201             : {
     202           0 :     std::map<CStrIntern, CStrIntern> map = defines.GetMap();
     203           0 :     for (std::map<CStrIntern, CStrIntern>::const_iterator it = map.begin(); it != map.end(); ++it)
     204           0 :         m_Preprocessor.Define(it->first.c_str(), it->first.length(), it->second.c_str(), it->second.length());
     205           0 : }
     206             : 
     207           0 : bool CPreprocessorWrapper::TestConditional(const CStr& expr)
     208             : {
     209             :     // Construct a dummy program so we can trigger the preprocessor's expression
     210             :     // code without modifying its public API.
     211             :     // Be careful that the API buggily returns a statically allocated pointer
     212             :     // (which we will try to free()) if the input just causes it to append a single
     213             :     // sequence of newlines to the output; the "\n" after the "#endif" is enough
     214             :     // to avoid this case.
     215           0 :     CStr input = "#if ";
     216           0 :     input += expr;
     217           0 :     input += "\n1\n#endif\n";
     218             : 
     219           0 :     size_t len = 0;
     220           0 :     char* output = m_Preprocessor.Parse(input.c_str(), input.size(), len);
     221             : 
     222           0 :     if (!output)
     223             :     {
     224           0 :         LOGERROR("Failed to parse conditional expression '{}'", expr);
     225           0 :         return false;
     226             :     }
     227             : 
     228           0 :     bool ret = (memchr(output, '1', len) != NULL);
     229             : 
     230             :     // Free output if it's not inside the source string
     231           0 :     if (!(output >= input.c_str() && output < input.c_str() + input.size()))
     232           0 :         free(output);
     233             : 
     234             :     return ret;
     235             : 
     236           0 : }
     237             : 
     238           6 : CStr CPreprocessorWrapper::ResolveIncludes(const CStr& source)
     239             : {
     240             :     // Stores intermediate blocks of text to avoid additional copying. Should
     241             :     // be constructed before views and destroyed after (currently guaranteed
     242             :     // by stack).
     243             :     // Short String Optimisation can make views point to container-managed data,
     244             :     // so push_back must not invalidate pointers (std::deque guarantees that).
     245           6 :     std::deque<std::string> chunks;
     246             :     // After resolving the following vector should contain a complete list
     247             :     // to concatenate.
     248           6 :     std::vector<std::string_view> processedParts;
     249           6 :     if (!ResolveIncludesImpl(source, m_IncludeCache, m_IncludeCallback, chunks, processedParts))
     250           2 :         return {};
     251           4 :     std::size_t totalSize = 0;
     252          23 :     for (const std::string_view& part : processedParts)
     253          19 :         totalSize += part.size();
     254           4 :     std::string processedSource;
     255           4 :     processedSource.reserve(totalSize);
     256          23 :     for (const std::string_view& part : processedParts)
     257          19 :         processedSource.append(part);
     258           8 :     return processedSource;
     259          10 : }
     260             : 
     261           6 : CStr CPreprocessorWrapper::Preprocess(const CStr& input)
     262             : {
     263           6 :     PROFILE("Preprocess shader source");
     264             : 
     265           6 :     CStr source = ResolveIncludes(input);
     266             : 
     267           6 :     size_t len = 0;
     268           6 :     char* output = m_Preprocessor.Parse(source.c_str(), source.size(), len);
     269             : 
     270           6 :     if (!output)
     271             :     {
     272           2 :         LOGERROR("Shader preprocessing failed");
     273           2 :         return "";
     274             :     }
     275             : 
     276           4 :     CStr ret(output, len);
     277             : 
     278             :     // Free output if it's not inside the source string
     279           4 :     if (!(output >= source.c_str() && output < source.c_str() + source.size()))
     280           2 :         free(output);
     281             : 
     282           4 :     return ret;
     283          10 : }

Generated by: LCOV version 1.16