Skip to content

Commit 40368cb

Browse files
committed
buildopt: a private fragment is a unit of its own after conditions; the purview is read as C++ tokens; private_fragment = conservative
1 parent d1fe871 commit 40368cb

3 files changed

Lines changed: 471 additions & 53 deletions

File tree

‎modules/buildopt/src/source.cppm‎

Lines changed: 262 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,34 @@
3131
//
3232
// WHAT MAKES A FRAGMENT NOT MOVABLE, AND IS THEREFORE LEFT AS WRITTEN. The
3333
// implementation unit sees what the interface declares in the module's
34-
// purview; it does not see what is local to the interface's translation unit.
35-
// Read from the text, with no semantic analysis, and refused when in doubt:
34+
// purview; it does not see what is local to the interface's translation unit,
35+
// nor what the preprocessor held there. Read from the text, with no semantic
36+
// analysis, and refused when in doubt:
3637
//
37-
// - a preprocessor directive in the purview before the fragment (a macro the
38-
// fragment may use; the global module fragment is copied, and is not this)
39-
// - an unnamed namespace, or `static` at namespace scope, before the fragment
38+
// - a directive in the purview before the fragment that changes what the
39+
// fragment means: `#define`, `#undef`, `#include`, `#pragma`, `#line`, and
40+
// any not named below. The conditionals (`#if`, `#ifdef`, `#ifndef`,
41+
// `#elif`, `#else`, `#endif`) and `#error`, `#warning` do not: a condition
42+
// only decides which declarations exist, and the implementation unit
43+
// receives them from the BMI. A condition that is open at the module
44+
// declaration or at the fragment is refused, since the units would not
45+
// close it. (The global module fragment is copied, and is not this.)
46+
// - a use of `_Pragma` or `__pragma` there
47+
// - an unnamed namespace, or `static` at namespace scope (a linkage
48+
// specification `extern "C" { ... }` is namespace scope), before the
49+
// fragment
4050
// - a using-directive at namespace scope before the fragment
51+
// - a line continuation (`\` before a newline) from the module declaration
52+
// to the fragment, where a physical line is not a logical one
4153
// - a module that is a partition, or no module declaration at all
4254
//
55+
// The text is read once as C++ tokens: comments, string and character
56+
// literals (raw strings included) are blanked, and a digit separator
57+
// (`1'000`) is part of a number, not the start of a literal. With
58+
// `private_fragment = "conservative"` any directive in that purview refuses,
59+
// which is the rule before the narrowed one and the one a compiler that
60+
// cannot build a fragment as written (GCC) is checked against.
61+
//
4362
// A fragment that passes these and still does not build as a unit names its
4463
// own lines in the compiler's error; `private_fragment = "as-written"` builds
4564
// the source as it is.
@@ -62,16 +81,18 @@ struct Units {
6281
// The units a source with a private module fragment is built as. nullopt: the
6382
// text has no private module fragment. An error: it has one that stays as
6483
// written, and why. `spelling` is the file's path as `#line` names it.
84+
// `conservative`: any directive in the purview before the fragment refuses,
85+
// as it did before the conditionals were let through.
6586
std::optional<std::expected<Units, std::string>>
66-
private_fragment(std::string_view text, std::string_view spelling);
87+
private_fragment(std::string_view text, std::string_view spelling, bool conservative = false);
6788

68-
// Whether this build builds private module fragments as units: the entry's
69-
// switch (`MCPP_PRIVATE_FRAGMENT`, then `[build] private_fragment`, then the
89+
// How this build builds private module fragments: the entry's switch
90+
// (`MCPP_PRIVATE_FRAGMENT`, then `[build] private_fragment`, then the
7091
// default, "unit"), under the statement that turns every entry off. A value
71-
// that is neither "unit" nor "as-written" is handed to `onInvalid` and the
72-
// default stands.
73-
bool private_fragment_as_unit(const mcpp::manifest::Manifest& m,
74-
const std::function<void(std::string_view)>& onInvalid = {});
92+
// that is none of the three is handed to `onInvalid` and the default stands.
93+
enum class Fragment { AsWritten, Unit, Conservative };
94+
Fragment private_fragment_policy(const mcpp::manifest::Manifest& m,
95+
const std::function<void(std::string_view)>& onInvalid = {});
7596

7697
} // namespace mcpp::buildopt::source
7798

