Debian Codegraph @

tests/test_domains/test_domain_cpp.py

raw
1 """Tests the C++ Domain"""
2
3 from __future__ import annotations
4
5 import itertools
6 import re
7 import zlib
8 from typing import TYPE_CHECKING
9
10 import pytest
11
12 import sphinx.domains.cpp
13 from sphinx import addnodes
14 from sphinx.addnodes import (
15 desc,
16 desc_content,
17 desc_name,
18 desc_parameter,
19 desc_parameterlist,
20 desc_sig_name,
21 desc_sig_space,
22 desc_signature,
23 desc_signature_line,
24 pending_xref,
25 )
26 from sphinx.domains.cpp._ids import _id_prefix, _max_id
27 from sphinx.domains.cpp._parser import DefinitionParser
28 from sphinx.domains.cpp._symbol import Symbol
29 from sphinx.ext.intersphinx._load import load_mappings, validate_intersphinx_mapping
30 from sphinx.testing import restructuredtext
31 from sphinx.testing.util import assert_node
32 from sphinx.util.cfamily import DefinitionError, NoOldIdError
33 from sphinx.writers.text import STDINDENT
34
35 from tests.utils import extract_node
36
37 if TYPE_CHECKING:
38 from io import StringIO
39
40 from sphinx.domains.cpp._ast import ASTTemplateParamType
41
42
43 def parse(name, string):
44 class Config:
45 cpp_id_attributes = ['id_attr']
46 cpp_paren_attributes = ['paren_attr']
47
48 parser = DefinitionParser(string, location=None, config=Config())
49 parser.allowFallbackExpressionParsing = False
50 ast = parser.parse_declaration(name, name)
51 parser.assert_end()
52 # The scopedness would usually have been set by CPPEnumObject
53 if name == 'enum':
54 # simulate unscoped enum
55 ast.scoped = None # ty: ignore[unresolved-attribute]
56 return ast
57
58
59 def _check(name, input, id_dict, output, key, as_text_output):
60 if key is None:
61 key = name
62 key += ' '
63 if name in {'function', 'member'}:
64 input_actual = input
65 output_ast = output
66 output_as_text = output
67 else:
68 input_actual = input.format(key='')
69 output_ast = output.format(key='')
70 output_as_text = output.format(key=key)
71 if as_text_output is not None:
72 output_as_text = as_text_output
73
74 # first a simple check of the AST
75 ast = parse(name, input_actual)
76 res = str(ast)
77 if res != output_ast:
78 print()
79 print('Input: ', input)
80 print('Result: ', res)
81 print('Expected: ', output_ast)
82 raise DefinitionError
83 root_symbol = Symbol(None, None, None, None, None, None, None)
84 symbol = root_symbol.add_declaration(ast, docname='TestDoc', line=42)
85 parent_node = addnodes.desc()
86 signode = addnodes.desc_signature(input, '')
87 parent_node += signode
88 ast.describe_signature(signode, 'lastIsName', symbol, options={})
89 res_as_text = parent_node.astext()
90 if res_as_text != output_as_text:
91 print()
92 print('Input: ', input)
93 print('astext(): ', res_as_text)
94 print('Expected: ', output_as_text)
95 print('Node:', parent_node)
96 raise DefinitionError
97
98 id_expected = [None]
99 for i in range(1, _max_id + 1):
100 if i in id_dict:
101 id_expected.append(id_dict[i])
102 else:
103 id_expected.append(id_expected[i - 1])
104 id_actual = [None]
105 for i in range(1, _max_id + 1):
106 try:
107 id = ast.get_id(version=i)
108 assert id is not None
109 id_actual.append(id[len(_id_prefix[i]) :])
110 except NoOldIdError:
111 id_actual.append(None)
112
113 res = [True]
114 for i in range(1, _max_id + 1):
115 res.append(id_expected[i] == id_actual[i])
116
117 if not all(res):
118 print('input: %s' % input.rjust(20))
119 for i in range(1, _max_id + 1):
120 if res[i]:
121 continue
122 print('Error in id version %d.' % i)
123 print('result: %s' % id_actual[i])
124 print('expected: %s' % id_expected[i])
125 print(root_symbol.dump(0))
126 raise DefinitionError
127
128
129 def check(name, input, id_dict, output=None, key=None, as_text_output=None):
130 if output is None:
131 output = input
132 # First, check without semicolon
133 _check(name, input, id_dict, output, key, as_text_output)
134 # Second, check with semicolon
135 _check(
136 name,
137 input + ' ;',
138 id_dict,
139 output + ';',
140 key,
141 as_text_output + ';' if as_text_output is not None else None,
142 )
143
144
145 @pytest.mark.parametrize(
146 ('type_', 'id_v2'),
147 sphinx.domains.cpp._ids._id_fundamental_v2.items(),
148 )
149 def test_domain_cpp_ast_fundamental_types(type_, id_v2):
150 # see https://en.cppreference.com/w/cpp/language/types
151 def make_id_v1():
152 if type_ == 'decltype(auto)':
153 return None
154 id_ = type_.replace(' ', '-').replace('long', 'l')
155 if '__int' not in type_:
156 id_ = id_.replace('int', 'i')
157 id_ = id_.replace('bool', 'b').replace('char', 'c')
158 id_ = id_.replace('wc_t', 'wchar_t').replace('c16_t', 'char16_t')
159 id_ = id_.replace('c8_t', 'char8_t')
160 id_ = id_.replace('c32_t', 'char32_t')
161 return f'f__{id_}'
162
163 def make_id_v2():
164 id_ = id_v2
165 if type_ == 'std::nullptr_t':
166 id_ = 'NSt9nullptr_tE'
167 return f'1f{id_}'
168
169 id1 = make_id_v1()
170 id2 = make_id_v2()
171
172 input = f'void f({type_.replace(" ", " ")} arg)'
173 output = f'void f({type_} arg)'
174
175 check('function', input, {1: id1, 2: id2}, output=output)
176 if ' ' in type_:
177 # try permutations of all components
178 tcs = type_.split()
179 for p in itertools.permutations(tcs):
180 input = f'void f({" ".join(p)} arg)'
181 check('function', input, {1: id1, 2: id2})
182
183
184 def test_domain_cpp_ast_expressions() -> None:
185 def expr_check(expr, id, id4=None):
186 ids = 'IE1CIA%s_1aE'
187 # call .format() on the expr to unescape double curly braces
188 id_dict = {2: ids % expr.format(), 3: ids % id}
189 if id4 is not None:
190 id_dict[4] = ids % id4
191 check('class', 'template<> {key}C<a[%s]>' % expr, id_dict)
192
193 class Config:
194 cpp_id_attributes = ['id_attr']
195 cpp_paren_attributes = ['paren_attr']
196
197 parser = DefinitionParser(expr, location=None, config=Config())
198 parser.allowFallbackExpressionParsing = False
199 ast = parser.parse_expression()
200 res = str(ast)
201 if res != expr:
202 print()
203 print('Input: ', expr)
204 print('Result: ', res)
205 raise DefinitionError
206 display_string = ast.get_display_string()
207 if res != display_string:
208 # note: if the expression contains an anon name then this will trigger a falsely
209 print()
210 print('Input: ', expr)
211 print('Result: ', res)
212 print('Display: ', display_string)
213 raise DefinitionError
214
215 # primary
216 expr_check('nullptr', 'LDnE')
217 expr_check('true', 'L1E')
218 expr_check('false', 'L0E')
219 ints = [
220 '5',
221 '0',
222 '075',
223 '0x0123456789ABCDEF',
224 '0XF',
225 '0b1',
226 '0B1',
227 "0b0'1'0",
228 "00'1'2",
229 "0x0'1'2",
230 "1'2'3",
231 ]
232 unsigned_suffix = ['', 'u', 'U']
233 long_suffix = ['', 'l', 'L', 'll', 'LL']
234 for i in ints:
235 for u in unsigned_suffix:
236 for l in long_suffix:
237 expr = i + u + l
238 expr_check(expr, 'L' + expr.replace("'", '') + 'E')
239 expr = i + l + u
240 expr_check(expr, 'L' + expr.replace("'", '') + 'E')
241 decimal_floats = [
242 '5e42',
243 '5e+42',
244 '5e-42',
245 '5.',
246 '5.e42',
247 '5.e+42',
248 '5.e-42',
249 '.5',
250 '.5e42',
251 '.5e+42',
252 '.5e-42',
253 '5.0',
254 '5.0e42',
255 '5.0e+42',
256 '5.0e-42',
257 "1'2'3e7'8'9",
258 "1'2'3.e7'8'9",
259 ".4'5'6e7'8'9",
260 "1'2'3.4'5'6e7'8'9",
261 ]
262 hex_floats = [
263 'ApF',
264 'Ap+F',
265 'Ap-F',
266 'A.',
267 'A.pF',
268 'A.p+F',
269 'A.p-F',
270 '.A',
271 '.ApF',
272 '.Ap+F',
273 '.Ap-F',
274 'A.B',
275 'A.BpF',
276 'A.Bp+F',
277 'A.Bp-F',
278 "A'B'Cp1'2'3",
279 "A'B'C.p1'2'3",
280 ".D'E'Fp1'2'3",
281 "A'B'C.D'E'Fp1'2'3",
282 ]
283 for suffix in ('', 'f', 'F', 'l', 'L'):
284 for e in decimal_floats:
285 expr = e + suffix
286 expr_check(expr, 'L' + expr.replace("'", '') + 'E')
287 for e in hex_floats:
288 expr = '0x' + e + suffix
289 expr_check(expr, 'L' + expr.replace("'", '') + 'E')
290 expr_check('"abc\\"cba"', 'LA8_KcE') # string
291 expr_check('this', 'fpT')
292 # character literals
293 char_prefix_and_ids = [('', 'c'), ('u8', 'c'), ('u', 'Ds'), ('U', 'Di'), ('L', 'w')]
294 chars = [
295 ('a', '97'),
296 ('\\n', '10'),
297 ('\\012', '10'),
298 ('\\0', '0'),
299 ('\\x0a', '10'),
300 ('\\x0A', '10'),
301 ('\\u0a42', '2626'),
302 ('\\u0A42', '2626'),
303 ('\\U0001f34c', '127820'),
304 ('\\U0001F34C', '127820'),
305 ]
306 for p, t in char_prefix_and_ids:
307 for c, val in chars:
308 expr_check(f"{p}'{c}'", t + val)
309 # user-defined literals
310 for i in ints:
311 expr_check(i + '_udl', 'clL_Zli4_udlEL' + i.replace("'", '') + 'EE')
312 expr_check(i + 'uludl', 'clL_Zli5uludlEL' + i.replace("'", '') + 'EE')
313 for f in decimal_floats:
314 expr_check(f + '_udl', 'clL_Zli4_udlEL' + f.replace("'", '') + 'EE')
315 expr_check(f + 'fudl', 'clL_Zli4fudlEL' + f.replace("'", '') + 'EE')
316 for f in hex_floats:
317 expr_check('0x' + f + '_udl', 'clL_Zli4_udlEL0x' + f.replace("'", '') + 'EE')
318 for p, t in char_prefix_and_ids:
319 for c, val in chars:
320 expr_check(f"{p}'{c}'_udl", 'clL_Zli4_udlE' + t + val + 'E')
321 expr_check('"abc"_udl', 'clL_Zli4_udlELA3_KcEE')
322 # from https://github.com/sphinx-doc/sphinx/issues/7294
323 expr_check('6.62607015e-34q_J', 'clL_Zli3q_JEL6.62607015e-34EE')
324
325 # fold expressions, paren, name
326 expr_check('(... + Ns)', '(... + Ns)', id4='flpl2Ns')
327 expr_check('(Ns + ...)', '(Ns + ...)', id4='frpl2Ns')
328 expr_check('(Ns + ... + 0)', '(Ns + ... + 0)', id4='fLpl2NsL0E')
329 expr_check('(5)', 'L5E')
330 expr_check('C', '1C')
331 # postfix
332 expr_check('A(2)', 'cl1AL2EE')
333 expr_check('A[2]', 'ix1AL2E')
334 expr_check('a.b.c', 'dtdt1a1b1c')
335 expr_check('a->b->c', 'ptpt1a1b1c')
336 expr_check('i++', 'pp1i')
337 expr_check('i--', 'mm1i')
338 expr_check('dynamic_cast<T&>(i)++', 'ppdcR1T1i')
339 expr_check('static_cast<T&>(i)++', 'ppscR1T1i')
340 expr_check('reinterpret_cast<T&>(i)++', 'pprcR1T1i')
341 expr_check('const_cast<T&>(i)++', 'ppccR1T1i')
342 expr_check('typeid(T).name', 'dtti1T4name')
343 expr_check('typeid(a + b).name', 'dttepl1a1b4name')
344 # unary
345 expr_check('++5', 'pp_L5E')
346 expr_check('--5', 'mm_L5E')
347 expr_check('*5', 'deL5E')
348 expr_check('&5', 'adL5E')
349 expr_check('+5', 'psL5E')
350 expr_check('-5', 'ngL5E')
351 expr_check('!5', 'ntL5E')
352 expr_check('not 5', 'ntL5E')
353 expr_check('~5', 'coL5E')
354 expr_check('compl 5', 'coL5E')
355 expr_check('sizeof...(a)', 'sZ1a')
356 expr_check('sizeof(T)', 'st1T')
357 expr_check('sizeof -42', 'szngL42E')
358 expr_check('alignof(T)', 'at1T')
359 expr_check('noexcept(-42)', 'nxngL42E')
360 # new-expression
361 expr_check('new int', 'nw_iE')
362 expr_check('new volatile int', 'nw_ViE')
363 expr_check('new int[42]', 'nw_AL42E_iE')
364 expr_check('new int()', 'nw_ipiE')
365 expr_check('new int(5, 42)', 'nw_ipiL5EL42EE')
366 expr_check('::new int', 'nw_iE')
367 expr_check('new int{{}}', 'nw_iilE')
368 expr_check('new int{{5, 42}}', 'nw_iilL5EL42EE')
369 # delete-expression
370 expr_check('delete p', 'dl1p')
371 expr_check('delete [] p', 'da1p')
372 expr_check('::delete p', 'dl1p')
373 expr_check('::delete [] p', 'da1p')
374 # cast
375 expr_check('(int)2', 'cviL2E')
376 # binary op
377 expr_check('5 || 42', 'ooL5EL42E')
378 expr_check('5 or 42', 'ooL5EL42E')
379 expr_check('5 && 42', 'aaL5EL42E')
380 expr_check('5 and 42', 'aaL5EL42E')
381 expr_check('5 | 42', 'orL5EL42E')
382 expr_check('5 bitor 42', 'orL5EL42E')
383 expr_check('5 ^ 42', 'eoL5EL42E')
384 expr_check('5 xor 42', 'eoL5EL42E')
385 expr_check('5 & 42', 'anL5EL42E')
386 expr_check('5 bitand 42', 'anL5EL42E')
387 # ['==', '!=']
388 expr_check('5 == 42', 'eqL5EL42E')
389 expr_check('5 != 42', 'neL5EL42E')
390 expr_check('5 not_eq 42', 'neL5EL42E')
391 # ['<=', '>=', '<', '>', '<=>']
392 expr_check('5 <= 42', 'leL5EL42E')
393 expr_check('A <= 42', 'le1AL42E')
394 expr_check('5 >= 42', 'geL5EL42E')
395 expr_check('5 < 42', 'ltL5EL42E')
396 expr_check('A < 42', 'lt1AL42E')
397 expr_check('5 > 42', 'gtL5EL42E')
398 expr_check('A > 42', 'gt1AL42E')
399 expr_check('5 <=> 42', 'ssL5EL42E')
400 expr_check('A <=> 42', 'ss1AL42E')
401 # ['<<', '>>']
402 expr_check('5 << 42', 'lsL5EL42E')
403 expr_check('A << 42', 'ls1AL42E')
404 expr_check('5 >> 42', 'rsL5EL42E')
405 # ['+', '-']
406 expr_check('5 + 42', 'plL5EL42E')
407 expr_check('5 - 42', 'miL5EL42E')
408 # ['*', '/', '%']
409 expr_check('5 * 42', 'mlL5EL42E')
410 expr_check('5 / 42', 'dvL5EL42E')
411 expr_check('5 % 42', 'rmL5EL42E')
412 # ['.*', '->*']
413 expr_check('5 .* 42', 'dsL5EL42E')
414 expr_check('5 ->* 42', 'pmL5EL42E')
415 # conditional
416 expr_check('5 ? 7 : 3', 'quL5EL7EL3E')
417 # assignment
418 expr_check('a = 5', 'aS1aL5E')
419 expr_check('a *= 5', 'mL1aL5E')
420 expr_check('a /= 5', 'dV1aL5E')
421 expr_check('a %= 5', 'rM1aL5E')
422 expr_check('a += 5', 'pL1aL5E')
423 expr_check('a -= 5', 'mI1aL5E')
424 expr_check('a >>= 5', 'rS1aL5E')
425 expr_check('a <<= 5', 'lS1aL5E')
426 expr_check('a &= 5', 'aN1aL5E')
427 expr_check('a and_eq 5', 'aN1aL5E')
428 expr_check('a ^= 5', 'eO1aL5E')
429 expr_check('a xor_eq 5', 'eO1aL5E')
430 expr_check('a |= 5', 'oR1aL5E')
431 expr_check('a or_eq 5', 'oR1aL5E')
432 expr_check('a = {{1, 2, 3}}', 'aS1ailL1EL2EL3EE')
433 # complex assignment and conditional
434 expr_check('5 = 6 = 7', 'aSL5EaSL6EL7E')
435 expr_check('5 = 6 ? 7 = 8 : 3', 'aSL5EquL6EaSL7EL8EL3E')
436 # comma operator
437 expr_check('a, 5', 'cm1aL5E')
438
439 # Additional tests
440 # a < expression that starts with something that could be a template
441 expr_check('A < 42', 'lt1AL42E')
442 check(
443 'function',
444 'template<> void f(A<B, 2> &v)',
445 {2: 'IE1fR1AI1BX2EE', 3: 'IE1fR1AI1BXL2EEE', 4: 'IE1fvR1AI1BXL2EEE'},
446 )
447 expr_check('A<1>::value', 'N1AIXL1EEE5valueE')
448 check('class', 'template<int T = 42> {key}A', {2: 'I_iE1A'})
449 check('enumerator', '{key}A = std::numeric_limits<unsigned long>::max()', {2: '1A'})
450
451 expr_check('operator()()', 'clclE')
452 expr_check('operator()<int>()', 'clclIiEE')
453
454 # pack expansion
455 expr_check('a(b(c, 1 + d...)..., e(f..., g))', 'cl1aspcl1b1cspplL1E1dEcl1esp1f1gEE')
456
457
458 def test_domain_cpp_ast_type_definitions() -> None:
459 check('type', 'public bool b', {1: 'b', 2: '1b'}, '{key}bool b', key='typedef')
460 check('type', '{key}bool A::b', {1: 'A::b', 2: 'N1A1bE'}, key='typedef')
461 check('type', '{key}bool *b', {1: 'b', 2: '1b'}, key='typedef')
462 check('type', '{key}bool *const b', {1: 'b', 2: '1b'}, key='typedef')
463 check('type', '{key}bool *volatile const b', {1: 'b', 2: '1b'}, key='typedef')
464 check('type', '{key}bool *volatile const b', {1: 'b', 2: '1b'}, key='typedef')
465 check('type', '{key}bool *volatile const *b', {1: 'b', 2: '1b'}, key='typedef')
466 check('type', '{key}bool &b', {1: 'b', 2: '1b'}, key='typedef')
467 check('type', '{key}bool b[]', {1: 'b', 2: '1b'}, key='typedef')
468 check(
469 'type',
470 '{key}std::pair<int, int> coord',
471 {1: 'coord', 2: '5coord'},
472 key='typedef',
473 )
474 check('type', '{key}long long int foo', {1: 'foo', 2: '3foo'}, key='typedef')
475 check(
476 'type',
477 '{key}std::vector<std::pair<std::string, long long>> module::blah',
478 {1: 'module::blah', 2: 'N6module4blahE'},
479 key='typedef',
480 )
481 check('type', '{key}std::function<void()> F', {1: 'F', 2: '1F'}, key='typedef')
482 check('type', '{key}std::function<R(A1, A2)> F', {1: 'F', 2: '1F'}, key='typedef')
483 check(
484 'type', '{key}std::function<R(A1, A2, A3)> F', {1: 'F', 2: '1F'}, key='typedef'
485 )
486 check(
487 'type',
488 '{key}std::function<R(A1, A2, A3, As...)> F',
489 {1: 'F', 2: '1F'},
490 key='typedef',
491 )
492 check(
493 'type',
494 '{key}MyContainer::const_iterator',
495 {1: 'MyContainer::const_iterator', 2: 'N11MyContainer14const_iteratorE'},
496 )
497 check(
498 'type',
499 'public MyContainer::const_iterator',
500 {1: 'MyContainer::const_iterator', 2: 'N11MyContainer14const_iteratorE'},
501 output='{key}MyContainer::const_iterator',
502 )
503 # test decl specs on right
504 check('type', '{key}bool const b', {1: 'b', 2: '1b'}, key='typedef')
505 # test name in global scope
506 check('type', '{key}bool ::B::b', {1: 'B::b', 2: 'N1B1bE'}, key='typedef')
507
508 check('type', '{key}A = B', {2: '1A'}, key='using')
509 check('type', '{key}A = decltype(b)', {2: '1A'}, key='using')
510
511 # from https://github.com/breathe-doc/breathe/issues/267
512 # (named function parameters for function pointers
513 check(
514 'type',
515 '{key}void (*gpio_callback_t)(struct device *port, uint32_t pin)',
516 {1: 'gpio_callback_t', 2: '15gpio_callback_t'},
517 key='typedef',
518 )
519 check(
520 'type',
521 '{key}void (*f)(std::function<void(int i)> g)',
522 {1: 'f', 2: '1f'},
523 key='typedef',
524 )
525
526 check(
527 'type',
528 '{key}T = A::template B<int>::template C<double>',
529 {2: '1T'},
530 key='using',
531 )
532
533 check('type', '{key}T = Q<A::operator()>', {2: '1T'}, key='using')
534 check('type', '{key}T = Q<A::operator()<int>>', {2: '1T'}, key='using')
535 check('type', '{key}T = Q<A::operator bool>', {2: '1T'}, key='using')
536
537
538 def test_domain_cpp_ast_concept_definitions() -> None:
539 check(
540 'concept',
541 'template<typename Param> {key}A::B::Concept',
542 {2: 'I0EN1A1B7ConceptE'},
543 )
544 check(
545 'concept',
546 'template<typename A, typename B, typename ...C> {key}Foo',
547 {2: 'I00DpE3Foo'},
548 )
549 with pytest.raises(DefinitionError):
550 parse('concept', '{key}Foo')
551 with pytest.raises(DefinitionError):
552 parse('concept', 'template<typename T> template<typename U> {key}Foo')
553
554
555 def test_domain_cpp_ast_member_definitions() -> None:
556 check(
557 'member',
558 ' const std::string & name = 42',
559 {1: 'name__ssCR', 2: '4name'},
560 output='const std::string &name = 42',
561 )
562 check(
563 'member',
564 ' const std::string & name',
565 {1: 'name__ssCR', 2: '4name'},
566 output='const std::string &name',
567 )
568 check(
569 'member',
570 ' const std::string & name [ n ]',
571 {1: 'name__ssCRA', 2: '4name'},
572 output='const std::string &name[n]',
573 )
574 check(
575 'member',
576 'const std::vector< unsigned int, long> &name',
577 {1: 'name__std::vector:unsigned-i.l:CR', 2: '4name'},
578 output='const std::vector<unsigned int, long> &name',
579 )
580 check('member', 'module::myclass foo[n]', {1: 'foo__module::myclassA', 2: '3foo'})
581 check('member', 'int *const p', {1: 'p__iPC', 2: '1p'})
582 check('member', 'extern int myInt', {1: 'myInt__i', 2: '5myInt'})
583 check('member', 'thread_local int myInt', {1: 'myInt__i', 2: '5myInt'})
584 check('member', 'extern thread_local int myInt', {1: 'myInt__i', 2: '5myInt'})
585 check(
586 'member',
587 'thread_local extern int myInt',
588 {1: 'myInt__i', 2: '5myInt'},
589 'extern thread_local int myInt',
590 )
591
592 # tests based on https://en.cppreference.com/w/cpp/language/bit_field
593 check('member', 'int b : 3', {1: 'b__i', 2: '1b'})
594 check('member', 'int b : 8 = 42', {1: 'b__i', 2: '1b'})
595 check('member', 'int b : 8{42}', {1: 'b__i', 2: '1b'})
596 # TODO: enable once the ternary operator is supported
597 # check('member', 'int b : true ? 8 : a = 42', {1: 'b__i', 2: '1b'})
598 # TODO: enable once the ternary operator is supported
599 # check('member', 'int b : (true ? 8 : a) = 42', {1: 'b__i', 2: '1b'})
600 check('member', 'int b : 1 || new int{0}', {1: 'b__i', 2: '1b'})
601
602 check('member', 'inline int n', {1: 'n__i', 2: '1n'})
603 check('member', 'constinit int n', {1: 'n__i', 2: '1n'})
604
605
606 def test_domain_cpp_ast_function_definitions() -> None:
607 check('function', 'void f(volatile int)', {1: 'f__iV', 2: '1fVi'})
608 check('function', 'void f(std::size_t)', {1: 'f__std::s', 2: '1fNSt6size_tE'})
609 check('function', 'operator bool() const', {1: 'castto-b-operatorC', 2: 'NKcvbEv'})
610 check(
611 'function',
612 'A::operator bool() const',
613 {1: 'A::castto-b-operatorC', 2: 'NK1AcvbEv'},
614 )
615 check(
616 'function',
617 'A::operator bool() volatile const &',
618 {1: 'A::castto-b-operatorVCR', 2: 'NVKR1AcvbEv'},
619 )
620 check(
621 'function',
622 'A::operator bool() volatile const &&',
623 {1: 'A::castto-b-operatorVCO', 2: 'NVKO1AcvbEv'},
624 )
625 check(
626 'function',
627 'bool namespaced::theclass::method(arg1, arg2)',
628 {
629 1: 'namespaced::theclass::method__arg1.arg2',
630 2: 'N10namespaced8theclass6methodE4arg14arg2',
631 },
632 )
633 x = (
634 'std::vector<std::pair<std::string, int>> &module::test(register int '
635 'foo, bar, std::string baz = "foobar, blah, bleh") const = 0'
636 )
637 check(
638 'function',
639 x,
640 {1: 'module::test__i.bar.ssC', 2: 'NK6module4testEi3barNSt6stringE'},
641 )
642 check(
643 'function',
644 'void f(std::pair<A, B>)',
645 {1: 'f__std::pair:A.B:', 2: '1fNSt4pairI1A1BEE'},
646 )
647 check(
648 'function',
649 'explicit module::myclass::foo::foo()',
650 {1: 'module::myclass::foo::foo', 2: 'N6module7myclass3foo3fooEv'},
651 )
652 check(
653 'function',
654 'module::myclass::foo::~foo()',
655 {1: 'module::myclass::foo::~foo', 2: 'N6module7myclass3fooD0Ev'},
656 )
657 check(
658 'function',
659 'int printf(const char *fmt, ...)',
660 {1: 'printf__cCP.z', 2: '6printfPKcz'},
661 )
662 check(
663 'function',
664 'int foo(const unsigned int j)',
665 {1: 'foo__unsigned-iC', 2: '3fooKj'},
666 )
667 check('function', 'int foo(const int *const ptr)', {1: 'foo__iCPC', 2: '3fooPCKi'})
668 check(
669 'function',
670 'module::myclass::operator std::vector<std::string>()',
671 {
672 1: 'module::myclass::castto-std::vector:ss:-operator',
673 2: 'N6module7myclasscvNSt6vectorINSt6stringEEEEv',
674 },
675 )
676 check(
677 'function',
678 'void operator()(const boost::array<VertexID, 2> &v) const',
679 {
680 1: 'call-operator__boost::array:VertexID.2:CRC',
681 2: 'NKclERKN5boost5arrayI8VertexIDX2EEE',
682 3: 'NKclERKN5boost5arrayI8VertexIDXL2EEEE',
683 },
684 )
685 check(
686 'function',
687 'void operator()(const boost::array<VertexID, 2, "foo, bar"> &v) const',
688 {
689 1: 'call-operator__boost::array:VertexID.2."foo,--bar":CRC',
690 2: 'NKclERKN5boost5arrayI8VertexIDX2EX"foo, bar"EEE',
691 3: 'NKclERKN5boost5arrayI8VertexIDXL2EEXLA9_KcEEEE',
692 },
693 )
694 check(
695 'function',
696 'MyClass::MyClass(MyClass::MyClass&&)',
697 {
698 1: 'MyClass::MyClass__MyClass::MyClassRR',
699 2: 'N7MyClass7MyClassERRN7MyClass7MyClassE',
700 },
701 )
702 check('function', 'constexpr int get_value()', {1: 'get_valueCE', 2: '9get_valuev'})
703 check(
704 'function',
705 'static constexpr int get_value()',
706 {1: 'get_valueCE', 2: '9get_valuev'},
707 )
708 check(
709 'function',
710 'int get_value() const noexcept',
711 {1: 'get_valueC', 2: 'NK9get_valueEv'},
712 )
713 check(
714 'function',
715 'int get_value() const noexcept(std::is_nothrow_move_constructible<T>::value)',
716 {1: 'get_valueC', 2: 'NK9get_valueEv'},
717 )
718 check(
719 'function',
720 'int get_value() const noexcept("see below")',
721 {1: 'get_valueC', 2: 'NK9get_valueEv'},
722 )
723 check(
724 'function',
725 'int get_value() const noexcept = delete',
726 {1: 'get_valueC', 2: 'NK9get_valueEv'},
727 )
728 check(
729 'function',
730 'int get_value() volatile const',
731 {1: 'get_valueVC', 2: 'NVK9get_valueEv'},
732 )
733 check(
734 'function',
735 'MyClass::MyClass(MyClass::MyClass&&) = default',
736 {
737 1: 'MyClass::MyClass__MyClass::MyClassRR',
738 2: 'N7MyClass7MyClassERRN7MyClass7MyClassE',
739 },
740 )
741 check(
742 'function',
743 'virtual MyClass::a_virtual_function() const override',
744 {1: 'MyClass::a_virtual_functionC', 2: 'NK7MyClass18a_virtual_functionEv'},
745 )
746 check('function', 'A B() override', {1: 'B', 2: '1Bv'})
747 check('function', 'A B() final', {1: 'B', 2: '1Bv'})
748 check('function', 'A B() final override', {1: 'B', 2: '1Bv'})
749 check(
750 'function',
751 'A B() override final',
752 {1: 'B', 2: '1Bv'},
753 output='A B() final override',
754 )
755 check(
756 'function',
757 'MyClass::a_member_function() volatile',
758 {1: 'MyClass::a_member_functionV', 2: 'NV7MyClass17a_member_functionEv'},
759 )
760 check(
761 'function',
762 'MyClass::a_member_function() volatile const',
763 {1: 'MyClass::a_member_functionVC', 2: 'NVK7MyClass17a_member_functionEv'},
764 )
765 check(
766 'function',
767 'MyClass::a_member_function() &&',
768 {1: 'MyClass::a_member_functionO', 2: 'NO7MyClass17a_member_functionEv'},
769 )
770 check(
771 'function',
772 'MyClass::a_member_function() &',
773 {1: 'MyClass::a_member_functionR', 2: 'NR7MyClass17a_member_functionEv'},
774 )
775 check(
776 'function',
777 'MyClass::a_member_function() const &',
778 {1: 'MyClass::a_member_functionCR', 2: 'NKR7MyClass17a_member_functionEv'},
779 )
780 check(
781 'function',
782 'int main(int argc, char *argv[])',
783 {1: 'main__i.cPA', 2: '4mainiA_Pc'},
784 )
785 check(
786 'function',
787 'MyClass &MyClass::operator++()',
788 {1: 'MyClass::inc-operator', 2: 'N7MyClassppEv'},
789 )
790 check(
791 'function',
792 'MyClass::pointer MyClass::operator->()',
793 {1: 'MyClass::pointer-operator', 2: 'N7MyClassptEv'},
794 )
795
796 x = (
797 'std::vector<std::pair<std::string, int>> &module::test(register int '
798 'foo, bar[n], std::string baz = "foobar, blah, bleh") const = 0'
799 )
800 check(
801 'function',
802 x,
803 {
804 1: 'module::test__i.barA.ssC',
805 2: 'NK6module4testEiAn_3barNSt6stringE',
806 3: 'NK6module4testEiA1n_3barNSt6stringE',
807 },
808 )
809 check(
810 'function',
811 'int foo(Foo f = Foo(double(), std::make_pair(int(2), double(3.4))))',
812 {1: 'foo__Foo', 2: '3foo3Foo'},
813 )
814 check('function', 'int foo(A a = x(a))', {1: 'foo__A', 2: '3foo1A'})
815 with pytest.raises(DefinitionError):
816 parse('function', 'int foo(B b=x(a)')
817 with pytest.raises(DefinitionError):
818 parse('function', 'int foo)C c=x(a))')
819 with pytest.raises(DefinitionError):
820 parse('function', 'int foo(D d=x(a')
821 check('function', 'int foo(const A&... a)', {1: 'foo__ACRDp', 2: '3fooDpRK1A'})
822 check('function', 'int foo(const A&...)', {1: 'foo__ACRDp', 2: '3fooDpRK1A'})
823 check('function', 'int foo(const A*... a)', {1: 'foo__ACPDp', 2: '3fooDpPK1A'})
824 check('function', 'int foo(const A*...)', {1: 'foo__ACPDp', 2: '3fooDpPK1A'})
825 check('function', 'int foo(const int A::*... a)', {2: '3fooDpM1AKi'})
826 check('function', 'int foo(const int A::*...)', {2: '3fooDpM1AKi'})
827 # check('function', 'int foo(int (*a)(A)...)', {1: "foo__ACRDp", 2: "3fooDpPK1A"})
828 # check('function', 'int foo(int (*)(A)...)', {1: "foo__ACRDp", 2: "3fooDpPK1A"})
829 check('function', 'virtual void f()', {1: 'f', 2: '1fv'})
830 # test for ::nestedName, from issue 1738
831 check(
832 'function',
833 'result(int val, ::std::error_category const &cat)',
834 {1: 'result__i.std::error_categoryCR', 2: '6resultiRKNSt14error_categoryE'},
835 )
836 check('function', 'int *f()', {1: 'f', 2: '1fv'})
837 # tests derived from https://github.com/sphinx-doc/sphinx/issues/1753
838 # (skip to keep sanity)
839 check('function', 'f(int (&array)[10])', {2: '1fRA10_i', 3: '1fRAL10E_i'})
840 check('function', 'void f(int (&array)[10])', {2: '1fRA10_i', 3: '1fRAL10E_i'})
841 check('function', 'void f(float *q(double))', {2: '1fFPfdE'})
842 check('function', 'void f(float *(*q)(double))', {2: '1fPFPfdE'})
843 check('function', 'void f(float (*q)(double))', {2: '1fPFfdE'})
844 check('function', 'int (*f(double d))(float)', {1: 'f__double', 2: '1fd'})
845 check('function', 'int (*f(bool b))[5]', {1: 'f__b', 2: '1fb'})
846 check(
847 'function',
848 'int (*A::f(double d) const)(float)',
849 {1: 'A::f__doubleC', 2: 'NK1A1fEd'},
850 )
851 check(
852 'function',
853 'void f(std::shared_ptr<int(double)> ptr)',
854 {2: '1fNSt10shared_ptrIFidEEE'},
855 )
856 check('function', 'void f(int *const p)', {1: 'f__iPC', 2: '1fPCi'})
857 check('function', 'void f(int *volatile const p)', {1: 'f__iPVC', 2: '1fPVCi'})
858
859 check('function', 'extern int f()', {1: 'f', 2: '1fv'})
860 check('function', 'consteval int f()', {1: 'f', 2: '1fv'})
861
862 check('function', 'explicit(true) void f()', {1: 'f', 2: '1fv'})
863
864 check('function', 'decltype(auto) f()', {1: 'f', 2: '1fv'})
865
866 # TODO: make tests for functions in a template, e.g., Test<int&&()>
867 # such that the id generation for function type types is correct.
868
869 check(
870 'function',
871 'friend std::ostream &f(std::ostream &s, int i)',
872 {1: 'f__osR.i', 2: '1fRNSt7ostreamEi'},
873 )
874
875 # from https://github.com/breathe-doc/breathe/issues/223
876 check('function', 'void f(struct E e)', {1: 'f__E', 2: '1f1E'})
877 check('function', 'void f(class E e)', {1: 'f__E', 2: '1f1E'})
878 check('function', 'void f(typename E e)', {1: 'f__E', 2: '1f1E'})
879 check('function', 'void f(enum E e)', {1: 'f__E', 2: '1f1E'})
880 check('function', 'void f(union E e)', {1: 'f__E', 2: '1f1E'})
881
882 # pointer to member (function)
883 check('function', 'void f(int C::*)', {2: '1fM1Ci'})
884 check('function', 'void f(int C::* p)', {2: '1fM1Ci'})
885 check('function', 'void f(int ::C::* p)', {2: '1fM1Ci'})
886 check('function', 'void f(int C::*const)', {2: '1fKM1Ci'})
887 check('function', 'void f(int C::*const&)', {2: '1fRKM1Ci'})
888 check('function', 'void f(int C::*volatile)', {2: '1fVM1Ci'})
889 check(
890 'function',
891 'void f(int C::*const volatile)',
892 {2: '1fVKM1Ci'},
893 output='void f(int C::*volatile const)',
894 )
895 check('function', 'void f(int C::*volatile const)', {2: '1fVKM1Ci'})
896 check('function', 'void f(int (C::*)(float, double))', {2: '1fM1CFifdE'})
897 check('function', 'void f(int (C::* p)(float, double))', {2: '1fM1CFifdE'})
898 check('function', 'void f(int (::C::* p)(float, double))', {2: '1fM1CFifdE'})
899 check('function', 'void f(void (C::*)() const &)', {2: '1fM1CKRFvvE'})
900 check('function', 'int C::* f(int, double)', {2: '1fid'})
901 check('function', 'void f(int C::* *p)', {2: '1fPM1Ci'})
902 check('function', 'void f(int C::**)', {2: '1fPM1Ci'})
903 check('function', 'void f(int C::*const *p)', {2: '1fPKM1Ci'})
904 check('function', 'void f(int C::*const*)', {2: '1fPKM1Ci'})
905
906 # exceptions from return type mangling
907 check('function', 'template<typename T> C()', {2: 'I0E1Cv'})
908 check('function', 'template<typename T> operator int()', {2: 'I0Ecviv'})
909
910 # trailing return types
911 ids = {1: 'f', 2: '1fv'}
912 check('function', 'int f()', ids)
913 check('function', 'auto f() -> int', ids)
914 check('function', 'virtual auto f() -> int = 0', ids)
915 check('function', 'virtual auto f() -> int final', ids)
916 check('function', 'virtual auto f() -> int override', ids)
917
918 ids = {2: 'I0E1fv', 4: 'I0E1fiv'}
919 check('function', 'template<typename T> int f()', ids)
920 check('function', 'template<typename T> f() -> int', ids)
921
922 # from https://github.com/breathe-doc/breathe/issues/441
923 check(
924 'function',
925 'auto MakeThingy() -> Thingy*',
926 {1: 'MakeThingy', 2: '10MakeThingyv'},
927 )
928
929 # from https://github.com/sphinx-doc/sphinx/issues/8960
930 check('function', 'void f(void (*p)(int, double), int i)', {2: '1fPFvidEi'})
931
932 # from https://github.com/sphinx-doc/sphinx/issues/9535 comment
933 check('function', 'void f(void (*p)(int) = &foo)', {2: '1fPFviE'})
934
935
936 def test_domain_cpp_ast_operators() -> None:
937 check('function', 'void operator new()', {1: 'new-operator', 2: 'nwv'})
938 check('function', 'void operator new[]()', {1: 'new-array-operator', 2: 'nav'})
939 check('function', 'void operator delete()', {1: 'delete-operator', 2: 'dlv'})
940 check(
941 'function', 'void operator delete[]()', {1: 'delete-array-operator', 2: 'dav'}
942 )
943 check('function', 'operator bool() const', {1: 'castto-b-operatorC', 2: 'NKcvbEv'})
944 check('function', 'void operator""_udl()', {2: 'li4_udlv'})
945
946 check('function', 'void operator~()', {1: 'inv-operator', 2: 'cov'})
947 check('function', 'void operator compl()', {2: 'cov'})
948 check('function', 'void operator+()', {1: 'add-operator', 2: 'plv'})
949 check('function', 'void operator-()', {1: 'sub-operator', 2: 'miv'})
950 check('function', 'void operator*()', {1: 'mul-operator', 2: 'mlv'})
951 check('function', 'void operator/()', {1: 'div-operator', 2: 'dvv'})
952 check('function', 'void operator%()', {1: 'mod-operator', 2: 'rmv'})
953 check('function', 'void operator&()', {1: 'and-operator', 2: 'anv'})
954 check('function', 'void operator bitand()', {2: 'anv'})
955 check('function', 'void operator|()', {1: 'or-operator', 2: 'orv'})
956 check('function', 'void operator bitor()', {2: 'orv'})
957 check('function', 'void operator^()', {1: 'xor-operator', 2: 'eov'})
958 check('function', 'void operator xor()', {2: 'eov'})
959 check('function', 'void operator=()', {1: 'assign-operator', 2: 'aSv'})
960 check('function', 'void operator+=()', {1: 'add-assign-operator', 2: 'pLv'})
961 check('function', 'void operator-=()', {1: 'sub-assign-operator', 2: 'mIv'})
962 check('function', 'void operator*=()', {1: 'mul-assign-operator', 2: 'mLv'})
963 check('function', 'void operator/=()', {1: 'div-assign-operator', 2: 'dVv'})
964 check('function', 'void operator%=()', {1: 'mod-assign-operator', 2: 'rMv'})
965 check('function', 'void operator&=()', {1: 'and-assign-operator', 2: 'aNv'})
966 check('function', 'void operator and_eq()', {2: 'aNv'})
967 check('function', 'void operator|=()', {1: 'or-assign-operator', 2: 'oRv'})
968 check('function', 'void operator or_eq()', {2: 'oRv'})
969 check('function', 'void operator^=()', {1: 'xor-assign-operator', 2: 'eOv'})
970 check('function', 'void operator xor_eq()', {2: 'eOv'})
971 check('function', 'void operator<<()', {1: 'lshift-operator', 2: 'lsv'})
972 check('function', 'void operator>>()', {1: 'rshift-operator', 2: 'rsv'})
973 check('function', 'void operator<<=()', {1: 'lshift-assign-operator', 2: 'lSv'})
974 check('function', 'void operator>>=()', {1: 'rshift-assign-operator', 2: 'rSv'})
975 check('function', 'void operator==()', {1: 'eq-operator', 2: 'eqv'})
976 check('function', 'void operator!=()', {1: 'neq-operator', 2: 'nev'})
977 check('function', 'void operator not_eq()', {2: 'nev'})
978 check('function', 'void operator<()', {1: 'lt-operator', 2: 'ltv'})
979 check('function', 'void operator>()', {1: 'gt-operator', 2: 'gtv'})
980 check('function', 'void operator<=()', {1: 'lte-operator', 2: 'lev'})
981 check('function', 'void operator>=()', {1: 'gte-operator', 2: 'gev'})
982 check('function', 'void operator<=>()', {2: 'ssv'})
983 check('function', 'void operator!()', {1: 'not-operator', 2: 'ntv'})
984 check('function', 'void operator not()', {2: 'ntv'})
985 check('function', 'void operator&&()', {1: 'sand-operator', 2: 'aav'})
986 check('function', 'void operator and()', {2: 'aav'})
987 check('function', 'void operator||()', {1: 'sor-operator', 2: 'oov'})
988 check('function', 'void operator or()', {2: 'oov'})
989 check('function', 'void operator++()', {1: 'inc-operator', 2: 'ppv'})
990 check('function', 'void operator--()', {1: 'dec-operator', 2: 'mmv'})
991 check('function', 'void operator,()', {1: 'comma-operator', 2: 'cmv'})
992 check(
993 'function', 'void operator->*()', {1: 'pointer-by-pointer-operator', 2: 'pmv'}
994 )
995 check('function', 'void operator->()', {1: 'pointer-operator', 2: 'ptv'})
996 check('function', 'void operator()()', {1: 'call-operator', 2: 'clv'})
997 check('function', 'void operator[]()', {1: 'subscript-operator', 2: 'ixv'})
998
999
1000 def test_domain_cpp_ast_nested_name() -> None:
1001 check('class', '{key}::A', {1: 'A', 2: '1A'})
1002 check('class', '{key}::A::B', {1: 'A::B', 2: 'N1A1BE'})
1003 check('function', 'void f(::A a)', {1: 'f__A', 2: '1f1A'})
1004 check('function', 'void f(::A::B a)', {1: 'f__A::B', 2: '1fN1A1BE'})
1005
1006
1007 def test_domain_cpp_ast_class_definitions() -> None:
1008 check('class', 'public A', {1: 'A', 2: '1A'}, output='{key}A')
1009 check('class', 'private {key}A', {1: 'A', 2: '1A'})
1010 check('class', '{key}A final', {1: 'A', 2: '1A'})
1011
1012 # test bases
1013 check('class', '{key}A', {1: 'A', 2: '1A'})
1014 check('class', '{key}A::B::C', {1: 'A::B::C', 2: 'N1A1B1CE'})
1015 check('class', '{key}A : B', {1: 'A', 2: '1A'})
1016 check('class', '{key}A : private B', {1: 'A', 2: '1A'})
1017 check('class', '{key}A : public B', {1: 'A', 2: '1A'})
1018 check('class', '{key}A : B, C', {1: 'A', 2: '1A'})
1019 check('class', '{key}A : B, protected C, D', {1: 'A', 2: '1A'})
1020 check(
1021 'class',
1022 'A : virtual private B',
1023 {1: 'A', 2: '1A'},
1024 output='{key}A : private virtual B',
1025 )
1026 check('class', '{key}A : private virtual B', {1: 'A', 2: '1A'})
1027 check('class', '{key}A : B, virtual C', {1: 'A', 2: '1A'})
1028 check('class', '{key}A : public virtual B', {1: 'A', 2: '1A'})
1029 check('class', '{key}A : B, C...', {1: 'A', 2: '1A'})
1030 check('class', '{key}A : B..., C', {1: 'A', 2: '1A'})
1031
1032 # from https://github.com/sphinx-doc/sphinx/issues/4094
1033 check(
1034 'class',
1035 'template<class, class = std::void_t<>> {key}has_var',
1036 {2: 'I00E7has_var'},
1037 )
1038 check(
1039 'class',
1040 'template<class T> {key}has_var<T, std::void_t<decltype(&T::var)>>',
1041 {2: 'I0E7has_varI1TNSt6void_tIDTadN1T3varEEEEE'},
1042 )
1043
1044 check(
1045 'class',
1046 'template<typename ...Ts> {key}T<int (*)(Ts)...>',
1047 {2: 'IDpE1TIJPFi2TsEEE'},
1048 )
1049 check(
1050 'class',
1051 'template<int... Is> {key}T<(Is)...>',
1052 {2: 'I_DpiE1TIJX(Is)EEE', 3: 'I_DpiE1TIJX2IsEEE'},
1053 )
1054
1055
1056 def test_domain_cpp_ast_union_definitions() -> None:
1057 check('union', '{key}A', {2: '1A'})
1058
1059
1060 def test_domain_cpp_ast_enum_definitions() -> None:
1061 check('enum', '{key}A', {2: '1A'})
1062 check('enum', '{key}A : std::underlying_type<B>::type', {2: '1A'})
1063 check('enum', '{key}A : unsigned int', {2: '1A'})
1064 check('enum', 'public A', {2: '1A'}, output='{key}A')
1065 check('enum', 'private {key}A', {2: '1A'})
1066
1067 check('enumerator', '{key}A', {2: '1A'})
1068 check('enumerator', '{key}A = std::numeric_limits<unsigned long>::max()', {2: '1A'})
1069
1070
1071 def test_domain_cpp_ast_anon_definitions() -> None:
1072 check('class', '@a', {3: 'Ut1_a'}, as_text_output='class [anonymous]')
1073 check('union', '@a', {3: 'Ut1_a'}, as_text_output='union [anonymous]')
1074 check('enum', '@a', {3: 'Ut1_a'}, as_text_output='enum [anonymous]')
1075 check('class', '@1', {3: 'Ut1_1'}, as_text_output='class [anonymous]')
1076 check('class', '@a::A', {3: 'NUt1_a1AE'}, as_text_output='class [anonymous]::A')
1077
1078 check(
1079 'function',
1080 'int f(int @a)',
1081 {1: 'f__i', 2: '1fi'},
1082 as_text_output='int f(int [anonymous])',
1083 )
1084
1085
1086 def test_domain_cpp_ast_templates() -> None:
1087 check('class', 'A<T>', {2: 'IE1AI1TE'}, output='template<> {key}A<T>')
1088 # first just check which objects support templating
1089 check('class', 'template<> {key}A', {2: 'IE1A'})
1090 check('function', 'template<> void A()', {2: 'IE1Av', 4: 'IE1Avv'})
1091 check('member', 'template<> A a', {2: 'IE1a'})
1092 check('type', 'template<> {key}a = A', {2: 'IE1a'}, key='using')
1093 with pytest.raises(DefinitionError):
1094 parse('enum', 'template<> A')
1095 with pytest.raises(DefinitionError):
1096 parse('enumerator', 'template<> A')
1097 # then all the real tests
1098 check('class', 'template<typename T1, typename T2> {key}A', {2: 'I00E1A'})
1099 check('type', 'template<> {key}a', {2: 'IE1a'}, key='using')
1100
1101 check('class', 'template<typename T> {key}A', {2: 'I0E1A'})
1102 check('class', 'template<class T> {key}A', {2: 'I0E1A'})
1103 check('class', 'template<typename ...T> {key}A', {2: 'IDpE1A'})
1104 check('class', 'template<typename...> {key}A', {2: 'IDpE1A'})
1105 check('class', 'template<typename = Test> {key}A', {2: 'I0E1A'})
1106 check('class', 'template<typename T = Test> {key}A', {2: 'I0E1A'})
1107
1108 check('class', 'template<template<typename> typename T> {key}A', {2: 'II0E0E1A'})
1109 check('class', 'template<template<typename> class T> {key}A', {2: 'II0E0E1A'})
1110 check('class', 'template<template<typename> typename> {key}A', {2: 'II0E0E1A'})
1111 check(
1112 'class',
1113 'template<template<typename> typename ...T> {key}A',
1114 {2: 'II0EDpE1A'},
1115 )
1116 check('class', 'template<template<typename> typename...> {key}A', {2: 'II0EDpE1A'})
1117 check(
1118 'class',
1119 'template<typename T, template<typename> typename...> {key}A',
1120 {2: 'I0I0EDpE1A'},
1121 )
1122
1123 check('class', 'template<int> {key}A', {2: 'I_iE1A'})
1124 check('class', 'template<int T> {key}A', {2: 'I_iE1A'})
1125 check('class', 'template<int... T> {key}A', {2: 'I_DpiE1A'})
1126 check('class', 'template<int T = 42> {key}A', {2: 'I_iE1A'})
1127 check('class', 'template<int = 42> {key}A', {2: 'I_iE1A'})
1128
1129 check('class', 'template<typename A<B>::C> {key}A', {2: 'I_N1AI1BE1CEE1A'})
1130 check('class', 'template<typename A<B>::C = 42> {key}A', {2: 'I_N1AI1BE1CEE1A'})
1131 # from https://github.com/sphinx-doc/sphinx/issues/7944
1132 check(
1133 'function',
1134 'template<typename T, '
1135 'typename std::enable_if<!has_overloaded_addressof<T>::value, bool>::type = false'
1136 '> constexpr T *static_addressof(T &ref)',
1137 {
1138 2: 'I0_NSt9enable_ifIX!has_overloaded_addressof<T>::valueEbE4typeEE16static_addressofR1T',
1139 3: 'I0_NSt9enable_ifIXntN24has_overloaded_addressofI1TE5valueEEbE4typeEE16static_addressofR1T',
1140 4: 'I0_NSt9enable_ifIXntN24has_overloaded_addressofI1TE5valueEEbE4typeEE16static_addressofP1TR1T',
1141 },
1142 )
1143
1144 check('class', 'template<> {key}A<NS::B<>>', {2: 'IE1AIN2NS1BIEEE'})
1145
1146 # from https://github.com/sphinx-doc/sphinx/issues/2058
1147 check(
1148 'function',
1149 'template<typename Char, typename Traits> '
1150 'inline std::basic_ostream<Char, Traits> &operator<<('
1151 'std::basic_ostream<Char, Traits> &os, '
1152 'const c_string_view_base<const Char, Traits> &str)',
1153 {
1154 2: 'I00ElsRNSt13basic_ostreamI4Char6TraitsEE'
1155 'RK18c_string_view_baseIK4Char6TraitsE',
1156 4: 'I00Els'
1157 'RNSt13basic_ostreamI4Char6TraitsEE'
1158 'RNSt13basic_ostreamI4Char6TraitsEE'
1159 'RK18c_string_view_baseIK4Char6TraitsE',
1160 },
1161 )
1162
1163 # template introductions
1164 with pytest.raises(DefinitionError):
1165 parse('enum', 'abc::ns::foo{id_0, id_1, id_2} A')
1166 with pytest.raises(DefinitionError):
1167 parse('enumerator', 'abc::ns::foo{id_0, id_1, id_2} A')
1168 check(
1169 'class',
1170 'abc::ns::foo{{id_0, id_1, id_2}} {key}xyz::bar',
1171 {2: 'I000EXN3abc2ns3fooEI4id_04id_14id_2EEN3xyz3barE'},
1172 )
1173 check(
1174 'class',
1175 'abc::ns::foo{{id_0, id_1, ...id_2}} {key}xyz::bar',
1176 {2: 'I00DpEXN3abc2ns3fooEI4id_04id_1sp4id_2EEN3xyz3barE'},
1177 )
1178 check(
1179 'class',
1180 'abc::ns::foo{{id_0, id_1, id_2}} {key}xyz::bar<id_0, id_1, id_2>',
1181 {2: 'I000EXN3abc2ns3fooEI4id_04id_14id_2EEN3xyz3barE'},
1182 )
1183 check(
1184 'class',
1185 'abc::ns::foo{{id_0, id_1, ...id_2}} {key}xyz::bar<id_0, id_1, id_2...>',
1186 {2: 'I00DpEXN3abc2ns3fooEI4id_04id_1sp4id_2EEN3xyz3barE'},
1187 )
1188
1189 check(
1190 'class',
1191 'template<> Concept{{U}} {key}A<int>::B',
1192 {2: 'IEI0EX7ConceptI1UEEN1AIiE1BE'},
1193 )
1194
1195 check(
1196 'type',
1197 'abc::ns::foo{{id_0, id_1, id_2}} {key}xyz::bar = ghi::qux',
1198 {2: 'I000EXN3abc2ns3fooEI4id_04id_14id_2EEN3xyz3barE'},
1199 key='using',
1200 )
1201 check(
1202 'type',
1203 'abc::ns::foo{{id_0, id_1, ...id_2}} {key}xyz::bar = ghi::qux',
1204 {2: 'I00DpEXN3abc2ns3fooEI4id_04id_1sp4id_2EEN3xyz3barE'},
1205 key='using',
1206 )
1207 check(
1208 'function',
1209 'abc::ns::foo{id_0, id_1, id_2} void xyz::bar()',
1210 {
1211 2: 'I000EXN3abc2ns3fooEI4id_04id_14id_2EEN3xyz3barEv',
1212 4: 'I000EXN3abc2ns3fooEI4id_04id_14id_2EEN3xyz3barEvv',
1213 },
1214 )
1215 check(
1216 'function',
1217 'abc::ns::foo{id_0, id_1, ...id_2} void xyz::bar()',
1218 {
1219 2: 'I00DpEXN3abc2ns3fooEI4id_04id_1sp4id_2EEN3xyz3barEv',
1220 4: 'I00DpEXN3abc2ns3fooEI4id_04id_1sp4id_2EEN3xyz3barEvv',
1221 },
1222 )
1223 check(
1224 'member',
1225 'abc::ns::foo{id_0, id_1, id_2} ghi::qux xyz::bar',
1226 {2: 'I000EXN3abc2ns3fooEI4id_04id_14id_2EEN3xyz3barE'},
1227 )
1228 check(
1229 'member',
1230 'abc::ns::foo{id_0, id_1, ...id_2} ghi::qux xyz::bar',
1231 {2: 'I00DpEXN3abc2ns3fooEI4id_04id_1sp4id_2EEN3xyz3barE'},
1232 )
1233 check(
1234 'concept', 'Iterator{{T, U}} {key}Another', {2: 'I00EX8IteratorI1T1UEE7Another'}
1235 )
1236 check(
1237 'concept',
1238 'template<typename ...Pack> {key}Numerics = (... && Numeric<Pack>)',
1239 {2: 'IDpE8Numerics'},
1240 )
1241
1242 # explicit specializations of members
1243 check('member', 'template<> int A<int>::a', {2: 'IEN1AIiE1aE'})
1244 # same as above
1245 check(
1246 'member',
1247 'template int A<int>::a',
1248 {2: 'IEN1AIiE1aE'},
1249 output='template<> int A<int>::a',
1250 )
1251 check(
1252 'member',
1253 'template<> template<> int A<int>::B<int>::b',
1254 {2: 'IEIEN1AIiE1BIiE1bE'},
1255 )
1256 # same as above
1257 check(
1258 'member',
1259 'template int A<int>::B<int>::b',
1260 {2: 'IEIEN1AIiE1BIiE1bE'},
1261 output='template<> template<> int A<int>::B<int>::b',
1262 )
1263
1264 # defaulted constrained type parameters
1265 check('type', 'template<C T = int&> {key}A', {2: 'I_1CE1A'}, key='using')
1266
1267 # pack expansion after non-type template parameter
1268 check(
1269 'type',
1270 'template<int (X::*)(bool)...> {key}A',
1271 {2: 'I_DpM1XFibEE1A'},
1272 key='using',
1273 )
1274
1275
1276 def test_domain_cpp_ast_placeholder_types() -> None:
1277 check(
1278 'function', 'void f(Sortable auto &v)', {1: 'f__SortableR', 2: '1fR8Sortable'}
1279 )
1280 check(
1281 'function',
1282 'void f(const Sortable auto &v)',
1283 {1: 'f__SortableCR', 2: '1fRK8Sortable'},
1284 )
1285 check(
1286 'function',
1287 'void f(Sortable decltype(auto) &v)',
1288 {1: 'f__SortableR', 2: '1fR8Sortable'},
1289 )
1290 check(
1291 'function',
1292 'void f(const Sortable decltype(auto) &v)',
1293 {1: 'f__SortableCR', 2: '1fRK8Sortable'},
1294 )
1295 check(
1296 'function',
1297 'void f(Sortable decltype ( auto ) &v)',
1298 {1: 'f__SortableR', 2: '1fR8Sortable'},
1299 output='void f(Sortable decltype(auto) &v)',
1300 )
1301
1302
1303 def test_domain_cpp_ast_requires_clauses() -> None:
1304 check(
1305 'function',
1306 'template<typename T> requires A auto f() -> void requires B',
1307 {4: 'I0EIQaa1A1BE1fvv'},
1308 )
1309 check(
1310 'function',
1311 'template<typename T> requires A || B or C void f()',
1312 {4: 'I0EIQoo1Aoo1B1CE1fvv'},
1313 )
1314 check('function', 'void f() requires A || B || C', {4: 'IQoo1Aoo1B1CE1fv'})
1315 check('function', 'Foo() requires A || B || C', {4: 'IQoo1Aoo1B1CE3Foov'})
1316 check(
1317 'function',
1318 'template<typename T> requires A && B || C and D void f()',
1319 {4: 'I0EIQooaa1A1Baa1C1DE1fvv'},
1320 )
1321 check(
1322 'function',
1323 'template<typename T> requires R<T> '
1324 'template<typename U> requires S<T> '
1325 'void A<T>::f() requires B',
1326 {4: 'I0EIQ1RI1TEEI0EIQaa1SI1TE1BEN1A1fEvv'},
1327 )
1328 check(
1329 'function',
1330 'template<template<typename T> requires R<T> typename X> void f()',
1331 {2: 'II0EIQ1RI1TEE0E1fv', 4: 'II0EIQ1RI1TEE0E1fvv'},
1332 )
1333 check(
1334 'type',
1335 'template<typename T> requires IsValid<T> {key}T = true_type',
1336 {4: 'I0EIQ7IsValidI1TEE1T'},
1337 key='using',
1338 )
1339 check(
1340 'class',
1341 'template<typename T> requires IsValid<T> {key}T : Base',
1342 {4: 'I0EIQ7IsValidI1TEE1T'},
1343 key='class',
1344 )
1345 check(
1346 'union',
1347 'template<typename T> requires IsValid<T> {key}T',
1348 {4: 'I0EIQ7IsValidI1TEE1T'},
1349 key='union',
1350 )
1351 check(
1352 'member',
1353 'template<typename T> requires IsValid<T> int Val = 7',
1354 {4: 'I0EIQ7IsValidI1TEE3Val'},
1355 )
1356
1357
1358 def test_domain_cpp_ast_template_args() -> None:
1359 # from https://github.com/breathe-doc/breathe/issues/218
1360 check(
1361 'function',
1362 'template<typename F> void allow(F *f, typename func<F, B, G != 1>::type tt)',
1363 {
1364 2: 'I0E5allowP1FN4funcI1F1BXG != 1EE4typeE',
1365 3: 'I0E5allowP1FN4funcI1F1BXne1GL1EEE4typeE',
1366 4: 'I0E5allowvP1FN4funcI1F1BXne1GL1EEE4typeE',
1367 },
1368 )
1369 # from https://github.com/sphinx-doc/sphinx/issues/3542
1370 check(
1371 'type',
1372 'template<typename T> {key}'
1373 'enable_if_not_array_t = std::enable_if_t<!is_array<T>::value, int>',
1374 {2: 'I0E21enable_if_not_array_t'},
1375 key='using',
1376 )
1377
1378
1379 def test_domain_cpp_ast_initializers() -> None:
1380 ids_member = {1: 'v__T', 2: '1v'}
1381 ids_function = {1: 'f__T', 2: '1f1T'}
1382 ids_template = {2: 'I_1TE1fv', 4: 'I_1TE1fvv'}
1383 # no init
1384 check('member', 'T v', ids_member)
1385 check('function', 'void f(T v)', ids_function)
1386 check('function', 'template<T v> void f()', ids_template)
1387 # with '=', assignment-expression
1388 check('member', 'T v = 42', ids_member)
1389 check('function', 'void f(T v = 42)', ids_function)
1390 check('function', 'template<T v = 42> void f()', ids_template)
1391 # with '=', braced-init
1392 check('member', 'T v = {}', ids_member)
1393 check('function', 'void f(T v = {})', ids_function)
1394 check('function', 'template<T v = {}> void f()', ids_template)
1395 check('member', 'T v = {42, 42, 42}', ids_member)
1396 check('function', 'void f(T v = {42, 42, 42})', ids_function)
1397 check('function', 'template<T v = {42, 42, 42}> void f()', ids_template)
1398 check('member', 'T v = {42, 42, 42,}', ids_member)
1399 check('function', 'void f(T v = {42, 42, 42,})', ids_function)
1400 check('function', 'template<T v = {42, 42, 42,}> void f()', ids_template)
1401 check('member', 'T v = {42, 42, args...}', ids_member)
1402 check('function', 'void f(T v = {42, 42, args...})', ids_function)
1403 check('function', 'template<T v = {42, 42, args...}> void f()', ids_template)
1404 # without '=', braced-init
1405 check('member', 'T v{}', ids_member)
1406 check('member', 'T v{42, 42, 42}', ids_member)
1407 check('member', 'T v{42, 42, 42,}', ids_member)
1408 check('member', 'T v{42, 42, args...}', ids_member)
1409 # other
1410 check('member', 'T v = T{}', ids_member)
1411
1412
1413 def test_domain_cpp_ast_attributes() -> None:
1414 # style: C++
1415 check('member', '[[]] int f', {1: 'f__i', 2: '1f'})
1416 check(
1417 'member',
1418 '[ [ ] ] int f',
1419 {1: 'f__i', 2: '1f'},
1420 # this will fail when the proper grammar is implemented
1421 output='[[ ]] int f',
1422 )
1423 check('member', '[[a]] int f', {1: 'f__i', 2: '1f'})
1424 # style: GNU
1425 check('member', '__attribute__(()) int f', {1: 'f__i', 2: '1f'})
1426 check('member', '__attribute__((a)) int f', {1: 'f__i', 2: '1f'})
1427 check('member', '__attribute__((a, b)) int f', {1: 'f__i', 2: '1f'})
1428 check('member', '__attribute__((optimize(3))) int f', {1: 'f__i', 2: '1f'})
1429 check('member', '__attribute__((format(printf, 1, 2))) int f', {1: 'f__i', 2: '1f'})
1430 # style: user-defined id
1431 check('member', 'id_attr int f', {1: 'f__i', 2: '1f'})
1432 # style: user-defined paren
1433 check('member', 'paren_attr() int f', {1: 'f__i', 2: '1f'})
1434 check('member', 'paren_attr(a) int f', {1: 'f__i', 2: '1f'})
1435 check('member', 'paren_attr("") int f', {1: 'f__i', 2: '1f'})
1436 check('member', 'paren_attr(()[{}][]{}) int f', {1: 'f__i', 2: '1f'})
1437 with pytest.raises(DefinitionError):
1438 parse('member', 'paren_attr(() int f')
1439 with pytest.raises(DefinitionError):
1440 parse('member', 'paren_attr([) int f')
1441 with pytest.raises(DefinitionError):
1442 parse('member', 'paren_attr({) int f')
1443 with pytest.raises(DefinitionError):
1444 parse('member', 'paren_attr([)]) int f')
1445 with pytest.raises(DefinitionError):
1446 parse('member', 'paren_attr((])) int f')
1447 with pytest.raises(DefinitionError):
1448 parse('member', 'paren_attr({]}) int f')
1449
1450 # position: decl specs
1451 check(
1452 'function',
1453 'static inline __attribute__(()) void f()',
1454 {1: 'f', 2: '1fv'},
1455 output='__attribute__(()) static inline void f()',
1456 )
1457 check('function', '[[attr1]] [[attr2]] void f()', {1: 'f', 2: '1fv'})
1458 # position: declarator
1459 check('member', 'int *[[attr1]] [[attr2]] i', {1: 'i__iP', 2: '1i'})
1460 check(
1461 'member',
1462 'int *const [[attr1]] [[attr2]] volatile i',
1463 {1: 'i__iPVC', 2: '1i'},
1464 output='int *[[attr1]] [[attr2]] volatile const i',
1465 )
1466 check('member', 'int &[[attr1]] [[attr2]] i', {1: 'i__iR', 2: '1i'})
1467 check('member', 'int *[[attr1]] [[attr2]] *i', {1: 'i__iPP', 2: '1i'})
1468 # position: parameters and qualifiers
1469 check('function', 'void f() [[attr1]] [[attr2]]', {1: 'f', 2: '1fv'})
1470
1471 # position: class, union, enum
1472 check('class', '{key}[[attr1]] [[attr2]] Foo', {1: 'Foo', 2: '3Foo'}, key='class')
1473 check('union', '{key}[[attr1]] [[attr2]] Foo', {2: '3Foo'}, key='union')
1474 check('enum', '{key}[[attr1]] [[attr2]] Foo', {2: '3Foo'}, key='enum')
1475 # position: enumerator
1476 check('enumerator', '{key}Foo [[attr1]] [[attr2]]', {2: '3Foo'})
1477 check('enumerator', '{key}Foo [[attr1]] [[attr2]] = 42', {2: '3Foo'})
1478
1479
1480 def check_ast_xref_parsing(target):
1481 class Config:
1482 cpp_id_attributes = ['id_attr']
1483 cpp_paren_attributes = ['paren_attr']
1484
1485 parser = DefinitionParser(target, location='', config=Config())
1486 parser.parse_xref_object()
1487 parser.assert_end()
1488
1489
1490 def test_domain_cpp_ast_xref_parsing() -> None:
1491 check_ast_xref_parsing('f')
1492 check_ast_xref_parsing('f()')
1493 check_ast_xref_parsing('void f()')
1494 check_ast_xref_parsing('T f()')
1495
1496
1497 @pytest.mark.parametrize(
1498 ('param', 'is_pack'),
1499 [
1500 ('typename', False),
1501 ('typename T', False),
1502 ('typename...', True),
1503 ('typename... T', True),
1504 ('int', False),
1505 ('int N', False),
1506 ('int* N', False),
1507 ('int& N', False),
1508 ('int&... N', True),
1509 ('int*... N', True),
1510 ('int...', True),
1511 ('int... N', True),
1512 ('auto', False),
1513 ('auto...', True),
1514 ('int X::*', False),
1515 ('int X::*...', True),
1516 ('int (X::*)(bool)', False),
1517 ('int (X::*x)(bool)', False),
1518 ('int (X::*)(bool)...', True),
1519 ('template<typename> class', False),
1520 ('template<typename> class...', True),
1521 ],
1522 )
1523 def test_domain_cpp_template_parameters_is_pack(param: str, is_pack: bool) -> None:
1524 def parse_template_parameter(param: str) -> ASTTemplateParamType:
1525 ast = parse('type', 'template<' + param + '> X')
1526 return ast.templatePrefix.templates[0].params[0]
1527
1528 ast = parse_template_parameter(param)
1529 assert ast.isPack == is_pack
1530
1531
1532 # def test_print() -> None:
1533 # # used for getting all the ids out for checking
1534 # for a in ids:
1535 # print(a)
1536 # raise DefinitionError
1537
1538
1539 def filter_warnings(warning: StringIO, file: str) -> list[str]:
1540 lines = warning.getvalue().split('\n')
1541 res = [
1542 l
1543 for l in lines
1544 if 'domain-cpp' in l
1545 and f'{file}.rst' in l
1546 and "WARNING: document isn't included in any toctree" not in l
1547 ]
1548 print(f"Filtered warnings for file '{file}':")
1549 for w in res:
1550 print(w)
1551 return res
1552
1553
1554 @pytest.mark.sphinx('html', testroot='domain-cpp', confoverrides={'nitpicky': True})
1555 def test_domain_cpp_build_multi_decl_lookup(app):
1556 app.build(force_all=True)
1557 ws = filter_warnings(app.warning, 'lookup-key-overload')
1558 assert len(ws) == 0
1559
1560 ws = filter_warnings(app.warning, 'multi-decl-lookup')
1561 assert len(ws) == 0
1562
1563
1564 @pytest.mark.sphinx('html', testroot='domain-cpp', confoverrides={'nitpicky': True})
1565 def test_domain_cpp_build_warn_template_param_qualified_name(app):
1566 app.build(force_all=True)
1567 ws = filter_warnings(app.warning, 'warn-template-param-qualified-name')
1568 assert len(ws) == 2
1569 assert 'WARNING: cpp:type reference target not found: T::typeWarn' in ws[0]
1570 assert 'WARNING: cpp:type reference target not found: T::U::typeWarn' in ws[1]
1571
1572
1573 @pytest.mark.sphinx('html', testroot='domain-cpp', confoverrides={'nitpicky': True})
1574 def test_domain_cpp_build_backslash_ok_true(app):
1575 app.build(force_all=True)
1576 ws = filter_warnings(app.warning, 'backslash')
1577 assert len(ws) == 0
1578
1579
1580 @pytest.mark.sphinx('html', testroot='domain-cpp', confoverrides={'nitpicky': True})
1581 def test_domain_cpp_build_semicolon(app):
1582 app.build(force_all=True)
1583 ws = filter_warnings(app.warning, 'semicolon')
1584 assert len(ws) == 0
1585
1586
1587 @pytest.mark.sphinx(
1588 'html',
1589 testroot='domain-cpp',
1590 confoverrides={'nitpicky': True, 'strip_signature_backslash': True},
1591 )
1592 def test_domain_cpp_build_backslash_ok_false(app):
1593 app.build(force_all=True)
1594 ws = filter_warnings(app.warning, 'backslash')
1595 assert len(ws) == 1
1596 assert 'WARNING: Parsing of expression failed. Using fallback parser.' in ws[0]
1597
1598
1599 @pytest.mark.sphinx('html', testroot='domain-cpp', confoverrides={'nitpicky': True})
1600 def test_domain_cpp_build_anon_dup_decl(app):
1601 app.build(force_all=True)
1602 ws = filter_warnings(app.warning, 'anon-dup-decl')
1603 assert len(ws) == 2
1604 assert 'WARNING: cpp:identifier reference target not found: @a' in ws[0]
1605 assert 'WARNING: cpp:identifier reference target not found: @b' in ws[1]
1606
1607
1608 @pytest.mark.sphinx('html', testroot='domain-cpp')
1609 def test_domain_cpp_build_misuse_of_roles(app):
1610 app.build(force_all=True)
1611 ws = filter_warnings(app.warning, 'roles-targets-ok')
1612 assert len(ws) == 0
1613
1614 ws = filter_warnings(app.warning, 'roles-targets-warn')
1615 # the roles that should be able to generate warnings:
1616 all_roles = [
1617 'class',
1618 'struct',
1619 'union',
1620 'func',
1621 'member',
1622 'var',
1623 'type',
1624 'concept',
1625 'enum',
1626 'enumerator',
1627 ]
1628 ok = [ # target_type, ok_roles
1629 ('class', ['class', 'struct', 'type']),
1630 ('union', ['union', 'type']),
1631 ('func', ['func', 'type']),
1632 ('member', ['member', 'var']),
1633 ('type', ['type']),
1634 ('concept', ['concept']),
1635 ('enum', ['type', 'enum']),
1636 ('enumerator', ['enumerator']),
1637 ('functionParam', ['member', 'var']),
1638 ('templateParam', ['class', 'struct', 'union', 'member', 'var', 'type']),
1639 ]
1640 warn = []
1641 for target_type, roles in ok:
1642 txt_target_type = 'function' if target_type == 'func' else target_type
1643 for r in all_roles:
1644 if r not in roles:
1645 warn.append(f'WARNING: cpp:{r} targets a {txt_target_type} (')
1646 if target_type == 'templateParam':
1647 warn.extend((
1648 f'WARNING: cpp:{r} targets a {txt_target_type} (',
1649 f'WARNING: cpp:{r} targets a {txt_target_type} (',
1650 ))
1651 warn = sorted(warn)
1652 for w in ws:
1653 assert 'targets a' in w
1654 ws = [w[w.index('WARNING:') :] for w in ws]
1655 ws = sorted(ws)
1656 print('Expected warnings:')
1657 for w in warn:
1658 print(w)
1659 print('Actual warnings:')
1660 for w in ws:
1661 print(w)
1662
1663 for i in range(min(len(warn), len(ws))):
1664 assert ws[i].startswith(warn[i])
1665
1666 assert len(ws) == len(warn)
1667
1668
1669 @pytest.mark.sphinx(
1670 'html',
1671 testroot='domain-cpp',
1672 confoverrides={'add_function_parentheses': True},
1673 )
1674 def test_domain_cpp_build_with_add_function_parentheses_is_True(app):
1675 app.build(force_all=True)
1676
1677 role_patterns = [
1678 'Sphinx',
1679 'Sphinx::version',
1680 'version',
1681 'List',
1682 'MyEnum',
1683 ]
1684 paren_patterns = [
1685 ('ref function without parens ', r'paren_1\(\)'),
1686 ('ref function with parens ', r'paren_2\(\)'),
1687 ('ref function without parens, explicit title ', 'paren_3_title'),
1688 ('ref function with parens, explicit title ', 'paren_4_title'),
1689 ('ref op call without parens ', r'paren_5::operator\(\)\(\)'),
1690 ('ref op call with parens ', r'paren_6::operator\(\)\(\)'),
1691 ('ref op call without parens, explicit title ', 'paren_7_title'),
1692 ('ref op call with parens, explicit title ', 'paren_8_title'),
1693 ]
1694
1695 text = (app.outdir / 'roles.html').read_text(encoding='utf8')
1696 for ref_text in role_patterns:
1697 pattern = (
1698 f'<li><p><a .*?><code .*?><span .*?>{ref_text}</span></code></a></p></li>'
1699 )
1700 match = re.search(pattern, text)
1701 assert match is not None, f'Pattern not found in roles.html:\n\t{pattern}'
1702 for desc_text, ref_text in paren_patterns:
1703 pattern = f'<li><p>{desc_text}<a .*?><code .*?><span .*?>{ref_text}</span></code></a></p></li>'
1704 match = re.search(pattern, text)
1705 assert match is not None, f'Pattern not found in roles.html:\n\t{pattern}'
1706
1707 text = (app.outdir / 'any-role.html').read_text(encoding='utf8')
1708 for desc_text, ref_text in paren_patterns:
1709 pattern = f'<li><p>{desc_text}<a .*?><code .*?><span .*?>{ref_text}</span></code></a></p></li>'
1710 match = re.search(pattern, text)
1711 assert match is not None, f'Pattern not found in any-role.html:\n\t{pattern}'
1712
1713
1714 @pytest.mark.sphinx(
1715 'html',
1716 testroot='domain-cpp',
1717 confoverrides={'add_function_parentheses': False},
1718 )
1719 def test_domain_cpp_build_with_add_function_parentheses_is_False(app):
1720 app.build(force_all=True)
1721
1722 role_patterns = [
1723 'Sphinx',
1724 'Sphinx::version',
1725 'version',
1726 'List',
1727 'MyEnum',
1728 ]
1729 paren_patterns = [
1730 ('ref function without parens ', 'paren_1'),
1731 ('ref function with parens ', 'paren_2'),
1732 ('ref function without parens, explicit title ', 'paren_3_title'),
1733 ('ref function with parens, explicit title ', 'paren_4_title'),
1734 ('ref op call without parens ', r'paren_5::operator\(\)'),
1735 ('ref op call with parens ', r'paren_6::operator\(\)'),
1736 ('ref op call without parens, explicit title ', 'paren_7_title'),
1737 ('ref op call with parens, explicit title ', 'paren_8_title'),
1738 ]
1739
1740 text = (app.outdir / 'roles.html').read_text(encoding='utf8')
1741 for ref_text in role_patterns:
1742 pattern = (
1743 f'<li><p><a .*?><code .*?><span .*?>{ref_text}</span></code></a></p></li>'
1744 )
1745 match = re.search(pattern, text)
1746 assert match is not None, f'Pattern not found in roles.html:\n\t{pattern}'
1747 for desc_text, ref_text in paren_patterns:
1748 pattern = f'<li><p>{desc_text}<a .*?><code .*?><span .*?>{ref_text}</span></code></a></p></li>'
1749 match = re.search(pattern, text)
1750 assert match is not None, f'Pattern not found in roles.html:\n\t{pattern}'
1751
1752 text = (app.outdir / 'any-role.html').read_text(encoding='utf8')
1753 for desc_text, ref_text in paren_patterns:
1754 pattern = f'<li><p>{desc_text}<a .*?><code .*?><span .*?>{ref_text}</span></code></a></p></li>'
1755 match = re.search(pattern, text)
1756 assert match is not None, f'Pattern not found in any-role.html:\n\t{pattern}'
1757
1758
1759 @pytest.mark.sphinx('html', testroot='domain-cpp')
1760 def test_domain_cpp_build_xref_consistency(app):
1761 app.build(force_all=True)
1762
1763 test = 'xref_consistency.html'
1764 output = (app.outdir / test).read_text(encoding='utf8')
1765
1766 def classes(role, tag):
1767 pattern = (
1768 rf'{role}-role:.*?'
1769 rf'<(?P<tag>{tag}) .*?class=["\'](?P<classes>.*?)["\'].*?>'
1770 r'.*'
1771 r'</(?P=tag)>'
1772 )
1773 result = re.search(pattern, output)
1774 expect = f"""\
1775 Pattern for role `{role}` with tag `{tag}`
1776 \t{pattern}
1777 not found in `{test}`
1778 """
1779 assert result, expect
1780 return set(result.group('classes').split())
1781
1782 class RoleClasses:
1783 """Collect the classes from the layout that was generated for a given role."""
1784
1785 def __init__(self, role, root, contents):
1786 self.name = role
1787 self.classes = classes(role, root)
1788 self.content_classes = {}
1789 for tag in contents:
1790 self.content_classes[tag] = classes(role, tag)
1791
1792 # not actually used as a reference point
1793 # code_role = RoleClasses('code', 'code', [])
1794 any_role = RoleClasses('any', 'a', ['code'])
1795 cpp_any_role = RoleClasses('cpp-any', 'a', ['code'])
1796 # NYI: consistent looks
1797 # texpr_role = RoleClasses('cpp-texpr', 'span', ['a', 'code'])
1798 expr_role = RoleClasses('cpp-expr', 'span', ['a'])
1799 texpr_role = RoleClasses('cpp-texpr', 'span', ['a', 'span'])
1800
1801 # XRefRole-style classes
1802
1803 # any and cpp:any do not put these classes at the root
1804
1805 # n.b. the generic any machinery finds the specific 'cpp-class' object type
1806 any_role_classes = any_role.content_classes['code']
1807 expect = 'any uses XRefRole classes'
1808 assert {'xref', 'any', 'cpp', 'cpp-class'} <= any_role_classes, expect
1809
1810 cpp_any_role_classes = cpp_any_role.content_classes['code']
1811 expect = 'cpp:any uses XRefRole classes'
1812 assert {'xref', 'cpp-any', 'cpp'} <= cpp_any_role_classes, expect
1813
1814 for role in (expr_role, texpr_role):
1815 name = role.name
1816 expect = f'`{name}` puts the domain and role classes at its root'
1817 assert {'sig', 'sig-inline', 'cpp', name} <= role.classes, expect
1818
1819 # reference classes
1820
1821 expect = 'the xref roles use the same reference classes'
1822 assert any_role.classes == cpp_any_role.classes, expect
1823 assert any_role.classes == expr_role.content_classes['a'], expect
1824 assert any_role.classes == texpr_role.content_classes['a'], expect
1825
1826
1827 @pytest.mark.sphinx('html', testroot='domain-cpp', confoverrides={'nitpicky': True})
1828 def test_domain_cpp_build_field_role(app):
1829 app.build(force_all=True)
1830 ws = filter_warnings(app.warning, 'field-role')
1831 assert len(ws) == 0
1832
1833
1834 @pytest.mark.sphinx('html', testroot='domain-cpp', confoverrides={'nitpicky': True})
1835 def test_domain_cpp_build_operator_lookup(app):
1836 app.build(force_all=True)
1837 ws = filter_warnings(app.warning, 'operator-lookup')
1838 assert len(ws) == 5
1839 # TODO: the first one should not happen
1840 assert ':10: WARNING: cpp:identifier reference target not found: _lit' in ws[0]
1841 assert ':18: WARNING: cpp:func reference target not found: int h' in ws[1]
1842 assert (
1843 ':19: WARNING: cpp:func reference target not found: int operator+(bool, bool)'
1844 ) in ws[2]
1845 assert (
1846 ':20: WARNING: cpp:func reference target not found: int operator""_udl'
1847 ) in ws[3]
1848 assert ':21: WARNING: cpp:func reference target not found: operator bool' in ws[4]
1849
1850
1851 @pytest.mark.sphinx(
1852 'html', testroot='domain-cpp-intersphinx', confoverrides={'nitpicky': True}
1853 )
1854 def test_domain_cpp_build_intersphinx(tmp_path, app):
1855 orig_source = """\
1856 .. cpp:class:: _class
1857 .. cpp:struct:: _struct
1858 .. cpp:union:: _union
1859 .. cpp:function:: void _function()
1860 .. cpp:member:: int _member
1861 .. cpp:var:: int _var
1862 .. cpp:type:: _type
1863 .. cpp:concept:: template<typename T> _concept
1864 .. cpp:enum:: _enum
1865
1866 .. cpp:enumerator:: _enumerator
1867
1868 .. cpp:enum-struct:: _enumStruct
1869
1870 .. cpp:enumerator:: _scopedEnumerator
1871
1872 .. cpp:enum-class:: _enumClass
1873 .. cpp:function:: void _functionParam(int param)
1874 .. cpp:function:: template<typename TParam> void _templateParam()
1875 """
1876 inv_file = tmp_path / 'inventory'
1877 inv_file.write_bytes(
1878 b"""\
1879 # Sphinx inventory version 2
1880 # Project: C Intersphinx Test
1881 # Version:
1882 # The remainder of this file is compressed using zlib.
1883 """
1884 + zlib.compress(b"""\
1885 _class cpp:class 1 index.html#_CPPv46$ -
1886 _concept cpp:concept 1 index.html#_CPPv4I0E8$ -
1887 _concept::T cpp:templateParam 1 index.html#_CPPv4I0E8_concept -
1888 _enum cpp:enum 1 index.html#_CPPv45$ -
1889 _enum::_enumerator cpp:enumerator 1 index.html#_CPPv4N5_enum11_enumeratorE -
1890 _enumClass cpp:enum 1 index.html#_CPPv410$ -
1891 _enumStruct cpp:enum 1 index.html#_CPPv411$ -
1892 _enumStruct::_scopedEnumerator cpp:enumerator 1 index.html#_CPPv4N11_enumStruct17_scopedEnumeratorE -
1893 _enumerator cpp:enumerator 1 index.html#_CPPv4N5_enum11_enumeratorE -
1894 _function cpp:function 1 index.html#_CPPv49_functionv -
1895 _functionParam cpp:function 1 index.html#_CPPv414_functionParami -
1896 _functionParam::param cpp:functionParam 1 index.html#_CPPv414_functionParami -
1897 _member cpp:member 1 index.html#_CPPv47$ -
1898 _struct cpp:class 1 index.html#_CPPv47$ -
1899 _templateParam cpp:function 1 index.html#_CPPv4I0E14_templateParamvv -
1900 _templateParam::TParam cpp:templateParam 1 index.html#_CPPv4I0E14_templateParamvv -
1901 _type cpp:type 1 index.html#_CPPv45$ -
1902 _union cpp:union 1 index.html#_CPPv46$ -
1903 _var cpp:member 1 index.html#_CPPv44$ -
1904 """)
1905 )
1906 app.config.intersphinx_mapping = {
1907 'test': ('https://localhost/intersphinx/cpp/', str(inv_file)),
1908 }
1909 app.config.intersphinx_cache_limit = 0
1910 # load the inventory and check if it's done correctly
1911 validate_intersphinx_mapping(app, app.config)
1912 load_mappings(app)
1913
1914 app.build(force_all=True)
1915 ws = filter_warnings(app.warning, 'index')
1916 assert len(ws) == 0
1917
1918
1919 @pytest.mark.sphinx('html', testroot='_blank')
1920 def test_domain_cpp_parse_no_index_entry(app):
1921 text = (
1922 '.. cpp:function:: void f()\n.. cpp:function:: void g()\n :no-index-entry:\n'
1923 )
1924 doctree = restructuredtext.parse(app, text)
1925 assert_node(doctree, (addnodes.index, desc, addnodes.index, desc))
1926 assert_node(
1927 doctree[0],
1928 addnodes.index,
1929 entries=[('single', 'f (C++ function)', '_CPPv41fv', '', None)],
1930 )
1931 assert_node(doctree[2], addnodes.index, entries=[])
1932
1933
1934 @pytest.mark.sphinx('html', testroot='_blank')
1935 def test_domain_cpp_parse_mix_decl_duplicate(app):
1936 # Issue 8270
1937 text = '.. cpp:struct:: A\n.. cpp:function:: void A()\n.. cpp:struct:: A\n'
1938 restructuredtext.parse(app, text)
1939 ws = app.warning.getvalue().split('\n')
1940 assert len(ws) == 5
1941 assert (
1942 'index.rst:2: WARNING: Duplicate C++ declaration, also defined at index:1.'
1943 ) in ws[0]
1944 assert "Declaration is '.. cpp:function:: void A()'." in ws[1]
1945 assert (
1946 'index.rst:3: WARNING: Duplicate C++ declaration, also defined at index:1.'
1947 ) in ws[2]
1948 assert "Declaration is '.. cpp:struct:: A'." in ws[3]
1949 assert ws[4] == ''
1950
1951
1952 # For some reason, using the default testroot of "root" leads to the contents of
1953 # `test-root/objects.txt` polluting the symbol table depending on the test
1954 # execution order. Using a testroot of "config" seems to avoid that problem.
1955 @pytest.mark.sphinx('html', testroot='config')
1956 def test_domain_cpp_normalize_unspecialized_template_args(make_app, app_params):
1957 args, kwargs = app_params
1958
1959 text1 = '.. cpp:class:: template <typename T> A\n'
1960 text2 = '.. cpp:class:: template <typename T> template <typename U> A<T>::B\n'
1961
1962 app1 = make_app(*args, **kwargs)
1963 restructuredtext.parse(app=app1, text=text1, docname='text1')
1964 root1 = app1.env.domaindata['cpp']['root_symbol']
1965
1966 assert root1.dump(1) == (
1967 ' ::\n'
1968 ' template<typename T> \n'
1969 ' A: {class} template<typename T> A\t(text1)\n'
1970 ' T: {templateParam} typename T\t(text1)\n'
1971 )
1972
1973 app2 = make_app(*args, **kwargs)
1974 restructuredtext.parse(app=app2, text=text2, docname='text2')
1975 root2 = app2.env.domaindata['cpp']['root_symbol']
1976
1977 assert root2.dump(1) == (
1978 ' ::\n'
1979 ' template<typename T> \n'
1980 ' A\n'
1981 ' T\n'
1982 ' template<typename U> \n'
1983 ' B: {class} template<typename T> template<typename U> A<T>::B\t(text2)\n'
1984 ' U: {templateParam} typename U\t(text2)\n'
1985 )
1986
1987 root2.merge_with(root1, ['text1'], app2.env)
1988
1989 assert root2.dump(1) == (
1990 ' ::\n'
1991 ' template<typename T> \n'
1992 ' A: {class} template<typename T> A\t(text1)\n'
1993 ' T: {templateParam} typename T\t(text1)\n'
1994 ' template<typename U> \n'
1995 ' B: {class} template<typename T> template<typename U> A<T>::B\t(text2)\n'
1996 ' U: {templateParam} typename U\t(text2)\n'
1997 )
1998 warning = app2._warning.getvalue()
1999 assert 'Internal C++ domain error during symbol merging' not in warning
2000
2001
2002 @pytest.mark.sphinx(
2003 'html',
2004 testroot='root',
2005 confoverrides={
2006 'cpp_maximum_signature_line_length': len('str hello(str name)'),
2007 },
2008 )
2009 def test_cpp_function_signature_with_cpp_maximum_signature_line_length_equal(app):
2010 text = '.. cpp:function:: str hello(str name)'
2011 doctree = restructuredtext.parse(app, text)
2012 assert_node(
2013 doctree,
2014 (
2015 addnodes.index,
2016 [
2017 desc,
2018 (
2019 [
2020 desc_signature,
2021 (
2022 [
2023 desc_signature_line,
2024 (
2025 pending_xref,
2026 desc_sig_space,
2027 [desc_name, [desc_sig_name, 'hello']],
2028 desc_parameterlist,
2029 ),
2030 ],
2031 ),
2032 ],
2033 desc_content,
2034 ),
2035 ],
2036 ),
2037 )
2038 assert_node(
2039 doctree[1],
2040 addnodes.desc,
2041 desctype='function',
2042 domain='cpp',
2043 objtype='function',
2044 no_index=False,
2045 )
2046 assert_node(
2047 extract_node(doctree, 1, 0, 0, 3),
2048 [
2049 desc_parameterlist,
2050 desc_parameter,
2051 (
2052 [pending_xref, [desc_sig_name, 'str']],
2053 desc_sig_space,
2054 [desc_sig_name, 'name'],
2055 ),
2056 ],
2057 )
2058 assert_node(
2059 extract_node(doctree, 1, 0, 0, 3),
2060 desc_parameterlist,
2061 multi_line_parameter_list=False,
2062 )
2063
2064
2065 @pytest.mark.sphinx(
2066 'html',
2067 testroot='root',
2068 confoverrides={
2069 'cpp_maximum_signature_line_length': len('str hello(str name)'),
2070 },
2071 )
2072 def test_cpp_function_signature_with_cpp_maximum_signature_line_length_force_single(
2073 app,
2074 ):
2075 text = '.. cpp:function:: str hello(str names)\n :single-line-parameter-list:'
2076 doctree = restructuredtext.parse(app, text)
2077 assert_node(
2078 doctree,
2079 (
2080 addnodes.index,
2081 [
2082 desc,
2083 (
2084 [
2085 desc_signature,
2086 (
2087 [
2088 desc_signature_line,
2089 (
2090 pending_xref,
2091 desc_sig_space,
2092 [desc_name, [desc_sig_name, 'hello']],
2093 desc_parameterlist,
2094 ),
2095 ],
2096 ),
2097 ],
2098 desc_content,
2099 ),
2100 ],
2101 ),
2102 )
2103 assert_node(
2104 doctree[1],
2105 addnodes.desc,
2106 desctype='function',
2107 domain='cpp',
2108 objtype='function',
2109 no_index=False,
2110 )
2111 assert_node(
2112 extract_node(doctree, 1, 0, 0, 3),
2113 [
2114 desc_parameterlist,
2115 desc_parameter,
2116 (
2117 [pending_xref, [desc_sig_name, 'str']],
2118 desc_sig_space,
2119 [desc_sig_name, 'names'],
2120 ),
2121 ],
2122 )
2123 assert_node(
2124 extract_node(doctree, 1, 0, 0, 3),
2125 desc_parameterlist,
2126 multi_line_parameter_list=False,
2127 )
2128
2129
2130 @pytest.mark.sphinx(
2131 'html',
2132 testroot='root',
2133 confoverrides={
2134 'cpp_maximum_signature_line_length': len('str hello(str name)'),
2135 },
2136 )
2137 def test_cpp_function_signature_with_cpp_maximum_signature_line_length_break(app):
2138 text = '.. cpp:function:: str hello(str names)'
2139 doctree = restructuredtext.parse(app, text)
2140 assert_node(
2141 doctree,
2142 (
2143 addnodes.index,
2144 [
2145 desc,
2146 (
2147 [
2148 desc_signature,
2149 (
2150 [
2151 desc_signature_line,
2152 (
2153 pending_xref,
2154 desc_sig_space,
2155 [desc_name, [desc_sig_name, 'hello']],
2156 desc_parameterlist,
2157 ),
2158 ],
2159 ),
2160 ],
2161 desc_content,
2162 ),
2163 ],
2164 ),
2165 )
2166 assert_node(
2167 doctree[1],
2168 addnodes.desc,
2169 desctype='function',
2170 domain='cpp',
2171 objtype='function',
2172 no_index=False,
2173 )
2174 assert_node(
2175 extract_node(doctree, 1, 0, 0, 3),
2176 [
2177 desc_parameterlist,
2178 desc_parameter,
2179 (
2180 [pending_xref, [desc_sig_name, 'str']],
2181 desc_sig_space,
2182 [desc_sig_name, 'names'],
2183 ),
2184 ],
2185 )
2186 assert_node(
2187 extract_node(doctree, 1, 0, 0, 3),
2188 desc_parameterlist,
2189 multi_line_parameter_list=True,
2190 )
2191
2192
2193 @pytest.mark.sphinx(
2194 'html',
2195 testroot='root',
2196 confoverrides={
2197 'maximum_signature_line_length': len('str hello(str name)'),
2198 },
2199 )
2200 def test_cpp_function_signature_with_maximum_signature_line_length_equal(app):
2201 text = '.. cpp:function:: str hello(str name)'
2202 doctree = restructuredtext.parse(app, text)
2203 assert_node(
2204 doctree,
2205 (
2206 addnodes.index,
2207 [
2208 desc,
2209 (
2210 [
2211 desc_signature,
2212 (
2213 [
2214 desc_signature_line,
2215 (
2216 pending_xref,
2217 desc_sig_space,
2218 [desc_name, [desc_sig_name, 'hello']],
2219 desc_parameterlist,
2220 ),
2221 ],
2222 ),
2223 ],
2224 desc_content,
2225 ),
2226 ],
2227 ),
2228 )
2229 assert_node(
2230 doctree[1],
2231 addnodes.desc,
2232 desctype='function',
2233 domain='cpp',
2234 objtype='function',
2235 no_index=False,
2236 )
2237 assert_node(
2238 extract_node(doctree, 1, 0, 0, 3),
2239 [
2240 desc_parameterlist,
2241 desc_parameter,
2242 (
2243 [pending_xref, [desc_sig_name, 'str']],
2244 desc_sig_space,
2245 [desc_sig_name, 'name'],
2246 ),
2247 ],
2248 )
2249 assert_node(
2250 extract_node(doctree, 1, 0, 0, 3),
2251 desc_parameterlist,
2252 multi_line_parameter_list=False,
2253 )
2254
2255
2256 @pytest.mark.sphinx(
2257 'html',
2258 testroot='root',
2259 confoverrides={
2260 'maximum_signature_line_length': len('str hello(str name)'),
2261 },
2262 )
2263 def test_cpp_function_signature_with_maximum_signature_line_length_force_single(app):
2264 text = '.. cpp:function:: str hello(str names)\n :single-line-parameter-list:'
2265 doctree = restructuredtext.parse(app, text)
2266 assert_node(
2267 doctree,
2268 (
2269 addnodes.index,
2270 [
2271 desc,
2272 (
2273 [
2274 desc_signature,
2275 (
2276 [
2277 desc_signature_line,
2278 (
2279 pending_xref,
2280 desc_sig_space,
2281 [desc_name, [desc_sig_name, 'hello']],
2282 desc_parameterlist,
2283 ),
2284 ],
2285 ),
2286 ],
2287 desc_content,
2288 ),
2289 ],
2290 ),
2291 )
2292 assert_node(
2293 doctree[1],
2294 addnodes.desc,
2295 desctype='function',
2296 domain='cpp',
2297 objtype='function',
2298 no_index=False,
2299 )
2300 assert_node(
2301 extract_node(doctree, 1, 0, 0, 3),
2302 [
2303 desc_parameterlist,
2304 desc_parameter,
2305 (
2306 [pending_xref, [desc_sig_name, 'str']],
2307 desc_sig_space,
2308 [desc_sig_name, 'names'],
2309 ),
2310 ],
2311 )
2312 assert_node(
2313 extract_node(doctree, 1, 0, 0, 3),
2314 desc_parameterlist,
2315 multi_line_parameter_list=False,
2316 )
2317
2318
2319 @pytest.mark.sphinx(
2320 'html',
2321 testroot='root',
2322 confoverrides={
2323 'maximum_signature_line_length': len('str hello(str name)'),
2324 },
2325 )
2326 def test_cpp_function_signature_with_maximum_signature_line_length_break(app):
2327 text = '.. cpp:function:: str hello(str names)'
2328 doctree = restructuredtext.parse(app, text)
2329 assert_node(
2330 doctree,
2331 (
2332 addnodes.index,
2333 [
2334 desc,
2335 (
2336 [
2337 desc_signature,
2338 (
2339 [
2340 desc_signature_line,
2341 (
2342 pending_xref,
2343 desc_sig_space,
2344 [desc_name, [desc_sig_name, 'hello']],
2345 desc_parameterlist,
2346 ),
2347 ],
2348 ),
2349 ],
2350 desc_content,
2351 ),
2352 ],
2353 ),
2354 )
2355 assert_node(
2356 doctree[1],
2357 addnodes.desc,
2358 desctype='function',
2359 domain='cpp',
2360 objtype='function',
2361 no_index=False,
2362 )
2363 assert_node(
2364 extract_node(doctree, 1, 0, 0, 3),
2365 [
2366 desc_parameterlist,
2367 desc_parameter,
2368 (
2369 [pending_xref, [desc_sig_name, 'str']],
2370 desc_sig_space,
2371 [desc_sig_name, 'names'],
2372 ),
2373 ],
2374 )
2375 assert_node(
2376 extract_node(doctree, 1, 0, 0, 3),
2377 desc_parameterlist,
2378 multi_line_parameter_list=True,
2379 )
2380
2381
2382 @pytest.mark.sphinx(
2383 'html',
2384 testroot='root',
2385 confoverrides={
2386 'cpp_maximum_signature_line_length': len('str hello(str name)'),
2387 'maximum_signature_line_length': 1,
2388 },
2389 )
2390 def test_cpp_maximum_signature_line_length_overrides_global(app):
2391 text = '.. cpp:function:: str hello(str name)'
2392 doctree = restructuredtext.parse(app, text)
2393 assert_node(
2394 doctree,
2395 (
2396 addnodes.index,
2397 [
2398 desc,
2399 (
2400 [
2401 desc_signature,
2402 ([
2403 desc_signature_line,
2404 (
2405 pending_xref,
2406 desc_sig_space,
2407 [desc_name, [desc_sig_name, 'hello']],
2408 desc_parameterlist,
2409 ),
2410 ]),
2411 ],
2412 desc_content,
2413 ),
2414 ],
2415 ),
2416 )
2417 assert_node(
2418 doctree[1],
2419 addnodes.desc,
2420 desctype='function',
2421 domain='cpp',
2422 objtype='function',
2423 no_index=False,
2424 )
2425 assert_node(
2426 extract_node(doctree, 1, 0, 0, 3),
2427 [
2428 desc_parameterlist,
2429 desc_parameter,
2430 (
2431 [pending_xref, [desc_sig_name, 'str']],
2432 desc_sig_space,
2433 [desc_sig_name, 'name'],
2434 ),
2435 ],
2436 )
2437 assert_node(
2438 extract_node(doctree, 1, 0, 0, 3),
2439 desc_parameterlist,
2440 multi_line_parameter_list=False,
2441 )
2442
2443
2444 @pytest.mark.sphinx('html', testroot='domain-cpp-cpp_maximum_signature_line_length')
2445 def test_domain_cpp_cpp_maximum_signature_line_length_in_html(app):
2446 app.build()
2447 content = (app.outdir / 'index.html').read_text(encoding='utf-8')
2448 expected = """\
2449
2450 <dl>
2451 <dd>\
2452 <span class="n"><span class="pre">str</span></span>\
2453 <span class="w"> </span>\
2454 <span class="n sig-param"><span class="pre">name</span></span>\
2455 </dd>
2456 </dl>
2457
2458 <span class="sig-paren">)</span>\
2459 <a class="headerlink" href=\
2460 """
2461 assert expected in content
2462
2463
2464 @pytest.mark.sphinx(
2465 'text',
2466 testroot='domain-cpp-cpp_maximum_signature_line_length',
2467 )
2468 def test_domain_cpp_cpp_maximum_signature_line_length_in_text(app):
2469 app.build()
2470 content = (app.outdir / 'index.txt').read_text(encoding='utf8')
2471 param_line_fmt = STDINDENT * ' ' + '{}\n'
2472
2473 expected_parameter_list_hello = '(\n{})'.format(param_line_fmt.format('str name'))
2474
2475 assert expected_parameter_list_hello in content