summaryrefslogtreecommitdiffstats
path: root/tests/test_domains
diff options
context:
space:
mode:
Diffstat (limited to 'tests/test_domains')
-rw-r--r--tests/test_domains/__init__.py0
-rw-r--r--tests/test_domains/test_domain_c.py1072
-rw-r--r--tests/test_domains/test_domain_cpp.py1753
-rw-r--r--tests/test_domains/test_domain_js.py505
-rw-r--r--tests/test_domains/test_domain_py.py1015
-rw-r--r--tests/test_domains/test_domain_py_canonical.py77
-rw-r--r--tests/test_domains/test_domain_py_fields.py326
-rw-r--r--tests/test_domains/test_domain_py_pyfunction.py396
-rw-r--r--tests/test_domains/test_domain_py_pyobject.py487
-rw-r--r--tests/test_domains/test_domain_rst.py137
-rw-r--r--tests/test_domains/test_domain_std.py517
11 files changed, 6285 insertions, 0 deletions
diff --git a/tests/test_domains/__init__.py b/tests/test_domains/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/tests/test_domains/__init__.py
diff --git a/tests/test_domains/test_domain_c.py b/tests/test_domains/test_domain_c.py
new file mode 100644
index 0000000..a8a92cb
--- /dev/null
+++ b/tests/test_domains/test_domain_c.py
@@ -0,0 +1,1072 @@
+"""Tests the C Domain"""
+
+import itertools
+import zlib
+from xml.etree import ElementTree
+
+import pytest
+
+from sphinx import addnodes
+from sphinx.addnodes import (
+ desc,
+ desc_content,
+ desc_name,
+ desc_parameter,
+ desc_parameterlist,
+ desc_sig_name,
+ desc_sig_space,
+ desc_signature,
+ desc_signature_line,
+ pending_xref,
+)
+from sphinx.domains.c._ids import _id_prefix, _macroKeywords, _max_id
+from sphinx.domains.c._parser import DefinitionParser
+from sphinx.domains.c._symbol import Symbol
+from sphinx.ext.intersphinx import load_mappings, normalize_intersphinx_mapping
+from sphinx.testing import restructuredtext
+from sphinx.testing.util import assert_node
+from sphinx.util.cfamily import DefinitionError
+from sphinx.writers.text import STDINDENT
+
+
+class Config:
+ c_id_attributes = ["id_attr", 'LIGHTGBM_C_EXPORT']
+ c_paren_attributes = ["paren_attr"]
+ c_extra_keywords = _macroKeywords
+
+
+def parse(name, string):
+ parser = DefinitionParser(string, location=None, config=Config())
+ parser.allowFallbackExpressionParsing = False
+ ast = parser.parse_declaration(name, name)
+ parser.assert_end()
+ return ast
+
+
+def _check(name, input, idDict, output, key, asTextOutput):
+ if key is None:
+ key = name
+ key += ' '
+ if name in ('function', 'member'):
+ inputActual = input
+ outputAst = output
+ outputAsText = output
+ else:
+ inputActual = input.format(key='')
+ outputAst = output.format(key='')
+ outputAsText = output.format(key=key)
+ if asTextOutput is not None:
+ outputAsText = asTextOutput
+
+ # first a simple check of the AST
+ ast = parse(name, inputActual)
+ res = str(ast)
+ if res != outputAst:
+ print()
+ print("Input: ", input)
+ print("Result: ", res)
+ print("Expected: ", outputAst)
+ raise DefinitionError
+ rootSymbol = Symbol(None, None, None, None, None)
+ symbol = rootSymbol.add_declaration(ast, docname="TestDoc", line=42)
+ parentNode = addnodes.desc()
+ signode = addnodes.desc_signature(input, '')
+ parentNode += signode
+ ast.describe_signature(signode, 'lastIsName', symbol, options={})
+ resAsText = parentNode.astext()
+ if resAsText != outputAsText:
+ print()
+ print("Input: ", input)
+ print("astext(): ", resAsText)
+ print("Expected: ", outputAsText)
+ raise DefinitionError
+
+ idExpected = [None]
+ for i in range(1, _max_id + 1):
+ if i in idDict:
+ idExpected.append(idDict[i])
+ else:
+ idExpected.append(idExpected[i - 1])
+ idActual = [None]
+ for i in range(1, _max_id + 1):
+ # try:
+ id = ast.get_id(version=i)
+ assert id is not None
+ idActual.append(id[len(_id_prefix[i]):])
+ # except NoOldIdError:
+ # idActual.append(None)
+
+ res = [True]
+ for i in range(1, _max_id + 1):
+ res.append(idExpected[i] == idActual[i])
+
+ if not all(res):
+ print("input: %s" % input.rjust(20))
+ for i in range(1, _max_id + 1):
+ if res[i]:
+ continue
+ print("Error in id version %d." % i)
+ print("result: %s" % idActual[i])
+ print("expected: %s" % idExpected[i])
+ # print(rootSymbol.dump(0))
+ raise DefinitionError
+
+
+def check(name, input, idDict, output=None, key=None, asTextOutput=None):
+ if output is None:
+ output = input
+ # First, check without semicolon
+ _check(name, input, idDict, output, key, asTextOutput)
+ if name != 'macro':
+ # Second, check with semicolon
+ _check(name, input + ' ;', idDict, output + ';', key,
+ asTextOutput + ';' if asTextOutput is not None else None)
+
+
+def test_domain_c_ast_expressions():
+ def exprCheck(expr, output=None):
+ parser = DefinitionParser(expr, location=None, config=Config())
+ parser.allowFallbackExpressionParsing = False
+ ast = parser.parse_expression()
+ parser.assert_end()
+ # first a simple check of the AST
+ if output is None:
+ output = expr
+ res = str(ast)
+ if res != output:
+ print()
+ print("Input: ", input)
+ print("Result: ", res)
+ print("Expected: ", output)
+ raise DefinitionError
+ displayString = ast.get_display_string()
+ if res != displayString:
+ # note: if the expression contains an anon name then this will trigger a falsely
+ print()
+ print("Input: ", expr)
+ print("Result: ", res)
+ print("Display: ", displayString)
+ raise DefinitionError
+
+ # type expressions
+ exprCheck('int*')
+ exprCheck('int *const*')
+ exprCheck('int *volatile*')
+ exprCheck('int *restrict*')
+ exprCheck('int *(*)(double)')
+ exprCheck('const int*')
+ exprCheck('__int64')
+ exprCheck('unsigned __int64')
+
+ # actual expressions
+
+ # primary
+ exprCheck('true')
+ exprCheck('false')
+ ints = ['5', '0', '075', '0x0123456789ABCDEF', '0XF', '0b1', '0B1',
+ "0b0'1'0", "00'1'2", "0x0'1'2", "1'2'3"]
+ unsignedSuffix = ['', 'u', 'U']
+ longSuffix = ['', 'l', 'L', 'll', 'LL']
+ for i in ints:
+ for u in unsignedSuffix:
+ for l in longSuffix:
+ expr = i + u + l
+ exprCheck(expr)
+ expr = i + l + u
+ exprCheck(expr)
+ for suffix in ['', 'f', 'F', 'l', 'L']:
+ for e in [
+ '5e42', '5e+42', '5e-42',
+ '5.', '5.e42', '5.e+42', '5.e-42',
+ '.5', '.5e42', '.5e+42', '.5e-42',
+ '5.0', '5.0e42', '5.0e+42', '5.0e-42',
+ "1'2'3e7'8'9", "1'2'3.e7'8'9",
+ ".4'5'6e7'8'9", "1'2'3.4'5'6e7'8'9"]:
+ expr = e + suffix
+ exprCheck(expr)
+ for e in [
+ 'ApF', 'Ap+F', 'Ap-F',
+ 'A.', 'A.pF', 'A.p+F', 'A.p-F',
+ '.A', '.ApF', '.Ap+F', '.Ap-F',
+ 'A.B', 'A.BpF', 'A.Bp+F', 'A.Bp-F',
+ "A'B'Cp1'2'3", "A'B'C.p1'2'3",
+ ".D'E'Fp1'2'3", "A'B'C.D'E'Fp1'2'3"]:
+ expr = "0x" + e + suffix
+ exprCheck(expr)
+ exprCheck('"abc\\"cba"') # string
+ # character literals
+ for p in ['', 'u8', 'u', 'U', 'L']:
+ exprCheck(p + "'a'")
+ exprCheck(p + "'\\n'")
+ exprCheck(p + "'\\012'")
+ exprCheck(p + "'\\0'")
+ exprCheck(p + "'\\x0a'")
+ exprCheck(p + "'\\x0A'")
+ exprCheck(p + "'\\u0a42'")
+ exprCheck(p + "'\\u0A42'")
+ exprCheck(p + "'\\U0001f34c'")
+ exprCheck(p + "'\\U0001F34C'")
+
+ exprCheck('(5)')
+ exprCheck('C')
+ # postfix
+ exprCheck('A(2)')
+ exprCheck('A[2]')
+ exprCheck('a.b.c')
+ exprCheck('a->b->c')
+ exprCheck('i++')
+ exprCheck('i--')
+ # unary
+ exprCheck('++5')
+ exprCheck('--5')
+ exprCheck('*5')
+ exprCheck('&5')
+ exprCheck('+5')
+ exprCheck('-5')
+ exprCheck('!5')
+ exprCheck('not 5')
+ exprCheck('~5')
+ exprCheck('compl 5')
+ exprCheck('sizeof(T)')
+ exprCheck('sizeof -42')
+ exprCheck('alignof(T)')
+ # cast
+ exprCheck('(int)2')
+ # binary op
+ exprCheck('5 || 42')
+ exprCheck('5 or 42')
+ exprCheck('5 && 42')
+ exprCheck('5 and 42')
+ exprCheck('5 | 42')
+ exprCheck('5 bitor 42')
+ exprCheck('5 ^ 42')
+ exprCheck('5 xor 42')
+ exprCheck('5 & 42')
+ exprCheck('5 bitand 42')
+ # ['==', '!=']
+ exprCheck('5 == 42')
+ exprCheck('5 != 42')
+ exprCheck('5 not_eq 42')
+ # ['<=', '>=', '<', '>']
+ exprCheck('5 <= 42')
+ exprCheck('5 >= 42')
+ exprCheck('5 < 42')
+ exprCheck('5 > 42')
+ # ['<<', '>>']
+ exprCheck('5 << 42')
+ exprCheck('5 >> 42')
+ # ['+', '-']
+ exprCheck('5 + 42')
+ exprCheck('5 - 42')
+ # ['*', '/', '%']
+ exprCheck('5 * 42')
+ exprCheck('5 / 42')
+ exprCheck('5 % 42')
+ # ['.*', '->*']
+ # conditional
+ # TODO
+ # assignment
+ exprCheck('a = 5')
+ exprCheck('a *= 5')
+ exprCheck('a /= 5')
+ exprCheck('a %= 5')
+ exprCheck('a += 5')
+ exprCheck('a -= 5')
+ exprCheck('a >>= 5')
+ exprCheck('a <<= 5')
+ exprCheck('a &= 5')
+ exprCheck('a and_eq 5')
+ exprCheck('a ^= 5')
+ exprCheck('a xor_eq 5')
+ exprCheck('a |= 5')
+ exprCheck('a or_eq 5')
+
+
+def test_domain_c_ast_fundamental_types():
+ def types():
+ def signed(t):
+ yield t
+ yield 'signed ' + t
+ yield 'unsigned ' + t
+
+ # integer types
+ # -------------
+ yield 'void'
+ yield from ('_Bool', 'bool')
+ yield from signed('char')
+ yield from signed('short')
+ yield from signed('short int')
+ yield from signed('int')
+ yield from ('signed', 'unsigned')
+ yield from signed('long')
+ yield from signed('long int')
+ yield from signed('long long')
+ yield from signed('long long int')
+ yield from ('__int128', '__uint128')
+ # extensions
+ for t in ('__int8', '__int16', '__int32', '__int64', '__int128'):
+ yield from signed(t)
+
+ # floating point types
+ # --------------------
+ yield from ('_Decimal32', '_Decimal64', '_Decimal128')
+ for f in ('float', 'double', 'long double'):
+ yield f
+ yield from (f + " _Complex", f + " complex")
+ yield from ("_Complex " + f, "complex " + f)
+ yield from ("_Imaginary " + f, "imaginary " + f)
+ # extensions
+ # https://gcc.gnu.org/onlinedocs/gcc/Floating-Types.html#Floating-Types
+ yield from ('__float80', '_Float64x',
+ '__float128', '_Float128',
+ '__ibm128')
+ # https://gcc.gnu.org/onlinedocs/gcc/Half-Precision.html#Half-Precision
+ yield '__fp16'
+
+ # fixed-point types (extension)
+ # -----------------------------
+ # https://gcc.gnu.org/onlinedocs/gcc/Fixed-Point.html#Fixed-Point
+ for sat in ('', '_Sat '):
+ for t in ('_Fract', 'fract', '_Accum', 'accum'):
+ for size in ('short ', '', 'long ', 'long long '):
+ for tt in signed(size + t):
+ yield sat + tt
+
+ for t in types():
+ input = "{key}%s foo" % t
+ output = ' '.join(input.split())
+ check('type', input, {1: 'foo'}, key='typedef', output=output)
+ if ' ' in t:
+ # try permutations of all components
+ tcs = t.split()
+ for p in itertools.permutations(tcs):
+ input = "{key}%s foo" % ' '.join(p)
+ output = ' '.join(input.split())
+ check("type", input, {1: 'foo'}, key='typedef', output=output)
+
+
+def test_domain_c_ast_type_definitions():
+ check('type', "{key}T", {1: "T"})
+
+ check('type', "{key}bool *b", {1: 'b'}, key='typedef')
+ check('type', "{key}bool *const b", {1: 'b'}, key='typedef')
+ check('type', "{key}bool *const *b", {1: 'b'}, key='typedef')
+ check('type', "{key}bool *volatile *b", {1: 'b'}, key='typedef')
+ check('type', "{key}bool *restrict *b", {1: 'b'}, key='typedef')
+ check('type', "{key}bool *volatile const b", {1: 'b'}, key='typedef')
+ check('type', "{key}bool *volatile const b", {1: 'b'}, key='typedef')
+ check('type', "{key}bool *volatile const *b", {1: 'b'}, key='typedef')
+ check('type', "{key}bool b[]", {1: 'b'}, key='typedef')
+ check('type', "{key}long long int foo", {1: 'foo'}, key='typedef')
+ # test decl specs on right
+ check('type', "{key}bool const b", {1: 'b'}, key='typedef')
+
+ # from breathe#267 (named function parameters for function pointers
+ check('type', '{key}void (*gpio_callback_t)(struct device *port, uint32_t pin)',
+ {1: 'gpio_callback_t'}, key='typedef')
+
+
+def test_domain_c_ast_macro_definitions():
+ check('macro', 'M', {1: 'M'})
+ check('macro', 'M()', {1: 'M'})
+ check('macro', 'M(arg)', {1: 'M'})
+ check('macro', 'M(arg1, arg2)', {1: 'M'})
+ check('macro', 'M(arg1, arg2, arg3)', {1: 'M'})
+ check('macro', 'M(...)', {1: 'M'})
+ check('macro', 'M(arg, ...)', {1: 'M'})
+ check('macro', 'M(arg1, arg2, ...)', {1: 'M'})
+ check('macro', 'M(arg1, arg2, arg3, ...)', {1: 'M'})
+ # GNU extension
+ check('macro', 'M(arg1, arg2, arg3...)', {1: 'M'})
+ with pytest.raises(DefinitionError):
+ check('macro', 'M(arg1, arg2..., arg3)', {1: 'M'})
+
+
+def test_domain_c_ast_member_definitions():
+ check('member', 'void a', {1: 'a'})
+ check('member', '_Bool a', {1: 'a'})
+ check('member', 'bool a', {1: 'a'})
+ check('member', 'char a', {1: 'a'})
+ check('member', 'int a', {1: 'a'})
+ check('member', 'float a', {1: 'a'})
+ check('member', 'double a', {1: 'a'})
+
+ check('member', 'unsigned long a', {1: 'a'})
+ check('member', '__int64 a', {1: 'a'})
+ check('member', 'unsigned __int64 a', {1: 'a'})
+
+ check('member', 'int .a', {1: 'a'})
+
+ check('member', 'int *a', {1: 'a'})
+ check('member', 'int **a', {1: 'a'})
+ check('member', 'const int a', {1: 'a'})
+ check('member', 'volatile int a', {1: 'a'})
+ check('member', 'restrict int a', {1: 'a'})
+ check('member', 'volatile const int a', {1: 'a'})
+ check('member', 'restrict const int a', {1: 'a'})
+ check('member', 'restrict volatile int a', {1: 'a'})
+ check('member', 'restrict volatile const int a', {1: 'a'})
+
+ check('member', 'T t', {1: 't'})
+
+ check('member', 'int a[]', {1: 'a'})
+
+ check('member', 'int (*p)[]', {1: 'p'})
+
+ check('member', 'int a[42]', {1: 'a'})
+ check('member', 'int a = 42', {1: 'a'})
+ check('member', 'T a = {}', {1: 'a'})
+ check('member', 'T a = {1}', {1: 'a'})
+ check('member', 'T a = {1, 2}', {1: 'a'})
+ check('member', 'T a = {1, 2, 3}', {1: 'a'})
+
+ # test from issue #1539
+ check('member', 'CK_UTF8CHAR model[16]', {1: 'model'})
+
+ check('member', 'auto int a', {1: 'a'})
+ check('member', 'register int a', {1: 'a'})
+ check('member', 'extern int a', {1: 'a'})
+ check('member', 'static int a', {1: 'a'})
+
+ check('member', 'thread_local int a', {1: 'a'})
+ check('member', '_Thread_local int a', {1: 'a'})
+ check('member', 'extern thread_local int a', {1: 'a'})
+ check('member', 'thread_local extern int a', {1: 'a'},
+ 'extern thread_local int a')
+ check('member', 'static thread_local int a', {1: 'a'})
+ check('member', 'thread_local static int a', {1: 'a'},
+ 'static thread_local int a')
+
+ check('member', 'int b : 3', {1: 'b'})
+
+
+def test_domain_c_ast_function_definitions():
+ check('function', 'void f()', {1: 'f'})
+ check('function', 'void f(int)', {1: 'f'})
+ check('function', 'void f(int i)', {1: 'f'})
+ check('function', 'void f(int i, int j)', {1: 'f'})
+ check('function', 'void f(...)', {1: 'f'})
+ check('function', 'void f(int i, ...)', {1: 'f'})
+ check('function', 'void f(struct T)', {1: 'f'})
+ check('function', 'void f(struct T t)', {1: 'f'})
+ check('function', 'void f(union T)', {1: 'f'})
+ check('function', 'void f(union T t)', {1: 'f'})
+ check('function', 'void f(enum T)', {1: 'f'})
+ check('function', 'void f(enum T t)', {1: 'f'})
+
+ # test from issue #1539
+ check('function', 'void f(A x[])', {1: 'f'})
+
+ # test from issue #2377
+ check('function', 'void (*signal(int sig, void (*func)(int)))(int)', {1: 'signal'})
+
+ check('function', 'extern void f()', {1: 'f'})
+ check('function', 'static void f()', {1: 'f'})
+ check('function', 'inline void f()', {1: 'f'})
+
+ # tests derived from issue #1753 (skip to keep sanity)
+ check('function', "void f(float *q(double))", {1: 'f'})
+ check('function', "void f(float *(*q)(double))", {1: 'f'})
+ check('function', "void f(float (*q)(double))", {1: 'f'})
+ check('function', "int (*f(double d))(float)", {1: 'f'})
+ check('function', "int (*f(bool b))[5]", {1: 'f'})
+ check('function', "void f(int *const p)", {1: 'f'})
+ check('function', "void f(int *volatile const p)", {1: 'f'})
+
+ # from breathe#223
+ check('function', 'void f(struct E e)', {1: 'f'})
+ check('function', 'void f(enum E e)', {1: 'f'})
+ check('function', 'void f(union E e)', {1: 'f'})
+
+ # array declarators
+ check('function', 'void f(int arr[])', {1: 'f'})
+ check('function', 'void f(int arr[*])', {1: 'f'})
+ cvrs = ['', 'const', 'volatile', 'restrict', 'restrict volatile const']
+ for cvr in cvrs:
+ space = ' ' if len(cvr) != 0 else ''
+ check('function', f'void f(int arr[{cvr}*])', {1: 'f'})
+ check('function', f'void f(int arr[{cvr}])', {1: 'f'})
+ check('function', f'void f(int arr[{cvr}{space}42])', {1: 'f'})
+ check('function', f'void f(int arr[static{space}{cvr} 42])', {1: 'f'})
+ check('function', f'void f(int arr[{cvr}{space}static 42])', {1: 'f'},
+ output=f'void f(int arr[static{space}{cvr} 42])')
+ check('function', 'void f(int arr[const static volatile 42])', {1: 'f'},
+ output='void f(int arr[static volatile const 42])')
+
+ with pytest.raises(DefinitionError):
+ parse('function', 'void f(int for)')
+
+ # from #8960
+ check('function', 'void f(void (*p)(int, double), int i)', {1: 'f'})
+
+
+def test_domain_c_ast_nested_name():
+ check('struct', '{key}.A', {1: "A"})
+ check('struct', '{key}.A.B', {1: "A.B"})
+ check('function', 'void f(.A a)', {1: "f"})
+ check('function', 'void f(.A.B a)', {1: "f"})
+
+
+def test_domain_c_ast_struct_definitions():
+ check('struct', '{key}A', {1: 'A'})
+
+
+def test_domain_c_ast_union_definitions():
+ check('union', '{key}A', {1: 'A'})
+
+
+def test_domain_c_ast_enum_definitions():
+ check('enum', '{key}A', {1: 'A'})
+
+ check('enumerator', '{key}A', {1: 'A'})
+ check('enumerator', '{key}A = 42', {1: 'A'})
+
+
+def test_domain_c_ast_anon_definitions():
+ check('struct', '@a', {1: "@a"}, asTextOutput='struct [anonymous]')
+ check('union', '@a', {1: "@a"}, asTextOutput='union [anonymous]')
+ check('enum', '@a', {1: "@a"}, asTextOutput='enum [anonymous]')
+ check('struct', '@1', {1: "@1"}, asTextOutput='struct [anonymous]')
+ check('struct', '@a.A', {1: "@a.A"}, asTextOutput='struct [anonymous].A')
+
+
+def test_domain_c_ast_initializers():
+ idsMember = {1: 'v'}
+ idsFunction = {1: 'f'}
+ # no init
+ check('member', 'T v', idsMember)
+ check('function', 'void f(T v)', idsFunction)
+ # with '=', assignment-expression
+ check('member', 'T v = 42', idsMember)
+ check('function', 'void f(T v = 42)', idsFunction)
+ # with '=', braced-init
+ check('member', 'T v = {}', idsMember)
+ check('function', 'void f(T v = {})', idsFunction)
+ check('member', 'T v = {42, 42, 42}', idsMember)
+ check('function', 'void f(T v = {42, 42, 42})', idsFunction)
+ check('member', 'T v = {42, 42, 42,}', idsMember)
+ check('function', 'void f(T v = {42, 42, 42,})', idsFunction)
+ # TODO: designator-list
+
+
+def test_domain_c_ast_attributes():
+ # style: C++
+ check('member', '[[]] int f', {1: 'f'})
+ check('member', '[ [ ] ] int f', {1: 'f'},
+ # this will fail when the proper grammar is implemented
+ output='[[ ]] int f')
+ check('member', '[[a]] int f', {1: 'f'})
+ # style: GNU
+ check('member', '__attribute__(()) int f', {1: 'f'})
+ check('member', '__attribute__((a)) int f', {1: 'f'})
+ check('member', '__attribute__((a, b)) int f', {1: 'f'})
+ check('member', '__attribute__((optimize(3))) int f', {1: 'f'})
+ check('member', '__attribute__((format(printf, 1, 2))) int f', {1: 'f'})
+ # style: user-defined id
+ check('member', 'id_attr int f', {1: 'f'})
+ # style: user-defined paren
+ check('member', 'paren_attr() int f', {1: 'f'})
+ check('member', 'paren_attr(a) int f', {1: 'f'})
+ check('member', 'paren_attr("") int f', {1: 'f'})
+ check('member', 'paren_attr(()[{}][]{}) int f', {1: 'f'})
+ with pytest.raises(DefinitionError):
+ parse('member', 'paren_attr(() int f')
+ with pytest.raises(DefinitionError):
+ parse('member', 'paren_attr([) int f')
+ with pytest.raises(DefinitionError):
+ parse('member', 'paren_attr({) int f')
+ with pytest.raises(DefinitionError):
+ parse('member', 'paren_attr([)]) int f')
+ with pytest.raises(DefinitionError):
+ parse('member', 'paren_attr((])) int f')
+ with pytest.raises(DefinitionError):
+ parse('member', 'paren_attr({]}) int f')
+
+ # position: decl specs
+ check('function', 'static inline __attribute__(()) void f()', {1: 'f'},
+ output='__attribute__(()) static inline void f()')
+ check('function', '[[attr1]] [[attr2]] void f()', {1: 'f'})
+ # position: declarator
+ check('member', 'int *[[attr1]] [[attr2]] i', {1: 'i'})
+ check('member', 'int *const [[attr1]] [[attr2]] volatile i', {1: 'i'},
+ output='int *[[attr1]] [[attr2]] volatile const i')
+ check('member', 'int *[[attr1]] [[attr2]] *i', {1: 'i'})
+ # position: parameters
+ check('function', 'void f() [[attr1]] [[attr2]]', {1: 'f'})
+
+ # position: enumerator
+ check('enumerator', '{key}Foo [[attr1]] [[attr2]]', {1: 'Foo'})
+ check('enumerator', '{key}Foo [[attr1]] [[attr2]] = 42', {1: 'Foo'})
+
+ # issue michaeljones/breathe#500
+ check('function', 'LIGHTGBM_C_EXPORT int LGBM_BoosterFree(int handle)',
+ {1: 'LGBM_BoosterFree'})
+
+
+def test_extra_keywords():
+ with pytest.raises(DefinitionError,
+ match='Expected identifier in nested name'):
+ parse('function', 'void complex(void)')
+
+
+# def test_print():
+# # used for getting all the ids out for checking
+# for a in ids:
+# print(a)
+# raise DefinitionError
+
+
+def split_warnigns(warning):
+ ws = warning.getvalue().split("\n")
+ assert len(ws) >= 1
+ assert ws[-1] == ""
+ return ws[:-1]
+
+
+def filter_warnings(warning, file):
+ lines = split_warnigns(warning)
+ res = [l for l in lines if "domain-c" in l and f"{file}.rst" in l and
+ "WARNING: document isn't included in any toctree" not in l]
+ print(f"Filtered warnings for file '{file}':")
+ for w in res:
+ print(w)
+ return res
+
+
+def extract_role_links(app, filename):
+ t = (app.outdir / filename).read_text(encoding='utf8')
+ lis = [l for l in t.split('\n') if l.startswith("<li")]
+ entries = []
+ for l in lis:
+ li = ElementTree.fromstring(l) # NoQA: S314 # using known data in tests
+ aList = list(li.iter('a'))
+ assert len(aList) == 1
+ a = aList[0]
+ target = a.attrib['href'].lstrip('#')
+ title = a.attrib['title']
+ assert len(a) == 1
+ code = a[0]
+ assert code.tag == 'code'
+ text = ''.join(code.itertext())
+ entries.append((target, title, text))
+ return entries
+
+
+@pytest.mark.sphinx(testroot='domain-c', confoverrides={'nitpicky': True})
+def test_domain_c_build(app, status, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "index")
+ assert len(ws) == 0
+
+
+@pytest.mark.sphinx(testroot='domain-c', confoverrides={'nitpicky': True})
+def test_domain_c_build_namespace(app, status, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "namespace")
+ assert len(ws) == 0
+ t = (app.outdir / "namespace.html").read_text(encoding='utf8')
+ for id_ in ('NS.NSVar', 'NULLVar', 'ZeroVar', 'NS2.NS3.NS2NS3Var', 'PopVar'):
+ assert f'id="c.{id_}"' in t
+
+
+@pytest.mark.sphinx(testroot='domain-c', confoverrides={'nitpicky': True})
+def test_domain_c_build_anon_dup_decl(app, status, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "anon-dup-decl")
+ assert len(ws) == 2
+ assert "WARNING: c:identifier reference target not found: @a" in ws[0]
+ assert "WARNING: c:identifier reference target not found: @b" in ws[1]
+
+
+@pytest.mark.sphinx(confoverrides={'nitpicky': True})
+def test_domain_c_build_semicolon(app, warning):
+ text = """
+.. c:member:: int member;
+.. c:var:: int var;
+.. c:function:: void f();
+.. .. c:macro:: NO_SEMICOLON;
+.. c:struct:: Struct;
+.. c:union:: Union;
+.. c:enum:: Enum;
+.. c:enumerator:: Enumerator;
+.. c:type:: Type;
+.. c:type:: int TypeDef;
+"""
+ restructuredtext.parse(app, text)
+ ws = split_warnigns(warning)
+ assert len(ws) == 0
+
+
+@pytest.mark.sphinx(testroot='domain-c', confoverrides={'nitpicky': True})
+def test_domain_c_build_function_param_target(app, warning):
+ # the anchor for function parameters should be the function
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "function_param_target")
+ assert len(ws) == 0
+ entries = extract_role_links(app, "function_param_target.html")
+ assert entries == [
+ ('c.function_param_target.f', 'i', 'i'),
+ ('c.function_param_target.f', 'f.i', 'f.i'),
+ ]
+
+
+@pytest.mark.sphinx(testroot='domain-c', confoverrides={'nitpicky': True})
+def test_domain_c_build_ns_lookup(app, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "ns_lookup")
+ assert len(ws) == 0
+
+
+@pytest.mark.sphinx(testroot='domain-c', confoverrides={'nitpicky': True})
+def test_domain_c_build_field_role(app, status, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "field-role")
+ assert len(ws) == 0
+
+
+def _get_obj(app, queryName):
+ domain = app.env.get_domain('c')
+ for name, _dispname, objectType, docname, anchor, _prio in domain.get_objects():
+ if name == queryName:
+ return (docname, anchor, objectType)
+ return (queryName, "not", "found")
+
+
+@pytest.mark.sphinx(testroot='domain-c-intersphinx', confoverrides={'nitpicky': True})
+def test_domain_c_build_intersphinx(tmp_path, app, status, warning):
+ # a splitting of test_ids_vs_tags0 into the primary directives in a remote project,
+ # and then the references in the test project
+ origSource = """\
+.. c:member:: int _member
+.. c:var:: int _var
+.. c:function:: void _function()
+.. c:macro:: _macro
+.. c:struct:: _struct
+.. c:union:: _union
+.. c:enum:: _enum
+
+ .. c:enumerator:: _enumerator
+
+.. c:type:: _type
+.. c:function:: void _functionParam(int param)
+""" # NoQA: F841
+ inv_file = tmp_path / 'inventory'
+ inv_file.write_bytes(b'''\
+# Sphinx inventory version 2
+# Project: C Intersphinx Test
+# Version:
+# The remainder of this file is compressed using zlib.
+''' + zlib.compress(b'''\
+_enum c:enum 1 index.html#c.$ -
+_enum._enumerator c:enumerator 1 index.html#c.$ -
+_enumerator c:enumerator 1 index.html#c._enum.$ -
+_function c:function 1 index.html#c.$ -
+_functionParam c:function 1 index.html#c.$ -
+_functionParam.param c:functionParam 1 index.html#c._functionParam -
+_macro c:macro 1 index.html#c.$ -
+_member c:member 1 index.html#c.$ -
+_struct c:struct 1 index.html#c.$ -
+_type c:type 1 index.html#c.$ -
+_union c:union 1 index.html#c.$ -
+_var c:member 1 index.html#c.$ -
+''')) # NoQA: W291
+ app.config.intersphinx_mapping = {
+ 'https://localhost/intersphinx/c/': str(inv_file),
+ }
+ app.config.intersphinx_cache_limit = 0
+ # load the inventory and check if it's done correctly
+ normalize_intersphinx_mapping(app, app.config)
+ load_mappings(app)
+
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "index")
+ assert len(ws) == 0
+
+
+def test_domain_c_parse_cfunction(app):
+ text = (".. c:function:: PyObject* "
+ "PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="c", objtype="function", no_index=False)
+
+ entry = _get_obj(app, 'PyType_GenericAlloc')
+ assert entry == ('index', 'c.PyType_GenericAlloc', 'function')
+
+
+def test_domain_c_parse_cmember(app):
+ text = ".. c:member:: PyObject* PyTypeObject.tp_bases"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree[1], addnodes.desc, desctype="member",
+ domain="c", objtype="member", no_index=False)
+
+ entry = _get_obj(app, 'PyTypeObject.tp_bases')
+ assert entry == ('index', 'c.PyTypeObject.tp_bases', 'member')
+
+
+def test_domain_c_parse_cvar(app):
+ text = ".. c:var:: PyObject* PyClass_Type"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree[1], addnodes.desc, desctype="var",
+ domain="c", objtype="var", no_index=False)
+
+ entry = _get_obj(app, 'PyClass_Type')
+ assert entry == ('index', 'c.PyClass_Type', 'member')
+
+
+def test_domain_c_parse_no_index_entry(app):
+ text = (".. c:function:: void f()\n"
+ ".. c:function:: void g()\n"
+ " :no-index-entry:\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index, desc, addnodes.index, desc))
+ assert_node(doctree[0], addnodes.index, entries=[('single', 'f (C function)', 'c.f', '', None)])
+ assert_node(doctree[2], addnodes.index, entries=[])
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'c_maximum_signature_line_length': len("str hello(str name)"),
+})
+def test_cfunction_signature_with_c_maximum_signature_line_length_equal(app):
+ text = ".. c:function:: str hello(str name)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, "hello"]],
+ desc_parameterlist,
+ )],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="c", objtype="function", no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, "str"]],
+ desc_sig_space,
+ [desc_sig_name, "name"],
+ )])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'c_maximum_signature_line_length': len("str hello(str name)"),
+})
+def test_cfunction_signature_with_c_maximum_signature_line_length_force_single(app):
+ text = (".. c:function:: str hello(str names)\n"
+ " :single-line-parameter-list:")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, "hello"]],
+ desc_parameterlist,
+ )],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="c", objtype="function", no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, "str"]],
+ desc_sig_space,
+ [desc_sig_name, "names"],
+ )])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'c_maximum_signature_line_length': len("str hello(str name)"),
+})
+def test_cfunction_signature_with_c_maximum_signature_line_length_break(app):
+ text = ".. c:function:: str hello(str names)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, "hello"]],
+ desc_parameterlist,
+ )],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="c", objtype="function", no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, "str"]],
+ desc_sig_space,
+ [desc_sig_name, "names"],
+ )])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=True)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'maximum_signature_line_length': len("str hello(str name)"),
+})
+def test_cfunction_signature_with_maximum_signature_line_length_equal(app):
+ text = ".. c:function:: str hello(str name)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, "hello"]],
+ desc_parameterlist,
+ )],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="c", objtype="function", no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, "str"]],
+ desc_sig_space,
+ [desc_sig_name, "name"],
+ )])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'maximum_signature_line_length': len("str hello(str name)"),
+})
+def test_cfunction_signature_with_maximum_signature_line_length_force_single(app):
+ text = (".. c:function:: str hello(str names)\n"
+ " :single-line-parameter-list:")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, "hello"]],
+ desc_parameterlist,
+ )],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="c", objtype="function", no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, "str"]],
+ desc_sig_space,
+ [desc_sig_name, "names"],
+ )])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'maximum_signature_line_length': len("str hello(str name)"),
+})
+def test_cfunction_signature_with_maximum_signature_line_length_break(app):
+ text = ".. c:function:: str hello(str names)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, "hello"]],
+ desc_parameterlist,
+ )],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="c", objtype="function", no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, "str"]],
+ desc_sig_space,
+ [desc_sig_name, "names"],
+ )])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=True)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'c_maximum_signature_line_length': len('str hello(str name)'),
+ 'maximum_signature_line_length': 1,
+})
+def test_c_maximum_signature_line_length_overrides_global(app):
+ text = '.. c:function:: str hello(str name)'
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, 'hello']],
+ desc_parameterlist,
+ )]
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype='function',
+ domain='c', objtype='function', no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, "str"]],
+ desc_sig_space,
+ [desc_sig_name, 'name'],
+ )])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', testroot='domain-c-c_maximum_signature_line_length')
+def test_domain_c_c_maximum_signature_line_length_in_html(app, status, warning):
+ app.build()
+ content = (app.outdir / 'index.html').read_text(encoding='utf-8')
+ expected = """\
+
+<dl>
+<dd>\
+<span class="n"><span class="pre">str</span></span>\
+<span class="w"> </span>\
+<span class="n"><span class="pre">name</span></span>,\
+</dd>
+</dl>
+
+<span class="sig-paren">)</span>\
+<a class="headerlink" href="#c.hello" title="Link to this definition">¶</a>\
+<br />\
+</dt>
+"""
+ assert expected in content
+
+
+@pytest.mark.sphinx(
+ 'text', testroot='domain-c-c_maximum_signature_line_length',
+)
+def test_domain_c_c_maximum_signature_line_length_in_text(app, status, warning):
+ app.build()
+ content = (app.outdir / 'index.txt').read_text(encoding='utf8')
+ param_line_fmt = STDINDENT * " " + "{}\n"
+
+ expected_parameter_list_hello = "(\n{})".format(param_line_fmt.format("str name,"))
+
+ assert expected_parameter_list_hello in content
diff --git a/tests/test_domains/test_domain_cpp.py b/tests/test_domains/test_domain_cpp.py
new file mode 100644
index 0000000..abd0f82
--- /dev/null
+++ b/tests/test_domains/test_domain_cpp.py
@@ -0,0 +1,1753 @@
+"""Tests the C++ Domain"""
+
+import itertools
+import re
+import zlib
+
+import pytest
+
+import sphinx.domains.cpp
+from sphinx import addnodes
+from sphinx.addnodes import (
+ desc,
+ desc_content,
+ desc_name,
+ desc_parameter,
+ desc_parameterlist,
+ desc_sig_name,
+ desc_sig_space,
+ desc_signature,
+ desc_signature_line,
+ pending_xref,
+)
+from sphinx.domains.cpp._ids import _id_prefix, _max_id
+from sphinx.domains.cpp._parser import DefinitionParser
+from sphinx.domains.cpp._symbol import Symbol
+from sphinx.ext.intersphinx import load_mappings, normalize_intersphinx_mapping
+from sphinx.testing import restructuredtext
+from sphinx.testing.util import assert_node
+from sphinx.util.cfamily import DefinitionError, NoOldIdError
+from sphinx.writers.text import STDINDENT
+
+
+def parse(name, string):
+ class Config:
+ cpp_id_attributes = ["id_attr"]
+ cpp_paren_attributes = ["paren_attr"]
+ parser = DefinitionParser(string, location=None, config=Config())
+ parser.allowFallbackExpressionParsing = False
+ ast = parser.parse_declaration(name, name)
+ parser.assert_end()
+ # The scopedness would usually have been set by CPPEnumObject
+ if name == "enum":
+ ast.scoped = None # simulate unscoped enum
+ return ast
+
+
+def _check(name, input, idDict, output, key, asTextOutput):
+ if key is None:
+ key = name
+ key += ' '
+ if name in ('function', 'member'):
+ inputActual = input
+ outputAst = output
+ outputAsText = output
+ else:
+ inputActual = input.format(key='')
+ outputAst = output.format(key='')
+ outputAsText = output.format(key=key)
+ if asTextOutput is not None:
+ outputAsText = asTextOutput
+
+ # first a simple check of the AST
+ ast = parse(name, inputActual)
+ res = str(ast)
+ if res != outputAst:
+ print()
+ print("Input: ", input)
+ print("Result: ", res)
+ print("Expected: ", outputAst)
+ raise DefinitionError
+ rootSymbol = Symbol(None, None, None, None, None, None, None)
+ symbol = rootSymbol.add_declaration(ast, docname="TestDoc", line=42)
+ parentNode = addnodes.desc()
+ signode = addnodes.desc_signature(input, '')
+ parentNode += signode
+ ast.describe_signature(signode, 'lastIsName', symbol, options={})
+ resAsText = parentNode.astext()
+ if resAsText != outputAsText:
+ print()
+ print("Input: ", input)
+ print("astext(): ", resAsText)
+ print("Expected: ", outputAsText)
+ print("Node:", parentNode)
+ raise DefinitionError
+
+ idExpected = [None]
+ for i in range(1, _max_id + 1):
+ if i in idDict:
+ idExpected.append(idDict[i])
+ else:
+ idExpected.append(idExpected[i - 1])
+ idActual = [None]
+ for i in range(1, _max_id + 1):
+ try:
+ id = ast.get_id(version=i)
+ assert id is not None
+ idActual.append(id[len(_id_prefix[i]):])
+ except NoOldIdError:
+ idActual.append(None)
+
+ res = [True]
+ for i in range(1, _max_id + 1):
+ res.append(idExpected[i] == idActual[i])
+
+ if not all(res):
+ print("input: %s" % input.rjust(20))
+ for i in range(1, _max_id + 1):
+ if res[i]:
+ continue
+ print("Error in id version %d." % i)
+ print("result: %s" % idActual[i])
+ print("expected: %s" % idExpected[i])
+ print(rootSymbol.dump(0))
+ raise DefinitionError
+
+
+def check(name, input, idDict, output=None, key=None, asTextOutput=None):
+ if output is None:
+ output = input
+ # First, check without semicolon
+ _check(name, input, idDict, output, key, asTextOutput)
+ # Second, check with semicolon
+ _check(name, input + ' ;', idDict, output + ';', key,
+ asTextOutput + ';' if asTextOutput is not None else None)
+
+
+@pytest.mark.parametrize(('type_', 'id_v2'),
+ sphinx.domains.cpp._ids._id_fundamental_v2.items())
+def test_domain_cpp_ast_fundamental_types(type_, id_v2):
+ # see https://en.cppreference.com/w/cpp/language/types
+ def make_id_v1():
+ if type_ == 'decltype(auto)':
+ return None
+ id_ = type_.replace(" ", "-").replace("long", "l")
+ if "__int" not in type_:
+ id_ = id_.replace("int", "i")
+ id_ = id_.replace("bool", "b").replace("char", "c")
+ id_ = id_.replace("wc_t", "wchar_t").replace("c16_t", "char16_t")
+ id_ = id_.replace("c8_t", "char8_t")
+ id_ = id_.replace("c32_t", "char32_t")
+ return f"f__{id_}"
+
+ def make_id_v2():
+ id_ = id_v2
+ if type_ == "std::nullptr_t":
+ id_ = "NSt9nullptr_tE"
+ return f"1f{id_}"
+
+ id1 = make_id_v1()
+ id2 = make_id_v2()
+
+ input = f"void f({type_.replace(' ', ' ')} arg)"
+ output = f"void f({type_} arg)"
+
+ check("function", input, {1: id1, 2: id2}, output=output)
+ if ' ' in type_:
+ # try permutations of all components
+ tcs = type_.split()
+ for p in itertools.permutations(tcs):
+ input = f"void f({' '.join(p)} arg)"
+ check("function", input, {1: id1, 2: id2})
+
+
+def test_domain_cpp_ast_expressions():
+ def exprCheck(expr, id, id4=None):
+ ids = 'IE1CIA%s_1aE'
+ # call .format() on the expr to unescape double curly braces
+ idDict = {2: ids % expr.format(), 3: ids % id}
+ if id4 is not None:
+ idDict[4] = ids % id4
+ check('class', 'template<> {key}C<a[%s]>' % expr, idDict)
+
+ class Config:
+ cpp_id_attributes = ["id_attr"]
+ cpp_paren_attributes = ["paren_attr"]
+
+ parser = DefinitionParser(expr, location=None,
+ config=Config())
+ parser.allowFallbackExpressionParsing = False
+ ast = parser.parse_expression()
+ res = str(ast)
+ if res != expr:
+ print()
+ print("Input: ", expr)
+ print("Result: ", res)
+ raise DefinitionError
+ displayString = ast.get_display_string()
+ if res != displayString:
+ # note: if the expression contains an anon name then this will trigger a falsely
+ print()
+ print("Input: ", expr)
+ print("Result: ", res)
+ print("Display: ", displayString)
+ raise DefinitionError
+
+ # primary
+ exprCheck('nullptr', 'LDnE')
+ exprCheck('true', 'L1E')
+ exprCheck('false', 'L0E')
+ ints = ['5', '0', '075', '0x0123456789ABCDEF', '0XF', '0b1', '0B1',
+ "0b0'1'0", "00'1'2", "0x0'1'2", "1'2'3"]
+ unsignedSuffix = ['', 'u', 'U']
+ longSuffix = ['', 'l', 'L', 'll', 'LL']
+ for i in ints:
+ for u in unsignedSuffix:
+ for l in longSuffix:
+ expr = i + u + l
+ exprCheck(expr, 'L' + expr.replace("'", "") + 'E')
+ expr = i + l + u
+ exprCheck(expr, 'L' + expr.replace("'", "") + 'E')
+ decimalFloats = ['5e42', '5e+42', '5e-42',
+ '5.', '5.e42', '5.e+42', '5.e-42',
+ '.5', '.5e42', '.5e+42', '.5e-42',
+ '5.0', '5.0e42', '5.0e+42', '5.0e-42',
+ "1'2'3e7'8'9", "1'2'3.e7'8'9",
+ ".4'5'6e7'8'9", "1'2'3.4'5'6e7'8'9"]
+ hexFloats = ['ApF', 'Ap+F', 'Ap-F',
+ 'A.', 'A.pF', 'A.p+F', 'A.p-F',
+ '.A', '.ApF', '.Ap+F', '.Ap-F',
+ 'A.B', 'A.BpF', 'A.Bp+F', 'A.Bp-F',
+ "A'B'Cp1'2'3", "A'B'C.p1'2'3",
+ ".D'E'Fp1'2'3", "A'B'C.D'E'Fp1'2'3"]
+ for suffix in ['', 'f', 'F', 'l', 'L']:
+ for e in decimalFloats:
+ expr = e + suffix
+ exprCheck(expr, 'L' + expr.replace("'", "") + 'E')
+ for e in hexFloats:
+ expr = "0x" + e + suffix
+ exprCheck(expr, 'L' + expr.replace("'", "") + 'E')
+ exprCheck('"abc\\"cba"', 'LA8_KcE') # string
+ exprCheck('this', 'fpT')
+ # character literals
+ charPrefixAndIds = [('', 'c'), ('u8', 'c'), ('u', 'Ds'), ('U', 'Di'), ('L', 'w')]
+ chars = [('a', '97'), ('\\n', '10'), ('\\012', '10'), ('\\0', '0'),
+ ('\\x0a', '10'), ('\\x0A', '10'), ('\\u0a42', '2626'), ('\\u0A42', '2626'),
+ ('\\U0001f34c', '127820'), ('\\U0001F34C', '127820')]
+ for p, t in charPrefixAndIds:
+ for c, val in chars:
+ exprCheck(f"{p}'{c}'", t + val)
+ # user-defined literals
+ for i in ints:
+ exprCheck(i + '_udl', 'clL_Zli4_udlEL' + i.replace("'", "") + 'EE')
+ exprCheck(i + 'uludl', 'clL_Zli5uludlEL' + i.replace("'", "") + 'EE')
+ for f in decimalFloats:
+ exprCheck(f + '_udl', 'clL_Zli4_udlEL' + f.replace("'", "") + 'EE')
+ exprCheck(f + 'fudl', 'clL_Zli4fudlEL' + f.replace("'", "") + 'EE')
+ for f in hexFloats:
+ exprCheck('0x' + f + '_udl', 'clL_Zli4_udlEL0x' + f.replace("'", "") + 'EE')
+ for p, t in charPrefixAndIds:
+ for c, val in chars:
+ exprCheck(f"{p}'{c}'_udl", 'clL_Zli4_udlE' + t + val + 'E')
+ exprCheck('"abc"_udl', 'clL_Zli4_udlELA3_KcEE')
+ # from issue #7294
+ exprCheck('6.62607015e-34q_J', 'clL_Zli3q_JEL6.62607015e-34EE')
+
+ # fold expressions, paren, name
+ exprCheck('(... + Ns)', '(... + Ns)', id4='flpl2Ns')
+ exprCheck('(Ns + ...)', '(Ns + ...)', id4='frpl2Ns')
+ exprCheck('(Ns + ... + 0)', '(Ns + ... + 0)', id4='fLpl2NsL0E')
+ exprCheck('(5)', 'L5E')
+ exprCheck('C', '1C')
+ # postfix
+ exprCheck('A(2)', 'cl1AL2EE')
+ exprCheck('A[2]', 'ix1AL2E')
+ exprCheck('a.b.c', 'dtdt1a1b1c')
+ exprCheck('a->b->c', 'ptpt1a1b1c')
+ exprCheck('i++', 'pp1i')
+ exprCheck('i--', 'mm1i')
+ exprCheck('dynamic_cast<T&>(i)++', 'ppdcR1T1i')
+ exprCheck('static_cast<T&>(i)++', 'ppscR1T1i')
+ exprCheck('reinterpret_cast<T&>(i)++', 'pprcR1T1i')
+ exprCheck('const_cast<T&>(i)++', 'ppccR1T1i')
+ exprCheck('typeid(T).name', 'dtti1T4name')
+ exprCheck('typeid(a + b).name', 'dttepl1a1b4name')
+ # unary
+ exprCheck('++5', 'pp_L5E')
+ exprCheck('--5', 'mm_L5E')
+ exprCheck('*5', 'deL5E')
+ exprCheck('&5', 'adL5E')
+ exprCheck('+5', 'psL5E')
+ exprCheck('-5', 'ngL5E')
+ exprCheck('!5', 'ntL5E')
+ exprCheck('not 5', 'ntL5E')
+ exprCheck('~5', 'coL5E')
+ exprCheck('compl 5', 'coL5E')
+ exprCheck('sizeof...(a)', 'sZ1a')
+ exprCheck('sizeof(T)', 'st1T')
+ exprCheck('sizeof -42', 'szngL42E')
+ exprCheck('alignof(T)', 'at1T')
+ exprCheck('noexcept(-42)', 'nxngL42E')
+ # new-expression
+ exprCheck('new int', 'nw_iE')
+ exprCheck('new volatile int', 'nw_ViE')
+ exprCheck('new int[42]', 'nw_AL42E_iE')
+ exprCheck('new int()', 'nw_ipiE')
+ exprCheck('new int(5, 42)', 'nw_ipiL5EL42EE')
+ exprCheck('::new int', 'nw_iE')
+ exprCheck('new int{{}}', 'nw_iilE')
+ exprCheck('new int{{5, 42}}', 'nw_iilL5EL42EE')
+ # delete-expression
+ exprCheck('delete p', 'dl1p')
+ exprCheck('delete [] p', 'da1p')
+ exprCheck('::delete p', 'dl1p')
+ exprCheck('::delete [] p', 'da1p')
+ # cast
+ exprCheck('(int)2', 'cviL2E')
+ # binary op
+ exprCheck('5 || 42', 'ooL5EL42E')
+ exprCheck('5 or 42', 'ooL5EL42E')
+ exprCheck('5 && 42', 'aaL5EL42E')
+ exprCheck('5 and 42', 'aaL5EL42E')
+ exprCheck('5 | 42', 'orL5EL42E')
+ exprCheck('5 bitor 42', 'orL5EL42E')
+ exprCheck('5 ^ 42', 'eoL5EL42E')
+ exprCheck('5 xor 42', 'eoL5EL42E')
+ exprCheck('5 & 42', 'anL5EL42E')
+ exprCheck('5 bitand 42', 'anL5EL42E')
+ # ['==', '!=']
+ exprCheck('5 == 42', 'eqL5EL42E')
+ exprCheck('5 != 42', 'neL5EL42E')
+ exprCheck('5 not_eq 42', 'neL5EL42E')
+ # ['<=', '>=', '<', '>', '<=>']
+ exprCheck('5 <= 42', 'leL5EL42E')
+ exprCheck('A <= 42', 'le1AL42E')
+ exprCheck('5 >= 42', 'geL5EL42E')
+ exprCheck('5 < 42', 'ltL5EL42E')
+ exprCheck('A < 42', 'lt1AL42E')
+ exprCheck('5 > 42', 'gtL5EL42E')
+ exprCheck('A > 42', 'gt1AL42E')
+ exprCheck('5 <=> 42', 'ssL5EL42E')
+ exprCheck('A <=> 42', 'ss1AL42E')
+ # ['<<', '>>']
+ exprCheck('5 << 42', 'lsL5EL42E')
+ exprCheck('A << 42', 'ls1AL42E')
+ exprCheck('5 >> 42', 'rsL5EL42E')
+ # ['+', '-']
+ exprCheck('5 + 42', 'plL5EL42E')
+ exprCheck('5 - 42', 'miL5EL42E')
+ # ['*', '/', '%']
+ exprCheck('5 * 42', 'mlL5EL42E')
+ exprCheck('5 / 42', 'dvL5EL42E')
+ exprCheck('5 % 42', 'rmL5EL42E')
+ # ['.*', '->*']
+ exprCheck('5 .* 42', 'dsL5EL42E')
+ exprCheck('5 ->* 42', 'pmL5EL42E')
+ # conditional
+ exprCheck('5 ? 7 : 3', 'quL5EL7EL3E')
+ # assignment
+ exprCheck('a = 5', 'aS1aL5E')
+ exprCheck('a *= 5', 'mL1aL5E')
+ exprCheck('a /= 5', 'dV1aL5E')
+ exprCheck('a %= 5', 'rM1aL5E')
+ exprCheck('a += 5', 'pL1aL5E')
+ exprCheck('a -= 5', 'mI1aL5E')
+ exprCheck('a >>= 5', 'rS1aL5E')
+ exprCheck('a <<= 5', 'lS1aL5E')
+ exprCheck('a &= 5', 'aN1aL5E')
+ exprCheck('a and_eq 5', 'aN1aL5E')
+ exprCheck('a ^= 5', 'eO1aL5E')
+ exprCheck('a xor_eq 5', 'eO1aL5E')
+ exprCheck('a |= 5', 'oR1aL5E')
+ exprCheck('a or_eq 5', 'oR1aL5E')
+ exprCheck('a = {{1, 2, 3}}', 'aS1ailL1EL2EL3EE')
+ # complex assignment and conditional
+ exprCheck('5 = 6 = 7', 'aSL5EaSL6EL7E')
+ exprCheck('5 = 6 ? 7 = 8 : 3', 'aSL5EquL6EaSL7EL8EL3E')
+ # comma operator
+ exprCheck('a, 5', 'cm1aL5E')
+
+ # Additional tests
+ # a < expression that starts with something that could be a template
+ exprCheck('A < 42', 'lt1AL42E')
+ check('function', 'template<> void f(A<B, 2> &v)',
+ {2: "IE1fR1AI1BX2EE", 3: "IE1fR1AI1BXL2EEE", 4: "IE1fvR1AI1BXL2EEE"})
+ exprCheck('A<1>::value', 'N1AIXL1EEE5valueE')
+ check('class', "template<int T = 42> {key}A", {2: "I_iE1A"})
+ check('enumerator', '{key}A = std::numeric_limits<unsigned long>::max()', {2: "1A"})
+
+ exprCheck('operator()()', 'clclE')
+ exprCheck('operator()<int>()', 'clclIiEE')
+
+ # pack expansion
+ exprCheck('a(b(c, 1 + d...)..., e(f..., g))', 'cl1aspcl1b1cspplL1E1dEcl1esp1f1gEE')
+
+
+def test_domain_cpp_ast_type_definitions():
+ check("type", "public bool b", {1: "b", 2: "1b"}, "{key}bool b", key='typedef')
+ check("type", "{key}bool A::b", {1: "A::b", 2: "N1A1bE"}, key='typedef')
+ check("type", "{key}bool *b", {1: "b", 2: "1b"}, key='typedef')
+ check("type", "{key}bool *const b", {1: "b", 2: "1b"}, key='typedef')
+ check("type", "{key}bool *volatile const b", {1: "b", 2: "1b"}, key='typedef')
+ check("type", "{key}bool *volatile const b", {1: "b", 2: "1b"}, key='typedef')
+ check("type", "{key}bool *volatile const *b", {1: "b", 2: "1b"}, key='typedef')
+ check("type", "{key}bool &b", {1: "b", 2: "1b"}, key='typedef')
+ check("type", "{key}bool b[]", {1: "b", 2: "1b"}, key='typedef')
+ check("type", "{key}std::pair<int, int> coord", {1: "coord", 2: "5coord"}, key='typedef')
+ check("type", "{key}long long int foo", {1: "foo", 2: "3foo"}, key='typedef')
+ check("type", '{key}std::vector<std::pair<std::string, long long>> module::blah',
+ {1: "module::blah", 2: "N6module4blahE"}, key='typedef')
+ check("type", "{key}std::function<void()> F", {1: "F", 2: "1F"}, key='typedef')
+ check("type", "{key}std::function<R(A1, A2)> F", {1: "F", 2: "1F"}, key='typedef')
+ check("type", "{key}std::function<R(A1, A2, A3)> F", {1: "F", 2: "1F"}, key='typedef')
+ check("type", "{key}std::function<R(A1, A2, A3, As...)> F", {1: "F", 2: "1F"}, key='typedef')
+ check("type", "{key}MyContainer::const_iterator",
+ {1: "MyContainer::const_iterator", 2: "N11MyContainer14const_iteratorE"})
+ check("type",
+ "public MyContainer::const_iterator",
+ {1: "MyContainer::const_iterator", 2: "N11MyContainer14const_iteratorE"},
+ output="{key}MyContainer::const_iterator")
+ # test decl specs on right
+ check("type", "{key}bool const b", {1: "b", 2: "1b"}, key='typedef')
+ # test name in global scope
+ check("type", "{key}bool ::B::b", {1: "B::b", 2: "N1B1bE"}, key='typedef')
+
+ check('type', '{key}A = B', {2: '1A'}, key='using')
+ check('type', '{key}A = decltype(b)', {2: '1A'}, key='using')
+
+ # from breathe#267 (named function parameters for function pointers
+ check('type', '{key}void (*gpio_callback_t)(struct device *port, uint32_t pin)',
+ {1: 'gpio_callback_t', 2: '15gpio_callback_t'}, key='typedef')
+ check('type', '{key}void (*f)(std::function<void(int i)> g)', {1: 'f', 2: '1f'},
+ key='typedef')
+
+ check('type', '{key}T = A::template B<int>::template C<double>', {2: '1T'}, key='using')
+
+ check('type', '{key}T = Q<A::operator()>', {2: '1T'}, key='using')
+ check('type', '{key}T = Q<A::operator()<int>>', {2: '1T'}, key='using')
+ check('type', '{key}T = Q<A::operator bool>', {2: '1T'}, key='using')
+
+
+def test_domain_cpp_ast_concept_definitions():
+ check('concept', 'template<typename Param> {key}A::B::Concept',
+ {2: 'I0EN1A1B7ConceptE'})
+ check('concept', 'template<typename A, typename B, typename ...C> {key}Foo',
+ {2: 'I00DpE3Foo'})
+ with pytest.raises(DefinitionError):
+ parse('concept', '{key}Foo')
+ with pytest.raises(DefinitionError):
+ parse('concept', 'template<typename T> template<typename U> {key}Foo')
+
+
+def test_domain_cpp_ast_member_definitions():
+ check('member', ' const std::string & name = 42',
+ {1: "name__ssCR", 2: "4name"}, output='const std::string &name = 42')
+ check('member', ' const std::string & name', {1: "name__ssCR", 2: "4name"},
+ output='const std::string &name')
+ check('member', ' const std::string & name [ n ]',
+ {1: "name__ssCRA", 2: "4name"}, output='const std::string &name[n]')
+ check('member', 'const std::vector< unsigned int, long> &name',
+ {1: "name__std::vector:unsigned-i.l:CR", 2: "4name"},
+ output='const std::vector<unsigned int, long> &name')
+ check('member', 'module::myclass foo[n]', {1: "foo__module::myclassA", 2: "3foo"})
+ check('member', 'int *const p', {1: 'p__iPC', 2: '1p'})
+ check('member', 'extern int myInt', {1: 'myInt__i', 2: '5myInt'})
+ check('member', 'thread_local int myInt', {1: 'myInt__i', 2: '5myInt'})
+ check('member', 'extern thread_local int myInt', {1: 'myInt__i', 2: '5myInt'})
+ check('member', 'thread_local extern int myInt', {1: 'myInt__i', 2: '5myInt'},
+ 'extern thread_local int myInt')
+
+ # tests based on https://en.cppreference.com/w/cpp/language/bit_field
+ check('member', 'int b : 3', {1: 'b__i', 2: '1b'})
+ check('member', 'int b : 8 = 42', {1: 'b__i', 2: '1b'})
+ check('member', 'int b : 8{42}', {1: 'b__i', 2: '1b'})
+ # TODO: enable once the ternary operator is supported
+ # check('member', 'int b : true ? 8 : a = 42', {1: 'b__i', 2: '1b'})
+ # TODO: enable once the ternary operator is supported
+ # check('member', 'int b : (true ? 8 : a) = 42', {1: 'b__i', 2: '1b'})
+ check('member', 'int b : 1 || new int{0}', {1: 'b__i', 2: '1b'})
+
+ check('member', 'inline int n', {1: 'n__i', 2: '1n'})
+ check('member', 'constinit int n', {1: 'n__i', 2: '1n'})
+
+
+def test_domain_cpp_ast_function_definitions():
+ check('function', 'void f(volatile int)', {1: "f__iV", 2: "1fVi"})
+ check('function', 'void f(std::size_t)', {1: "f__std::s", 2: "1fNSt6size_tE"})
+ check('function', 'operator bool() const', {1: "castto-b-operatorC", 2: "NKcvbEv"})
+ check('function', 'A::operator bool() const',
+ {1: "A::castto-b-operatorC", 2: "NK1AcvbEv"})
+ check('function', 'A::operator bool() volatile const &',
+ {1: "A::castto-b-operatorVCR", 2: "NVKR1AcvbEv"})
+ check('function', 'A::operator bool() volatile const &&',
+ {1: "A::castto-b-operatorVCO", 2: "NVKO1AcvbEv"})
+ check('function', 'bool namespaced::theclass::method(arg1, arg2)',
+ {1: "namespaced::theclass::method__arg1.arg2",
+ 2: "N10namespaced8theclass6methodE4arg14arg2"})
+ x = 'std::vector<std::pair<std::string, int>> &module::test(register int ' \
+ 'foo, bar, std::string baz = "foobar, blah, bleh") const = 0'
+ check('function', x, {1: "module::test__i.bar.ssC",
+ 2: "NK6module4testEi3barNSt6stringE"})
+ check('function', 'void f(std::pair<A, B>)',
+ {1: "f__std::pair:A.B:", 2: "1fNSt4pairI1A1BEE"})
+ check('function', 'explicit module::myclass::foo::foo()',
+ {1: "module::myclass::foo::foo", 2: "N6module7myclass3foo3fooEv"})
+ check('function', 'module::myclass::foo::~foo()',
+ {1: "module::myclass::foo::~foo", 2: "N6module7myclass3fooD0Ev"})
+ check('function', 'int printf(const char *fmt, ...)',
+ {1: "printf__cCP.z", 2: "6printfPKcz"})
+ check('function', 'int foo(const unsigned int j)',
+ {1: "foo__unsigned-iC", 2: "3fooKj"})
+ check('function', 'int foo(const int *const ptr)',
+ {1: "foo__iCPC", 2: "3fooPCKi"})
+ check('function', 'module::myclass::operator std::vector<std::string>()',
+ {1: "module::myclass::castto-std::vector:ss:-operator",
+ 2: "N6module7myclasscvNSt6vectorINSt6stringEEEEv"})
+ check('function',
+ 'void operator()(const boost::array<VertexID, 2> &v) const',
+ {1: "call-operator__boost::array:VertexID.2:CRC",
+ 2: "NKclERKN5boost5arrayI8VertexIDX2EEE",
+ 3: "NKclERKN5boost5arrayI8VertexIDXL2EEEE"})
+ check('function',
+ 'void operator()(const boost::array<VertexID, 2, "foo, bar"> &v) const',
+ {1: 'call-operator__boost::array:VertexID.2."foo,--bar":CRC',
+ 2: 'NKclERKN5boost5arrayI8VertexIDX2EX"foo, bar"EEE',
+ 3: 'NKclERKN5boost5arrayI8VertexIDXL2EEXLA9_KcEEEE'})
+ check('function', 'MyClass::MyClass(MyClass::MyClass&&)',
+ {1: "MyClass::MyClass__MyClass::MyClassRR",
+ 2: "N7MyClass7MyClassERRN7MyClass7MyClassE"})
+ check('function', 'constexpr int get_value()', {1: "get_valueCE", 2: "9get_valuev"})
+ check('function', 'static constexpr int get_value()',
+ {1: "get_valueCE", 2: "9get_valuev"})
+ check('function', 'int get_value() const noexcept',
+ {1: "get_valueC", 2: "NK9get_valueEv"})
+ check('function', 'int get_value() const noexcept(std::is_nothrow_move_constructible<T>::value)',
+ {1: "get_valueC", 2: "NK9get_valueEv"})
+ check('function', 'int get_value() const noexcept("see below")',
+ {1: "get_valueC", 2: "NK9get_valueEv"})
+ check('function', 'int get_value() const noexcept = delete',
+ {1: "get_valueC", 2: "NK9get_valueEv"})
+ check('function', 'int get_value() volatile const',
+ {1: "get_valueVC", 2: "NVK9get_valueEv"})
+ check('function', 'MyClass::MyClass(MyClass::MyClass&&) = default',
+ {1: "MyClass::MyClass__MyClass::MyClassRR",
+ 2: "N7MyClass7MyClassERRN7MyClass7MyClassE"})
+ check('function', 'virtual MyClass::a_virtual_function() const override',
+ {1: "MyClass::a_virtual_functionC", 2: "NK7MyClass18a_virtual_functionEv"})
+ check('function', 'A B() override', {1: "B", 2: "1Bv"})
+ check('function', 'A B() final', {1: "B", 2: "1Bv"})
+ check('function', 'A B() final override', {1: "B", 2: "1Bv"})
+ check('function', 'A B() override final', {1: "B", 2: "1Bv"},
+ output='A B() final override')
+ check('function', 'MyClass::a_member_function() volatile',
+ {1: "MyClass::a_member_functionV", 2: "NV7MyClass17a_member_functionEv"})
+ check('function', 'MyClass::a_member_function() volatile const',
+ {1: "MyClass::a_member_functionVC", 2: "NVK7MyClass17a_member_functionEv"})
+ check('function', 'MyClass::a_member_function() &&',
+ {1: "MyClass::a_member_functionO", 2: "NO7MyClass17a_member_functionEv"})
+ check('function', 'MyClass::a_member_function() &',
+ {1: "MyClass::a_member_functionR", 2: "NR7MyClass17a_member_functionEv"})
+ check('function', 'MyClass::a_member_function() const &',
+ {1: "MyClass::a_member_functionCR", 2: "NKR7MyClass17a_member_functionEv"})
+ check('function', 'int main(int argc, char *argv[])',
+ {1: "main__i.cPA", 2: "4mainiA_Pc"})
+ check('function', 'MyClass &MyClass::operator++()',
+ {1: "MyClass::inc-operator", 2: "N7MyClassppEv"})
+ check('function', 'MyClass::pointer MyClass::operator->()',
+ {1: "MyClass::pointer-operator", 2: "N7MyClassptEv"})
+
+ x = 'std::vector<std::pair<std::string, int>> &module::test(register int ' \
+ 'foo, bar[n], std::string baz = "foobar, blah, bleh") const = 0'
+ check('function', x, {1: "module::test__i.barA.ssC",
+ 2: "NK6module4testEiAn_3barNSt6stringE",
+ 3: "NK6module4testEiA1n_3barNSt6stringE"})
+ check('function',
+ 'int foo(Foo f = Foo(double(), std::make_pair(int(2), double(3.4))))',
+ {1: "foo__Foo", 2: "3foo3Foo"})
+ check('function', 'int foo(A a = x(a))', {1: "foo__A", 2: "3foo1A"})
+ with pytest.raises(DefinitionError):
+ parse('function', 'int foo(B b=x(a)')
+ with pytest.raises(DefinitionError):
+ parse('function', 'int foo)C c=x(a))')
+ with pytest.raises(DefinitionError):
+ parse('function', 'int foo(D d=x(a')
+ check('function', 'int foo(const A&... a)', {1: "foo__ACRDp", 2: "3fooDpRK1A"})
+ check('function', 'int foo(const A&...)', {1: "foo__ACRDp", 2: "3fooDpRK1A"})
+ check('function', 'int foo(const A*... a)', {1: "foo__ACPDp", 2: "3fooDpPK1A"})
+ check('function', 'int foo(const A*...)', {1: "foo__ACPDp", 2: "3fooDpPK1A"})
+ check('function', 'int foo(const int A::*... a)', {2: "3fooDpM1AKi"})
+ check('function', 'int foo(const int A::*...)', {2: "3fooDpM1AKi"})
+ # check('function', 'int foo(int (*a)(A)...)', {1: "foo__ACRDp", 2: "3fooDpPK1A"})
+ # check('function', 'int foo(int (*)(A)...)', {1: "foo__ACRDp", 2: "3fooDpPK1A"})
+ check('function', 'virtual void f()', {1: "f", 2: "1fv"})
+ # test for ::nestedName, from issue 1738
+ check("function", "result(int val, ::std::error_category const &cat)",
+ {1: "result__i.std::error_categoryCR", 2: "6resultiRKNSt14error_categoryE"})
+ check("function", "int *f()", {1: "f", 2: "1fv"})
+ # tests derived from issue #1753 (skip to keep sanity)
+ check("function", "f(int (&array)[10])", {2: "1fRA10_i", 3: "1fRAL10E_i"})
+ check("function", "void f(int (&array)[10])", {2: "1fRA10_i", 3: "1fRAL10E_i"})
+ check("function", "void f(float *q(double))", {2: "1fFPfdE"})
+ check("function", "void f(float *(*q)(double))", {2: "1fPFPfdE"})
+ check("function", "void f(float (*q)(double))", {2: "1fPFfdE"})
+ check("function", "int (*f(double d))(float)", {1: "f__double", 2: "1fd"})
+ check("function", "int (*f(bool b))[5]", {1: "f__b", 2: "1fb"})
+ check("function", "int (*A::f(double d) const)(float)",
+ {1: "A::f__doubleC", 2: "NK1A1fEd"})
+ check("function", "void f(std::shared_ptr<int(double)> ptr)",
+ {2: "1fNSt10shared_ptrIFidEEE"})
+ check("function", "void f(int *const p)", {1: "f__iPC", 2: "1fPCi"})
+ check("function", "void f(int *volatile const p)", {1: "f__iPVC", 2: "1fPVCi"})
+
+ check('function', 'extern int f()', {1: 'f', 2: '1fv'})
+ check('function', 'consteval int f()', {1: 'f', 2: '1fv'})
+
+ check('function', 'explicit(true) void f()', {1: 'f', 2: '1fv'})
+
+ check('function', 'decltype(auto) f()', {1: 'f', 2: "1fv"})
+
+ # TODO: make tests for functions in a template, e.g., Test<int&&()>
+ # such that the id generation for function type types is correct.
+
+ check('function', 'friend std::ostream &f(std::ostream &s, int i)',
+ {1: 'f__osR.i', 2: '1fRNSt7ostreamEi'})
+
+ # from breathe#223
+ check('function', 'void f(struct E e)', {1: 'f__E', 2: '1f1E'})
+ check('function', 'void f(class E e)', {1: 'f__E', 2: '1f1E'})
+ check('function', 'void f(typename E e)', {1: 'f__E', 2: '1f1E'})
+ check('function', 'void f(enum E e)', {1: 'f__E', 2: '1f1E'})
+ check('function', 'void f(union E e)', {1: 'f__E', 2: '1f1E'})
+
+ # pointer to member (function)
+ check('function', 'void f(int C::*)', {2: '1fM1Ci'})
+ check('function', 'void f(int C::* p)', {2: '1fM1Ci'})
+ check('function', 'void f(int ::C::* p)', {2: '1fM1Ci'})
+ check('function', 'void f(int C::*const)', {2: '1fKM1Ci'})
+ check('function', 'void f(int C::*const&)', {2: '1fRKM1Ci'})
+ check('function', 'void f(int C::*volatile)', {2: '1fVM1Ci'})
+ check('function', 'void f(int C::*const volatile)', {2: '1fVKM1Ci'},
+ output='void f(int C::*volatile const)')
+ check('function', 'void f(int C::*volatile const)', {2: '1fVKM1Ci'})
+ check('function', 'void f(int (C::*)(float, double))', {2: '1fM1CFifdE'})
+ check('function', 'void f(int (C::* p)(float, double))', {2: '1fM1CFifdE'})
+ check('function', 'void f(int (::C::* p)(float, double))', {2: '1fM1CFifdE'})
+ check('function', 'void f(void (C::*)() const &)', {2: '1fM1CKRFvvE'})
+ check('function', 'int C::* f(int, double)', {2: '1fid'})
+ check('function', 'void f(int C::* *p)', {2: '1fPM1Ci'})
+ check('function', 'void f(int C::**)', {2: '1fPM1Ci'})
+ check('function', 'void f(int C::*const *p)', {2: '1fPKM1Ci'})
+ check('function', 'void f(int C::*const*)', {2: '1fPKM1Ci'})
+
+ # exceptions from return type mangling
+ check('function', 'template<typename T> C()', {2: 'I0E1Cv'})
+ check('function', 'template<typename T> operator int()', {2: 'I0Ecviv'})
+
+ # trailing return types
+ ids = {1: 'f', 2: '1fv'}
+ check('function', 'int f()', ids)
+ check('function', 'auto f() -> int', ids)
+ check('function', 'virtual auto f() -> int = 0', ids)
+ check('function', 'virtual auto f() -> int final', ids)
+ check('function', 'virtual auto f() -> int override', ids)
+
+ ids = {2: 'I0E1fv', 4: 'I0E1fiv'}
+ check('function', 'template<typename T> int f()', ids)
+ check('function', 'template<typename T> f() -> int', ids)
+
+ # from breathe#441
+ check('function', 'auto MakeThingy() -> Thingy*', {1: 'MakeThingy', 2: '10MakeThingyv'})
+
+ # from #8960
+ check('function', 'void f(void (*p)(int, double), int i)', {2: '1fPFvidEi'})
+
+ # from #9535 comment
+ check('function', 'void f(void (*p)(int) = &foo)', {2: '1fPFviE'})
+
+
+def test_domain_cpp_ast_operators():
+ check('function', 'void operator new()', {1: "new-operator", 2: "nwv"})
+ check('function', 'void operator new[]()', {1: "new-array-operator", 2: "nav"})
+ check('function', 'void operator delete()', {1: "delete-operator", 2: "dlv"})
+ check('function', 'void operator delete[]()', {1: "delete-array-operator", 2: "dav"})
+ check('function', 'operator bool() const', {1: "castto-b-operatorC", 2: "NKcvbEv"})
+ check('function', 'void operator""_udl()', {2: 'li4_udlv'})
+
+ check('function', 'void operator~()', {1: "inv-operator", 2: "cov"})
+ check('function', 'void operator compl()', {2: "cov"})
+ check('function', 'void operator+()', {1: "add-operator", 2: "plv"})
+ check('function', 'void operator-()', {1: "sub-operator", 2: "miv"})
+ check('function', 'void operator*()', {1: "mul-operator", 2: "mlv"})
+ check('function', 'void operator/()', {1: "div-operator", 2: "dvv"})
+ check('function', 'void operator%()', {1: "mod-operator", 2: "rmv"})
+ check('function', 'void operator&()', {1: "and-operator", 2: "anv"})
+ check('function', 'void operator bitand()', {2: "anv"})
+ check('function', 'void operator|()', {1: "or-operator", 2: "orv"})
+ check('function', 'void operator bitor()', {2: "orv"})
+ check('function', 'void operator^()', {1: "xor-operator", 2: "eov"})
+ check('function', 'void operator xor()', {2: "eov"})
+ check('function', 'void operator=()', {1: "assign-operator", 2: "aSv"})
+ check('function', 'void operator+=()', {1: "add-assign-operator", 2: "pLv"})
+ check('function', 'void operator-=()', {1: "sub-assign-operator", 2: "mIv"})
+ check('function', 'void operator*=()', {1: "mul-assign-operator", 2: "mLv"})
+ check('function', 'void operator/=()', {1: "div-assign-operator", 2: "dVv"})
+ check('function', 'void operator%=()', {1: "mod-assign-operator", 2: "rMv"})
+ check('function', 'void operator&=()', {1: "and-assign-operator", 2: "aNv"})
+ check('function', 'void operator and_eq()', {2: "aNv"})
+ check('function', 'void operator|=()', {1: "or-assign-operator", 2: "oRv"})
+ check('function', 'void operator or_eq()', {2: "oRv"})
+ check('function', 'void operator^=()', {1: "xor-assign-operator", 2: "eOv"})
+ check('function', 'void operator xor_eq()', {2: "eOv"})
+ check('function', 'void operator<<()', {1: "lshift-operator", 2: "lsv"})
+ check('function', 'void operator>>()', {1: "rshift-operator", 2: "rsv"})
+ check('function', 'void operator<<=()', {1: "lshift-assign-operator", 2: "lSv"})
+ check('function', 'void operator>>=()', {1: "rshift-assign-operator", 2: "rSv"})
+ check('function', 'void operator==()', {1: "eq-operator", 2: "eqv"})
+ check('function', 'void operator!=()', {1: "neq-operator", 2: "nev"})
+ check('function', 'void operator not_eq()', {2: "nev"})
+ check('function', 'void operator<()', {1: "lt-operator", 2: "ltv"})
+ check('function', 'void operator>()', {1: "gt-operator", 2: "gtv"})
+ check('function', 'void operator<=()', {1: "lte-operator", 2: "lev"})
+ check('function', 'void operator>=()', {1: "gte-operator", 2: "gev"})
+ check('function', 'void operator<=>()', {2: "ssv"})
+ check('function', 'void operator!()', {1: "not-operator", 2: "ntv"})
+ check('function', 'void operator not()', {2: "ntv"})
+ check('function', 'void operator&&()', {1: "sand-operator", 2: "aav"})
+ check('function', 'void operator and()', {2: "aav"})
+ check('function', 'void operator||()', {1: "sor-operator", 2: "oov"})
+ check('function', 'void operator or()', {2: "oov"})
+ check('function', 'void operator++()', {1: "inc-operator", 2: "ppv"})
+ check('function', 'void operator--()', {1: "dec-operator", 2: "mmv"})
+ check('function', 'void operator,()', {1: "comma-operator", 2: "cmv"})
+ check('function', 'void operator->*()', {1: "pointer-by-pointer-operator", 2: "pmv"})
+ check('function', 'void operator->()', {1: "pointer-operator", 2: "ptv"})
+ check('function', 'void operator()()', {1: "call-operator", 2: "clv"})
+ check('function', 'void operator[]()', {1: "subscript-operator", 2: "ixv"})
+
+
+def test_domain_cpp_ast_nested_name():
+ check('class', '{key}::A', {1: "A", 2: "1A"})
+ check('class', '{key}::A::B', {1: "A::B", 2: "N1A1BE"})
+ check('function', 'void f(::A a)', {1: "f__A", 2: "1f1A"})
+ check('function', 'void f(::A::B a)', {1: "f__A::B", 2: "1fN1A1BE"})
+
+
+def test_domain_cpp_ast_class_definitions():
+ check('class', 'public A', {1: "A", 2: "1A"}, output='{key}A')
+ check('class', 'private {key}A', {1: "A", 2: "1A"})
+ check('class', '{key}A final', {1: 'A', 2: '1A'})
+
+ # test bases
+ check('class', '{key}A', {1: "A", 2: "1A"})
+ check('class', '{key}A::B::C', {1: "A::B::C", 2: "N1A1B1CE"})
+ check('class', '{key}A : B', {1: "A", 2: "1A"})
+ check('class', '{key}A : private B', {1: "A", 2: "1A"})
+ check('class', '{key}A : public B', {1: "A", 2: "1A"})
+ check('class', '{key}A : B, C', {1: "A", 2: "1A"})
+ check('class', '{key}A : B, protected C, D', {1: "A", 2: "1A"})
+ check('class', 'A : virtual private B', {1: 'A', 2: '1A'}, output='{key}A : private virtual B')
+ check('class', '{key}A : private virtual B', {1: 'A', 2: '1A'})
+ check('class', '{key}A : B, virtual C', {1: 'A', 2: '1A'})
+ check('class', '{key}A : public virtual B', {1: 'A', 2: '1A'})
+ check('class', '{key}A : B, C...', {1: 'A', 2: '1A'})
+ check('class', '{key}A : B..., C', {1: 'A', 2: '1A'})
+
+ # from #4094
+ check('class', 'template<class, class = std::void_t<>> {key}has_var', {2: 'I00E7has_var'})
+ check('class', 'template<class T> {key}has_var<T, std::void_t<decltype(&T::var)>>',
+ {2: 'I0E7has_varI1TNSt6void_tIDTadN1T3varEEEEE'})
+
+ check('class', 'template<typename ...Ts> {key}T<int (*)(Ts)...>',
+ {2: 'IDpE1TIJPFi2TsEEE'})
+ check('class', 'template<int... Is> {key}T<(Is)...>',
+ {2: 'I_DpiE1TIJX(Is)EEE', 3: 'I_DpiE1TIJX2IsEEE'})
+
+
+def test_domain_cpp_ast_union_definitions():
+ check('union', '{key}A', {2: "1A"})
+
+
+def test_domain_cpp_ast_enum_definitions():
+ check('enum', '{key}A', {2: "1A"})
+ check('enum', '{key}A : std::underlying_type<B>::type', {2: "1A"})
+ check('enum', '{key}A : unsigned int', {2: "1A"})
+ check('enum', 'public A', {2: "1A"}, output='{key}A')
+ check('enum', 'private {key}A', {2: "1A"})
+
+ check('enumerator', '{key}A', {2: "1A"})
+ check('enumerator', '{key}A = std::numeric_limits<unsigned long>::max()', {2: "1A"})
+
+
+def test_domain_cpp_ast_anon_definitions():
+ check('class', '@a', {3: "Ut1_a"}, asTextOutput='class [anonymous]')
+ check('union', '@a', {3: "Ut1_a"}, asTextOutput='union [anonymous]')
+ check('enum', '@a', {3: "Ut1_a"}, asTextOutput='enum [anonymous]')
+ check('class', '@1', {3: "Ut1_1"}, asTextOutput='class [anonymous]')
+ check('class', '@a::A', {3: "NUt1_a1AE"}, asTextOutput='class [anonymous]::A')
+
+ check('function', 'int f(int @a)', {1: 'f__i', 2: '1fi'},
+ asTextOutput='int f(int [anonymous])')
+
+
+def test_domain_cpp_ast_templates():
+ check('class', "A<T>", {2: "IE1AI1TE"}, output="template<> {key}A<T>")
+ # first just check which objects support templating
+ check('class', "template<> {key}A", {2: "IE1A"})
+ check('function', "template<> void A()", {2: "IE1Av", 4: "IE1Avv"})
+ check('member', "template<> A a", {2: "IE1a"})
+ check('type', "template<> {key}a = A", {2: "IE1a"}, key='using')
+ with pytest.raises(DefinitionError):
+ parse('enum', "template<> A")
+ with pytest.raises(DefinitionError):
+ parse('enumerator', "template<> A")
+ # then all the real tests
+ check('class', "template<typename T1, typename T2> {key}A", {2: "I00E1A"})
+ check('type', "template<> {key}a", {2: "IE1a"}, key='using')
+
+ check('class', "template<typename T> {key}A", {2: "I0E1A"})
+ check('class', "template<class T> {key}A", {2: "I0E1A"})
+ check('class', "template<typename ...T> {key}A", {2: "IDpE1A"})
+ check('class', "template<typename...> {key}A", {2: "IDpE1A"})
+ check('class', "template<typename = Test> {key}A", {2: "I0E1A"})
+ check('class', "template<typename T = Test> {key}A", {2: "I0E1A"})
+
+ check('class', "template<template<typename> typename T> {key}A", {2: "II0E0E1A"})
+ check('class', "template<template<typename> class T> {key}A", {2: "II0E0E1A"})
+ check('class', "template<template<typename> typename> {key}A", {2: "II0E0E1A"})
+ check('class', "template<template<typename> typename ...T> {key}A", {2: "II0EDpE1A"})
+ check('class', "template<template<typename> typename...> {key}A", {2: "II0EDpE1A"})
+ check('class', "template<typename T, template<typename> typename...> {key}A", {2: "I0I0EDpE1A"})
+
+ check('class', "template<int> {key}A", {2: "I_iE1A"})
+ check('class', "template<int T> {key}A", {2: "I_iE1A"})
+ check('class', "template<int... T> {key}A", {2: "I_DpiE1A"})
+ check('class', "template<int T = 42> {key}A", {2: "I_iE1A"})
+ check('class', "template<int = 42> {key}A", {2: "I_iE1A"})
+
+ check('class', "template<typename A<B>::C> {key}A", {2: "I_N1AI1BE1CEE1A"})
+ check('class', "template<typename A<B>::C = 42> {key}A", {2: "I_N1AI1BE1CEE1A"})
+ # from #7944
+ check('function', "template<typename T, "
+ "typename std::enable_if<!has_overloaded_addressof<T>::value, bool>::type = false"
+ "> constexpr T *static_addressof(T &ref)",
+ {2: "I0_NSt9enable_ifIX!has_overloaded_addressof<T>::valueEbE4typeEE16static_addressofR1T",
+ 3: "I0_NSt9enable_ifIXntN24has_overloaded_addressofI1TE5valueEEbE4typeEE16static_addressofR1T",
+ 4: "I0_NSt9enable_ifIXntN24has_overloaded_addressofI1TE5valueEEbE4typeEE16static_addressofP1TR1T"})
+
+ check('class', "template<> {key}A<NS::B<>>", {2: "IE1AIN2NS1BIEEE"})
+
+ # from #2058
+ check('function',
+ "template<typename Char, typename Traits> "
+ "inline std::basic_ostream<Char, Traits> &operator<<("
+ "std::basic_ostream<Char, Traits> &os, "
+ "const c_string_view_base<const Char, Traits> &str)",
+ {2: "I00ElsRNSt13basic_ostreamI4Char6TraitsEE"
+ "RK18c_string_view_baseIK4Char6TraitsE",
+ 4: "I00Els"
+ "RNSt13basic_ostreamI4Char6TraitsEE"
+ "RNSt13basic_ostreamI4Char6TraitsEE"
+ "RK18c_string_view_baseIK4Char6TraitsE"})
+
+ # template introductions
+ with pytest.raises(DefinitionError):
+ parse('enum', 'abc::ns::foo{id_0, id_1, id_2} A')
+ with pytest.raises(DefinitionError):
+ parse('enumerator', 'abc::ns::foo{id_0, id_1, id_2} A')
+ check('class', 'abc::ns::foo{{id_0, id_1, id_2}} {key}xyz::bar',
+ {2: 'I000EXN3abc2ns3fooEI4id_04id_14id_2EEN3xyz3barE'})
+ check('class', 'abc::ns::foo{{id_0, id_1, ...id_2}} {key}xyz::bar',
+ {2: 'I00DpEXN3abc2ns3fooEI4id_04id_1sp4id_2EEN3xyz3barE'})
+ check('class', 'abc::ns::foo{{id_0, id_1, id_2}} {key}xyz::bar<id_0, id_1, id_2>',
+ {2: 'I000EXN3abc2ns3fooEI4id_04id_14id_2EEN3xyz3barE'})
+ check('class', 'abc::ns::foo{{id_0, id_1, ...id_2}} {key}xyz::bar<id_0, id_1, id_2...>',
+ {2: 'I00DpEXN3abc2ns3fooEI4id_04id_1sp4id_2EEN3xyz3barE'})
+
+ check('class', 'template<> Concept{{U}} {key}A<int>::B', {2: 'IEI0EX7ConceptI1UEEN1AIiE1BE'})
+
+ check('type', 'abc::ns::foo{{id_0, id_1, id_2}} {key}xyz::bar = ghi::qux',
+ {2: 'I000EXN3abc2ns3fooEI4id_04id_14id_2EEN3xyz3barE'}, key='using')
+ check('type', 'abc::ns::foo{{id_0, id_1, ...id_2}} {key}xyz::bar = ghi::qux',
+ {2: 'I00DpEXN3abc2ns3fooEI4id_04id_1sp4id_2EEN3xyz3barE'}, key='using')
+ check('function', 'abc::ns::foo{id_0, id_1, id_2} void xyz::bar()',
+ {2: 'I000EXN3abc2ns3fooEI4id_04id_14id_2EEN3xyz3barEv',
+ 4: 'I000EXN3abc2ns3fooEI4id_04id_14id_2EEN3xyz3barEvv'})
+ check('function', 'abc::ns::foo{id_0, id_1, ...id_2} void xyz::bar()',
+ {2: 'I00DpEXN3abc2ns3fooEI4id_04id_1sp4id_2EEN3xyz3barEv',
+ 4: 'I00DpEXN3abc2ns3fooEI4id_04id_1sp4id_2EEN3xyz3barEvv'})
+ check('member', 'abc::ns::foo{id_0, id_1, id_2} ghi::qux xyz::bar',
+ {2: 'I000EXN3abc2ns3fooEI4id_04id_14id_2EEN3xyz3barE'})
+ check('member', 'abc::ns::foo{id_0, id_1, ...id_2} ghi::qux xyz::bar',
+ {2: 'I00DpEXN3abc2ns3fooEI4id_04id_1sp4id_2EEN3xyz3barE'})
+ check('concept', 'Iterator{{T, U}} {key}Another', {2: 'I00EX8IteratorI1T1UEE7Another'})
+ check('concept', 'template<typename ...Pack> {key}Numerics = (... && Numeric<Pack>)',
+ {2: 'IDpE8Numerics'})
+
+ # explicit specializations of members
+ check('member', 'template<> int A<int>::a', {2: 'IEN1AIiE1aE'})
+ check('member', 'template int A<int>::a', {2: 'IEN1AIiE1aE'},
+ output='template<> int A<int>::a') # same as above
+ check('member', 'template<> template<> int A<int>::B<int>::b', {2: 'IEIEN1AIiE1BIiE1bE'})
+ check('member', 'template int A<int>::B<int>::b', {2: 'IEIEN1AIiE1BIiE1bE'},
+ output='template<> template<> int A<int>::B<int>::b') # same as above
+
+ # defaulted constrained type parameters
+ check('type', 'template<C T = int&> {key}A', {2: 'I_1CE1A'}, key='using')
+
+ # pack expansion after non-type template parameter
+ check('type', 'template<int (X::*)(bool)...> {key}A', {2: 'I_DpM1XFibEE1A'}, key='using')
+
+
+def test_domain_cpp_ast_placeholder_types():
+ check('function', 'void f(Sortable auto &v)', {1: 'f__SortableR', 2: '1fR8Sortable'})
+ check('function', 'void f(const Sortable auto &v)', {1: 'f__SortableCR', 2: '1fRK8Sortable'})
+ check('function', 'void f(Sortable decltype(auto) &v)', {1: 'f__SortableR', 2: '1fR8Sortable'})
+ check('function', 'void f(const Sortable decltype(auto) &v)', {1: 'f__SortableCR', 2: '1fRK8Sortable'})
+ check('function', 'void f(Sortable decltype ( auto ) &v)', {1: 'f__SortableR', 2: '1fR8Sortable'},
+ output='void f(Sortable decltype(auto) &v)')
+
+
+def test_domain_cpp_ast_requires_clauses():
+ check('function', 'template<typename T> requires A auto f() -> void requires B',
+ {4: 'I0EIQaa1A1BE1fvv'})
+ check('function', 'template<typename T> requires A || B or C void f()',
+ {4: 'I0EIQoo1Aoo1B1CE1fvv'})
+ check('function', 'void f() requires A || B || C',
+ {4: 'IQoo1Aoo1B1CE1fv'})
+ check('function', 'Foo() requires A || B || C',
+ {4: 'IQoo1Aoo1B1CE3Foov'})
+ check('function', 'template<typename T> requires A && B || C and D void f()',
+ {4: 'I0EIQooaa1A1Baa1C1DE1fvv'})
+ check('function',
+ 'template<typename T> requires R<T> ' +
+ 'template<typename U> requires S<T> ' +
+ 'void A<T>::f() requires B',
+ {4: 'I0EIQ1RI1TEEI0EIQaa1SI1TE1BEN1A1fEvv'})
+ check('function',
+ 'template<template<typename T> requires R<T> typename X> ' +
+ 'void f()',
+ {2: 'II0EIQ1RI1TEE0E1fv', 4: 'II0EIQ1RI1TEE0E1fvv'})
+ check('type',
+ 'template<typename T> requires IsValid<T> {key}T = true_type',
+ {4: 'I0EIQ7IsValidI1TEE1T'}, key='using')
+ check('class',
+ 'template<typename T> requires IsValid<T> {key}T : Base',
+ {4: 'I0EIQ7IsValidI1TEE1T'}, key='class')
+ check('union',
+ 'template<typename T> requires IsValid<T> {key}T',
+ {4: 'I0EIQ7IsValidI1TEE1T'}, key='union')
+ check('member',
+ 'template<typename T> requires IsValid<T> int Val = 7',
+ {4: 'I0EIQ7IsValidI1TEE3Val'})
+
+
+def test_domain_cpp_ast_template_args():
+ # from breathe#218
+ check('function',
+ "template<typename F> "
+ "void allow(F *f, typename func<F, B, G != 1>::type tt)",
+ {2: "I0E5allowP1FN4funcI1F1BXG != 1EE4typeE",
+ 3: "I0E5allowP1FN4funcI1F1BXne1GL1EEE4typeE",
+ 4: "I0E5allowvP1FN4funcI1F1BXne1GL1EEE4typeE"})
+ # from #3542
+ check('type', "template<typename T> {key}"
+ "enable_if_not_array_t = std::enable_if_t<!is_array<T>::value, int>",
+ {2: "I0E21enable_if_not_array_t"},
+ key='using')
+
+
+def test_domain_cpp_ast_initializers():
+ idsMember = {1: 'v__T', 2: '1v'}
+ idsFunction = {1: 'f__T', 2: '1f1T'}
+ idsTemplate = {2: 'I_1TE1fv', 4: 'I_1TE1fvv'}
+ # no init
+ check('member', 'T v', idsMember)
+ check('function', 'void f(T v)', idsFunction)
+ check('function', 'template<T v> void f()', idsTemplate)
+ # with '=', assignment-expression
+ check('member', 'T v = 42', idsMember)
+ check('function', 'void f(T v = 42)', idsFunction)
+ check('function', 'template<T v = 42> void f()', idsTemplate)
+ # with '=', braced-init
+ check('member', 'T v = {}', idsMember)
+ check('function', 'void f(T v = {})', idsFunction)
+ check('function', 'template<T v = {}> void f()', idsTemplate)
+ check('member', 'T v = {42, 42, 42}', idsMember)
+ check('function', 'void f(T v = {42, 42, 42})', idsFunction)
+ check('function', 'template<T v = {42, 42, 42}> void f()', idsTemplate)
+ check('member', 'T v = {42, 42, 42,}', idsMember)
+ check('function', 'void f(T v = {42, 42, 42,})', idsFunction)
+ check('function', 'template<T v = {42, 42, 42,}> void f()', idsTemplate)
+ check('member', 'T v = {42, 42, args...}', idsMember)
+ check('function', 'void f(T v = {42, 42, args...})', idsFunction)
+ check('function', 'template<T v = {42, 42, args...}> void f()', idsTemplate)
+ # without '=', braced-init
+ check('member', 'T v{}', idsMember)
+ check('member', 'T v{42, 42, 42}', idsMember)
+ check('member', 'T v{42, 42, 42,}', idsMember)
+ check('member', 'T v{42, 42, args...}', idsMember)
+ # other
+ check('member', 'T v = T{}', idsMember)
+
+
+def test_domain_cpp_ast_attributes():
+ # style: C++
+ check('member', '[[]] int f', {1: 'f__i', 2: '1f'})
+ check('member', '[ [ ] ] int f', {1: 'f__i', 2: '1f'},
+ # this will fail when the proper grammar is implemented
+ output='[[ ]] int f')
+ check('member', '[[a]] int f', {1: 'f__i', 2: '1f'})
+ # style: GNU
+ check('member', '__attribute__(()) int f', {1: 'f__i', 2: '1f'})
+ check('member', '__attribute__((a)) int f', {1: 'f__i', 2: '1f'})
+ check('member', '__attribute__((a, b)) int f', {1: 'f__i', 2: '1f'})
+ check('member', '__attribute__((optimize(3))) int f', {1: 'f__i', 2: '1f'})
+ check('member', '__attribute__((format(printf, 1, 2))) int f', {1: 'f__i', 2: '1f'})
+ # style: user-defined id
+ check('member', 'id_attr int f', {1: 'f__i', 2: '1f'})
+ # style: user-defined paren
+ check('member', 'paren_attr() int f', {1: 'f__i', 2: '1f'})
+ check('member', 'paren_attr(a) int f', {1: 'f__i', 2: '1f'})
+ check('member', 'paren_attr("") int f', {1: 'f__i', 2: '1f'})
+ check('member', 'paren_attr(()[{}][]{}) int f', {1: 'f__i', 2: '1f'})
+ with pytest.raises(DefinitionError):
+ parse('member', 'paren_attr(() int f')
+ with pytest.raises(DefinitionError):
+ parse('member', 'paren_attr([) int f')
+ with pytest.raises(DefinitionError):
+ parse('member', 'paren_attr({) int f')
+ with pytest.raises(DefinitionError):
+ parse('member', 'paren_attr([)]) int f')
+ with pytest.raises(DefinitionError):
+ parse('member', 'paren_attr((])) int f')
+ with pytest.raises(DefinitionError):
+ parse('member', 'paren_attr({]}) int f')
+
+ # position: decl specs
+ check('function', 'static inline __attribute__(()) void f()',
+ {1: 'f', 2: '1fv'},
+ output='__attribute__(()) static inline void f()')
+ check('function', '[[attr1]] [[attr2]] void f()', {1: 'f', 2: '1fv'})
+ # position: declarator
+ check('member', 'int *[[attr1]] [[attr2]] i', {1: 'i__iP', 2: '1i'})
+ check('member', 'int *const [[attr1]] [[attr2]] volatile i', {1: 'i__iPVC', 2: '1i'},
+ output='int *[[attr1]] [[attr2]] volatile const i')
+ check('member', 'int &[[attr1]] [[attr2]] i', {1: 'i__iR', 2: '1i'})
+ check('member', 'int *[[attr1]] [[attr2]] *i', {1: 'i__iPP', 2: '1i'})
+ # position: parameters and qualifiers
+ check('function', 'void f() [[attr1]] [[attr2]]', {1: 'f', 2: '1fv'})
+
+ # position: class, union, enum
+ check('class', '{key}[[attr1]] [[attr2]] Foo', {1: 'Foo', 2: '3Foo'}, key='class')
+ check('union', '{key}[[attr1]] [[attr2]] Foo', {2: '3Foo'}, key='union')
+ check('enum', '{key}[[attr1]] [[attr2]] Foo', {2: '3Foo'}, key='enum')
+ # position: enumerator
+ check('enumerator', '{key}Foo [[attr1]] [[attr2]]', {2: '3Foo'})
+ check('enumerator', '{key}Foo [[attr1]] [[attr2]] = 42', {2: '3Foo'})
+
+
+def test_domain_cpp_ast_xref_parsing():
+ def check(target):
+ class Config:
+ cpp_id_attributes = ["id_attr"]
+ cpp_paren_attributes = ["paren_attr"]
+ parser = DefinitionParser(target, location=None,
+ config=Config())
+ ast, isShorthand = parser.parse_xref_object()
+ parser.assert_end()
+ check('f')
+ check('f()')
+ check('void f()')
+ check('T f()')
+
+
+@pytest.mark.parametrize(
+ ("param", "is_pack"),
+ [('typename', False),
+ ('typename T', False),
+ ('typename...', True),
+ ('typename... T', True),
+ ('int', False),
+ ('int N', False),
+ ('int* N', False),
+ ('int& N', False),
+ ('int&... N', True),
+ ('int*... N', True),
+ ('int...', True),
+ ('int... N', True),
+ ('auto', False),
+ ('auto...', True),
+ ('int X::*', False),
+ ('int X::*...', True),
+ ('int (X::*)(bool)', False),
+ ('int (X::*x)(bool)', False),
+ ('int (X::*)(bool)...', True),
+ ('template<typename> class', False),
+ ('template<typename> class...', True),
+ ])
+def test_domain_cpp_template_parameters_is_pack(param: str, is_pack: bool):
+ def parse_template_parameter(param: str):
+ ast = parse('type', 'template<' + param + '> X')
+ return ast.templatePrefix.templates[0].params[0]
+ ast = parse_template_parameter(param)
+ assert ast.isPack == is_pack
+
+
+# def test_print():
+# # used for getting all the ids out for checking
+# for a in ids:
+# print(a)
+# raise DefinitionError
+
+
+def filter_warnings(warning, file):
+ lines = warning.getvalue().split("\n")
+ res = [l for l in lines if "domain-cpp" in l and f"{file}.rst" in l and
+ "WARNING: document isn't included in any toctree" not in l]
+ print(f"Filtered warnings for file '{file}':")
+ for w in res:
+ print(w)
+ return res
+
+
+@pytest.mark.sphinx(testroot='domain-cpp', confoverrides={'nitpicky': True})
+def test_domain_cpp_build_multi_decl_lookup(app, status, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "lookup-key-overload")
+ assert len(ws) == 0
+
+ ws = filter_warnings(warning, "multi-decl-lookup")
+ assert len(ws) == 0
+
+
+@pytest.mark.sphinx(testroot='domain-cpp', confoverrides={'nitpicky': True})
+def test_domain_cpp_build_warn_template_param_qualified_name(app, status, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "warn-template-param-qualified-name")
+ assert len(ws) == 2
+ assert "WARNING: cpp:type reference target not found: T::typeWarn" in ws[0]
+ assert "WARNING: cpp:type reference target not found: T::U::typeWarn" in ws[1]
+
+
+@pytest.mark.sphinx(testroot='domain-cpp', confoverrides={'nitpicky': True})
+def test_domain_cpp_build_backslash_ok_true(app, status, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "backslash")
+ assert len(ws) == 0
+
+
+@pytest.mark.sphinx(testroot='domain-cpp', confoverrides={'nitpicky': True})
+def test_domain_cpp_build_semicolon(app, status, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "semicolon")
+ assert len(ws) == 0
+
+
+@pytest.mark.sphinx(testroot='domain-cpp',
+ confoverrides={'nitpicky': True, 'strip_signature_backslash': True})
+def test_domain_cpp_build_backslash_ok_false(app, status, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "backslash")
+ assert len(ws) == 1
+ assert "WARNING: Parsing of expression failed. Using fallback parser." in ws[0]
+
+
+@pytest.mark.sphinx(testroot='domain-cpp', confoverrides={'nitpicky': True})
+def test_domain_cpp_build_anon_dup_decl(app, status, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "anon-dup-decl")
+ assert len(ws) == 2
+ assert "WARNING: cpp:identifier reference target not found: @a" in ws[0]
+ assert "WARNING: cpp:identifier reference target not found: @b" in ws[1]
+
+
+@pytest.mark.sphinx(testroot='domain-cpp')
+def test_domain_cpp_build_misuse_of_roles(app, status, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "roles-targets-ok")
+ assert len(ws) == 0
+
+ ws = filter_warnings(warning, "roles-targets-warn")
+ # the roles that should be able to generate warnings:
+ allRoles = ['class', 'struct', 'union', 'func', 'member', 'var', 'type', 'concept', 'enum', 'enumerator']
+ ok = [ # targetType, okRoles
+ ('class', ['class', 'struct', 'type']),
+ ('union', ['union', 'type']),
+ ('func', ['func', 'type']),
+ ('member', ['member', 'var']),
+ ('type', ['type']),
+ ('concept', ['concept']),
+ ('enum', ['type', 'enum']),
+ ('enumerator', ['enumerator']),
+ ('functionParam', ['member', 'var']),
+ ('templateParam', ['class', 'struct', 'union', 'member', 'var', 'type']),
+ ]
+ warn = []
+ for targetType, roles in ok:
+ txtTargetType = "function" if targetType == "func" else targetType
+ for r in allRoles:
+ if r not in roles:
+ warn.append(f"WARNING: cpp:{r} targets a {txtTargetType} (")
+ if targetType == 'templateParam':
+ warn.append(f"WARNING: cpp:{r} targets a {txtTargetType} (")
+ warn.append(f"WARNING: cpp:{r} targets a {txtTargetType} (")
+ warn = sorted(warn)
+ for w in ws:
+ assert "targets a" in w
+ ws = [w[w.index("WARNING:"):] for w in ws]
+ ws = sorted(ws)
+ print("Expected warnings:")
+ for w in warn:
+ print(w)
+ print("Actual warnings:")
+ for w in ws:
+ print(w)
+
+ for i in range(min(len(warn), len(ws))):
+ assert ws[i].startswith(warn[i])
+
+ assert len(ws) == len(warn)
+
+
+@pytest.mark.sphinx(testroot='domain-cpp', confoverrides={'add_function_parentheses': True})
+def test_domain_cpp_build_with_add_function_parentheses_is_True(app, status, warning):
+ app.build(force_all=True)
+
+ def check(spec, text, file):
+ pattern = '<li><p>%s<a .*?><code .*?><span .*?>%s</span></code></a></p></li>' % spec
+ res = re.search(pattern, text)
+ if not res:
+ print(f"Pattern\n\t{pattern}\nnot found in {file}")
+ raise AssertionError
+ rolePatterns = [
+ ('', 'Sphinx'),
+ ('', 'Sphinx::version'),
+ ('', 'version'),
+ ('', 'List'),
+ ('', 'MyEnum'),
+ ]
+ parenPatterns = [
+ ('ref function without parens ', r'paren_1\(\)'),
+ ('ref function with parens ', r'paren_2\(\)'),
+ ('ref function without parens, explicit title ', 'paren_3_title'),
+ ('ref function with parens, explicit title ', 'paren_4_title'),
+ ('ref op call without parens ', r'paren_5::operator\(\)\(\)'),
+ ('ref op call with parens ', r'paren_6::operator\(\)\(\)'),
+ ('ref op call without parens, explicit title ', 'paren_7_title'),
+ ('ref op call with parens, explicit title ', 'paren_8_title'),
+ ]
+
+ f = 'roles.html'
+ t = (app.outdir / f).read_text(encoding='utf8')
+ for s in rolePatterns:
+ check(s, t, f)
+ for s in parenPatterns:
+ check(s, t, f)
+
+ f = 'any-role.html'
+ t = (app.outdir / f).read_text(encoding='utf8')
+ for s in parenPatterns:
+ check(s, t, f)
+
+
+@pytest.mark.sphinx(testroot='domain-cpp', confoverrides={'add_function_parentheses': False})
+def test_domain_cpp_build_with_add_function_parentheses_is_False(app, status, warning):
+ app.build(force_all=True)
+
+ def check(spec, text, file):
+ pattern = '<li><p>%s<a .*?><code .*?><span .*?>%s</span></code></a></p></li>' % spec
+ res = re.search(pattern, text)
+ if not res:
+ print(f"Pattern\n\t{pattern}\nnot found in {file}")
+ raise AssertionError
+ rolePatterns = [
+ ('', 'Sphinx'),
+ ('', 'Sphinx::version'),
+ ('', 'version'),
+ ('', 'List'),
+ ('', 'MyEnum'),
+ ]
+ parenPatterns = [
+ ('ref function without parens ', 'paren_1'),
+ ('ref function with parens ', 'paren_2'),
+ ('ref function without parens, explicit title ', 'paren_3_title'),
+ ('ref function with parens, explicit title ', 'paren_4_title'),
+ ('ref op call without parens ', r'paren_5::operator\(\)'),
+ ('ref op call with parens ', r'paren_6::operator\(\)'),
+ ('ref op call without parens, explicit title ', 'paren_7_title'),
+ ('ref op call with parens, explicit title ', 'paren_8_title'),
+ ]
+
+ f = 'roles.html'
+ t = (app.outdir / f).read_text(encoding='utf8')
+ for s in rolePatterns:
+ check(s, t, f)
+ for s in parenPatterns:
+ check(s, t, f)
+
+ f = 'any-role.html'
+ t = (app.outdir / f).read_text(encoding='utf8')
+ for s in parenPatterns:
+ check(s, t, f)
+
+
+@pytest.mark.sphinx(testroot='domain-cpp')
+def test_domain_cpp_build_xref_consistency(app, status, warning):
+ app.build(force_all=True)
+
+ test = 'xref_consistency.html'
+ output = (app.outdir / test).read_text(encoding='utf8')
+
+ def classes(role, tag):
+ pattern = (fr'{role}-role:.*?'
+ fr'<(?P<tag>{tag}) .*?class=["\'](?P<classes>.*?)["\'].*?>'
+ r'.*'
+ r'</(?P=tag)>')
+ result = re.search(pattern, output)
+ expect = f'''\
+Pattern for role `{role}` with tag `{tag}`
+\t{pattern}
+not found in `{test}`
+'''
+ assert result, expect
+ return set(result.group('classes').split())
+
+ class RoleClasses:
+ """Collect the classes from the layout that was generated for a given role."""
+
+ def __init__(self, role, root, contents):
+ self.name = role
+ self.classes = classes(role, root)
+ self.content_classes = {}
+ for tag in contents:
+ self.content_classes[tag] = classes(role, tag)
+
+ # not actually used as a reference point
+ # code_role = RoleClasses('code', 'code', [])
+ any_role = RoleClasses('any', 'a', ['code'])
+ cpp_any_role = RoleClasses('cpp-any', 'a', ['code'])
+ # NYI: consistent looks
+ # texpr_role = RoleClasses('cpp-texpr', 'span', ['a', 'code'])
+ expr_role = RoleClasses('cpp-expr', 'span', ['a'])
+ texpr_role = RoleClasses('cpp-texpr', 'span', ['a', 'span'])
+
+ # XRefRole-style classes
+
+ # any and cpp:any do not put these classes at the root
+
+ # n.b. the generic any machinery finds the specific 'cpp-class' object type
+ expect = 'any uses XRefRole classes'
+ assert {'xref', 'any', 'cpp', 'cpp-class'} <= any_role.content_classes['code'], expect
+
+ expect = 'cpp:any uses XRefRole classes'
+ assert {'xref', 'cpp-any', 'cpp'} <= cpp_any_role.content_classes['code'], expect
+
+ for role in (expr_role, texpr_role):
+ name = role.name
+ expect = f'`{name}` puts the domain and role classes at its root'
+ assert {'sig', 'sig-inline', 'cpp', name} <= role.classes, expect
+
+ # reference classes
+
+ expect = 'the xref roles use the same reference classes'
+ assert any_role.classes == cpp_any_role.classes, expect
+ assert any_role.classes == expr_role.content_classes['a'], expect
+ assert any_role.classes == texpr_role.content_classes['a'], expect
+
+
+@pytest.mark.sphinx(testroot='domain-cpp', confoverrides={'nitpicky': True})
+def test_domain_cpp_build_field_role(app, status, warning):
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "field-role")
+ assert len(ws) == 0
+
+
+@pytest.mark.sphinx(testroot='domain-cpp', confoverrides={'nitpicky': True})
+def test_domain_cpp_build_operator_lookup(app, status, warning):
+ app.builder.build_all()
+ ws = filter_warnings(warning, "operator-lookup")
+ assert len(ws) == 5
+ # TODO: the first one should not happen
+ assert ":10: WARNING: cpp:identifier reference target not found: _lit" in ws[0]
+ assert ":18: WARNING: cpp:func reference target not found: int h" in ws[1]
+ assert ":19: WARNING: cpp:func reference target not found: int operator+(bool, bool)" in ws[2]
+ assert ":20: WARNING: cpp:func reference target not found: int operator\"\"_udl" in ws[3]
+ assert ":21: WARNING: cpp:func reference target not found: operator bool" in ws[4]
+
+
+@pytest.mark.sphinx(testroot='domain-cpp-intersphinx', confoverrides={'nitpicky': True})
+def test_domain_cpp_build_intersphinx(tmp_path, app, status, warning):
+ origSource = """\
+.. cpp:class:: _class
+.. cpp:struct:: _struct
+.. cpp:union:: _union
+.. cpp:function:: void _function()
+.. cpp:member:: int _member
+.. cpp:var:: int _var
+.. cpp:type:: _type
+.. cpp:concept:: template<typename T> _concept
+.. cpp:enum:: _enum
+
+ .. cpp:enumerator:: _enumerator
+
+.. cpp:enum-struct:: _enumStruct
+
+ .. cpp:enumerator:: _scopedEnumerator
+
+.. cpp:enum-class:: _enumClass
+.. cpp:function:: void _functionParam(int param)
+.. cpp:function:: template<typename TParam> void _templateParam()
+""" # NoQA: F841
+ inv_file = tmp_path / 'inventory'
+ inv_file.write_bytes(b'''\
+# Sphinx inventory version 2
+# Project: C Intersphinx Test
+# Version:
+# The remainder of this file is compressed using zlib.
+''' + zlib.compress(b'''\
+_class cpp:class 1 index.html#_CPPv46$ -
+_concept cpp:concept 1 index.html#_CPPv4I0E8$ -
+_concept::T cpp:templateParam 1 index.html#_CPPv4I0E8_concept -
+_enum cpp:enum 1 index.html#_CPPv45$ -
+_enum::_enumerator cpp:enumerator 1 index.html#_CPPv4N5_enum11_enumeratorE -
+_enumClass cpp:enum 1 index.html#_CPPv410$ -
+_enumStruct cpp:enum 1 index.html#_CPPv411$ -
+_enumStruct::_scopedEnumerator cpp:enumerator 1 index.html#_CPPv4N11_enumStruct17_scopedEnumeratorE -
+_enumerator cpp:enumerator 1 index.html#_CPPv4N5_enum11_enumeratorE -
+_function cpp:function 1 index.html#_CPPv49_functionv -
+_functionParam cpp:function 1 index.html#_CPPv414_functionParami -
+_functionParam::param cpp:functionParam 1 index.html#_CPPv414_functionParami -
+_member cpp:member 1 index.html#_CPPv47$ -
+_struct cpp:class 1 index.html#_CPPv47$ -
+_templateParam cpp:function 1 index.html#_CPPv4I0E14_templateParamvv -
+_templateParam::TParam cpp:templateParam 1 index.html#_CPPv4I0E14_templateParamvv -
+_type cpp:type 1 index.html#_CPPv45$ -
+_union cpp:union 1 index.html#_CPPv46$ -
+_var cpp:member 1 index.html#_CPPv44$ -
+''')) # NoQA: W291
+ app.config.intersphinx_mapping = {
+ 'https://localhost/intersphinx/cpp/': str(inv_file),
+ }
+ app.config.intersphinx_cache_limit = 0
+ # load the inventory and check if it's done correctly
+ normalize_intersphinx_mapping(app, app.config)
+ load_mappings(app)
+
+ app.build(force_all=True)
+ ws = filter_warnings(warning, "index")
+ assert len(ws) == 0
+
+
+def test_domain_cpp_parse_no_index_entry(app):
+ text = (".. cpp:function:: void f()\n"
+ ".. cpp:function:: void g()\n"
+ " :no-index-entry:\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index, desc, addnodes.index, desc))
+ assert_node(doctree[0], addnodes.index, entries=[('single', 'f (C++ function)', '_CPPv41fv', '', None)])
+ assert_node(doctree[2], addnodes.index, entries=[])
+
+
+def test_domain_cpp_parse_mix_decl_duplicate(app, warning):
+ # Issue 8270
+ text = (".. cpp:struct:: A\n"
+ ".. cpp:function:: void A()\n"
+ ".. cpp:struct:: A\n")
+ restructuredtext.parse(app, text)
+ ws = warning.getvalue().split("\n")
+ assert len(ws) == 5
+ assert "index.rst:2: WARNING: Duplicate C++ declaration, also defined at index:1." in ws[0]
+ assert "Declaration is '.. cpp:function:: void A()'." in ws[1]
+ assert "index.rst:3: WARNING: Duplicate C++ declaration, also defined at index:1." in ws[2]
+ assert "Declaration is '.. cpp:struct:: A'." in ws[3]
+ assert ws[4] == ""
+
+
+# For some reason, using the default testroot of "root" leads to the contents of
+# `test-root/objects.txt` polluting the symbol table depending on the test
+# execution order. Using a testroot of "config" seems to avoid that problem.
+@pytest.mark.sphinx(testroot='config')
+def test_domain_cpp_normalize_unspecialized_template_args(make_app, app_params):
+ args, kwargs = app_params
+
+ text1 = (".. cpp:class:: template <typename T> A\n")
+ text2 = (".. cpp:class:: template <typename T> template <typename U> A<T>::B\n")
+
+ app1 = make_app(*args, **kwargs)
+ restructuredtext.parse(app=app1, text=text1, docname='text1')
+ root1 = app1.env.domaindata['cpp']['root_symbol']
+
+ assert root1.dump(1) == (
+ ' ::\n'
+ ' template<typename T> \n'
+ ' A: {class} template<typename T> A\t(text1)\n'
+ ' T: {templateParam} typename T\t(text1)\n'
+ )
+
+ app2 = make_app(*args, **kwargs)
+ restructuredtext.parse(app=app2, text=text2, docname='text2')
+ root2 = app2.env.domaindata['cpp']['root_symbol']
+
+ assert root2.dump(1) == (
+ ' ::\n'
+ ' template<typename T> \n'
+ ' A\n'
+ ' T\n'
+ ' template<typename U> \n'
+ ' B: {class} template<typename T> template<typename U> A<T>::B\t(text2)\n'
+ ' U: {templateParam} typename U\t(text2)\n'
+ )
+
+ root2.merge_with(root1, ['text1'], app2.env)
+
+ assert root2.dump(1) == (
+ ' ::\n'
+ ' template<typename T> \n'
+ ' A: {class} template<typename T> A\t(text1)\n'
+ ' T: {templateParam} typename T\t(text1)\n'
+ ' template<typename U> \n'
+ ' B: {class} template<typename T> template<typename U> A<T>::B\t(text2)\n'
+ ' U: {templateParam} typename U\t(text2)\n'
+ )
+ warning = app2._warning.getvalue()
+ assert 'Internal C++ domain error during symbol merging' not in warning
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'cpp_maximum_signature_line_length': len('str hello(str name)'),
+})
+def test_cpp_function_signature_with_cpp_maximum_signature_line_length_equal(app):
+ text = '.. cpp:function:: str hello(str name)'
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, 'hello']],
+ desc_parameterlist,
+ )],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype='function',
+ domain='cpp', objtype='function', no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, 'str']],
+ desc_sig_space,
+ [desc_sig_name, 'name'],
+ )])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'cpp_maximum_signature_line_length': len('str hello(str name)'),
+})
+def test_cpp_function_signature_with_cpp_maximum_signature_line_length_force_single(app):
+ text = ('.. cpp:function:: str hello(str names)\n'
+ ' :single-line-parameter-list:')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, 'hello']],
+ desc_parameterlist,
+ )],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype='function',
+ domain='cpp', objtype='function', no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, 'str']],
+ desc_sig_space,
+ [desc_sig_name, 'names']),
+ ])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'cpp_maximum_signature_line_length': len("str hello(str name)"),
+})
+def test_cpp_function_signature_with_cpp_maximum_signature_line_length_break(app):
+ text = '.. cpp:function:: str hello(str names)'
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, 'hello']],
+ desc_parameterlist,
+ )],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype='function',
+ domain='cpp', objtype='function', no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, 'str']],
+ desc_sig_space,
+ [desc_sig_name, 'names']),
+ ])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=True)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'maximum_signature_line_length': len('str hello(str name)'),
+})
+def test_cpp_function_signature_with_maximum_signature_line_length_equal(app):
+ text = '.. cpp:function:: str hello(str name)'
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, 'hello']],
+ desc_parameterlist,
+ )],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype='function',
+ domain='cpp', objtype='function', no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, 'str']],
+ desc_sig_space,
+ [desc_sig_name, 'name'],
+ )])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'maximum_signature_line_length': len('str hello(str name)'),
+})
+def test_cpp_function_signature_with_maximum_signature_line_length_force_single(app):
+ text = ('.. cpp:function:: str hello(str names)\n'
+ ' :single-line-parameter-list:')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, 'hello']],
+ desc_parameterlist,
+ )],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype='function',
+ domain='cpp', objtype='function', no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, 'str']],
+ desc_sig_space,
+ [desc_sig_name, 'names']),
+ ])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'maximum_signature_line_length': len("str hello(str name)"),
+})
+def test_cpp_function_signature_with_maximum_signature_line_length_break(app):
+ text = '.. cpp:function:: str hello(str names)'
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_signature_line, (
+ pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, 'hello']],
+ desc_parameterlist,
+ )],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype='function',
+ domain='cpp', objtype='function', no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, 'str']],
+ desc_sig_space,
+ [desc_sig_name, 'names']),
+ ])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=True)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'cpp_maximum_signature_line_length': len('str hello(str name)'),
+ 'maximum_signature_line_length': 1,
+})
+def test_cpp_maximum_signature_line_length_overrides_global(app):
+ text = '.. cpp:function:: str hello(str name)'
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, ([desc_signature, ([desc_signature_line, (pending_xref,
+ desc_sig_space,
+ [desc_name, [desc_sig_name, "hello"]],
+ desc_parameterlist)])],
+ desc_content)],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype='function',
+ domain='cpp', objtype='function', no_index=False)
+ assert_node(doctree[1][0][0][3], [desc_parameterlist, desc_parameter, (
+ [pending_xref, [desc_sig_name, 'str']],
+ desc_sig_space,
+ [desc_sig_name, 'name'],
+ )])
+ assert_node(doctree[1][0][0][3], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', testroot='domain-cpp-cpp_maximum_signature_line_length')
+def test_domain_cpp_cpp_maximum_signature_line_length_in_html(app, status, warning):
+ app.build()
+ content = (app.outdir / 'index.html').read_text(encoding='utf-8')
+ expected = """\
+
+<dl>
+<dd>\
+<span class="n"><span class="pre">str</span></span>\
+<span class="w"> </span>\
+<span class="n sig-param"><span class="pre">name</span></span>,\
+</dd>
+</dl>
+
+<span class="sig-paren">)</span>\
+<a class="headerlink" href=\
+"""
+ assert expected in content
+
+
+@pytest.mark.sphinx(
+ 'text', testroot='domain-cpp-cpp_maximum_signature_line_length',
+)
+def test_domain_cpp_cpp_maximum_signature_line_length_in_text(app, status, warning):
+ app.build()
+ content = (app.outdir / 'index.txt').read_text(encoding='utf8')
+ param_line_fmt = STDINDENT * " " + "{}\n"
+
+ expected_parameter_list_hello = "(\n{})".format(param_line_fmt.format("str name,"))
+
+ assert expected_parameter_list_hello in content
diff --git a/tests/test_domains/test_domain_js.py b/tests/test_domains/test_domain_js.py
new file mode 100644
index 0000000..995a440
--- /dev/null
+++ b/tests/test_domains/test_domain_js.py
@@ -0,0 +1,505 @@
+"""Tests the JavaScript Domain"""
+
+from unittest.mock import Mock
+
+import docutils.utils
+import pytest
+from docutils import nodes
+
+from sphinx import addnodes
+from sphinx.addnodes import (
+ desc,
+ desc_annotation,
+ desc_content,
+ desc_name,
+ desc_parameter,
+ desc_parameterlist,
+ desc_sig_keyword,
+ desc_sig_name,
+ desc_sig_space,
+ desc_signature,
+)
+from sphinx.domains.javascript import JavaScriptDomain
+from sphinx.testing import restructuredtext
+from sphinx.testing.util import assert_node
+from sphinx.writers.text import STDINDENT
+
+
+@pytest.mark.sphinx('dummy', testroot='domain-js')
+def test_domain_js_xrefs(app, status, warning):
+ """Domain objects have correct prefixes when looking up xrefs"""
+ app.build(force_all=True)
+
+ def assert_refnode(node, mod_name, prefix, target, reftype=None,
+ domain='js'):
+ attributes = {
+ 'refdomain': domain,
+ 'reftarget': target,
+ }
+ if reftype is not None:
+ attributes['reftype'] = reftype
+ if mod_name is not False:
+ attributes['js:module'] = mod_name
+ if prefix is not False:
+ attributes['js:object'] = prefix
+ assert_node(node, **attributes)
+
+ doctree = app.env.get_doctree('roles')
+ refnodes = list(doctree.findall(addnodes.pending_xref))
+ assert_refnode(refnodes[0], None, None, 'TopLevel', 'class')
+ assert_refnode(refnodes[1], None, None, 'top_level', 'func')
+ assert_refnode(refnodes[2], None, 'NestedParentA', 'child_1', 'func')
+ assert_refnode(refnodes[3], None, 'NestedParentA', 'NestedChildA.subchild_2', 'func')
+ assert_refnode(refnodes[4], None, 'NestedParentA', 'child_2', 'func')
+ assert_refnode(refnodes[5], False, 'NestedParentA', 'any_child', domain='')
+ assert_refnode(refnodes[6], None, 'NestedParentA', 'NestedChildA', 'class')
+ assert_refnode(refnodes[7], None, 'NestedParentA.NestedChildA', 'subchild_2', 'func')
+ assert_refnode(refnodes[8], None, 'NestedParentA.NestedChildA',
+ 'NestedParentA.child_1', 'func')
+ assert_refnode(refnodes[9], None, 'NestedParentA', 'NestedChildA.subchild_1', 'func')
+ assert_refnode(refnodes[10], None, 'NestedParentB', 'child_1', 'func')
+ assert_refnode(refnodes[11], None, 'NestedParentB', 'NestedParentB', 'class')
+ assert_refnode(refnodes[12], None, None, 'NestedParentA.NestedChildA', 'class')
+ assert len(refnodes) == 13
+
+ doctree = app.env.get_doctree('module')
+ refnodes = list(doctree.findall(addnodes.pending_xref))
+ assert_refnode(refnodes[0], 'module_a.submodule', None, 'ModTopLevel',
+ 'class')
+ assert_refnode(refnodes[1], 'module_a.submodule', 'ModTopLevel',
+ 'mod_child_1', 'meth')
+ assert_refnode(refnodes[2], 'module_a.submodule', 'ModTopLevel',
+ 'ModTopLevel.mod_child_1', 'meth')
+ assert_refnode(refnodes[3], 'module_a.submodule', 'ModTopLevel',
+ 'mod_child_2', 'meth')
+ assert_refnode(refnodes[4], 'module_a.submodule', 'ModTopLevel',
+ 'module_a.submodule.ModTopLevel.mod_child_1', 'meth')
+ assert_refnode(refnodes[5], 'module_b.submodule', None, 'ModTopLevel',
+ 'class')
+ assert_refnode(refnodes[6], 'module_b.submodule', 'ModTopLevel',
+ 'module_a.submodule', 'mod')
+ assert len(refnodes) == 7
+
+
+@pytest.mark.sphinx('dummy', testroot='domain-js')
+def test_domain_js_objects(app, status, warning):
+ app.build(force_all=True)
+
+ modules = app.env.domains['js'].data['modules']
+ objects = app.env.domains['js'].data['objects']
+
+ assert 'module_a.submodule' in modules
+ assert 'module_a.submodule' in objects
+ assert 'module_b.submodule' in modules
+ assert 'module_b.submodule' in objects
+
+ assert objects['module_a.submodule.ModTopLevel'][2] == 'class'
+ assert objects['module_a.submodule.ModTopLevel.mod_child_1'][2] == 'method'
+ assert objects['module_a.submodule.ModTopLevel.mod_child_2'][2] == 'method'
+ assert objects['module_b.submodule.ModTopLevel'][2] == 'class'
+
+ assert objects['TopLevel'][2] == 'class'
+ assert objects['top_level'][2] == 'function'
+ assert objects['NestedParentA'][2] == 'class'
+ assert objects['NestedParentA.child_1'][2] == 'function'
+ assert objects['NestedParentA.any_child'][2] == 'function'
+ assert objects['NestedParentA.NestedChildA'][2] == 'class'
+ assert objects['NestedParentA.NestedChildA.subchild_1'][2] == 'function'
+ assert objects['NestedParentA.NestedChildA.subchild_2'][2] == 'function'
+ assert objects['NestedParentA.child_2'][2] == 'function'
+ assert objects['NestedParentB'][2] == 'class'
+ assert objects['NestedParentB.child_1'][2] == 'function'
+
+
+@pytest.mark.sphinx('dummy', testroot='domain-js')
+def test_domain_js_find_obj(app, status, warning):
+
+ def find_obj(mod_name, prefix, obj_name, obj_type, searchmode=0):
+ return app.env.domains['js'].find_obj(
+ app.env, mod_name, prefix, obj_name, obj_type, searchmode)
+
+ app.build(force_all=True)
+
+ assert (find_obj(None, None, 'NONEXISTANT', 'class') == (None, None))
+ assert (find_obj(None, None, 'NestedParentA', 'class') ==
+ ('NestedParentA', ('roles', 'NestedParentA', 'class')))
+ assert (find_obj(None, None, 'NestedParentA.NestedChildA', 'class') ==
+ ('NestedParentA.NestedChildA',
+ ('roles', 'NestedParentA.NestedChildA', 'class')))
+ assert (find_obj(None, 'NestedParentA', 'NestedChildA', 'class') ==
+ ('NestedParentA.NestedChildA',
+ ('roles', 'NestedParentA.NestedChildA', 'class')))
+ assert (find_obj(None, None, 'NestedParentA.NestedChildA.subchild_1', 'func') ==
+ ('NestedParentA.NestedChildA.subchild_1',
+ ('roles', 'NestedParentA.NestedChildA.subchild_1', 'function')))
+ assert (find_obj(None, 'NestedParentA', 'NestedChildA.subchild_1', 'func') ==
+ ('NestedParentA.NestedChildA.subchild_1',
+ ('roles', 'NestedParentA.NestedChildA.subchild_1', 'function')))
+ assert (find_obj(None, 'NestedParentA.NestedChildA', 'subchild_1', 'func') ==
+ ('NestedParentA.NestedChildA.subchild_1',
+ ('roles', 'NestedParentA.NestedChildA.subchild_1', 'function')))
+ assert (find_obj('module_a.submodule', 'ModTopLevel', 'mod_child_2', 'meth') ==
+ ('module_a.submodule.ModTopLevel.mod_child_2',
+ ('module', 'module_a.submodule.ModTopLevel.mod_child_2', 'method')))
+ assert (find_obj('module_b.submodule', 'ModTopLevel', 'module_a.submodule', 'mod') ==
+ ('module_a.submodule',
+ ('module', 'module-module_a.submodule', 'module')))
+
+
+def test_get_full_qualified_name():
+ env = Mock(domaindata={})
+ domain = JavaScriptDomain(env)
+
+ # non-js references
+ node = nodes.reference()
+ assert domain.get_full_qualified_name(node) is None
+
+ # simple reference
+ node = nodes.reference(reftarget='func')
+ assert domain.get_full_qualified_name(node) == 'func'
+
+ # with js:module context
+ kwargs = {'js:module': 'module1'}
+ node = nodes.reference(reftarget='func', **kwargs)
+ assert domain.get_full_qualified_name(node) == 'module1.func'
+
+ # with js:object context
+ kwargs = {'js:object': 'Class'}
+ node = nodes.reference(reftarget='func', **kwargs)
+ assert domain.get_full_qualified_name(node) == 'Class.func'
+
+ # with both js:module and js:object context
+ kwargs = {'js:module': 'module1', 'js:object': 'Class'}
+ node = nodes.reference(reftarget='func', **kwargs)
+ assert domain.get_full_qualified_name(node) == 'module1.Class.func'
+
+
+def test_js_module(app):
+ text = ".. js:module:: sphinx"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ nodes.target))
+ assert_node(doctree[0], addnodes.index,
+ entries=[("single", "sphinx (module)", "module-sphinx", "", None)])
+ assert_node(doctree[1], nodes.target, ids=["module-sphinx"])
+
+
+def test_js_function(app):
+ text = ".. js:function:: sum(a, b)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, ([desc_sig_name, "sum"])],
+ desc_parameterlist)],
+ [desc_content, ()])]))
+ assert_node(doctree[1][0][1], [desc_parameterlist, ([desc_parameter, ([desc_sig_name, "a"])],
+ [desc_parameter, ([desc_sig_name, "b"])])])
+ assert_node(doctree[0], addnodes.index,
+ entries=[("single", "sum() (built-in function)", "sum", "", None)])
+ assert_node(doctree[1], addnodes.desc, domain="js", objtype="function", no_index=False)
+
+
+def test_js_class(app):
+ text = ".. js:class:: Application"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_annotation, ([desc_sig_keyword, 'class'],
+ desc_sig_space)],
+ [desc_name, ([desc_sig_name, "Application"])],
+ [desc_parameterlist, ()])],
+ [desc_content, ()])]))
+ assert_node(doctree[0], addnodes.index,
+ entries=[("single", "Application() (class)", "Application", "", None)])
+ assert_node(doctree[1], addnodes.desc, domain="js", objtype="class", no_index=False)
+
+
+def test_js_data(app):
+ text = ".. js:data:: name"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, ([desc_sig_name, "name"])])],
+ [desc_content, ()])]))
+ assert_node(doctree[0], addnodes.index,
+ entries=[("single", "name (global variable or constant)", "name", "", None)])
+ assert_node(doctree[1], addnodes.desc, domain="js", objtype="data", no_index=False)
+
+
+def test_no_index_entry(app):
+ text = (".. js:function:: f()\n"
+ ".. js:function:: g()\n"
+ " :no-index-entry:\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index, desc, addnodes.index, desc))
+ assert_node(doctree[0], addnodes.index, entries=[('single', 'f() (built-in function)', 'f', '', None)])
+ assert_node(doctree[2], addnodes.index, entries=[])
+
+
+def test_module_content_line_number(app):
+ text = (".. js:module:: foo\n" +
+ "\n" +
+ " Some link here: :ref:`abc`\n")
+ doc = restructuredtext.parse(app, text)
+ xrefs = list(doc.findall(condition=addnodes.pending_xref))
+ assert len(xrefs) == 1
+ source, line = docutils.utils.get_source_line(xrefs[0])
+ assert 'index.rst' in source
+ assert line == 3
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'javascript_maximum_signature_line_length': len("hello(name)"),
+})
+def test_jsfunction_signature_with_javascript_maximum_signature_line_length_equal(app):
+ text = ".. js:function:: hello(name)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, ([desc_sig_name, "hello"])],
+ desc_parameterlist,
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], desc, desctype="function",
+ domain="js", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, desc_parameter, ([desc_sig_name, "name"])])
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'javascript_maximum_signature_line_length': len("hello(name)"),
+})
+def test_jsfunction_signature_with_javascript_maximum_signature_line_length_force_single(app):
+ text = (".. js:function:: hello(names)\n"
+ " :single-line-parameter-list:")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, ([desc_sig_name, "hello"])],
+ desc_parameterlist,
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], desc, desctype="function",
+ domain="js", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, desc_parameter, ([desc_sig_name, "names"])])
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'javascript_maximum_signature_line_length': len("hello(name)"),
+})
+def test_jsfunction_signature_with_javascript_maximum_signature_line_length_break(app):
+ text = ".. js:function:: hello(names)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, ([desc_sig_name, "hello"])],
+ desc_parameterlist,
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], desc, desctype="function",
+ domain="js", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, desc_parameter, ([desc_sig_name, "names"])])
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=True)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'maximum_signature_line_length': len("hello(name)"),
+})
+def test_jsfunction_signature_with_maximum_signature_line_length_equal(app):
+ text = ".. js:function:: hello(name)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, ([desc_sig_name, "hello"])],
+ desc_parameterlist,
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], desc, desctype="function",
+ domain="js", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, desc_parameter, ([desc_sig_name, "name"])])
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'maximum_signature_line_length': len("hello(name)"),
+})
+def test_jsfunction_signature_with_maximum_signature_line_length_force_single(app):
+ text = (".. js:function:: hello(names)\n"
+ " :single-line-parameter-list:")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, ([desc_sig_name, "hello"])],
+ desc_parameterlist,
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], desc, desctype="function",
+ domain="js", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, desc_parameter, ([desc_sig_name, "names"])])
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'maximum_signature_line_length': len("hello(name)"),
+})
+def test_jsfunction_signature_with_maximum_signature_line_length_break(app):
+ text = ".. js:function:: hello(names)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, ([desc_sig_name, "hello"])],
+ desc_parameterlist,
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], desc, desctype="function",
+ domain="js", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, desc_parameter, ([desc_sig_name, "names"])])
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=True)
+
+
+@pytest.mark.sphinx(
+ 'html',
+ confoverrides={
+ 'javascript_maximum_signature_line_length': len("hello(name)"),
+ 'maximum_signature_line_length': 1,
+ },
+)
+def test_javascript_maximum_signature_line_length_overrides_global(app):
+ text = ".. js:function:: hello(name)"
+ doctree = restructuredtext.parse(app, text)
+ expected_doctree = (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, ([desc_sig_name, "hello"])],
+ desc_parameterlist)],
+ desc_content)])
+ assert_node(doctree, expected_doctree)
+ assert_node(doctree[1], desc, desctype="function",
+ domain="js", objtype="function", no_index=False)
+ expected_sig = [desc_parameterlist, desc_parameter, [desc_sig_name, "name"]]
+ assert_node(doctree[1][0][1], expected_sig)
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx(
+ 'html', testroot='domain-js-javascript_maximum_signature_line_length',
+)
+def test_domain_js_javascript_maximum_signature_line_length_in_html(app, status, warning):
+ app.build()
+ content = (app.outdir / 'index.html').read_text(encoding='utf8')
+ expected_parameter_list_hello = """\
+
+<dl>
+<dd>\
+<em class="sig-param">\
+<span class="n"><span class="pre">name</span></span>\
+</em>,\
+</dd>
+</dl>
+
+<span class="sig-paren">)</span>\
+<a class="headerlink" href="#hello" title="Link to this definition">¶</a>\
+</dt>\
+"""
+ assert expected_parameter_list_hello in content
+
+ param_line_fmt = '<dd>{}</dd>\n'
+ param_name_fmt = (
+ '<em class="sig-param"><span class="n"><span class="pre">{}</span></span></em>'
+ )
+ optional_fmt = '<span class="optional">{}</span>'
+
+ expected_a = param_line_fmt.format(
+ optional_fmt.format("[") + param_name_fmt.format("a") + "," + optional_fmt.format("["),
+ )
+ assert expected_a in content
+
+ expected_b = param_line_fmt.format(
+ param_name_fmt.format("b") + "," + optional_fmt.format("]") + optional_fmt.format("]"),
+ )
+ assert expected_b in content
+
+ expected_c = param_line_fmt.format(param_name_fmt.format("c") + ",")
+ assert expected_c in content
+
+ expected_d = param_line_fmt.format(param_name_fmt.format("d") + optional_fmt.format("[") + ",")
+ assert expected_d in content
+
+ expected_e = param_line_fmt.format(param_name_fmt.format("e") + ",")
+ assert expected_e in content
+
+ expected_f = param_line_fmt.format(param_name_fmt.format("f") + "," + optional_fmt.format("]"))
+ assert expected_f in content
+
+ expected_parameter_list_foo = """\
+
+<dl>
+{}{}{}{}{}{}</dl>
+
+<span class="sig-paren">)</span>\
+<a class="headerlink" href="#foo" title="Link to this definition">¶</a>\
+</dt>\
+""".format(expected_a, expected_b, expected_c, expected_d, expected_e, expected_f)
+ assert expected_parameter_list_foo in content
+
+
+@pytest.mark.sphinx(
+ 'text', testroot='domain-js-javascript_maximum_signature_line_length',
+)
+def test_domain_js_javascript_maximum_signature_line_length_in_text(app, status, warning):
+ app.build()
+ content = (app.outdir / 'index.txt').read_text(encoding='utf8')
+ param_line_fmt = STDINDENT * " " + "{}\n"
+
+ expected_parameter_list_hello = "(\n{})".format(param_line_fmt.format("name,"))
+
+ assert expected_parameter_list_hello in content
+
+ expected_a = param_line_fmt.format("[a,[")
+ assert expected_a in content
+
+ expected_b = param_line_fmt.format("b,]]")
+ assert expected_b in content
+
+ expected_c = param_line_fmt.format("c,")
+ assert expected_c in content
+
+ expected_d = param_line_fmt.format("d[,")
+ assert expected_d in content
+
+ expected_e = param_line_fmt.format("e,")
+ assert expected_e in content
+
+ expected_f = param_line_fmt.format("f,]")
+ assert expected_f in content
+
+ expected_parameter_list_foo = "(\n{}{}{}{}{}{})".format(
+ expected_a, expected_b, expected_c, expected_d, expected_e, expected_f,
+ )
+ assert expected_parameter_list_foo in content
diff --git a/tests/test_domains/test_domain_py.py b/tests/test_domains/test_domain_py.py
new file mode 100644
index 0000000..e653c80
--- /dev/null
+++ b/tests/test_domains/test_domain_py.py
@@ -0,0 +1,1015 @@
+"""Tests the Python Domain"""
+
+from __future__ import annotations
+
+import re
+from unittest.mock import Mock
+
+import docutils.utils
+import pytest
+from docutils import nodes
+
+from sphinx import addnodes
+from sphinx.addnodes import (
+ desc,
+ desc_annotation,
+ desc_content,
+ desc_name,
+ desc_parameter,
+ desc_parameterlist,
+ desc_returns,
+ desc_sig_keyword,
+ desc_sig_literal_number,
+ desc_sig_literal_string,
+ desc_sig_name,
+ desc_sig_operator,
+ desc_sig_punctuation,
+ desc_sig_space,
+ desc_signature,
+ desc_type_parameter,
+ desc_type_parameter_list,
+ pending_xref,
+)
+from sphinx.domains import IndexEntry
+from sphinx.domains.python import PythonDomain, PythonModuleIndex
+from sphinx.domains.python._annotations import _parse_annotation, _pseudo_parse_arglist
+from sphinx.domains.python._object import py_sig_re
+from sphinx.testing import restructuredtext
+from sphinx.testing.util import assert_node
+from sphinx.writers.text import STDINDENT
+
+
+def parse(sig):
+ m = py_sig_re.match(sig)
+ if m is None:
+ raise ValueError
+ name_prefix, tp_list, name, arglist, retann = m.groups()
+ signode = addnodes.desc_signature(sig, '')
+ _pseudo_parse_arglist(signode, arglist)
+ return signode.astext()
+
+
+def test_function_signatures():
+ rv = parse('func(a=1) -> int object')
+ assert rv == '(a=1)'
+
+ rv = parse('func(a=1, [b=None])')
+ assert rv == '(a=1, [b=None])'
+
+ rv = parse('func(a=1[, b=None])')
+ assert rv == '(a=1, [b=None])'
+
+ rv = parse("compile(source : string, filename, symbol='file')")
+ assert rv == "(source : string, filename, symbol='file')"
+
+ rv = parse('func(a=[], [b=None])')
+ assert rv == '(a=[], [b=None])'
+
+ rv = parse('func(a=[][, b=None])')
+ assert rv == '(a=[], [b=None])'
+
+
+@pytest.mark.sphinx('dummy', testroot='domain-py')
+def test_domain_py_xrefs(app, status, warning):
+ """Domain objects have correct prefixes when looking up xrefs"""
+ app.build(force_all=True)
+
+ def assert_refnode(node, module_name, class_name, target, reftype=None,
+ domain='py'):
+ attributes = {
+ 'refdomain': domain,
+ 'reftarget': target,
+ }
+ if reftype is not None:
+ attributes['reftype'] = reftype
+ if module_name is not False:
+ attributes['py:module'] = module_name
+ if class_name is not False:
+ attributes['py:class'] = class_name
+ assert_node(node, **attributes)
+
+ doctree = app.env.get_doctree('roles')
+ refnodes = list(doctree.findall(pending_xref))
+ assert_refnode(refnodes[0], None, None, 'TopLevel', 'class')
+ assert_refnode(refnodes[1], None, None, 'top_level', 'meth')
+ assert_refnode(refnodes[2], None, 'NestedParentA', 'child_1', 'meth')
+ assert_refnode(refnodes[3], None, 'NestedParentA', 'NestedChildA.subchild_2', 'meth')
+ assert_refnode(refnodes[4], None, 'NestedParentA', 'child_2', 'meth')
+ assert_refnode(refnodes[5], False, 'NestedParentA', 'any_child', domain='')
+ assert_refnode(refnodes[6], None, 'NestedParentA', 'NestedChildA', 'class')
+ assert_refnode(refnodes[7], None, 'NestedParentA.NestedChildA', 'subchild_2', 'meth')
+ assert_refnode(refnodes[8], None, 'NestedParentA.NestedChildA',
+ 'NestedParentA.child_1', 'meth')
+ assert_refnode(refnodes[9], None, 'NestedParentA', 'NestedChildA.subchild_1', 'meth')
+ assert_refnode(refnodes[10], None, 'NestedParentB', 'child_1', 'meth')
+ assert_refnode(refnodes[11], None, 'NestedParentB', 'NestedParentB', 'class')
+ assert_refnode(refnodes[12], None, None, 'NestedParentA.NestedChildA', 'class')
+ assert len(refnodes) == 13
+
+ doctree = app.env.get_doctree('module')
+ refnodes = list(doctree.findall(pending_xref))
+ assert_refnode(refnodes[0], 'module_a.submodule', None,
+ 'ModTopLevel', 'class')
+ assert_refnode(refnodes[1], 'module_a.submodule', 'ModTopLevel',
+ 'mod_child_1', 'meth')
+ assert_refnode(refnodes[2], 'module_a.submodule', 'ModTopLevel',
+ 'ModTopLevel.mod_child_1', 'meth')
+ assert_refnode(refnodes[3], 'module_a.submodule', 'ModTopLevel',
+ 'mod_child_2', 'meth')
+ assert_refnode(refnodes[4], 'module_a.submodule', 'ModTopLevel',
+ 'module_a.submodule.ModTopLevel.mod_child_1', 'meth')
+ assert_refnode(refnodes[5], 'module_a.submodule', 'ModTopLevel',
+ 'prop', 'attr')
+ assert_refnode(refnodes[6], 'module_a.submodule', 'ModTopLevel',
+ 'prop', 'meth')
+ assert_refnode(refnodes[7], 'module_b.submodule', None,
+ 'ModTopLevel', 'class')
+ assert_refnode(refnodes[8], 'module_b.submodule', 'ModTopLevel',
+ 'ModNoModule', 'class')
+ assert_refnode(refnodes[9], False, False, 'int', 'class')
+ assert_refnode(refnodes[10], False, False, 'tuple', 'class')
+ assert_refnode(refnodes[11], False, False, 'str', 'class')
+ assert_refnode(refnodes[12], False, False, 'float', 'class')
+ assert_refnode(refnodes[13], False, False, 'list', 'class')
+ assert_refnode(refnodes[14], False, False, 'ModTopLevel', 'class')
+ assert_refnode(refnodes[15], False, False, 'index', 'doc', domain='std')
+ assert_refnode(refnodes[16], False, False, 'typing.Literal', 'obj', domain='py')
+ assert_refnode(refnodes[17], False, False, 'typing.Literal', 'obj', domain='py')
+ assert len(refnodes) == 18
+
+ doctree = app.env.get_doctree('module_option')
+ refnodes = list(doctree.findall(pending_xref))
+ print(refnodes)
+ print(refnodes[0])
+ print(refnodes[1])
+ assert_refnode(refnodes[0], 'test.extra', 'B', 'foo', 'meth')
+ assert_refnode(refnodes[1], 'test.extra', 'B', 'foo', 'meth')
+ assert len(refnodes) == 2
+
+
+@pytest.mark.sphinx('html', testroot='domain-py')
+def test_domain_py_xrefs_abbreviations(app, status, warning):
+ app.build(force_all=True)
+
+ content = (app.outdir / 'abbr.html').read_text(encoding='utf8')
+ assert re.search(r'normal: <a .* href="module.html#module_a.submodule.ModTopLevel.'
+ r'mod_child_1" .*><.*>module_a.submodule.ModTopLevel.mod_child_1\(\)'
+ r'<.*></a>',
+ content)
+ assert re.search(r'relative: <a .* href="module.html#module_a.submodule.ModTopLevel.'
+ r'mod_child_1" .*><.*>ModTopLevel.mod_child_1\(\)<.*></a>',
+ content)
+ assert re.search(r'short name: <a .* href="module.html#module_a.submodule.ModTopLevel.'
+ r'mod_child_1" .*><.*>mod_child_1\(\)<.*></a>',
+ content)
+ assert re.search(r'relative \+ short name: <a .* href="module.html#module_a.submodule.'
+ r'ModTopLevel.mod_child_1" .*><.*>mod_child_1\(\)<.*></a>',
+ content)
+ assert re.search(r'short name \+ relative: <a .* href="module.html#module_a.submodule.'
+ r'ModTopLevel.mod_child_1" .*><.*>mod_child_1\(\)<.*></a>',
+ content)
+
+
+@pytest.mark.sphinx('dummy', testroot='domain-py')
+def test_domain_py_objects(app, status, warning):
+ app.build(force_all=True)
+
+ modules = app.env.domains['py'].data['modules']
+ objects = app.env.domains['py'].data['objects']
+
+ assert 'module_a.submodule' in modules
+ assert 'module_a.submodule' in objects
+ assert 'module_b.submodule' in modules
+ assert 'module_b.submodule' in objects
+
+ assert objects['module_a.submodule.ModTopLevel'][2] == 'class'
+ assert objects['module_a.submodule.ModTopLevel.mod_child_1'][2] == 'method'
+ assert objects['module_a.submodule.ModTopLevel.mod_child_2'][2] == 'method'
+ assert 'ModTopLevel.ModNoModule' not in objects
+ assert objects['ModNoModule'][2] == 'class'
+ assert objects['module_b.submodule.ModTopLevel'][2] == 'class'
+
+ assert objects['TopLevel'][2] == 'class'
+ assert objects['top_level'][2] == 'method'
+ assert objects['NestedParentA'][2] == 'class'
+ assert objects['NestedParentA.child_1'][2] == 'method'
+ assert objects['NestedParentA.any_child'][2] == 'method'
+ assert objects['NestedParentA.NestedChildA'][2] == 'class'
+ assert objects['NestedParentA.NestedChildA.subchild_1'][2] == 'method'
+ assert objects['NestedParentA.NestedChildA.subchild_2'][2] == 'method'
+ assert objects['NestedParentA.child_2'][2] == 'method'
+ assert objects['NestedParentB'][2] == 'class'
+ assert objects['NestedParentB.child_1'][2] == 'method'
+
+
+@pytest.mark.sphinx('html', testroot='domain-py')
+def test_resolve_xref_for_properties(app, status, warning):
+ app.build(force_all=True)
+
+ content = (app.outdir / 'module.html').read_text(encoding='utf8')
+ assert ('Link to <a class="reference internal" href="#module_a.submodule.ModTopLevel.prop"'
+ ' title="module_a.submodule.ModTopLevel.prop">'
+ '<code class="xref py py-attr docutils literal notranslate"><span class="pre">'
+ 'prop</span> <span class="pre">attribute</span></code></a>' in content)
+ assert ('Link to <a class="reference internal" href="#module_a.submodule.ModTopLevel.prop"'
+ ' title="module_a.submodule.ModTopLevel.prop">'
+ '<code class="xref py py-meth docutils literal notranslate"><span class="pre">'
+ 'prop</span> <span class="pre">method</span></code></a>' in content)
+ assert ('Link to <a class="reference internal" href="#module_a.submodule.ModTopLevel.prop"'
+ ' title="module_a.submodule.ModTopLevel.prop">'
+ '<code class="xref py py-attr docutils literal notranslate"><span class="pre">'
+ 'prop</span> <span class="pre">attribute</span></code></a>' in content)
+
+
+@pytest.mark.sphinx('dummy', testroot='domain-py')
+def test_domain_py_find_obj(app, status, warning):
+
+ def find_obj(modname, prefix, obj_name, obj_type, searchmode=0):
+ return app.env.domains['py'].find_obj(
+ app.env, modname, prefix, obj_name, obj_type, searchmode)
+
+ app.build(force_all=True)
+
+ assert (find_obj(None, None, 'NONEXISTANT', 'class') == [])
+ assert (find_obj(None, None, 'NestedParentA', 'class') ==
+ [('NestedParentA', ('roles', 'NestedParentA', 'class', False))])
+ assert (find_obj(None, None, 'NestedParentA.NestedChildA', 'class') ==
+ [('NestedParentA.NestedChildA',
+ ('roles', 'NestedParentA.NestedChildA', 'class', False))])
+ assert (find_obj(None, 'NestedParentA', 'NestedChildA', 'class') ==
+ [('NestedParentA.NestedChildA',
+ ('roles', 'NestedParentA.NestedChildA', 'class', False))])
+ assert (find_obj(None, None, 'NestedParentA.NestedChildA.subchild_1', 'meth') ==
+ [('NestedParentA.NestedChildA.subchild_1',
+ ('roles', 'NestedParentA.NestedChildA.subchild_1', 'method', False))])
+ assert (find_obj(None, 'NestedParentA', 'NestedChildA.subchild_1', 'meth') ==
+ [('NestedParentA.NestedChildA.subchild_1',
+ ('roles', 'NestedParentA.NestedChildA.subchild_1', 'method', False))])
+ assert (find_obj(None, 'NestedParentA.NestedChildA', 'subchild_1', 'meth') ==
+ [('NestedParentA.NestedChildA.subchild_1',
+ ('roles', 'NestedParentA.NestedChildA.subchild_1', 'method', False))])
+
+
+def test_get_full_qualified_name():
+ env = Mock(domaindata={})
+ domain = PythonDomain(env)
+
+ # non-python references
+ node = nodes.reference()
+ assert domain.get_full_qualified_name(node) is None
+
+ # simple reference
+ node = nodes.reference(reftarget='func')
+ assert domain.get_full_qualified_name(node) == 'func'
+
+ # with py:module context
+ kwargs = {'py:module': 'module1'}
+ node = nodes.reference(reftarget='func', **kwargs)
+ assert domain.get_full_qualified_name(node) == 'module1.func'
+
+ # with py:class context
+ kwargs = {'py:class': 'Class'}
+ node = nodes.reference(reftarget='func', **kwargs)
+ assert domain.get_full_qualified_name(node) == 'Class.func'
+
+ # with both py:module and py:class context
+ kwargs = {'py:module': 'module1', 'py:class': 'Class'}
+ node = nodes.reference(reftarget='func', **kwargs)
+ assert domain.get_full_qualified_name(node) == 'module1.Class.func'
+
+
+def test_parse_annotation(app):
+ doctree = _parse_annotation("int", app.env)
+ assert_node(doctree, ([pending_xref, "int"],))
+ assert_node(doctree[0], pending_xref, refdomain="py", reftype="class", reftarget="int")
+
+ doctree = _parse_annotation("List[int]", app.env)
+ assert_node(doctree, ([pending_xref, "List"],
+ [desc_sig_punctuation, "["],
+ [pending_xref, "int"],
+ [desc_sig_punctuation, "]"]))
+
+ doctree = _parse_annotation("Tuple[int, int]", app.env)
+ assert_node(doctree, ([pending_xref, "Tuple"],
+ [desc_sig_punctuation, "["],
+ [pending_xref, "int"],
+ [desc_sig_punctuation, ","],
+ desc_sig_space,
+ [pending_xref, "int"],
+ [desc_sig_punctuation, "]"]))
+
+ doctree = _parse_annotation("Tuple[()]", app.env)
+ assert_node(doctree, ([pending_xref, "Tuple"],
+ [desc_sig_punctuation, "["],
+ [desc_sig_punctuation, "("],
+ [desc_sig_punctuation, ")"],
+ [desc_sig_punctuation, "]"]))
+
+ doctree = _parse_annotation("Tuple[int, ...]", app.env)
+ assert_node(doctree, ([pending_xref, "Tuple"],
+ [desc_sig_punctuation, "["],
+ [pending_xref, "int"],
+ [desc_sig_punctuation, ","],
+ desc_sig_space,
+ [desc_sig_punctuation, "..."],
+ [desc_sig_punctuation, "]"]))
+
+ doctree = _parse_annotation("Callable[[int, int], int]", app.env)
+ assert_node(doctree, ([pending_xref, "Callable"],
+ [desc_sig_punctuation, "["],
+ [desc_sig_punctuation, "["],
+ [pending_xref, "int"],
+ [desc_sig_punctuation, ","],
+ desc_sig_space,
+ [pending_xref, "int"],
+ [desc_sig_punctuation, "]"],
+ [desc_sig_punctuation, ","],
+ desc_sig_space,
+ [pending_xref, "int"],
+ [desc_sig_punctuation, "]"]))
+
+ doctree = _parse_annotation("Callable[[], int]", app.env)
+ assert_node(doctree, ([pending_xref, "Callable"],
+ [desc_sig_punctuation, "["],
+ [desc_sig_punctuation, "["],
+ [desc_sig_punctuation, "]"],
+ [desc_sig_punctuation, ","],
+ desc_sig_space,
+ [pending_xref, "int"],
+ [desc_sig_punctuation, "]"]))
+
+ doctree = _parse_annotation("List[None]", app.env)
+ assert_node(doctree, ([pending_xref, "List"],
+ [desc_sig_punctuation, "["],
+ [pending_xref, "None"],
+ [desc_sig_punctuation, "]"]))
+
+ # None type makes an object-reference (not a class reference)
+ doctree = _parse_annotation("None", app.env)
+ assert_node(doctree, ([pending_xref, "None"],))
+ assert_node(doctree[0], pending_xref, refdomain="py", reftype="obj", reftarget="None")
+
+ # Literal type makes an object-reference (not a class reference)
+ doctree = _parse_annotation("typing.Literal['a', 'b']", app.env)
+ assert_node(doctree, ([pending_xref, "Literal"],
+ [desc_sig_punctuation, "["],
+ [desc_sig_literal_string, "'a'"],
+ [desc_sig_punctuation, ","],
+ desc_sig_space,
+ [desc_sig_literal_string, "'b'"],
+ [desc_sig_punctuation, "]"]))
+ assert_node(doctree[0], pending_xref, refdomain="py", reftype="obj", reftarget="typing.Literal")
+
+
+def test_parse_annotation_suppress(app):
+ doctree = _parse_annotation("~typing.Dict[str, str]", app.env)
+ assert_node(doctree, ([pending_xref, "Dict"],
+ [desc_sig_punctuation, "["],
+ [pending_xref, "str"],
+ [desc_sig_punctuation, ","],
+ desc_sig_space,
+ [pending_xref, "str"],
+ [desc_sig_punctuation, "]"]))
+ assert_node(doctree[0], pending_xref, refdomain="py", reftype="obj", reftarget="typing.Dict")
+
+
+def test_parse_annotation_Literal(app):
+ doctree = _parse_annotation("Literal[True, False]", app.env)
+ assert_node(doctree, ([pending_xref, "Literal"],
+ [desc_sig_punctuation, "["],
+ [desc_sig_keyword, "True"],
+ [desc_sig_punctuation, ","],
+ desc_sig_space,
+ [desc_sig_keyword, "False"],
+ [desc_sig_punctuation, "]"]))
+
+ doctree = _parse_annotation("typing.Literal[0, 1, 'abc']", app.env)
+ assert_node(doctree, ([pending_xref, "Literal"],
+ [desc_sig_punctuation, "["],
+ [desc_sig_literal_number, "0"],
+ [desc_sig_punctuation, ","],
+ desc_sig_space,
+ [desc_sig_literal_number, "1"],
+ [desc_sig_punctuation, ","],
+ desc_sig_space,
+ [desc_sig_literal_string, "'abc'"],
+ [desc_sig_punctuation, "]"]))
+
+
+@pytest.mark.sphinx(freshenv=True)
+def test_module_index(app):
+ text = (".. py:module:: docutils\n"
+ ".. py:module:: sphinx\n"
+ ".. py:module:: sphinx.config\n"
+ ".. py:module:: sphinx.builders\n"
+ ".. py:module:: sphinx.builders.html\n"
+ ".. py:module:: sphinx_intl\n")
+ restructuredtext.parse(app, text)
+ index = PythonModuleIndex(app.env.get_domain('py'))
+ assert index.generate() == (
+ [('d', [IndexEntry('docutils', 0, 'index', 'module-docutils', '', '', '')]),
+ ('s', [IndexEntry('sphinx', 1, 'index', 'module-sphinx', '', '', ''),
+ IndexEntry('sphinx.builders', 2, 'index', 'module-sphinx.builders', '', '', ''),
+ IndexEntry('sphinx.builders.html', 2, 'index', 'module-sphinx.builders.html', '', '', ''),
+ IndexEntry('sphinx.config', 2, 'index', 'module-sphinx.config', '', '', ''),
+ IndexEntry('sphinx_intl', 0, 'index', 'module-sphinx_intl', '', '', '')])],
+ False,
+ )
+
+
+@pytest.mark.sphinx(freshenv=True)
+def test_module_index_submodule(app):
+ text = ".. py:module:: sphinx.config\n"
+ restructuredtext.parse(app, text)
+ index = PythonModuleIndex(app.env.get_domain('py'))
+ assert index.generate() == (
+ [('s', [IndexEntry('sphinx', 1, '', '', '', '', ''),
+ IndexEntry('sphinx.config', 2, 'index', 'module-sphinx.config', '', '', '')])],
+ False,
+ )
+
+
+@pytest.mark.sphinx(freshenv=True)
+def test_module_index_not_collapsed(app):
+ text = (".. py:module:: docutils\n"
+ ".. py:module:: sphinx\n")
+ restructuredtext.parse(app, text)
+ index = PythonModuleIndex(app.env.get_domain('py'))
+ assert index.generate() == (
+ [('d', [IndexEntry('docutils', 0, 'index', 'module-docutils', '', '', '')]),
+ ('s', [IndexEntry('sphinx', 0, 'index', 'module-sphinx', '', '', '')])],
+ True,
+ )
+
+
+@pytest.mark.sphinx(freshenv=True, confoverrides={'modindex_common_prefix': ['sphinx.']})
+def test_modindex_common_prefix(app):
+ text = (".. py:module:: docutils\n"
+ ".. py:module:: sphinx\n"
+ ".. py:module:: sphinx.config\n"
+ ".. py:module:: sphinx.builders\n"
+ ".. py:module:: sphinx.builders.html\n"
+ ".. py:module:: sphinx_intl\n")
+ restructuredtext.parse(app, text)
+ index = PythonModuleIndex(app.env.get_domain('py'))
+ assert index.generate() == (
+ [('b', [IndexEntry('sphinx.builders', 1, 'index', 'module-sphinx.builders', '', '', ''),
+ IndexEntry('sphinx.builders.html', 2, 'index', 'module-sphinx.builders.html', '', '', '')]),
+ ('c', [IndexEntry('sphinx.config', 0, 'index', 'module-sphinx.config', '', '', '')]),
+ ('d', [IndexEntry('docutils', 0, 'index', 'module-docutils', '', '', '')]),
+ ('s', [IndexEntry('sphinx', 0, 'index', 'module-sphinx', '', '', ''),
+ IndexEntry('sphinx_intl', 0, 'index', 'module-sphinx_intl', '', '', '')])],
+ True,
+ )
+
+
+def test_no_index_entry(app):
+ text = (".. py:function:: f()\n"
+ ".. py:function:: g()\n"
+ " :no-index-entry:\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index, desc, addnodes.index, desc))
+ assert_node(doctree[0], addnodes.index, entries=[('pair', 'built-in function; f()', 'f', '', None)])
+ assert_node(doctree[2], addnodes.index, entries=[])
+
+ text = (".. py:class:: f\n"
+ ".. py:class:: g\n"
+ " :no-index-entry:\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index, desc, addnodes.index, desc))
+ assert_node(doctree[0], addnodes.index, entries=[('single', 'f (built-in class)', 'f', '', None)])
+ assert_node(doctree[2], addnodes.index, entries=[])
+
+
+@pytest.mark.sphinx('html', testroot='domain-py-python_use_unqualified_type_names')
+def test_python_python_use_unqualified_type_names(app, status, warning):
+ app.build()
+ content = (app.outdir / 'index.html').read_text(encoding='utf8')
+ assert ('<span class="n"><a class="reference internal" href="#foo.Name" title="foo.Name">'
+ '<span class="pre">Name</span></a></span>' in content)
+ assert '<span class="n"><span class="pre">foo.Age</span></span>' in content
+ assert ('<p><strong>name</strong> (<a class="reference internal" href="#foo.Name" '
+ 'title="foo.Name"><em>Name</em></a>) – blah blah</p>' in content)
+ assert '<p><strong>age</strong> (<em>foo.Age</em>) – blah blah</p>' in content
+
+
+@pytest.mark.sphinx('html', testroot='domain-py-python_use_unqualified_type_names',
+ confoverrides={'python_use_unqualified_type_names': False})
+def test_python_python_use_unqualified_type_names_disabled(app, status, warning):
+ app.build()
+ content = (app.outdir / 'index.html').read_text(encoding='utf8')
+ assert ('<span class="n"><a class="reference internal" href="#foo.Name" title="foo.Name">'
+ '<span class="pre">foo.Name</span></a></span>' in content)
+ assert '<span class="n"><span class="pre">foo.Age</span></span>' in content
+ assert ('<p><strong>name</strong> (<a class="reference internal" href="#foo.Name" '
+ 'title="foo.Name"><em>foo.Name</em></a>) – blah blah</p>' in content)
+ assert '<p><strong>age</strong> (<em>foo.Age</em>) – blah blah</p>' in content
+
+
+@pytest.mark.sphinx('dummy', testroot='domain-py-xref-warning')
+def test_warn_missing_reference(app, status, warning):
+ app.build()
+ assert "index.rst:6: WARNING: undefined label: 'no-label'" in warning.getvalue()
+ assert ("index.rst:6: WARNING: Failed to create a cross reference. "
+ "A title or caption not found: 'existing-label'") in warning.getvalue()
+
+
+@pytest.mark.sphinx(confoverrides={'nitpicky': True})
+@pytest.mark.parametrize('include_options', [True, False])
+def test_signature_line_number(app, include_options):
+ text = (".. py:function:: foo(bar : string)\n" +
+ (" :no-index-entry:\n" if include_options else ""))
+ doc = restructuredtext.parse(app, text)
+ xrefs = list(doc.findall(condition=addnodes.pending_xref))
+ assert len(xrefs) == 1
+ source, line = docutils.utils.get_source_line(xrefs[0])
+ assert 'index.rst' in source
+ assert line == 1
+
+
+@pytest.mark.sphinx(
+ 'html',
+ confoverrides={
+ 'python_maximum_signature_line_length': len("hello(name: str) -> str"),
+ 'maximum_signature_line_length': 1,
+ },
+)
+def test_python_maximum_signature_line_length_overrides_global(app):
+ text = ".. py:function:: hello(name: str) -> str"
+ doctree = restructuredtext.parse(app, text)
+ expected_doctree = (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "hello"],
+ desc_parameterlist,
+ [desc_returns, pending_xref, "str"])],
+ desc_content)])
+ assert_node(doctree, expected_doctree)
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="py", objtype="function", no_index=False)
+ signame_node = [desc_sig_name, "name"]
+ expected_sig = [desc_parameterlist, desc_parameter, (signame_node,
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [nodes.inline, pending_xref, "str"])]
+ assert_node(doctree[1][0][1], expected_sig)
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx(
+ 'html', testroot='domain-py-python_maximum_signature_line_length',
+)
+def test_domain_py_python_maximum_signature_line_length_in_html(app, status, warning):
+ app.build()
+ content = (app.outdir / 'index.html').read_text(encoding='utf8')
+ expected_parameter_list_hello = """\
+
+<dl>
+<dd>\
+<em class="sig-param">\
+<span class="n"><span class="pre">name</span></span>\
+<span class="p"><span class="pre">:</span></span>\
+<span class="w"> </span>\
+<span class="n"><span class="pre">str</span></span>\
+</em>,\
+</dd>
+</dl>
+
+<span class="sig-paren">)</span> \
+<span class="sig-return">\
+<span class="sig-return-icon">&#x2192;</span> \
+<span class="sig-return-typehint"><span class="pre">str</span></span>\
+</span>\
+<a class="headerlink" href="#hello" title="Link to this definition">¶</a>\
+</dt>\
+"""
+ assert expected_parameter_list_hello in content
+
+ param_line_fmt = '<dd>{}</dd>\n'
+ param_name_fmt = (
+ '<em class="sig-param"><span class="n"><span class="pre">{}</span></span></em>'
+ )
+ optional_fmt = '<span class="optional">{}</span>'
+
+ expected_a = param_line_fmt.format(
+ optional_fmt.format("[") + param_name_fmt.format("a") + "," + optional_fmt.format("["),
+ )
+ assert expected_a in content
+
+ expected_b = param_line_fmt.format(
+ param_name_fmt.format("b") + "," + optional_fmt.format("]") + optional_fmt.format("]"),
+ )
+ assert expected_b in content
+
+ expected_c = param_line_fmt.format(param_name_fmt.format("c") + ",")
+ assert expected_c in content
+
+ expected_d = param_line_fmt.format(param_name_fmt.format("d") + optional_fmt.format("[") + ",")
+ assert expected_d in content
+
+ expected_e = param_line_fmt.format(param_name_fmt.format("e") + ",")
+ assert expected_e in content
+
+ expected_f = param_line_fmt.format(param_name_fmt.format("f") + "," + optional_fmt.format("]"))
+ assert expected_f in content
+
+ expected_parameter_list_foo = """\
+
+<dl>
+{}{}{}{}{}{}</dl>
+
+<span class="sig-paren">)</span>\
+<a class="headerlink" href="#foo" title="Link to this definition">¶</a>\
+</dt>\
+""".format(expected_a, expected_b, expected_c, expected_d, expected_e, expected_f)
+ assert expected_parameter_list_foo in content
+
+
+@pytest.mark.sphinx(
+ 'text', testroot='domain-py-python_maximum_signature_line_length',
+)
+def test_domain_py_python_maximum_signature_line_length_in_text(app, status, warning):
+ app.build()
+ content = (app.outdir / 'index.txt').read_text(encoding='utf8')
+ param_line_fmt = STDINDENT * " " + "{}\n"
+
+ expected_parameter_list_hello = "(\n{}) -> str".format(param_line_fmt.format("name: str,"))
+
+ assert expected_parameter_list_hello in content
+
+ expected_a = param_line_fmt.format("[a,[")
+ assert expected_a in content
+
+ expected_b = param_line_fmt.format("b,]]")
+ assert expected_b in content
+
+ expected_c = param_line_fmt.format("c,")
+ assert expected_c in content
+
+ expected_d = param_line_fmt.format("d[,")
+ assert expected_d in content
+
+ expected_e = param_line_fmt.format("e,")
+ assert expected_e in content
+
+ expected_f = param_line_fmt.format("f,]")
+ assert expected_f in content
+
+ expected_parameter_list_foo = "(\n{}{}{}{}{}{})".format(
+ expected_a, expected_b, expected_c, expected_d, expected_e, expected_f,
+ )
+ assert expected_parameter_list_foo in content
+
+
+def test_module_content_line_number(app):
+ text = (".. py:module:: foo\n" +
+ "\n" +
+ " Some link here: :ref:`abc`\n")
+ doc = restructuredtext.parse(app, text)
+ xrefs = list(doc.findall(condition=addnodes.pending_xref))
+ assert len(xrefs) == 1
+ source, line = docutils.utils.get_source_line(xrefs[0])
+ assert 'index.rst' in source
+ assert line == 3
+
+
+@pytest.mark.sphinx(freshenv=True, confoverrides={'python_display_short_literal_types': True})
+def test_short_literal_types(app):
+ text = """\
+.. py:function:: literal_ints(x: Literal[1, 2, 3] = 1) -> None
+.. py:function:: literal_union(x: Union[Literal["a"], Literal["b"], Literal["c"]]) -> None
+"""
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, 'literal_ints'],
+ [desc_parameterlist, (
+ [desc_parameter, (
+ [desc_sig_name, 'x'],
+ [desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [desc_sig_name, (
+ [desc_sig_literal_number, '1'],
+ desc_sig_space,
+ [desc_sig_punctuation, '|'],
+ desc_sig_space,
+ [desc_sig_literal_number, '2'],
+ desc_sig_space,
+ [desc_sig_punctuation, '|'],
+ desc_sig_space,
+ [desc_sig_literal_number, '3'],
+ )],
+ desc_sig_space,
+ [desc_sig_operator, '='],
+ desc_sig_space,
+ [nodes.inline, '1'],
+ )],
+ )],
+ [desc_returns, pending_xref, 'None'],
+ )],
+ [desc_content, ()],
+ )],
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, 'literal_union'],
+ [desc_parameterlist, (
+ [desc_parameter, (
+ [desc_sig_name, 'x'],
+ [desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [desc_sig_name, (
+ [desc_sig_literal_string, "'a'"],
+ desc_sig_space,
+ [desc_sig_punctuation, '|'],
+ desc_sig_space,
+ [desc_sig_literal_string, "'b'"],
+ desc_sig_space,
+ [desc_sig_punctuation, '|'],
+ desc_sig_space,
+ [desc_sig_literal_string, "'c'"],
+ )],
+ )],
+ )],
+ [desc_returns, pending_xref, 'None'],
+ )],
+ [desc_content, ()],
+ )],
+ ))
+
+
+def test_function_pep_695(app):
+ text = """.. py:function:: func[\
+ S,\
+ T: int,\
+ U: (int, str),\
+ R: int | int,\
+ A: int | Annotated[int, ctype("char")],\
+ *V,\
+ **P\
+ ]
+ """
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, 'func'],
+ [desc_type_parameter_list, (
+ [desc_type_parameter, ([desc_sig_name, 'S'])],
+ [desc_type_parameter, (
+ [desc_sig_name, 'T'],
+ [desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [desc_sig_name, ([pending_xref, 'int'])],
+ )],
+ [desc_type_parameter, (
+ [desc_sig_name, 'U'],
+ [desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [desc_sig_punctuation, '('],
+ [desc_sig_name, (
+ [pending_xref, 'int'],
+ [desc_sig_punctuation, ','],
+ desc_sig_space,
+ [pending_xref, 'str'],
+ )],
+ [desc_sig_punctuation, ')'],
+ )],
+ [desc_type_parameter, (
+ [desc_sig_name, 'R'],
+ [desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [desc_sig_name, (
+ [pending_xref, 'int'],
+ desc_sig_space,
+ [desc_sig_punctuation, '|'],
+ desc_sig_space,
+ [pending_xref, 'int'],
+ )],
+ )],
+ [desc_type_parameter, (
+ [desc_sig_name, 'A'],
+ [desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [desc_sig_name, ([pending_xref, 'int | Annotated[int, ctype("char")]'])],
+ )],
+ [desc_type_parameter, (
+ [desc_sig_operator, '*'],
+ [desc_sig_name, 'V'],
+ )],
+ [desc_type_parameter, (
+ [desc_sig_operator, '**'],
+ [desc_sig_name, 'P'],
+ )],
+ )],
+ [desc_parameterlist, ()],
+ )],
+ [desc_content, ()],
+ )],
+ ))
+
+
+def test_class_def_pep_695(app):
+ # Non-concrete unbound generics are allowed at runtime but type checkers
+ # should fail (https://peps.python.org/pep-0695/#type-parameter-scopes)
+ text = """.. py:class:: Class[S: Sequence[T], T, KT, VT](Dict[KT, VT])"""
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_annotation, ('class', desc_sig_space)],
+ [desc_name, 'Class'],
+ [desc_type_parameter_list, (
+ [desc_type_parameter, (
+ [desc_sig_name, 'S'],
+ [desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [desc_sig_name, (
+ [pending_xref, 'Sequence'],
+ [desc_sig_punctuation, '['],
+ [pending_xref, 'T'],
+ [desc_sig_punctuation, ']'],
+ )],
+ )],
+ [desc_type_parameter, ([desc_sig_name, 'T'])],
+ [desc_type_parameter, ([desc_sig_name, 'KT'])],
+ [desc_type_parameter, ([desc_sig_name, 'VT'])],
+ )],
+ [desc_parameterlist, ([desc_parameter, 'Dict[KT, VT]'])],
+ )],
+ [desc_content, ()],
+ )],
+ ))
+
+
+def test_class_def_pep_696(app):
+ # test default values for type variables without using PEP 696 AST parser
+ text = """.. py:class:: Class[\
+ T, KT, VT,\
+ J: int,\
+ K = list,\
+ S: str = str,\
+ L: (T, tuple[T, ...], collections.abc.Iterable[T]) = set[T],\
+ Q: collections.abc.Mapping[KT, VT] = dict[KT, VT],\
+ *V = *tuple[*Ts, bool],\
+ **P = [int, Annotated[int, ValueRange(3, 10), ctype("char")]]\
+ ](Other[T, KT, VT, J, S, L, Q, *V, **P])
+ """
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_annotation, ('class', desc_sig_space)],
+ [desc_name, 'Class'],
+ [desc_type_parameter_list, (
+ [desc_type_parameter, ([desc_sig_name, 'T'])],
+ [desc_type_parameter, ([desc_sig_name, 'KT'])],
+ [desc_type_parameter, ([desc_sig_name, 'VT'])],
+ # J: int
+ [desc_type_parameter, (
+ [desc_sig_name, 'J'],
+ [desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [desc_sig_name, ([pending_xref, 'int'])],
+ )],
+ # K = list
+ [desc_type_parameter, (
+ [desc_sig_name, 'K'],
+ desc_sig_space,
+ [desc_sig_operator, '='],
+ desc_sig_space,
+ [nodes.inline, 'list'],
+ )],
+ # S: str = str
+ [desc_type_parameter, (
+ [desc_sig_name, 'S'],
+ [desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [desc_sig_name, ([pending_xref, 'str'])],
+ desc_sig_space,
+ [desc_sig_operator, '='],
+ desc_sig_space,
+ [nodes.inline, 'str'],
+ )],
+ [desc_type_parameter, (
+ [desc_sig_name, 'L'],
+ [desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [desc_sig_punctuation, '('],
+ [desc_sig_name, (
+ # T
+ [pending_xref, 'T'],
+ [desc_sig_punctuation, ','],
+ desc_sig_space,
+ # tuple[T, ...]
+ [pending_xref, 'tuple'],
+ [desc_sig_punctuation, '['],
+ [pending_xref, 'T'],
+ [desc_sig_punctuation, ','],
+ desc_sig_space,
+ [desc_sig_punctuation, '...'],
+ [desc_sig_punctuation, ']'],
+ [desc_sig_punctuation, ','],
+ desc_sig_space,
+ # collections.abc.Iterable[T]
+ [pending_xref, 'collections.abc.Iterable'],
+ [desc_sig_punctuation, '['],
+ [pending_xref, 'T'],
+ [desc_sig_punctuation, ']'],
+ )],
+ [desc_sig_punctuation, ')'],
+ desc_sig_space,
+ [desc_sig_operator, '='],
+ desc_sig_space,
+ [nodes.inline, 'set[T]'],
+ )],
+ [desc_type_parameter, (
+ [desc_sig_name, 'Q'],
+ [desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [desc_sig_name, (
+ [pending_xref, 'collections.abc.Mapping'],
+ [desc_sig_punctuation, '['],
+ [pending_xref, 'KT'],
+ [desc_sig_punctuation, ','],
+ desc_sig_space,
+ [pending_xref, 'VT'],
+ [desc_sig_punctuation, ']'],
+ )],
+ desc_sig_space,
+ [desc_sig_operator, '='],
+ desc_sig_space,
+ [nodes.inline, 'dict[KT, VT]'],
+ )],
+ [desc_type_parameter, (
+ [desc_sig_operator, '*'],
+ [desc_sig_name, 'V'],
+ desc_sig_space,
+ [desc_sig_operator, '='],
+ desc_sig_space,
+ [nodes.inline, '*tuple[*Ts, bool]'],
+ )],
+ [desc_type_parameter, (
+ [desc_sig_operator, '**'],
+ [desc_sig_name, 'P'],
+ desc_sig_space,
+ [desc_sig_operator, '='],
+ desc_sig_space,
+ [nodes.inline, '[int, Annotated[int, ValueRange(3, 10), ctype("char")]]'],
+ )],
+ )],
+ [desc_parameterlist, (
+ [desc_parameter, 'Other[T, KT, VT, J, S, L, Q, *V, **P]'],
+ )],
+ )],
+ [desc_content, ()],
+ )],
+ ))
+
+
+@pytest.mark.parametrize(('tp_list', 'tptext'), [
+ ('[T:int]', '[T: int]'),
+ ('[T:*Ts]', '[T: *Ts]'),
+ ('[T:int|(*Ts)]', '[T: int | (*Ts)]'),
+ ('[T:(*Ts)|int]', '[T: (*Ts) | int]'),
+ ('[T:(int|(*Ts))]', '[T: (int | (*Ts))]'),
+ ('[T:((*Ts)|int)]', '[T: ((*Ts) | int)]'),
+ ('[T:Annotated[int,ctype("char")]]', '[T: Annotated[int, ctype("char")]]'),
+])
+def test_pep_695_and_pep_696_whitespaces_in_bound(app, tp_list, tptext):
+ text = f'.. py:function:: f{tp_list}()'
+ doctree = restructuredtext.parse(app, text)
+ assert doctree.astext() == f'\n\nf{tptext}()\n\n'
+
+
+@pytest.mark.parametrize(('tp_list', 'tptext'), [
+ ('[T:(int,str)]', '[T: (int, str)]'),
+ ('[T:(int|str,*Ts)]', '[T: (int | str, *Ts)]'),
+])
+def test_pep_695_and_pep_696_whitespaces_in_constraints(app, tp_list, tptext):
+ text = f'.. py:function:: f{tp_list}()'
+ doctree = restructuredtext.parse(app, text)
+ assert doctree.astext() == f'\n\nf{tptext}()\n\n'
+
+
+@pytest.mark.parametrize(('tp_list', 'tptext'), [
+ ('[T=int]', '[T = int]'),
+ ('[T:int=int]', '[T: int = int]'),
+ ('[*V=*Ts]', '[*V = *Ts]'),
+ ('[*V=(*Ts)]', '[*V = (*Ts)]'),
+ ('[*V=*tuple[str,...]]', '[*V = *tuple[str, ...]]'),
+ ('[*V=*tuple[*Ts,...]]', '[*V = *tuple[*Ts, ...]]'),
+ ('[*V=*tuple[int,*Ts]]', '[*V = *tuple[int, *Ts]]'),
+ ('[*V=*tuple[*Ts,int]]', '[*V = *tuple[*Ts, int]]'),
+ ('[**P=[int,*Ts]]', '[**P = [int, *Ts]]'),
+ ('[**P=[int, int*3]]', '[**P = [int, int * 3]]'),
+ ('[**P=[int, *Ts*3]]', '[**P = [int, *Ts * 3]]'),
+ ('[**P=[int,A[int,ctype("char")]]]', '[**P = [int, A[int, ctype("char")]]]'),
+])
+def test_pep_695_and_pep_696_whitespaces_in_default(app, tp_list, tptext):
+ text = f'.. py:function:: f{tp_list}()'
+ doctree = restructuredtext.parse(app, text)
+ assert doctree.astext() == f'\n\nf{tptext}()\n\n'
diff --git a/tests/test_domains/test_domain_py_canonical.py b/tests/test_domains/test_domain_py_canonical.py
new file mode 100644
index 0000000..3635cd1
--- /dev/null
+++ b/tests/test_domains/test_domain_py_canonical.py
@@ -0,0 +1,77 @@
+"""Tests the Python Domain"""
+
+from __future__ import annotations
+
+import pytest
+
+from sphinx import addnodes
+from sphinx.addnodes import (
+ desc,
+ desc_addname,
+ desc_annotation,
+ desc_content,
+ desc_name,
+ desc_sig_space,
+ desc_signature,
+)
+from sphinx.testing import restructuredtext
+from sphinx.testing.util import assert_node
+
+
+@pytest.mark.sphinx('html', testroot='domain-py', freshenv=True)
+def test_domain_py_canonical(app, status, warning):
+ app.build(force_all=True)
+
+ content = (app.outdir / 'canonical.html').read_text(encoding='utf8')
+ assert ('<a class="reference internal" href="#canonical.Foo" title="canonical.Foo">'
+ '<code class="xref py py-class docutils literal notranslate">'
+ '<span class="pre">Foo</span></code></a>' in content)
+ assert warning.getvalue() == ''
+
+
+def test_canonical(app):
+ text = (".. py:class:: io.StringIO\n"
+ " :canonical: _io.StringIO")
+ domain = app.env.get_domain('py')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_annotation, ("class", desc_sig_space)],
+ [desc_addname, "io."],
+ [desc_name, "StringIO"])],
+ desc_content)]))
+ assert 'io.StringIO' in domain.objects
+ assert domain.objects['io.StringIO'] == ('index', 'io.StringIO', 'class', False)
+ assert domain.objects['_io.StringIO'] == ('index', 'io.StringIO', 'class', True)
+
+
+def test_canonical_definition_overrides(app, warning):
+ text = (".. py:class:: io.StringIO\n"
+ " :canonical: _io.StringIO\n"
+ ".. py:class:: _io.StringIO\n")
+ restructuredtext.parse(app, text)
+ assert warning.getvalue() == ""
+
+ domain = app.env.get_domain('py')
+ assert domain.objects['_io.StringIO'] == ('index', 'id0', 'class', False)
+
+
+def test_canonical_definition_skip(app, warning):
+ text = (".. py:class:: _io.StringIO\n"
+ ".. py:class:: io.StringIO\n"
+ " :canonical: _io.StringIO\n")
+
+ restructuredtext.parse(app, text)
+ assert warning.getvalue() == ""
+
+ domain = app.env.get_domain('py')
+ assert domain.objects['_io.StringIO'] == ('index', 'io.StringIO', 'class', False)
+
+
+def test_canonical_duplicated(app, warning):
+ text = (".. py:class:: mypackage.StringIO\n"
+ " :canonical: _io.StringIO\n"
+ ".. py:class:: io.StringIO\n"
+ " :canonical: _io.StringIO\n")
+
+ restructuredtext.parse(app, text)
+ assert warning.getvalue() != ""
diff --git a/tests/test_domains/test_domain_py_fields.py b/tests/test_domains/test_domain_py_fields.py
new file mode 100644
index 0000000..47c40f5
--- /dev/null
+++ b/tests/test_domains/test_domain_py_fields.py
@@ -0,0 +1,326 @@
+"""Tests the Python Domain"""
+
+from __future__ import annotations
+
+from docutils import nodes
+
+from sphinx import addnodes
+from sphinx.addnodes import (
+ desc,
+ desc_addname,
+ desc_annotation,
+ desc_content,
+ desc_name,
+ desc_sig_punctuation,
+ desc_sig_space,
+ desc_signature,
+ pending_xref,
+)
+from sphinx.testing import restructuredtext
+from sphinx.testing.util import assert_node
+
+
+def test_info_field_list(app):
+ text = (".. py:module:: example\n"
+ ".. py:class:: Class\n"
+ "\n"
+ " :meta blah: this meta-field must not show up in the toc-tree\n"
+ " :param str name: blah blah\n"
+ " :meta another meta field:\n"
+ " :param age: blah blah\n"
+ " :type age: int\n"
+ " :param items: blah blah\n"
+ " :type items: Tuple[str, ...]\n"
+ " :param Dict[str, str] params: blah blah\n")
+ doctree = restructuredtext.parse(app, text)
+ print(doctree)
+
+ assert_node(doctree, (addnodes.index,
+ addnodes.index,
+ nodes.target,
+ [desc, ([desc_signature, ([desc_annotation, ("class", desc_sig_space)],
+ [desc_addname, "example."],
+ [desc_name, "Class"])],
+ [desc_content, nodes.field_list, nodes.field])]))
+ assert_node(doctree[3][1][0][0],
+ ([nodes.field_name, "Parameters"],
+ [nodes.field_body, nodes.bullet_list, ([nodes.list_item, nodes.paragraph],
+ [nodes.list_item, nodes.paragraph],
+ [nodes.list_item, nodes.paragraph],
+ [nodes.list_item, nodes.paragraph])]))
+
+ # :param str name:
+ assert_node(doctree[3][1][0][0][1][0][0][0],
+ ([addnodes.literal_strong, "name"],
+ " (",
+ [pending_xref, addnodes.literal_emphasis, "str"],
+ ")",
+ " -- ",
+ "blah blah"))
+ assert_node(doctree[3][1][0][0][1][0][0][0][2], pending_xref,
+ refdomain="py", reftype="class", reftarget="str",
+ **{"py:module": "example", "py:class": "Class"})
+
+ # :param age: + :type age:
+ assert_node(doctree[3][1][0][0][1][0][1][0],
+ ([addnodes.literal_strong, "age"],
+ " (",
+ [pending_xref, addnodes.literal_emphasis, "int"],
+ ")",
+ " -- ",
+ "blah blah"))
+ assert_node(doctree[3][1][0][0][1][0][1][0][2], pending_xref,
+ refdomain="py", reftype="class", reftarget="int",
+ **{"py:module": "example", "py:class": "Class"})
+
+ # :param items: + :type items:
+ assert_node(doctree[3][1][0][0][1][0][2][0],
+ ([addnodes.literal_strong, "items"],
+ " (",
+ [pending_xref, addnodes.literal_emphasis, "Tuple"],
+ [addnodes.literal_emphasis, "["],
+ [pending_xref, addnodes.literal_emphasis, "str"],
+ [addnodes.literal_emphasis, ", "],
+ [addnodes.literal_emphasis, "..."],
+ [addnodes.literal_emphasis, "]"],
+ ")",
+ " -- ",
+ "blah blah"))
+ assert_node(doctree[3][1][0][0][1][0][2][0][2], pending_xref,
+ refdomain="py", reftype="class", reftarget="Tuple",
+ **{"py:module": "example", "py:class": "Class"})
+ assert_node(doctree[3][1][0][0][1][0][2][0][4], pending_xref,
+ refdomain="py", reftype="class", reftarget="str",
+ **{"py:module": "example", "py:class": "Class"})
+
+ # :param Dict[str, str] params:
+ assert_node(doctree[3][1][0][0][1][0][3][0],
+ ([addnodes.literal_strong, "params"],
+ " (",
+ [pending_xref, addnodes.literal_emphasis, "Dict"],
+ [addnodes.literal_emphasis, "["],
+ [pending_xref, addnodes.literal_emphasis, "str"],
+ [addnodes.literal_emphasis, ", "],
+ [pending_xref, addnodes.literal_emphasis, "str"],
+ [addnodes.literal_emphasis, "]"],
+ ")",
+ " -- ",
+ "blah blah"))
+ assert_node(doctree[3][1][0][0][1][0][3][0][2], pending_xref,
+ refdomain="py", reftype="class", reftarget="Dict",
+ **{"py:module": "example", "py:class": "Class"})
+ assert_node(doctree[3][1][0][0][1][0][3][0][4], pending_xref,
+ refdomain="py", reftype="class", reftarget="str",
+ **{"py:module": "example", "py:class": "Class"})
+ assert_node(doctree[3][1][0][0][1][0][3][0][6], pending_xref,
+ refdomain="py", reftype="class", reftarget="str",
+ **{"py:module": "example", "py:class": "Class"})
+
+
+def test_info_field_list_piped_type(app):
+ text = (".. py:module:: example\n"
+ ".. py:class:: Class\n"
+ "\n"
+ " :param age: blah blah\n"
+ " :type age: int | str\n")
+ doctree = restructuredtext.parse(app, text)
+
+ assert_node(doctree,
+ (addnodes.index,
+ addnodes.index,
+ nodes.target,
+ [desc, ([desc_signature, ([desc_annotation, ("class", desc_sig_space)],
+ [desc_addname, "example."],
+ [desc_name, "Class"])],
+ [desc_content, nodes.field_list, nodes.field, (nodes.field_name,
+ nodes.field_body)])]))
+ assert_node(doctree[3][1][0][0][1],
+ ([nodes.paragraph, ([addnodes.literal_strong, "age"],
+ " (",
+ [pending_xref, addnodes.literal_emphasis, "int"],
+ [addnodes.literal_emphasis, " | "],
+ [pending_xref, addnodes.literal_emphasis, "str"],
+ ")",
+ " -- ",
+ "blah blah")],))
+ assert_node(doctree[3][1][0][0][1][0][2], pending_xref,
+ refdomain="py", reftype="class", reftarget="int",
+ **{"py:module": "example", "py:class": "Class"})
+ assert_node(doctree[3][1][0][0][1][0][4], pending_xref,
+ refdomain="py", reftype="class", reftarget="str",
+ **{"py:module": "example", "py:class": "Class"})
+
+
+def test_info_field_list_Literal(app):
+ text = (".. py:module:: example\n"
+ ".. py:class:: Class\n"
+ "\n"
+ " :param age: blah blah\n"
+ " :type age: Literal['foo', 'bar', 'baz']\n")
+ doctree = restructuredtext.parse(app, text)
+
+ assert_node(doctree,
+ (addnodes.index,
+ addnodes.index,
+ nodes.target,
+ [desc, ([desc_signature, ([desc_annotation, ("class", desc_sig_space)],
+ [desc_addname, "example."],
+ [desc_name, "Class"])],
+ [desc_content, nodes.field_list, nodes.field, (nodes.field_name,
+ nodes.field_body)])]))
+ assert_node(doctree[3][1][0][0][1],
+ ([nodes.paragraph, ([addnodes.literal_strong, "age"],
+ " (",
+ [pending_xref, addnodes.literal_emphasis, "Literal"],
+ [addnodes.literal_emphasis, "["],
+ [addnodes.literal_emphasis, "'foo'"],
+ [addnodes.literal_emphasis, ", "],
+ [addnodes.literal_emphasis, "'bar'"],
+ [addnodes.literal_emphasis, ", "],
+ [addnodes.literal_emphasis, "'baz'"],
+ [addnodes.literal_emphasis, "]"],
+ ")",
+ " -- ",
+ "blah blah")],))
+ assert_node(doctree[3][1][0][0][1][0][2], pending_xref,
+ refdomain="py", reftype="class", reftarget="Literal",
+ **{"py:module": "example", "py:class": "Class"})
+
+
+def test_info_field_list_var(app):
+ text = (".. py:class:: Class\n"
+ "\n"
+ " :var int attr: blah blah\n")
+ doctree = restructuredtext.parse(app, text)
+
+ assert_node(doctree, (addnodes.index,
+ [desc, (desc_signature,
+ [desc_content, nodes.field_list, nodes.field])]))
+ assert_node(doctree[1][1][0][0], ([nodes.field_name, "Variables"],
+ [nodes.field_body, nodes.paragraph]))
+
+ # :var int attr:
+ assert_node(doctree[1][1][0][0][1][0],
+ ([addnodes.literal_strong, "attr"],
+ " (",
+ [pending_xref, addnodes.literal_emphasis, "int"],
+ ")",
+ " -- ",
+ "blah blah"))
+ assert_node(doctree[1][1][0][0][1][0][2], pending_xref,
+ refdomain="py", reftype="class", reftarget="int", **{"py:class": "Class"})
+
+
+def test_info_field_list_napoleon_deliminator_of(app):
+ text = (".. py:module:: example\n"
+ ".. py:class:: Class\n"
+ "\n"
+ " :param list_str_var: example description.\n"
+ " :type list_str_var: list of str\n"
+ " :param tuple_int_var: example description.\n"
+ " :type tuple_int_var: tuple of tuple of int\n"
+ )
+ doctree = restructuredtext.parse(app, text)
+
+ # :param list of str list_str_var:
+ assert_node(doctree[3][1][0][0][1][0][0][0],
+ ([addnodes.literal_strong, "list_str_var"],
+ " (",
+ [pending_xref, addnodes.literal_emphasis, "list"],
+ [addnodes.literal_emphasis, " of "],
+ [pending_xref, addnodes.literal_emphasis, "str"],
+ ")",
+ " -- ",
+ "example description."))
+
+ # :param tuple of tuple of int tuple_int_var:
+ assert_node(doctree[3][1][0][0][1][0][1][0],
+ ([addnodes.literal_strong, "tuple_int_var"],
+ " (",
+ [pending_xref, addnodes.literal_emphasis, "tuple"],
+ [addnodes.literal_emphasis, " of "],
+ [pending_xref, addnodes.literal_emphasis, "tuple"],
+ [addnodes.literal_emphasis, " of "],
+ [pending_xref, addnodes.literal_emphasis, "int"],
+ ")",
+ " -- ",
+ "example description."))
+
+
+def test_info_field_list_napoleon_deliminator_or(app):
+ text = (".. py:module:: example\n"
+ ".. py:class:: Class\n"
+ "\n"
+ " :param bool_str_var: example description.\n"
+ " :type bool_str_var: bool or str\n"
+ " :param str_float_int_var: example description.\n"
+ " :type str_float_int_var: str or float or int\n"
+ )
+ doctree = restructuredtext.parse(app, text)
+
+ # :param bool or str bool_str_var:
+ assert_node(doctree[3][1][0][0][1][0][0][0],
+ ([addnodes.literal_strong, "bool_str_var"],
+ " (",
+ [pending_xref, addnodes.literal_emphasis, "bool"],
+ [addnodes.literal_emphasis, " or "],
+ [pending_xref, addnodes.literal_emphasis, "str"],
+ ")",
+ " -- ",
+ "example description."))
+
+ # :param str or float or int str_float_int_var:
+ assert_node(doctree[3][1][0][0][1][0][1][0],
+ ([addnodes.literal_strong, "str_float_int_var"],
+ " (",
+ [pending_xref, addnodes.literal_emphasis, "str"],
+ [addnodes.literal_emphasis, " or "],
+ [pending_xref, addnodes.literal_emphasis, "float"],
+ [addnodes.literal_emphasis, " or "],
+ [pending_xref, addnodes.literal_emphasis, "int"],
+ ")",
+ " -- ",
+ "example description."))
+
+
+def test_type_field(app):
+ text = (".. py:data:: var1\n"
+ " :type: .int\n"
+ ".. py:data:: var2\n"
+ " :type: ~builtins.int\n"
+ ".. py:data:: var3\n"
+ " :type: typing.Optional[typing.Tuple[int, typing.Any]]\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "var1"],
+ [desc_annotation, ([desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [pending_xref, "int"])])],
+ [desc_content, ()])],
+ addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "var2"],
+ [desc_annotation, ([desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [pending_xref, "int"])])],
+ [desc_content, ()])],
+ addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "var3"],
+ [desc_annotation, ([desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [pending_xref, "Optional"],
+ [desc_sig_punctuation, "["],
+ [pending_xref, "Tuple"],
+ [desc_sig_punctuation, "["],
+ [pending_xref, "int"],
+ [desc_sig_punctuation, ","],
+ desc_sig_space,
+ [pending_xref, "Any"],
+ [desc_sig_punctuation, "]"],
+ [desc_sig_punctuation, "]"])])],
+ [desc_content, ()])]))
+ assert_node(doctree[1][0][1][2], pending_xref, reftarget='int', refspecific=True)
+ assert_node(doctree[3][0][1][2], pending_xref, reftarget='builtins.int', refspecific=False)
+ assert_node(doctree[5][0][1][2], pending_xref, reftarget='typing.Optional', refspecific=False)
+ assert_node(doctree[5][0][1][4], pending_xref, reftarget='typing.Tuple', refspecific=False)
+ assert_node(doctree[5][0][1][6], pending_xref, reftarget='int', refspecific=False)
+ assert_node(doctree[5][0][1][9], pending_xref, reftarget='typing.Any', refspecific=False)
diff --git a/tests/test_domains/test_domain_py_pyfunction.py b/tests/test_domains/test_domain_py_pyfunction.py
new file mode 100644
index 0000000..187b919
--- /dev/null
+++ b/tests/test_domains/test_domain_py_pyfunction.py
@@ -0,0 +1,396 @@
+"""Tests the Python Domain"""
+
+from __future__ import annotations
+
+import pytest
+from docutils import nodes
+
+from sphinx import addnodes
+from sphinx.addnodes import (
+ desc,
+ desc_addname,
+ desc_annotation,
+ desc_content,
+ desc_name,
+ desc_optional,
+ desc_parameter,
+ desc_parameterlist,
+ desc_returns,
+ desc_sig_keyword,
+ desc_sig_name,
+ desc_sig_operator,
+ desc_sig_punctuation,
+ desc_sig_space,
+ desc_signature,
+ pending_xref,
+)
+from sphinx.testing import restructuredtext
+from sphinx.testing.util import assert_node
+
+
+def test_pyfunction(app):
+ text = (".. py:function:: func1\n"
+ ".. py:module:: example\n"
+ ".. py:function:: func2\n"
+ " :async:\n")
+ domain = app.env.get_domain('py')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "func1"],
+ [desc_parameterlist, ()])],
+ [desc_content, ()])],
+ addnodes.index,
+ addnodes.index,
+ nodes.target,
+ [desc, ([desc_signature, ([desc_annotation, ([desc_sig_keyword, 'async'],
+ desc_sig_space)],
+ [desc_addname, "example."],
+ [desc_name, "func2"],
+ [desc_parameterlist, ()])],
+ [desc_content, ()])]))
+ assert_node(doctree[0], addnodes.index,
+ entries=[('pair', 'built-in function; func1()', 'func1', '', None)])
+ assert_node(doctree[2], addnodes.index,
+ entries=[('pair', 'module; example', 'module-example', '', None)])
+ assert_node(doctree[3], addnodes.index,
+ entries=[('single', 'func2() (in module example)', 'example.func2', '', None)])
+
+ assert 'func1' in domain.objects
+ assert domain.objects['func1'] == ('index', 'func1', 'function', False)
+ assert 'example.func2' in domain.objects
+ assert domain.objects['example.func2'] == ('index', 'example.func2', 'function', False)
+
+
+def test_pyfunction_signature(app):
+ text = ".. py:function:: hello(name: str) -> str"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "hello"],
+ desc_parameterlist,
+ [desc_returns, pending_xref, "str"])],
+ desc_content)]))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="py", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, desc_parameter, ([desc_sig_name, "name"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [nodes.inline, pending_xref, "str"])])
+
+
+def test_pyfunction_signature_full(app):
+ text = (".. py:function:: hello(a: str, b = 1, *args: str, "
+ "c: bool = True, d: tuple = (1, 2), **kwargs: str) -> str")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "hello"],
+ desc_parameterlist,
+ [desc_returns, pending_xref, "str"])],
+ desc_content)]))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="py", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, ([desc_parameter, ([desc_sig_name, "a"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [desc_sig_name, pending_xref, "str"])],
+ [desc_parameter, ([desc_sig_name, "b"],
+ [desc_sig_operator, "="],
+ [nodes.inline, "1"])],
+ [desc_parameter, ([desc_sig_operator, "*"],
+ [desc_sig_name, "args"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [desc_sig_name, pending_xref, "str"])],
+ [desc_parameter, ([desc_sig_name, "c"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [desc_sig_name, pending_xref, "bool"],
+ desc_sig_space,
+ [desc_sig_operator, "="],
+ desc_sig_space,
+ [nodes.inline, "True"])],
+ [desc_parameter, ([desc_sig_name, "d"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [desc_sig_name, pending_xref, "tuple"],
+ desc_sig_space,
+ [desc_sig_operator, "="],
+ desc_sig_space,
+ [nodes.inline, "(1, 2)"])],
+ [desc_parameter, ([desc_sig_operator, "**"],
+ [desc_sig_name, "kwargs"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [desc_sig_name, pending_xref, "str"])])])
+ # case: separator at head
+ text = ".. py:function:: hello(*, a)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, ([desc_parameter, nodes.inline, "*"],
+ [desc_parameter, desc_sig_name, "a"])])
+
+ # case: separator in the middle
+ text = ".. py:function:: hello(a, /, b, *, c)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, ([desc_parameter, desc_sig_name, "a"],
+ [desc_parameter, desc_sig_operator, "/"],
+ [desc_parameter, desc_sig_name, "b"],
+ [desc_parameter, desc_sig_operator, "*"],
+ [desc_parameter, desc_sig_name, "c"])])
+
+ # case: separator in the middle (2)
+ text = ".. py:function:: hello(a, /, *, b)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, ([desc_parameter, desc_sig_name, "a"],
+ [desc_parameter, desc_sig_operator, "/"],
+ [desc_parameter, desc_sig_operator, "*"],
+ [desc_parameter, desc_sig_name, "b"])])
+
+ # case: separator at tail
+ text = ".. py:function:: hello(a, /)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, ([desc_parameter, desc_sig_name, "a"],
+ [desc_parameter, desc_sig_operator, "/"])])
+
+
+def test_pyfunction_with_unary_operators(app):
+ text = ".. py:function:: menu(egg=+1, bacon=-1, sausage=~1, spam=not spam)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, ([desc_parameter, ([desc_sig_name, "egg"],
+ [desc_sig_operator, "="],
+ [nodes.inline, "+1"])],
+ [desc_parameter, ([desc_sig_name, "bacon"],
+ [desc_sig_operator, "="],
+ [nodes.inline, "-1"])],
+ [desc_parameter, ([desc_sig_name, "sausage"],
+ [desc_sig_operator, "="],
+ [nodes.inline, "~1"])],
+ [desc_parameter, ([desc_sig_name, "spam"],
+ [desc_sig_operator, "="],
+ [nodes.inline, "not spam"])])])
+
+
+def test_pyfunction_with_binary_operators(app):
+ text = ".. py:function:: menu(spam=2**64)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, ([desc_parameter, ([desc_sig_name, "spam"],
+ [desc_sig_operator, "="],
+ [nodes.inline, "2**64"])])])
+
+
+def test_pyfunction_with_number_literals(app):
+ text = ".. py:function:: hello(age=0x10, height=1_6_0)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, ([desc_parameter, ([desc_sig_name, "age"],
+ [desc_sig_operator, "="],
+ [nodes.inline, "0x10"])],
+ [desc_parameter, ([desc_sig_name, "height"],
+ [desc_sig_operator, "="],
+ [nodes.inline, "1_6_0"])])])
+
+
+def test_pyfunction_with_union_type_operator(app):
+ text = ".. py:function:: hello(age: int | None)"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree[1][0][1],
+ [desc_parameterlist, ([desc_parameter, ([desc_sig_name, "age"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [desc_sig_name, ([pending_xref, "int"],
+ desc_sig_space,
+ [desc_sig_punctuation, "|"],
+ desc_sig_space,
+ [pending_xref, "None"])])])])
+
+
+def test_optional_pyfunction_signature(app):
+ text = ".. py:function:: compile(source [, filename [, symbol]]) -> ast object"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "compile"],
+ desc_parameterlist,
+ [desc_returns, pending_xref, "ast object"])],
+ desc_content)]))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="py", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1],
+ ([desc_parameter, ([desc_sig_name, "source"])],
+ [desc_optional, ([desc_parameter, ([desc_sig_name, "filename"])],
+ [desc_optional, desc_parameter, ([desc_sig_name, "symbol"])])]))
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'python_maximum_signature_line_length': len("hello(name: str) -> str"),
+})
+def test_pyfunction_signature_with_python_maximum_signature_line_length_equal(app):
+ text = ".. py:function:: hello(name: str) -> str"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, "hello"],
+ desc_parameterlist,
+ [desc_returns, pending_xref, "str"],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="py", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1], [desc_parameterlist, desc_parameter, (
+ [desc_sig_name, "name"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [nodes.inline, pending_xref, "str"],
+ )])
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'python_maximum_signature_line_length': len("hello(name: str) -> str"),
+})
+def test_pyfunction_signature_with_python_maximum_signature_line_length_force_single(app):
+ text = (".. py:function:: hello(names: str) -> str\n"
+ " :single-line-parameter-list:")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, "hello"],
+ desc_parameterlist,
+ [desc_returns, pending_xref, "str"],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="py", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1], [desc_parameterlist, desc_parameter, (
+ [desc_sig_name, "names"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [nodes.inline, pending_xref, "str"],
+ )])
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'python_maximum_signature_line_length': len("hello(name: str) -> str"),
+})
+def test_pyfunction_signature_with_python_maximum_signature_line_length_break(app):
+ text = ".. py:function:: hello(names: str) -> str"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, "hello"],
+ desc_parameterlist,
+ [desc_returns, pending_xref, "str"],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="py", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1], [desc_parameterlist, desc_parameter, (
+ [desc_sig_name, "names"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [nodes.inline, pending_xref, "str"],
+ )])
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=True)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'maximum_signature_line_length': len("hello(name: str) -> str"),
+})
+def test_pyfunction_signature_with_maximum_signature_line_length_equal(app):
+ text = ".. py:function:: hello(name: str) -> str"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, "hello"],
+ desc_parameterlist,
+ [desc_returns, pending_xref, "str"],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="py", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1], [desc_parameterlist, desc_parameter, (
+ [desc_sig_name, "name"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [nodes.inline, pending_xref, "str"],
+ )])
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'maximum_signature_line_length': len("hello(name: str) -> str"),
+})
+def test_pyfunction_signature_with_maximum_signature_line_length_force_single(app):
+ text = (".. py:function:: hello(names: str) -> str\n"
+ " :single-line-parameter-list:")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, "hello"],
+ desc_parameterlist,
+ [desc_returns, pending_xref, "str"],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="py", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1], [desc_parameterlist, desc_parameter, (
+ [desc_sig_name, "names"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [nodes.inline, pending_xref, "str"],
+ )])
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=False)
+
+
+@pytest.mark.sphinx('html', confoverrides={
+ 'maximum_signature_line_length': len("hello(name: str) -> str"),
+})
+def test_pyfunction_signature_with_maximum_signature_line_length_break(app):
+ text = ".. py:function:: hello(names: str) -> str"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, "hello"],
+ desc_parameterlist,
+ [desc_returns, pending_xref, "str"],
+ )],
+ desc_content,
+ )],
+ ))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="py", objtype="function", no_index=False)
+ assert_node(doctree[1][0][1], [desc_parameterlist, desc_parameter, (
+ [desc_sig_name, "names"],
+ [desc_sig_punctuation, ":"],
+ desc_sig_space,
+ [nodes.inline, pending_xref, "str"],
+ )])
+ assert_node(doctree[1][0][1], desc_parameterlist, multi_line_parameter_list=True)
diff --git a/tests/test_domains/test_domain_py_pyobject.py b/tests/test_domains/test_domain_py_pyobject.py
new file mode 100644
index 0000000..04f9341
--- /dev/null
+++ b/tests/test_domains/test_domain_py_pyobject.py
@@ -0,0 +1,487 @@
+"""Tests the Python Domain"""
+
+from __future__ import annotations
+
+from docutils import nodes
+
+from sphinx import addnodes
+from sphinx.addnodes import (
+ desc,
+ desc_addname,
+ desc_annotation,
+ desc_content,
+ desc_name,
+ desc_parameterlist,
+ desc_sig_punctuation,
+ desc_sig_space,
+ desc_signature,
+ pending_xref,
+)
+from sphinx.testing import restructuredtext
+from sphinx.testing.util import assert_node
+
+
+def test_pyexception_signature(app):
+ text = ".. py:exception:: builtins.IOError"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_annotation, ('exception', desc_sig_space)],
+ [desc_addname, "builtins."],
+ [desc_name, "IOError"])],
+ desc_content)]))
+ assert_node(doctree[1], desc, desctype="exception",
+ domain="py", objtype="exception", no_index=False)
+
+
+def test_pydata_signature(app):
+ text = (".. py:data:: version\n"
+ " :type: int\n"
+ " :value: 1\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "version"],
+ [desc_annotation, ([desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [pending_xref, "int"])],
+ [desc_annotation, (
+ desc_sig_space,
+ [desc_sig_punctuation, '='],
+ desc_sig_space,
+ "1")],
+ )],
+ desc_content)]))
+ assert_node(doctree[1], addnodes.desc, desctype="data",
+ domain="py", objtype="data", no_index=False)
+
+
+def test_pydata_signature_old(app):
+ text = (".. py:data:: version\n"
+ " :annotation: = 1\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "version"],
+ [desc_annotation, (desc_sig_space,
+ "= 1")])],
+ desc_content)]))
+ assert_node(doctree[1], addnodes.desc, desctype="data",
+ domain="py", objtype="data", no_index=False)
+
+
+def test_pydata_with_union_type_operator(app):
+ text = (".. py:data:: version\n"
+ " :type: int | str")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree[1][0],
+ ([desc_name, "version"],
+ [desc_annotation, ([desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [pending_xref, "int"],
+ desc_sig_space,
+ [desc_sig_punctuation, "|"],
+ desc_sig_space,
+ [pending_xref, "str"])]))
+
+
+def test_pyobject_prefix(app):
+ text = (".. py:class:: Foo\n"
+ "\n"
+ " .. py:method:: Foo.say\n"
+ " .. py:method:: FooBar.say")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_annotation, ('class', desc_sig_space)],
+ [desc_name, "Foo"])],
+ [desc_content, (addnodes.index,
+ desc,
+ addnodes.index,
+ desc)])]))
+ assert doctree[1][1][1].astext().strip() == 'say()' # prefix is stripped
+ assert doctree[1][1][3].astext().strip() == 'FooBar.say()' # not stripped
+
+
+def test_pydata(app):
+ text = (".. py:module:: example\n"
+ ".. py:data:: var\n"
+ " :type: int\n")
+ domain = app.env.get_domain('py')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ addnodes.index,
+ nodes.target,
+ [desc, ([desc_signature, ([desc_addname, "example."],
+ [desc_name, "var"],
+ [desc_annotation, ([desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [pending_xref, "int"])])],
+ [desc_content, ()])]))
+ assert_node(doctree[3][0][2][2], pending_xref, **{"py:module": "example"})
+ assert 'example.var' in domain.objects
+ assert domain.objects['example.var'] == ('index', 'example.var', 'data', False)
+
+
+def test_pyclass_options(app):
+ text = (".. py:class:: Class1\n"
+ ".. py:class:: Class2\n"
+ " :final:\n")
+ domain = app.env.get_domain('py')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_annotation, ("class", desc_sig_space)],
+ [desc_name, "Class1"])],
+ [desc_content, ()])],
+ addnodes.index,
+ [desc, ([desc_signature, ([desc_annotation, ("final",
+ desc_sig_space,
+ "class",
+ desc_sig_space)],
+ [desc_name, "Class2"])],
+ [desc_content, ()])]))
+
+ # class
+ assert_node(doctree[0], addnodes.index,
+ entries=[('single', 'Class1 (built-in class)', 'Class1', '', None)])
+ assert 'Class1' in domain.objects
+ assert domain.objects['Class1'] == ('index', 'Class1', 'class', False)
+
+ # :final:
+ assert_node(doctree[2], addnodes.index,
+ entries=[('single', 'Class2 (built-in class)', 'Class2', '', None)])
+ assert 'Class2' in domain.objects
+ assert domain.objects['Class2'] == ('index', 'Class2', 'class', False)
+
+
+def test_pymethod_options(app):
+ text = (".. py:class:: Class\n"
+ "\n"
+ " .. py:method:: meth1\n"
+ " .. py:method:: meth2\n"
+ " :classmethod:\n"
+ " .. py:method:: meth3\n"
+ " :staticmethod:\n"
+ " .. py:method:: meth4\n"
+ " :async:\n"
+ " .. py:method:: meth5\n"
+ " :abstractmethod:\n"
+ " .. py:method:: meth6\n"
+ " :final:\n")
+ domain = app.env.get_domain('py')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_annotation, ("class", desc_sig_space)],
+ [desc_name, "Class"])],
+ [desc_content, (addnodes.index,
+ desc,
+ addnodes.index,
+ desc,
+ addnodes.index,
+ desc,
+ addnodes.index,
+ desc,
+ addnodes.index,
+ desc,
+ addnodes.index,
+ desc)])]))
+
+ # method
+ assert_node(doctree[1][1][0], addnodes.index,
+ entries=[('single', 'meth1() (Class method)', 'Class.meth1', '', None)])
+ assert_node(doctree[1][1][1], ([desc_signature, ([desc_name, "meth1"],
+ [desc_parameterlist, ()])],
+ [desc_content, ()]))
+ assert 'Class.meth1' in domain.objects
+ assert domain.objects['Class.meth1'] == ('index', 'Class.meth1', 'method', False)
+
+ # :classmethod:
+ assert_node(doctree[1][1][2], addnodes.index,
+ entries=[('single', 'meth2() (Class class method)', 'Class.meth2', '', None)])
+ assert_node(doctree[1][1][3], ([desc_signature, ([desc_annotation, ("classmethod", desc_sig_space)],
+ [desc_name, "meth2"],
+ [desc_parameterlist, ()])],
+ [desc_content, ()]))
+ assert 'Class.meth2' in domain.objects
+ assert domain.objects['Class.meth2'] == ('index', 'Class.meth2', 'method', False)
+
+ # :staticmethod:
+ assert_node(doctree[1][1][4], addnodes.index,
+ entries=[('single', 'meth3() (Class static method)', 'Class.meth3', '', None)])
+ assert_node(doctree[1][1][5], ([desc_signature, ([desc_annotation, ("static", desc_sig_space)],
+ [desc_name, "meth3"],
+ [desc_parameterlist, ()])],
+ [desc_content, ()]))
+ assert 'Class.meth3' in domain.objects
+ assert domain.objects['Class.meth3'] == ('index', 'Class.meth3', 'method', False)
+
+ # :async:
+ assert_node(doctree[1][1][6], addnodes.index,
+ entries=[('single', 'meth4() (Class method)', 'Class.meth4', '', None)])
+ assert_node(doctree[1][1][7], ([desc_signature, ([desc_annotation, ("async", desc_sig_space)],
+ [desc_name, "meth4"],
+ [desc_parameterlist, ()])],
+ [desc_content, ()]))
+ assert 'Class.meth4' in domain.objects
+ assert domain.objects['Class.meth4'] == ('index', 'Class.meth4', 'method', False)
+
+ # :abstractmethod:
+ assert_node(doctree[1][1][8], addnodes.index,
+ entries=[('single', 'meth5() (Class method)', 'Class.meth5', '', None)])
+ assert_node(doctree[1][1][9], ([desc_signature, ([desc_annotation, ("abstract", desc_sig_space)],
+ [desc_name, "meth5"],
+ [desc_parameterlist, ()])],
+ [desc_content, ()]))
+ assert 'Class.meth5' in domain.objects
+ assert domain.objects['Class.meth5'] == ('index', 'Class.meth5', 'method', False)
+
+ # :final:
+ assert_node(doctree[1][1][10], addnodes.index,
+ entries=[('single', 'meth6() (Class method)', 'Class.meth6', '', None)])
+ assert_node(doctree[1][1][11], ([desc_signature, ([desc_annotation, ("final", desc_sig_space)],
+ [desc_name, "meth6"],
+ [desc_parameterlist, ()])],
+ [desc_content, ()]))
+ assert 'Class.meth6' in domain.objects
+ assert domain.objects['Class.meth6'] == ('index', 'Class.meth6', 'method', False)
+
+
+def test_pyclassmethod(app):
+ text = (".. py:class:: Class\n"
+ "\n"
+ " .. py:classmethod:: meth\n")
+ domain = app.env.get_domain('py')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_annotation, ("class", desc_sig_space)],
+ [desc_name, "Class"])],
+ [desc_content, (addnodes.index,
+ desc)])]))
+ assert_node(doctree[1][1][0], addnodes.index,
+ entries=[('single', 'meth() (Class class method)', 'Class.meth', '', None)])
+ assert_node(doctree[1][1][1], ([desc_signature, ([desc_annotation, ("classmethod", desc_sig_space)],
+ [desc_name, "meth"],
+ [desc_parameterlist, ()])],
+ [desc_content, ()]))
+ assert 'Class.meth' in domain.objects
+ assert domain.objects['Class.meth'] == ('index', 'Class.meth', 'method', False)
+
+
+def test_pystaticmethod(app):
+ text = (".. py:class:: Class\n"
+ "\n"
+ " .. py:staticmethod:: meth\n")
+ domain = app.env.get_domain('py')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_annotation, ("class", desc_sig_space)],
+ [desc_name, "Class"])],
+ [desc_content, (addnodes.index,
+ desc)])]))
+ assert_node(doctree[1][1][0], addnodes.index,
+ entries=[('single', 'meth() (Class static method)', 'Class.meth', '', None)])
+ assert_node(doctree[1][1][1], ([desc_signature, ([desc_annotation, ("static", desc_sig_space)],
+ [desc_name, "meth"],
+ [desc_parameterlist, ()])],
+ [desc_content, ()]))
+ assert 'Class.meth' in domain.objects
+ assert domain.objects['Class.meth'] == ('index', 'Class.meth', 'method', False)
+
+
+def test_pyattribute(app):
+ text = (".. py:class:: Class\n"
+ "\n"
+ " .. py:attribute:: attr\n"
+ " :type: Optional[str]\n"
+ " :value: ''\n")
+ domain = app.env.get_domain('py')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_annotation, ("class", desc_sig_space)],
+ [desc_name, "Class"])],
+ [desc_content, (addnodes.index,
+ desc)])]))
+ assert_node(doctree[1][1][0], addnodes.index,
+ entries=[('single', 'attr (Class attribute)', 'Class.attr', '', None)])
+ assert_node(doctree[1][1][1], ([desc_signature, ([desc_name, "attr"],
+ [desc_annotation, ([desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [pending_xref, "str"],
+ desc_sig_space,
+ [desc_sig_punctuation, "|"],
+ desc_sig_space,
+ [pending_xref, "None"])],
+ [desc_annotation, (desc_sig_space,
+ [desc_sig_punctuation, '='],
+ desc_sig_space,
+ "''")],
+ )],
+ [desc_content, ()]))
+ assert_node(doctree[1][1][1][0][1][2], pending_xref, **{"py:class": "Class"})
+ assert_node(doctree[1][1][1][0][1][6], pending_xref, **{"py:class": "Class"})
+ assert 'Class.attr' in domain.objects
+ assert domain.objects['Class.attr'] == ('index', 'Class.attr', 'attribute', False)
+
+
+def test_pyproperty(app):
+ text = (".. py:class:: Class\n"
+ "\n"
+ " .. py:property:: prop1\n"
+ " :abstractmethod:\n"
+ " :type: str\n"
+ "\n"
+ " .. py:property:: prop2\n"
+ " :classmethod:\n"
+ " :type: str\n")
+ domain = app.env.get_domain('py')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_annotation, ("class", desc_sig_space)],
+ [desc_name, "Class"])],
+ [desc_content, (addnodes.index,
+ desc,
+ addnodes.index,
+ desc)])]))
+ assert_node(doctree[1][1][0], addnodes.index,
+ entries=[('single', 'prop1 (Class property)', 'Class.prop1', '', None)])
+ assert_node(doctree[1][1][1], ([desc_signature, ([desc_annotation, ("abstract", desc_sig_space,
+ "property", desc_sig_space)],
+ [desc_name, "prop1"],
+ [desc_annotation, ([desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [pending_xref, "str"])])],
+ [desc_content, ()]))
+ assert_node(doctree[1][1][2], addnodes.index,
+ entries=[('single', 'prop2 (Class property)', 'Class.prop2', '', None)])
+ assert_node(doctree[1][1][3], ([desc_signature, ([desc_annotation, ("class", desc_sig_space,
+ "property", desc_sig_space)],
+ [desc_name, "prop2"],
+ [desc_annotation, ([desc_sig_punctuation, ':'],
+ desc_sig_space,
+ [pending_xref, "str"])])],
+ [desc_content, ()]))
+ assert 'Class.prop1' in domain.objects
+ assert domain.objects['Class.prop1'] == ('index', 'Class.prop1', 'property', False)
+ assert 'Class.prop2' in domain.objects
+ assert domain.objects['Class.prop2'] == ('index', 'Class.prop2', 'property', False)
+
+
+def test_pydecorator_signature(app):
+ text = ".. py:decorator:: deco"
+ domain = app.env.get_domain('py')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_addname, "@"],
+ [desc_name, "deco"])],
+ desc_content)]))
+ assert_node(doctree[1], addnodes.desc, desctype="function",
+ domain="py", objtype="function", no_index=False)
+
+ assert 'deco' in domain.objects
+ assert domain.objects['deco'] == ('index', 'deco', 'function', False)
+
+
+def test_pydecoratormethod_signature(app):
+ text = ".. py:decoratormethod:: deco"
+ domain = app.env.get_domain('py')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_addname, "@"],
+ [desc_name, "deco"])],
+ desc_content)]))
+ assert_node(doctree[1], addnodes.desc, desctype="method",
+ domain="py", objtype="method", no_index=False)
+
+ assert 'deco' in domain.objects
+ assert domain.objects['deco'] == ('index', 'deco', 'method', False)
+
+
+def test_pycurrentmodule(app):
+ text = (".. py:module:: Other\n"
+ "\n"
+ ".. py:module:: Module\n"
+ ".. py:class:: A\n"
+ "\n"
+ " .. py:method:: m1\n"
+ " .. py:method:: m2\n"
+ "\n"
+ ".. py:currentmodule:: Other\n"
+ "\n"
+ ".. py:class:: B\n"
+ "\n"
+ " .. py:method:: m3\n"
+ " .. py:method:: m4\n")
+ domain = app.env.get_domain('py')
+ doctree = restructuredtext.parse(app, text)
+ print(doctree)
+ assert_node(
+ doctree, (
+ addnodes.index,
+ addnodes.index,
+ addnodes.index,
+ nodes.target,
+ nodes.target,
+ [desc, (
+ [desc_signature, (
+ [desc_annotation, ("class", desc_sig_space)],
+ [desc_addname, "Module."],
+ [desc_name, "A"],
+ )],
+ [desc_content, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, "m1"],
+ [desc_parameterlist, ()],
+ )],
+ [desc_content, ()],
+ )],
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, "m2"],
+ [desc_parameterlist, ()],
+ )],
+ [desc_content, ()],
+ )],
+ )],
+ )],
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_annotation, ("class", desc_sig_space)],
+ [desc_addname, "Other."],
+ [desc_name, "B"],
+ )],
+ [desc_content, (
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, "m3"],
+ [desc_parameterlist, ()],
+ )],
+ [desc_content, ()],
+ )],
+ addnodes.index,
+ [desc, (
+ [desc_signature, (
+ [desc_name, "m4"],
+ [desc_parameterlist, ()],
+ )],
+ [desc_content, ()],
+ )],
+ )],
+ )],
+ ))
+ assert 'Module' in domain.objects
+ assert domain.objects['Module'] == ('index', 'module-Module', 'module', False)
+ assert 'Other' in domain.objects
+ assert domain.objects['Other'] == ('index', 'module-Other', 'module', False)
+ assert 'Module.A' in domain.objects
+ assert domain.objects['Module.A'] == ('index', 'Module.A', 'class', False)
+ assert 'Other.B' in domain.objects
+ assert domain.objects['Other.B'] == ('index', 'Other.B', 'class', False)
+ assert 'Module.A.m1' in domain.objects
+ assert domain.objects['Module.A.m1'] == ('index', 'Module.A.m1', 'method', False)
+ assert 'Module.A.m2' in domain.objects
+ assert domain.objects['Module.A.m2'] == ('index', 'Module.A.m2', 'method', False)
+ assert 'Other.B.m3' in domain.objects
+ assert domain.objects['Other.B.m3'] == ('index', 'Other.B.m3', 'method', False)
+ assert 'Other.B.m4' in domain.objects
+ assert domain.objects['Other.B.m4'] == ('index', 'Other.B.m4', 'method', False)
diff --git a/tests/test_domains/test_domain_rst.py b/tests/test_domains/test_domain_rst.py
new file mode 100644
index 0000000..4445da1
--- /dev/null
+++ b/tests/test_domains/test_domain_rst.py
@@ -0,0 +1,137 @@
+"""Tests the reStructuredText domain."""
+
+from sphinx import addnodes
+from sphinx.addnodes import (
+ desc,
+ desc_addname,
+ desc_annotation,
+ desc_content,
+ desc_name,
+ desc_signature,
+)
+from sphinx.domains.rst import parse_directive
+from sphinx.testing import restructuredtext
+from sphinx.testing.util import assert_node
+
+
+def test_parse_directive():
+ s = parse_directive(' foö ')
+ assert s == ('foö', '')
+
+ s = parse_directive(' .. foö :: ')
+ assert s == ('foö', '')
+
+ s = parse_directive('.. foö:: args1 args2')
+ assert s == ('foö', ' args1 args2')
+
+ s = parse_directive('.. :: bar')
+ assert s == ('.. :: bar', '')
+
+
+def test_rst_directive(app):
+ # bare
+ text = ".. rst:directive:: toctree"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, desc_name, ".. toctree::"],
+ [desc_content, ()])]))
+ assert_node(doctree[0],
+ entries=[("single", "toctree (directive)", "directive-toctree", "", None)])
+ assert_node(doctree[1], addnodes.desc, desctype="directive",
+ domain="rst", objtype="directive", no_index=False)
+
+ # decorated
+ text = ".. rst:directive:: .. toctree::"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, desc_name, ".. toctree::"],
+ [desc_content, ()])]))
+ assert_node(doctree[0],
+ entries=[("single", "toctree (directive)", "directive-toctree", "", None)])
+ assert_node(doctree[1], addnodes.desc, desctype="directive",
+ domain="rst", objtype="directive", no_index=False)
+
+
+def test_rst_directive_with_argument(app):
+ text = ".. rst:directive:: .. toctree:: foo bar baz"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, ".. toctree::"],
+ [desc_addname, " foo bar baz"])],
+ [desc_content, ()])]))
+ assert_node(doctree[0],
+ entries=[("single", "toctree (directive)", "directive-toctree", "", None)])
+ assert_node(doctree[1], addnodes.desc, desctype="directive",
+ domain="rst", objtype="directive", no_index=False)
+
+
+def test_rst_directive_option(app):
+ text = ".. rst:directive:option:: foo"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, desc_name, ":foo:"],
+ [desc_content, ()])]))
+ assert_node(doctree[0],
+ entries=[("single", ":foo: (directive option)",
+ "directive-option-foo", "", "F")])
+ assert_node(doctree[1], addnodes.desc, desctype="directive:option",
+ domain="rst", objtype="directive:option", no_index=False)
+
+
+def test_rst_directive_option_with_argument(app):
+ text = ".. rst:directive:option:: foo: bar baz"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, ":foo:"],
+ [desc_annotation, " bar baz"])],
+ [desc_content, ()])]))
+ assert_node(doctree[0],
+ entries=[("single", ":foo: (directive option)",
+ "directive-option-foo", "", "F")])
+ assert_node(doctree[1], addnodes.desc, desctype="directive:option",
+ domain="rst", objtype="directive:option", no_index=False)
+
+
+def test_rst_directive_option_type(app):
+ text = (".. rst:directive:option:: foo\n"
+ " :type: directives.flags\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, ":foo:"],
+ [desc_annotation, " (directives.flags)"])],
+ [desc_content, ()])]))
+ assert_node(doctree[0],
+ entries=[("single", ":foo: (directive option)",
+ "directive-option-foo", "", "F")])
+ assert_node(doctree[1], addnodes.desc, desctype="directive:option",
+ domain="rst", objtype="directive:option", no_index=False)
+
+
+def test_rst_directive_and_directive_option(app):
+ text = (".. rst:directive:: foo\n"
+ "\n"
+ " .. rst:directive:option:: bar\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, desc_name, ".. foo::"],
+ [desc_content, (addnodes.index,
+ desc)])]))
+ assert_node(doctree[1][1][0],
+ entries=[("pair", "foo (directive); :bar: (directive option)",
+ "directive-option-foo-bar", "", "B")])
+ assert_node(doctree[1][1][1], ([desc_signature, desc_name, ":bar:"],
+ [desc_content, ()]))
+ assert_node(doctree[1][1][1], addnodes.desc, desctype="directive:option",
+ domain="rst", objtype="directive:option", no_index=False)
+
+
+def test_rst_role(app):
+ text = ".. rst:role:: ref"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, desc_name, ":ref:"],
+ [desc_content, ()])]))
+ assert_node(doctree[0],
+ entries=[("single", "ref (role)", "role-ref", "", None)])
+ assert_node(doctree[1], addnodes.desc, desctype="role",
+ domain="rst", objtype="role", no_index=False)
diff --git a/tests/test_domains/test_domain_std.py b/tests/test_domains/test_domain_std.py
new file mode 100644
index 0000000..52ecdf5
--- /dev/null
+++ b/tests/test_domains/test_domain_std.py
@@ -0,0 +1,517 @@
+"""Tests the std domain"""
+
+from unittest import mock
+
+import pytest
+from docutils import nodes
+from docutils.nodes import definition, definition_list, definition_list_item, term
+
+from sphinx import addnodes
+from sphinx.addnodes import (
+ desc,
+ desc_addname,
+ desc_content,
+ desc_name,
+ desc_signature,
+ glossary,
+ index,
+ pending_xref,
+)
+from sphinx.domains.std import StandardDomain
+from sphinx.testing import restructuredtext
+from sphinx.testing.util import assert_node, etree_parse
+
+
+def test_process_doc_handle_figure_caption():
+ env = mock.Mock(domaindata={})
+ env.app.registry.enumerable_nodes = {}
+ figure_node = nodes.figure(
+ '',
+ nodes.caption('caption text', 'caption text'),
+ )
+ document = mock.Mock(
+ nametypes={'testname': True},
+ nameids={'testname': 'testid'},
+ ids={'testid': figure_node},
+ citation_refs={},
+ )
+ document.findall.return_value = []
+
+ domain = StandardDomain(env)
+ if 'testname' in domain.data['labels']:
+ del domain.data['labels']['testname']
+ domain.process_doc(env, 'testdoc', document)
+ assert 'testname' in domain.data['labels']
+ assert domain.data['labels']['testname'] == (
+ 'testdoc', 'testid', 'caption text')
+
+
+def test_process_doc_handle_table_title():
+ env = mock.Mock(domaindata={})
+ env.app.registry.enumerable_nodes = {}
+ table_node = nodes.table(
+ '',
+ nodes.title('title text', 'title text'),
+ )
+ document = mock.Mock(
+ nametypes={'testname': True},
+ nameids={'testname': 'testid'},
+ ids={'testid': table_node},
+ citation_refs={},
+ )
+ document.findall.return_value = []
+
+ domain = StandardDomain(env)
+ if 'testname' in domain.data['labels']:
+ del domain.data['labels']['testname']
+ domain.process_doc(env, 'testdoc', document)
+ assert 'testname' in domain.data['labels']
+ assert domain.data['labels']['testname'] == (
+ 'testdoc', 'testid', 'title text')
+
+
+def test_get_full_qualified_name():
+ env = mock.Mock(domaindata={})
+ env.app.registry.enumerable_nodes = {}
+ domain = StandardDomain(env)
+
+ # normal references
+ node = nodes.reference()
+ assert domain.get_full_qualified_name(node) is None
+
+ # simple reference to options
+ node = nodes.reference(reftype='option', reftarget='-l')
+ assert domain.get_full_qualified_name(node) is None
+
+ # options with std:program context
+ kwargs = {'std:program': 'ls'}
+ node = nodes.reference(reftype='option', reftarget='-l', **kwargs)
+ assert domain.get_full_qualified_name(node) == 'ls.-l'
+
+
+def test_cmd_option_with_optional_value(app):
+ text = ".. option:: -j[=N]"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (index,
+ [desc, ([desc_signature, ([desc_name, '-j'],
+ [desc_addname, '[=N]'])],
+ [desc_content, ()])]))
+ assert_node(doctree[0], addnodes.index,
+ entries=[('pair', 'command line option; -j', 'cmdoption-j', '', None)])
+
+ objects = list(app.env.get_domain("std").get_objects())
+ assert ('-j', '-j', 'cmdoption', 'index', 'cmdoption-j', 1) in objects
+
+
+def test_cmd_option_starting_with_bracket(app):
+ text = ".. option:: [enable=]PATTERN"
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (index,
+ [desc, ([desc_signature, ([desc_name, '[enable'],
+ [desc_addname, '=]PATTERN'])],
+ [desc_content, ()])]))
+ objects = list(app.env.get_domain("std").get_objects())
+ assert ('[enable', '[enable', 'cmdoption', 'index', 'cmdoption-arg-enable', 1) in objects
+
+
+def test_glossary(app):
+ text = (".. glossary::\n"
+ "\n"
+ " term1\n"
+ " TERM2\n"
+ " description\n"
+ "\n"
+ " term3 : classifier\n"
+ " description\n"
+ " description\n"
+ "\n"
+ " term4 : class1 : class2\n"
+ " description\n")
+
+ # doctree
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ [glossary, definition_list, ([definition_list_item, ([term, ("term1",
+ index)],
+ [term, ("TERM2",
+ index)],
+ definition)],
+ [definition_list_item, ([term, ("term3",
+ index)],
+ definition)],
+ [definition_list_item, ([term, ("term4",
+ index)],
+ definition)])],
+ ))
+ assert_node(doctree[0][0][0][0][1],
+ entries=[("single", "term1", "term-term1", "main", None)])
+ assert_node(doctree[0][0][0][1][1],
+ entries=[("single", "TERM2", "term-TERM2", "main", None)])
+ assert_node(doctree[0][0][0][2],
+ [definition, nodes.paragraph, "description"])
+ assert_node(doctree[0][0][1][0][1],
+ entries=[("single", "term3", "term-term3", "main", "classifier")])
+ assert_node(doctree[0][0][1][1],
+ [definition, nodes.paragraph, ("description\n"
+ "description")])
+ assert_node(doctree[0][0][2][0][1],
+ entries=[("single", "term4", "term-term4", "main", "class1")])
+ assert_node(doctree[0][0][2][1],
+ [nodes.definition, nodes.paragraph, "description"])
+
+ # index
+ domain = app.env.get_domain("std")
+ objects = list(domain.get_objects())
+ assert ("term1", "term1", "term", "index", "term-term1", -1) in objects
+ assert ("TERM2", "TERM2", "term", "index", "term-TERM2", -1) in objects
+ assert ("term3", "term3", "term", "index", "term-term3", -1) in objects
+ assert ("term4", "term4", "term", "index", "term-term4", -1) in objects
+
+ # term reference (case sensitive)
+ refnode = domain.resolve_xref(app.env, 'index', app.builder, 'term', 'term1',
+ pending_xref(), nodes.paragraph())
+ assert_node(refnode, nodes.reference, refid="term-term1")
+
+ # term reference (case insensitive)
+ refnode = domain.resolve_xref(app.env, 'index', app.builder, 'term', 'term2',
+ pending_xref(), nodes.paragraph())
+ assert_node(refnode, nodes.reference, refid="term-TERM2")
+
+
+def test_glossary_warning(app, status, warning):
+ # empty line between terms
+ text = (".. glossary::\n"
+ "\n"
+ " term1\n"
+ "\n"
+ " term2\n")
+ restructuredtext.parse(app, text, "case1")
+ assert ("case1.rst:4: WARNING: glossary terms must not be separated by empty lines"
+ in warning.getvalue())
+
+ # glossary starts with indented item
+ text = (".. glossary::\n"
+ "\n"
+ " description\n"
+ " term\n")
+ restructuredtext.parse(app, text, "case2")
+ assert ("case2.rst:3: WARNING: glossary term must be preceded by empty line"
+ in warning.getvalue())
+
+ # empty line between terms
+ text = (".. glossary::\n"
+ "\n"
+ " term1\n"
+ " description\n"
+ " term2\n")
+ restructuredtext.parse(app, text, "case3")
+ assert ("case3.rst:4: WARNING: glossary term must be preceded by empty line"
+ in warning.getvalue())
+
+ # duplicated terms
+ text = (".. glossary::\n"
+ "\n"
+ " term-case4\n"
+ " term-case4\n")
+ restructuredtext.parse(app, text, "case4")
+ assert ("case4.rst:3: WARNING: duplicate term description of term-case4, "
+ "other instance in case4" in warning.getvalue())
+
+
+def test_glossary_comment(app):
+ text = (".. glossary::\n"
+ "\n"
+ " term1\n"
+ " description\n"
+ " .. term2\n"
+ " description\n"
+ " description\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ [glossary, definition_list, definition_list_item, ([term, ("term1",
+ index)],
+ definition)],
+ ))
+ assert_node(doctree[0][0][0][1],
+ [nodes.definition, nodes.paragraph, "description"])
+
+
+def test_glossary_comment2(app):
+ text = (".. glossary::\n"
+ "\n"
+ " term1\n"
+ " description\n"
+ "\n"
+ " .. term2\n"
+ " term3\n"
+ " description\n"
+ " description\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ [glossary, definition_list, ([definition_list_item, ([term, ("term1",
+ index)],
+ definition)],
+ [definition_list_item, ([term, ("term3",
+ index)],
+ definition)])],
+ ))
+ assert_node(doctree[0][0][0][1],
+ [nodes.definition, nodes.paragraph, "description"])
+ assert_node(doctree[0][0][1][1],
+ [nodes.definition, nodes.paragraph, ("description\n"
+ "description")])
+
+
+def test_glossary_sorted(app):
+ text = (".. glossary::\n"
+ " :sorted:\n"
+ "\n"
+ " term3\n"
+ " description\n"
+ "\n"
+ " term2\n"
+ " term1\n"
+ " description\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (
+ [glossary, definition_list, ([definition_list_item, ([term, ("term2",
+ index)],
+ [term, ("term1",
+ index)],
+ definition)],
+ [definition_list_item, ([term, ("term3",
+ index)],
+ definition)])],
+ ))
+ assert_node(doctree[0][0][0][2],
+ [nodes.definition, nodes.paragraph, "description"])
+ assert_node(doctree[0][0][1][1],
+ [nodes.definition, nodes.paragraph, "description"])
+
+
+def test_glossary_alphanumeric(app):
+ text = (".. glossary::\n"
+ "\n"
+ " 1\n"
+ " /\n")
+ restructuredtext.parse(app, text)
+ objects = list(app.env.get_domain("std").get_objects())
+ assert ("1", "1", "term", "index", "term-1", -1) in objects
+ assert ("/", "/", "term", "index", "term-0", -1) in objects
+
+
+def test_glossary_conflicted_labels(app):
+ text = (".. _term-foo:\n"
+ ".. glossary::\n"
+ "\n"
+ " foo\n")
+ restructuredtext.parse(app, text)
+ objects = list(app.env.get_domain("std").get_objects())
+ assert ("foo", "foo", "term", "index", "term-0", -1) in objects
+
+
+def test_cmdoption(app):
+ text = (".. program:: ls\n"
+ "\n"
+ ".. option:: -l\n")
+ domain = app.env.get_domain('std')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "-l"],
+ [desc_addname, ()])],
+ [desc_content, ()])]))
+ assert_node(doctree[0], addnodes.index,
+ entries=[('pair', 'ls command line option; -l', 'cmdoption-ls-l', '', None)])
+ assert ('ls', '-l') in domain.progoptions
+ assert domain.progoptions[('ls', '-l')] == ('index', 'cmdoption-ls-l')
+
+
+def test_cmdoption_for_None(app):
+ text = (".. program:: ls\n"
+ ".. program:: None\n"
+ "\n"
+ ".. option:: -l\n")
+ domain = app.env.get_domain('std')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "-l"],
+ [desc_addname, ()])],
+ [desc_content, ()])]))
+ assert_node(doctree[0], addnodes.index,
+ entries=[('pair', 'command line option; -l', 'cmdoption-l', '', None)])
+ assert (None, '-l') in domain.progoptions
+ assert domain.progoptions[(None, '-l')] == ('index', 'cmdoption-l')
+
+
+def test_multiple_cmdoptions(app):
+ text = (".. program:: cmd\n"
+ "\n"
+ ".. option:: -o directory, --output directory\n")
+ domain = app.env.get_domain('std')
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, (addnodes.index,
+ [desc, ([desc_signature, ([desc_name, "-o"],
+ [desc_addname, " directory"],
+ [desc_addname, ", "],
+ [desc_name, "--output"],
+ [desc_addname, " directory"])],
+ [desc_content, ()])]))
+ assert_node(doctree[0], addnodes.index,
+ entries=[('pair', 'cmd command line option; -o', 'cmdoption-cmd-o', '', None),
+ ('pair', 'cmd command line option; --output', 'cmdoption-cmd-o', '', None)])
+ assert ('cmd', '-o') in domain.progoptions
+ assert ('cmd', '--output') in domain.progoptions
+ assert domain.progoptions[('cmd', '-o')] == ('index', 'cmdoption-cmd-o')
+ assert domain.progoptions[('cmd', '--output')] == ('index', 'cmdoption-cmd-o')
+
+
+@pytest.mark.sphinx(testroot='productionlist')
+def test_productionlist(app, status, warning):
+ app.build(force_all=True)
+
+ warnings = warning.getvalue().split("\n")
+ assert len(warnings) == 2
+ assert warnings[-1] == ''
+ assert "Dup2.rst:4: WARNING: duplicate token description of Dup, other instance in Dup1" in warnings[0]
+
+ etree = etree_parse(app.outdir / 'index.html')
+ nodes = list(etree.iter('ul'))
+ assert len(nodes) >= 2
+
+ ul = nodes[1]
+ cases = []
+ for li in list(ul):
+ assert len(list(li)) == 1
+ p = list(li)[0]
+ assert p.tag == 'p'
+ text = str(p.text).strip(' :')
+ assert len(list(p)) == 1
+ a = list(p)[0]
+ assert a.tag == 'a'
+ link = a.get('href')
+ assert len(list(a)) == 1
+ code = list(a)[0]
+ assert code.tag == 'code'
+ assert len(list(code)) == 1
+ span = list(code)[0]
+ assert span.tag == 'span'
+ linkText = span.text.strip()
+ cases.append((text, link, linkText))
+ assert cases == [
+ ('A', 'Bare.html#grammar-token-A', 'A'),
+ ('B', 'Bare.html#grammar-token-B', 'B'),
+ ('P1:A', 'P1.html#grammar-token-P1-A', 'P1:A'),
+ ('P1:B', 'P1.html#grammar-token-P1-B', 'P1:B'),
+ ('P2:A', 'P1.html#grammar-token-P1-A', 'P1:A'),
+ ('P2:B', 'P2.html#grammar-token-P2-B', 'P2:B'),
+ ('Explicit title A, plain', 'Bare.html#grammar-token-A', 'MyTitle'),
+ ('Explicit title A, colon', 'Bare.html#grammar-token-A', 'My:Title'),
+ ('Explicit title P1:A, plain', 'P1.html#grammar-token-P1-A', 'MyTitle'),
+ ('Explicit title P1:A, colon', 'P1.html#grammar-token-P1-A', 'My:Title'),
+ ('Tilde A', 'Bare.html#grammar-token-A', 'A'),
+ ('Tilde P1:A', 'P1.html#grammar-token-P1-A', 'A'),
+ ('Tilde explicit title P1:A', 'P1.html#grammar-token-P1-A', '~MyTitle'),
+ ('Tilde, explicit title P1:A', 'P1.html#grammar-token-P1-A', 'MyTitle'),
+ ('Dup', 'Dup2.html#grammar-token-Dup', 'Dup'),
+ ('FirstLine', 'firstLineRule.html#grammar-token-FirstLine', 'FirstLine'),
+ ('SecondLine', 'firstLineRule.html#grammar-token-SecondLine', 'SecondLine'),
+ ]
+
+ text = (app.outdir / 'LineContinuation.html').read_text(encoding='utf8')
+ assert "A</strong> ::= B C D E F G" in text
+
+
+def test_productionlist2(app):
+ text = (".. productionlist:: P2\n"
+ " A: `:A` `A`\n"
+ " B: `P1:B` `~P1:B`\n")
+ doctree = restructuredtext.parse(app, text)
+ refnodes = list(doctree.findall(pending_xref))
+ assert_node(refnodes[0], pending_xref, reftarget="A")
+ assert_node(refnodes[1], pending_xref, reftarget="P2:A")
+ assert_node(refnodes[2], pending_xref, reftarget="P1:B")
+ assert_node(refnodes[3], pending_xref, reftarget="P1:B")
+ assert_node(refnodes[0], [pending_xref, nodes.literal, "A"])
+ assert_node(refnodes[1], [pending_xref, nodes.literal, "A"])
+ assert_node(refnodes[2], [pending_xref, nodes.literal, "P1:B"])
+ assert_node(refnodes[3], [pending_xref, nodes.literal, "B"])
+
+
+def test_disabled_docref(app):
+ text = (":doc:`index`\n"
+ ":doc:`!index`\n")
+ doctree = restructuredtext.parse(app, text)
+ assert_node(doctree, ([nodes.paragraph, ([pending_xref, nodes.inline, "index"],
+ "\n",
+ [nodes.inline, "index"])],))
+
+
+def test_labeled_rubric(app):
+ text = (".. _label:\n"
+ ".. rubric:: blah *blah* blah\n")
+ restructuredtext.parse(app, text)
+
+ domain = app.env.get_domain("std")
+ assert 'label' in domain.labels
+ assert domain.labels['label'] == ('index', 'label', 'blah blah blah')
+
+
+def test_labeled_definition(app):
+ text = (".. _label1:\n"
+ "\n"
+ "Foo blah *blah* blah\n"
+ " Definition\n"
+ "\n"
+ ".. _label2:\n"
+ "\n"
+ "Bar blah *blah* blah\n"
+ " Definition\n"
+ "\n")
+ restructuredtext.parse(app, text)
+
+ domain = app.env.get_domain("std")
+ assert 'label1' in domain.labels
+ assert domain.labels['label1'] == ('index', 'label1', 'Foo blah blah blah')
+ assert 'label2' in domain.labels
+ assert domain.labels['label2'] == ('index', 'label2', 'Bar blah blah blah')
+
+
+def test_labeled_field(app):
+ text = (".. _label1:\n"
+ "\n"
+ ":Foo blah *blah* blah:\n"
+ " Definition\n"
+ "\n"
+ ".. _label2:\n"
+ "\n"
+ ":Bar blah *blah* blah:\n"
+ " Definition\n"
+ "\n")
+ restructuredtext.parse(app, text)
+
+ domain = app.env.get_domain("std")
+ assert 'label1' in domain.labels
+ assert domain.labels['label1'] == ('index', 'label1', 'Foo blah blah blah')
+ assert 'label2' in domain.labels
+ assert domain.labels['label2'] == ('index', 'label2', 'Bar blah blah blah')
+
+
+@pytest.mark.sphinx('html', testroot='manpage_url',
+ confoverrides={'manpages_url': 'https://example.com/{page}.{section}'})
+def test_html_manpage(app):
+ app.build(force_all=True)
+
+ content = (app.outdir / 'index.html').read_text(encoding='utf8')
+ assert ('<em class="manpage">'
+ '<a class="manpage reference external" href="https://example.com/man.1">man(1)</a>'
+ '</em>') in content
+ assert ('<em class="manpage">'
+ '<a class="manpage reference external" href="https://example.com/ls.1">ls.1</a>'
+ '</em>') in content
+ assert ('<em class="manpage">'
+ '<a class="manpage reference external" href="https://example.com/sphinx.">sphinx</a>'
+ '</em>') in content
+ assert ('<em class="manpage">'
+ '<a class="manpage reference external" href="https://example.com/bsd-mailx/mailx.1">mailx(1)</a>'
+ '</em>') in content
+ assert '<em class="manpage">man(1)</em>' in content