@@ -85,11 +106,12 @@ std::string_view trim(std::string_view s) {
85106
return s;
86107
}
87108

109+
bool ident_char(char c) { return std::isalnum(static_cast<unsigned char>(c)) || c == '_'; }
110+
88111
bool word_at(std::string_view s, std::size_t at, std::string_view word) {
89-
auto ident = [](char c) { return std::isalnum(static_cast<unsigned char>(c)) || c == '_'; };
90112
if (s.substr(at, word.size()) != word) return false;
91-
if (at > 0 && ident(s[at - 1])) return false;
92-
return at + word.size() >= s.size() || !ident(s[at + word.size()]);
113+
if (at > 0 && ident_char(s[at - 1])) return false;
114+
return at + word.size() >= s.size() || !ident_char(s[at + word.size()]);
93115
}
94116

95117
bool has_word(std::string_view s, std::string_view word) {
@@ -98,28 +120,177 @@ bool has_word(std::string_view s, std::string_view word) {
98120
return false;
99121
}
100122

101-
// One line's code: comments removed, string and character literals blanked.
102-
// `inBlock` carries a block comment over lines.
103-
std::string code_of(std::string_view line, bool& inBlock) {
104-
std::string out;
105-
for (std::size_t i = 0; i < line.size(); ++i) {
106-
if (inBlock) {
107-
if (line.substr(i, 2) == "*/") { inBlock = false; ++i; }
108-
continue;
123+
// THE TEXT AS C++ TOKENS, to the length it has. Comments and the contents of
124+
// string and character literals are blanked (the newlines stay, so a line is a
125+
// line), and `joins` holds the offsets of a backslash that joins its line to
126+
// the next. Three things a reader by lines gets wrong are read here:
127+
//
128+
// 1'000 a digit separator is part of a number; taken for the start of
129+
// a character literal it hid the rest of the line, `;` and `{`
130+
// R"d(...)d" a raw string runs over lines and holds anything, `"` and
131+
// `module :private;` included
132+
// \<newline> a comment, a literal or a directive goes on to the next line
133+
struct Code {
134+
std::string text;
135+
std::vector<std::size_t> joins;
136+
};
137+
138+
// The newline at `at` is joined to the next line by a backslash before it.
139+
bool joined(std::string_view t, std::size_t at) {
140+
if (at > 0 && t[at - 1] == '\r') --at;
141+
return at > 0 && t[at - 1] == '\\';
142+
}
143+
144+
// The end of the logical line that holds `from`: its newline, or the text's end.
145+
std::size_t line_end(std::string_view t, std::size_t from, std::vector<std::size_t>& joins) {
146+
for (std::size_t j = from; j < t.size(); ++j) {
147+
if (t[j] != '\n') continue;
148+
if (!joined(t, j)) return j;
149+
joins.push_back(j);
150+
}
151+
return t.size();
152+
}
153+
154+
// A raw string opens at the quote at `at` when an `R` (with its encoding
155+
// prefix, if any) stands before it as a word of its own.
156+
bool raw_string_at(std::string_view t, std::size_t at) {
157+
if (at == 0 || t[at - 1] != 'R') return false;
158+
std::size_t from = at - 1;
159+
while (from > 0 && ident_char(t[from - 1])) --from;
160+
const auto prefix = t.substr(from, at - from);
161+
return prefix == "R" || prefix == "u8R" || prefix == "uR" || prefix == "UR" || prefix == "LR";
162+
}
163+
164+
// One past the end of the raw string opened at `at`; npos when it is not
165+
// well formed (no `(`, a delimiter of more than 16 characters or with a
166+
// character it may not have, no closing), and the compiler then says why.
167+
std::size_t raw_string_end(std::string_view t, std::size_t at) {
168+
const auto open = t.find('(', at + 1);
169+
if (open == std::string_view::npos || open - at - 1 > 16) return std::string_view::npos;
170+
const auto delimiter = t.substr(at + 1, open - at - 1);
171+
if (delimiter.find_first_of(" ()\\\t\r\n") != std::string_view::npos) return std::string_view::npos;
172+
const auto closing = std::format("){}\"", delimiter);
173+
const auto end = t.find(closing, open + 1);
174+
return end == std::string_view::npos ? end : end + closing.size();
175+
}
176+
177+
// One past the closing quote of the literal opened by the quote at `at`; where
178+
// a newline comes first the literal is not closed, and ends before it.
179+
std::size_t quoted_end(std::string_view t, std::size_t at, std::vector<std::size_t>& joins) {
180+
const char quote = t[at];
181+
for (std::size_t j = at + 1; j < t.size(); ++j) {
182+
if (t[j] == '\\') {
183+
std::size_t next = j + 1;
184+
if (next + 1 < t.size() && t[next] == '\r' && t[next + 1] == '\n') ++next;
185+
if (next < t.size() && t[next] == '\n') joins.push_back(j);
186+
j = next;
187+
} else if (t[j] == quote) {
188+
return j + 1;
189+
} else if (t[j] == '\n') {
190+
return j;
109191
}
110-
if (line.substr(i, 2) == "//") break;
111-
if (line.substr(i, 2) == "/*") { inBlock = true; ++i; continue; }
112-
if (line[i] == '"' || line[i] == '\'') {
113-
const char quote = line[i];
114-
out += quote;
115-
for (++i; i < line.size() && line[i] != quote; ++i)
116-
if (line[i] == '\\') ++i;
117-
out += quote;
192+
}
193+
return t.size();
194+
}
195+
196+
// One past the end of the pp-number that starts at `at`: identifier characters
197+
// and dots, a sign after an exponent, and a `'` before one more of them.
198+
std::size_t number_end(std::string_view t, std::size_t at) {
199+
std::size_t j = at;
200+
for (; j < t.size(); ++j) {
201+
const char c = t[j];
202+
const bool sign = (c == '+' || c == '-') && j > at && std::string_view("eEpP").contains(t[j - 1]);
203+
const bool separator = c == '\'' && j + 1 < t.size() && ident_char(t[j + 1]);
204+
if (!(ident_char(c) || c == '.' || sign || separator)) break;
205+
}
206+
return j;
207+
}
208+
209+
// The directives whose rest of the line is not tokens (`#include <a'b>`,
210+
// `#error don't`).
211+
bool text_directive(std::string_view word) {
212+
return word == "include" || word == "include_next" || word == "import" || word == "error" || word == "warning";
213+
}
214+
215+
Code read_code(std::string_view t) {
216+
Code r{std::string(t), {}};
217+
auto blank = [&](std::size_t from, std::size_t to) {
218+
for (; from < to && from < r.text.size(); ++from)
219+
if (r.text[from] != '\n' && r.text[from] != '\r') r.text[from] = ' ';
220+
};
221+
bool lineStart = true;
222+
for (std::size_t i = 0; i < t.size();) {
223+
const char c = t[i];
224+
if (c == '\n') { lineStart = true; ++i; continue; }
225+
if (c == ' ' || c == '\t' || c == '\r') { ++i; continue; }
226+
if (c == '\\') {
227+
std::size_t next = i + 1;
228+
if (next + 1 < t.size() && t[next] == '\r' && t[next + 1] == '\n') ++next;
229+
if (next < t.size() && t[next] == '\n') { r.joins.push_back(i); i = next + 1; continue; }
230+
}
231+
const bool atLineStart = std::exchange(lineStart, false);
232+
if (c == '#' && atLineStart) {
233+
std::size_t w = i + 1;
234+
while (w < t.size() && (t[w] == ' ' || t[w] == '\t')) ++w;
235+
std::size_t e = w;
236+
while (e < t.size() && ident_char(t[e])) ++e;
237+
if (text_directive(t.substr(w, e - w))) {
238+
const auto end = line_end(t, e, r.joins);
239+
blank(e, end);
240+
i = end;
241+
continue;
242+
}
243+
} else if (t.substr(i, 2) == "//") {
244+
const auto end = line_end(t, i, r.joins);
245+
blank(i, end);
246+
i = end;
247+
continue;
248+
} else if (t.substr(i, 2) == "/*") {
249+
const auto close = t.find("*/", i + 2);
250+
const auto end = close == std::string_view::npos ? t.size() : close + 2;
251+
blank(i, end);
252+
i = end;
253+
continue;
254+
} else if (c == '"' && raw_string_at(t, i) && raw_string_end(t, i) != std::string_view::npos) {
255+
const auto end = raw_string_end(t, i);
256+
blank(i + 1, end - 1);
257+
i = end;
258+
continue;
259+
} else if (c == '"' || c == '\'') {
260+
const auto end = quoted_end(t, i, r.joins);
261+
blank(i + 1, end > i + 1 && t[end - 1] == c ? end - 1 : end);
262+
i = end;
263+
continue;
264+
} else if ((std::isdigit(static_cast<unsigned char>(c))
265+
|| (c == '.' && i + 1 < t.size() && std::isdigit(static_cast<unsigned char>(t[i + 1]))))
266+
&& (i == 0 || !ident_char(t[i - 1]))) {
267+
i = number_end(t, i);
118268
continue;
119269
}
120-
out += line[i];
270+
++i;
121271
}
122-
return out;
272+
return r;
273+
}
274+
275+
// The word after the `#` of a directive line (empty for a line that is `#`
276+
// alone, and for one whose next token is not a word: `# 12 "file"`); nullopt
277+
// when the line is not a directive.
278+
std::optional<std::string_view> directive_of(std::string_view line) {
279+
line = trim(line);
280+
if (!line.starts_with('#')) return std::nullopt;
281+
line = trim(line.substr(1));
282+
std::size_t n = 0;
283+
while (n < line.size() && ident_char(line[n])) ++n;
284+
return n == 0 && !line.empty() ? std::string_view("?") : line.substr(0, n);
285+
}
286+
287+
// What a directive does to the fragment's meaning. The conditionals only
288+
// decide which declarations exist, and the implementation unit receives those
289+
// from the interface; `#error` and `#warning` are said where they stand.
290+
bool opens_condition(std::string_view w) { return w == "if" || w == "ifdef" || w == "ifndef"; }
291+
bool leaves_meaning(std::string_view w) {
292+
return w.empty() || opens_condition(w) || w == "endif" || w == "else" || w == "elif" || w == "elifdef"
293+
|| w == "elifndef" || w == "error" || w == "warning";
123294
}
124295

125296
std::string line_directive(std::size_t line, std::string_view spelling) {
@@ -131,22 +302,35 @@ std::string line_directive(std::size_t line, std::string_view spelling) {
131302
return std::format("#line {} \"{}\"\n", line, quoted);
132303
}
133304

305+
// The conditional directives open at line `to` (not counting it).
306+
int open_conditions(const std::vector<std::string>& code, std::size_t to) {
307+
int depth = 0;
308+
for (std::size_t i = 0; i < to; ++i) {
309+
const auto w = directive_of(code[i]);
310+
if (!w) continue;
311+
if (opens_condition(*w)) ++depth;
312+
else if (*w == "endif") --depth;
313+
}
314+
return depth;
315+
}
316+
134317
} // namespace
135318

136319
std::optional<std::expected<Units, std::string>>
137-
private_fragment(std::string_view text, std::string_view spelling) {
320+
private_fragment(std::string_view text, std::string_view spelling, bool conservative) {
138321
std::vector<std::string_view> lines;
322+
std::vector<std::size_t> starts;
139323
for (std::size_t at = 0; at <= text.size();) {
140324
const auto end = text.find('\n', at);
325+
starts.push_back(at);
141326
lines.push_back(text.substr(at, end == std::string_view::npos ? std::string_view::npos : end - at));
142327
if (end == std::string_view::npos) break;
143328
at = end + 1;
144329
}
145-
std::vector<std::string> code(lines.size());
146-
{
147-
bool inBlock = false;
148-
for (std::size_t i = 0; i < lines.size(); ++i) code[i] = code_of(lines[i], inBlock);
149-
}
330+
const auto scanned = read_code(text);
331+
std::vector<std::string> code;
332+
for (std::size_t i = 0; i < lines.size(); ++i)
333+
code.emplace_back(std::string_view(scanned.text).substr(starts[i], lines[i].size()));
150334
auto compact = [](std::string_view s) {
151335
std::string c;
152336
for (char ch : s)
@@ -176,15 +360,40 @@ private_fragment(std::string_view text, std::string_view spelling) {
176360
if (moduleName.find(':') != std::string::npos)
177361
return Result{std::unexpected("the unit is a partition")};
178362

363+
// Where a physical line is not a logical one, the lines below are not the
364+
// text the compiler reads.
365+
for (auto at : scanned.joins) {
366+
const auto line = static_cast<std::size_t>(std::ranges::upper_bound(starts, at) - starts.begin()) - 1;
367+
if (line >= *declared && line <= *fragment)
368+
return Result{std::unexpected(std::format(
369+
"line {}: a line continuation between the module declaration and the fragment", line + 1))};
370+
}
371+
// A condition that holds the declaration or the fragment is not closed by
372+
// the unit that ends before the one and begins at the other.
373+
if (!conservative) {
374+
if (open_conditions(code, *declared) != 0)
375+
return Result{std::unexpected(std::format(
376+
"line {}: a conditional directive is open at the module declaration", *declared + 1))};
377+
if (open_conditions(code, *fragment) != 0)
378+
return Result{std::unexpected(std::format(
379+
"line {}: a conditional directive is open at the fragment", *fragment + 1))};
380+
}
381+
179382
// The purview before the fragment: what is local to the interface's
180383
// translation unit, and so not seen by an implementation unit.
181384
std::vector<bool> scopes; // one a brace still open; true: a namespace's
182385
std::string statement; // the code since the last `;`, `{` or `}`
183386
for (std::size_t i = *declared + 1; i < *fragment; ++i) {
184387
const auto c = trim(code[i]);
185-
if (c.starts_with("#"))
388+
if (const auto word = directive_of(c)) {
389+
if (conservative || !leaves_meaning(*word))
390+
return Result{std::unexpected(std::format(
391+
"line {}: a preprocessor directive in the module's purview before the fragment", i + 1))};
392+
continue;
393+
}
394+
if (has_word(c, "_Pragma") || has_word(c, "__pragma"))
186395
return Result{std::unexpected(std::format(
187-
"line {}: a preprocessor directive in the module's purview before the fragment", i + 1))};
396+
"line {}: a pragma in the module's purview before the fragment", i + 1))};
188397
for (char ch : c) {
189398
if (ch == '{') {
190399
const bool ns = has_word(statement, "namespace") && statement.find('(') == std::string::npos;
@@ -200,7 +409,11 @@ private_fragment(std::string_view text, std::string_view spelling) {
200409
&& std::ranges::all_of(scopes, [](bool s) { return s; }))
201410
return Result{std::unexpected(std::format(
202411
"line {}: `static` at namespace scope before the fragment", i + 1))};
203-
scopes.push_back(ns);
412+
// `extern "C" {` holds declarations of the scope it stands in.
413+
const auto st = trim(statement);
414+
const bool linkage = st.starts_with("extern") && word_at(st, 0, "extern")
415+
&& trim(st.substr(6)).starts_with('"') && trim(st.substr(6)).ends_with('"');
416+
scopes.push_back(ns || linkage);
204417
statement.clear();
205418
} else if (ch == '}') {
206419
if (!scopes.empty()) scopes.pop_back();
@@ -245,16 +458,17 @@ private_fragment(std::string_view text, std::string_view spelling) {
245458
return Result{std::move(units)};
246459
}
247460

248-
bool private_fragment_as_unit(const mcpp::manifest::Manifest& m,
249-
const std::function<void(std::string_view)>& onInvalid) {
250-
if (registry::standard_only()) return false;
461+
Fragment private_fragment_policy(const mcpp::manifest::Manifest& m,
462+
const std::function<void(std::string_view)>& onInvalid) {
463+
if (registry::standard_only()) return Fragment::AsWritten;
251464
std::string v;
252465
if (auto e = mcpp::invocation::get("MCPP_PRIVATE_FRAGMENT")) v = *e;
253466
else v = m.buildConfig.privateFragment;
254-
if (v.empty() || v == "unit") return true;
255-
if (v == "as-written") return false;
467+
if (v.empty() || v == "unit") return Fragment::Unit;
468+
if (v == "conservative") return Fragment::Conservative;
469+
if (v == "as-written") return Fragment::AsWritten;
256470
if (onInvalid) onInvalid(v);
257-
return true;
471+
return Fragment::Unit;
258472
}
259473

260474
} // namespace mcpp::buildopt::source

0 commit comments

Comments
 (0)