File: PreprocessorWrapper.cpp

package info (click to toggle)
0ad 0.0.26-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 130,460 kB
  • sloc: cpp: 261,824; ansic: 198,392; javascript: 19,067; python: 14,557; sh: 7,629; perl: 4,072; xml: 849; makefile: 741; java: 533; ruby: 229; php: 190; pascal: 30; sql: 21; tcl: 4
file content (274 lines) | stat: -rw-r--r-- 9,309 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/* Copyright (C) 2021 Wildfire Games.
 * This file is part of 0 A.D.
 *
 * 0 A.D. is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * 0 A.D. is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "precompiled.h"

#include "PreprocessorWrapper.h"

#include "graphics/ShaderDefines.h"
#include "ps/CLogger.h"
#include "ps/Profile.h"

#include <cctype>
#include <deque>
#include <string>
#include <string_view>
#include <vector>

namespace
{

struct MatchIncludeResult
{
	bool found;
	bool error;
	size_t nextLineStart;
	size_t pathFirst, pathLast;

	static MatchIncludeResult MakeNotFound(const std::string_view& source, size_t pos)
	{
		while (pos < source.size() && source[pos] != '\n')
			++pos;
		return MatchIncludeResult{
			false, false, pos < source.size() ? pos + 1 : source.size(), 0, 0};
	}

	static MatchIncludeResult MakeError(
		const char* message, const std::string_view& source, const size_t lineStart, const size_t currentPos)
	{
		ENSURE(currentPos >= lineStart);
		size_t lineEnd = currentPos;
		while (lineEnd < source.size() && source[lineEnd] != '\n' && source[lineEnd] != '\r')
			++lineEnd;
		const std::string_view line = source.substr(lineStart, lineEnd - lineStart);
		while (lineEnd < source.size() && source[lineEnd] != '\n')
			++lineEnd;
		const size_t nextLineStart = lineEnd < source.size() ? lineEnd + 1 : source.size();
		LOGERROR("Preprocessor error: %s: '%s'\n", message, std::string(line).c_str());
		return MatchIncludeResult{false, true, nextLineStart, 0, 0};
	}
};

MatchIncludeResult MatchIncludeUntilEOLorEOS(const std::string_view& source, const size_t lineStart)
{
	// We need to match a line like this:
	// ^[ \t]*#[ \t]*include[ \t]*"[^"]+".*$
	//  ^     ^^     ^      ^     ^^    ^
	//  1     23     4      5     67    8    <- steps
	const CStr INCLUDE = "include";
	size_t pos = lineStart;
	// Matching step #1.
	while (pos < source.size() && std::isblank(source[pos]))
		++pos;
	// Matching step #2.
	if (pos == source.size() || source[pos] != '#')
		return MatchIncludeResult::MakeNotFound(source, pos);
	++pos;
	// Matching step #3.
	while (pos < source.size() && std::isblank(source[pos]))
		++pos;
	// Matching step #4.
	if (pos + INCLUDE.size() >= source.size() || source.substr(pos, INCLUDE.size()) != INCLUDE)
		return MatchIncludeResult::MakeNotFound(source, pos);
	pos += INCLUDE.size();
	// Matching step #5.
	while (pos < source.size() && std::isblank(source[pos]))
		++pos;
	// Matching step #6.
	if (pos == source.size() || source[pos] != '"')
		return MatchIncludeResult::MakeError("#include should be followed by quote", source, lineStart, pos);
	++pos;
	// Matching step #7.
	const size_t pathFirst = pos;
	while (pos < source.size() && source[pos] != '"' && source[pos] != '\n')
		++pos;
	const size_t pathLast = pos;
	// Matching step #8.
	if (pos == source.size() || source[pos] != '"')
		return MatchIncludeResult::MakeError("#include has invalid quote pair", source, lineStart, pos);
	if (pathLast - pathFirst <= 1)
		return MatchIncludeResult::MakeError("#include path shouldn't be empty", source, lineStart, pos);
	while (pos < source.size() && source[pos] != '\n')
		++pos;
	return MatchIncludeResult{true, false, pos < source.size() ? pos + 1 : source.size(), pathFirst, pathLast};
}

bool ResolveIncludesImpl(
	std::string_view currentPart,
	std::unordered_map<CStr, CStr>& includeCache, const CPreprocessorWrapper::IncludeRetrieverCallback& includeCallback,
	std::deque<std::string>& chunks, std::vector<std::string_view>& processedParts)
{
	static const CStr lineDirective = "#line ";
	for (size_t lineStart = 0, line = 1; lineStart < currentPart.size(); ++line)
	{
		MatchIncludeResult match = MatchIncludeUntilEOLorEOS(currentPart, lineStart);
		if (match.error)
			return {};
		else if (!match.found)
		{
			if (lineStart + lineDirective.size() < currentPart.size() &&
				currentPart.substr(lineStart, lineDirective.size()) == lineDirective)
			{
				size_t newLineNumber = 0;
				size_t pos = lineStart + lineDirective.size();
				while (pos < match.nextLineStart && std::isdigit(currentPart[pos]))
				{
					newLineNumber = newLineNumber * 10 + (currentPart[pos] - '0');
					++pos;
				}
				if (newLineNumber > 0)
					line = newLineNumber - 1;
			}

			lineStart = match.nextLineStart;
			continue;
		}
		const std::string path(currentPart.substr(match.pathFirst, match.pathLast - match.pathFirst));
		auto it = includeCache.find(path);
		if (it == includeCache.end())
		{
			CStr includeContent;
			if (!includeCallback(path, includeContent))
			{
				LOGERROR("Preprocessor error: line %zu: Can't load #include file: '%s'", line, path.c_str());
				return false;
			}
			it = includeCache.emplace(path, std::move(includeContent)).first;
		}
		// We need to insert #line directives to have correct line numbers in errors.
		chunks.emplace_back(lineDirective + "1\n" + it->second + "\n" + lineDirective + CStr::FromUInt(line + 1) + "\n");
		processedParts.emplace_back(currentPart.substr(0, lineStart));
		if (!ResolveIncludesImpl(chunks.back(), includeCache, includeCallback, chunks, processedParts))
			return false;
		currentPart = currentPart.substr(match.nextLineStart);
		lineStart = 0;
	}
	if (!currentPart.empty())
		processedParts.emplace_back(currentPart);
	return true;
}

} // anonymous namespace

void CPreprocessorWrapper::PyrogenesisShaderError(int iLine, const char* iError, const Ogre::CPreprocessor::Token* iToken)
{
	if (iToken)
		LOGERROR("Preprocessor error: line %d: %s: '%s'\n", iLine, iError, std::string(iToken->String, iToken->Length).c_str());
	else
		LOGERROR("Preprocessor error: line %d: %s\n", iLine, iError);
}

CPreprocessorWrapper::CPreprocessorWrapper()
	: CPreprocessorWrapper(IncludeRetrieverCallback{})
{
}

CPreprocessorWrapper::CPreprocessorWrapper(const IncludeRetrieverCallback& includeCallback)
	: m_IncludeCallback(includeCallback)
{
	Ogre::CPreprocessor::ErrorHandler = CPreprocessorWrapper::PyrogenesisShaderError;
}

void CPreprocessorWrapper::AddDefine(const char* name, const char* value)
{
	m_Preprocessor.Define(name, strlen(name), value, strlen(value));
}

void CPreprocessorWrapper::AddDefines(const CShaderDefines& defines)
{
	std::map<CStrIntern, CStrIntern> map = defines.GetMap();
	for (std::map<CStrIntern, CStrIntern>::const_iterator it = map.begin(); it != map.end(); ++it)
		m_Preprocessor.Define(it->first.c_str(), it->first.length(), it->second.c_str(), it->second.length());
}

bool CPreprocessorWrapper::TestConditional(const CStr& expr)
{
	// Construct a dummy program so we can trigger the preprocessor's expression
	// code without modifying its public API.
	// Be careful that the API buggily returns a statically allocated pointer
	// (which we will try to free()) if the input just causes it to append a single
	// sequence of newlines to the output; the "\n" after the "#endif" is enough
	// to avoid this case.
	CStr input = "#if ";
	input += expr;
	input += "\n1\n#endif\n";

	size_t len = 0;
	char* output = m_Preprocessor.Parse(input.c_str(), input.size(), len);

	if (!output)
	{
		LOGERROR("Failed to parse conditional expression '%s'", expr.c_str());
		return false;
	}

	bool ret = (memchr(output, '1', len) != NULL);

	// Free output if it's not inside the source string
	if (!(output >= input.c_str() && output < input.c_str() + input.size()))
		free(output);

	return ret;

}

CStr CPreprocessorWrapper::ResolveIncludes(const CStr& source)
{
	// Stores intermediate blocks of text to avoid additional copying. Should
	// be constructed before views and destroyed after (currently guaranteed
	// by stack).
	// Short String Optimisation can make views point to container-managed data,
	// so push_back must not invalidate pointers (std::deque guarantees that).
	std::deque<std::string> chunks;
	// After resolving the following vector should contain a complete list
	// to concatenate.
	std::vector<std::string_view> processedParts;
	if (!ResolveIncludesImpl(source, m_IncludeCache, m_IncludeCallback, chunks, processedParts))
		return {};
	std::size_t totalSize = 0;
	for (const std::string_view& part : processedParts)
		totalSize += part.size();
	std::string processedSource;
	processedSource.reserve(totalSize);
	for (const std::string_view& part : processedParts)
		processedSource.append(part);
	return processedSource;
}

CStr CPreprocessorWrapper::Preprocess(const CStr& input)
{
	PROFILE("Preprocess shader source");

	CStr source = ResolveIncludes(input);

	size_t len = 0;
	char* output = m_Preprocessor.Parse(source.c_str(), source.size(), len);

	if (!output)
	{
		LOGERROR("Shader preprocessing failed");
		return "";
	}

	CStr ret(output, len);

	// Free output if it's not inside the source string
	if (!(output >= source.c_str() && output < source.c_str() + source.size()))
		free(output);

	return ret;
}