Handle functions in C++ API snapshot (#55692)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/55692

Changelog: [Internal]

Adds support for handling functions and methods in the C++ API parser

Reviewed By: cipolleschi

Differential Revision: D94073981

fbshipit-source-id: 1c22a8cd4584868a220974335b321d523e6a3dc2
This commit is contained in:
Jakub Piasecki authored and meta-codesync[bot] committed 2026-02-25 01:12:30 -08:00
1 parent e69c08bf04
commit efc15289be
24 files changed
+1114 -2

No files matched your search

+2 -1
View File
@@ -4,6 +4,7 @@
# LICENSE file in the root directory of this source tree.
from .main import build_snapshot
from .member import FunctionMember, FunctionModifiers
from .path_utils import get_repo_root
__all__ = ["build_snapshot", "get_repo_root"]
__all__ = ["build_snapshot", "FunctionMember", "FunctionModifiers", "get_repo_root"]
+44 -1
View File
@@ -10,7 +10,7 @@ from pprint import pprint
from doxmlparser import compound, index
from .member import EnumMember, VariableMember
from .member import EnumMember, FunctionMember, VariableMember
from .scope import StructLikeScopeKind
from .snapshot import Snapshot
@@ -138,6 +138,34 @@ def get_variable_member(
)
def get_function_member(
function_def: compound.MemberdefType,
visibility: str,
is_static: bool = False,
) -> FunctionMember:
"""
Get the function member from a member definition.
"""
function_name = function_def.get_name()
function_type = resolve_ref_text_name(function_def.get_type())
function_arg_string = function_def.get_argsstring()
function_virtual = (
function_def.get_virt() == "virtual"
or function_def.get_virt() == "pure-virtual"
)
function = FunctionMember(
function_name,
function_type,
visibility,
function_arg_string,
function_virtual,
is_static,
)
return function
def create_enum_scope(snapshot: Snapshot, enum_def: compound.EnumdefType):
"""
Create an enum scope in the snapshot.
@@ -222,6 +250,13 @@ def build_snapshot(xml_dir: str) -> Snapshot:
member_def, visibility, is_static
)
)
elif member_type == "func":
for function_def in section_def.memberdef:
class_scope.add_member(
get_function_member(
function_def, visibility, is_static
)
)
elif member_type == "type":
for member_def in section_def.memberdef:
if member_def.kind == "enum":
@@ -259,6 +294,14 @@ def build_snapshot(xml_dir: str) -> Snapshot:
namespace_scope.add_member(
get_variable_member(variable_def, "public", is_static)
)
elif section_def.kind == "func":
for function_def in section_def.memberdef:
function_static = function_def.static == "yes"
if not function_static:
namespace_scope.add_member(
get_function_member(function_def, "public")
)
elif section_def.kind == "enum":
for enum_def in section_def.memberdef:
create_enum_scope(snapshot, enum_def)
+421
View File
@@ -128,3 +128,424 @@ class VariableMember(Member):
result += ";"
return result
@dataclass
class FunctionModifiers:
"""Parsed function modifiers that appear after the parameter list."""
is_const: bool = False
is_override: bool = False
is_final: bool = False
is_noexcept: bool = False
noexcept_expr: str | None = None
is_pure_virtual: bool = False
is_default: bool = False
is_delete: bool = False
# Pattern for function pointer / pointer to member / reference to array:
# Matches: (*name), (Class::*name), (&name), (*name)[N]
# Group 1: the identifier name
_FUNC_PTR_PATTERN = re.compile(
r"\(\s*" # Opening paren
r"(?:[a-zA-Z_][a-zA-Z0-9_]*\s*::\s*)?" # Optional Class::
r"[*&]\s*" # * or &
r"([a-zA-Z_][a-zA-Z0-9_]*)" # Capture: identifier name
r"\s*\)" # Closing paren
)
class FunctionMember(Member):
def __init__(
self,
name: str,
type: str,
visibility: str,
arg_string: str,
is_virtual: bool,
is_static: bool,
) -> None:
super().__init__(name, visibility)
self.type: str = type
self.is_virtual: bool = is_virtual
self.is_static: bool = is_static
self.arguments, self.modifiers = FunctionMember.parse_arg_string(arg_string)
self.is_const = self.modifiers.is_const
self.is_override = self.modifiers.is_override
def close(self, scope: Scope):
# TODO: handle unqualified references
pass
def to_string(
self,
indent: int = 0,
qualification: str | None = None,
hide_visibility: bool = False,
) -> str:
name = self._get_qualified_name(qualification)
result = ""
result += " " * indent
if not hide_visibility:
result += self.visibility + " "
if self.is_virtual:
result += "virtual "
if self.is_static:
result += "static "
if self.type:
result += f"{self.type} "
result += f"{name}("
for i, (arg_type, arg_name, arg_default) in enumerate(self.arguments):
if arg_name:
result += f"{arg_type} {arg_name}"
else:
result += arg_type
if arg_default:
result += f" = {arg_default}"
if i < len(self.arguments) - 1:
result += ", "
result += ")"
if self.modifiers.is_const:
result += " const"
if self.modifiers.is_noexcept:
if self.modifiers.noexcept_expr:
result += f" noexcept({self.modifiers.noexcept_expr})"
else:
result += " noexcept"
if self.modifiers.is_override:
result += " override"
if self.modifiers.is_final:
result += " final"
if self.modifiers.is_pure_virtual:
result += " = 0"
elif self.modifiers.is_default:
result += " = default"
elif self.modifiers.is_delete:
result += " = delete"
result += ";"
return result
@staticmethod
def _find_matching_paren(s: str, start: int = 0) -> int:
"""Find the index of the closing parenthesis matching the opening one at start.
Handles nested parentheses and angle brackets (for templates).
Returns -1 if no matching parenthesis is found.
"""
if start >= len(s) or s[start] != "(":
return -1
depth = 0
angle_depth = 0
i = start
while i < len(s):
c = s[i]
if c == "<":
angle_depth += 1
elif c == ">":
angle_depth -= 1
elif c == "(":
depth += 1
elif c == ")":
depth -= 1
if depth == 0:
return i
i += 1
return -1
@staticmethod
def _find_matching_angle(s: str, start: int = 0) -> int:
"""Find the index of the closing angle bracket matching the opening one at start.
Handles nested angle brackets and parentheses.
Returns -1 if no matching bracket is found.
"""
if start >= len(s) or s[start] != "<":
return -1
depth = 0
paren_depth = 0
i = start
while i < len(s):
c = s[i]
if c == "(":
paren_depth += 1
elif c == ")":
paren_depth -= 1
elif c == "<" and paren_depth == 0:
depth += 1
elif c == ">" and paren_depth == 0:
depth -= 1
if depth == 0:
return i
i += 1
return -1
@staticmethod
def _split_arguments(args_str: str) -> list[str]:
"""Split arguments by comma, respecting nested structures.
Handles:
- Nested parentheses: std::function<int(int, int)>
- Nested angle brackets: std::map<K, V>
- Brace initializers: std::vector<int> v = {1, 2, 3}
"""
result = []
current = []
paren_depth = 0
angle_depth = 0
brace_depth = 0
for c in args_str:
if c == "<":
angle_depth += 1
elif c == ">":
angle_depth = max(0, angle_depth - 1)
elif c == "(":
paren_depth += 1
elif c == ")":
paren_depth = max(0, paren_depth - 1)
elif c == "{":
brace_depth += 1
elif c == "}":
brace_depth = max(0, brace_depth - 1)
elif (
c == "," and paren_depth == 0 and angle_depth == 0 and brace_depth == 0
):
result.append("".join(current).strip())
current = []
continue
current.append(c)
if current:
result.append("".join(current).strip())
return [arg for arg in result if arg]
# C++ reserved keywords that serve as type qualifiers/specifiers.
# When ALL tokens in the prefix (everything before the last token) are
# from this set, the last token must be part of the type, not a name.
# Primitive type names (int, bool, char, etc.) are intentionally excluded
# to avoid ambiguity with common named params like "int x" or "bool flag".
_CPP_TYPE_QUALIFIERS = frozenset(
{
"const",
"volatile",
"mutable",
"unsigned",
"signed",
"long",
"short",
}
)
@staticmethod
def _prefix_is_all_qualifiers(prefix: str) -> bool:
"""Check if all tokens in the prefix are type qualifiers/specifiers.
When the prefix consists entirely of reserved qualifiers (e.g., "const",
"const unsigned"), the following token cannot be a parameter name — it
must be completing the type.
"""
return all(t in FunctionMember._CPP_TYPE_QUALIFIERS for t in prefix.split())
@staticmethod
def _looks_like_type_token(token: str) -> bool:
"""Check if a token ends with type-related punctuation.
Returns True if the token ends with pointer, reference, template closer,
or array bracket — indicating it's part of a type, not a name.
"""
return (
token.endswith("*")
or token.endswith("&")
or token.endswith(">")
or token.endswith("]")
)
@staticmethod
def _parse_single_argument(arg: str) -> tuple[str, str, str | None]:
"""Parse a single C++ argument into (type, name, default_value).
Handles complex cases:
- Regular: "int x" -> ("int", "x", None)
- With default: "int x = 5" -> ("int", "x", "5")
- Function pointer: "int (*callback)(int, int)" -> ("int (*)(int, int)", "callback", None)
- Pointer to member: "void (Class::*method)()" -> ("void (Class::*)()", "method", None)
- Reference to array: "int (&arr)[10]" -> ("int (&)[10]", "arr", None)
- No name (void): "void" -> ("void", "", None)
- Unnamed multi-token: "const bool" -> ("const bool", "", None)
"""
arg = arg.strip()
if not arg:
return ("", "", None)
default_value: str | None = None
base_arg = arg
# Handle default values: split on '=' but respect nested structures
eq_pos = FunctionMember._find_default_value_start(arg)
if eq_pos != -1:
base_arg = arg[:eq_pos].strip()
default_value = arg[eq_pos + 1 :].strip()
# Try to match function pointer / pointer to member / reference to array pattern
match = _FUNC_PTR_PATTERN.search(base_arg)
if match:
name = match.group(1)
# Reconstruct type by removing the name from the pattern
type_str = base_arg[: match.start(1)] + base_arg[match.end(1) :]
return (type_str.strip(), name, default_value)
# Regular case: last token is the name
parts = base_arg.rsplit(None, 1)
if len(parts) == 2:
prefix, potential_name = parts
if FunctionMember._looks_like_type_token(
potential_name
) or FunctionMember._prefix_is_all_qualifiers(prefix):
return (base_arg, "", default_value)
return (prefix, potential_name, default_value)
else:
return (base_arg, "", default_value)
@staticmethod
def _find_default_value_start(arg: str) -> int:
"""Find the position of '=' that starts a default value.
Returns -1 if no default value found.
Ignores '=' inside nested structures like templates or lambdas.
"""
paren_depth = 0
angle_depth = 0
brace_depth = 0
i = 0
while i < len(arg):
c = arg[i]
if c == "<":
angle_depth += 1
elif c == ">":
angle_depth = max(0, angle_depth - 1)
elif c == "(":
paren_depth += 1
elif c == ")":
paren_depth = max(0, paren_depth - 1)
elif c == "{":
brace_depth += 1
elif c == "}":
brace_depth = max(0, brace_depth - 1)
elif (
c == "=" and paren_depth == 0 and angle_depth == 0 and brace_depth == 0
):
return i
i += 1
return -1
@staticmethod
def _parse_modifiers(modifiers_str: str) -> FunctionModifiers:
"""Parse function modifiers after the parameter list.
Handles: const, override, final, noexcept, noexcept(expr), = 0, = default, = delete
"""
result = FunctionModifiers()
s = modifiers_str.strip()
# Handle = 0, = default, = delete
eq_match = re.search(r"=\s*(0|default|delete)\s*$", s)
if eq_match:
value = eq_match.group(1)
if value == "0":
result.is_pure_virtual = True
elif value == "default":
result.is_default = True
elif value == "delete":
result.is_delete = True
s = s[: eq_match.start()].strip()
# Handle noexcept with optional expression
noexcept_match = re.search(r"\bnoexcept\b", s)
if noexcept_match:
result.is_noexcept = True
# Check for noexcept(expr)
rest = s[noexcept_match.end() :]
rest_stripped = rest.lstrip()
if rest_stripped.startswith("("):
paren_end = FunctionMember._find_matching_paren(rest_stripped, 0)
if paren_end != -1:
result.noexcept_expr = rest_stripped[1:paren_end].strip()
# Remove noexcept and its expression from the string for further parsing
s = s[: noexcept_match.start()] + s[noexcept_match.end() :]
if result.noexcept_expr:
# Also remove the (expr) part
s = re.sub(r"\([^)]*\)", "", s, count=1)
# Parse remaining tokens
tokens = s.split()
for token in tokens:
if token == "const":
result.is_const = True
elif token == "override":
result.is_override = True
elif token == "final":
result.is_final = True
return result
@staticmethod
def parse_arg_string(
arg_string: str,
) -> tuple[list[tuple[str, str, str | None]], FunctionModifiers]:
"""Parse a C++ function argument string.
Args:
arg_string: String in format "(type1 arg1, type2 arg2 = default) [modifiers]"
Returns:
Tuple of (arguments, modifiers) where:
- arguments: list of (type, name, default_value) tuples
- modifiers: FunctionModifiers dataclass with parsed modifier flags
"""
arg_string = arg_string.strip()
if not arg_string.startswith("("):
return ([], FunctionModifiers())
close_paren = FunctionMember._find_matching_paren(arg_string, 0)
if close_paren == -1:
return ([], FunctionModifiers())
args_content = arg_string[1:close_paren].strip()
modifiers_str = arg_string[close_paren + 1 :]
arguments: list[tuple[str, str, str | None]] = []
if args_content:
for arg in FunctionMember._split_arguments(args_content):
parsed = FunctionMember._parse_single_argument(arg)
if parsed[0] or parsed[1]:
arguments.append(parsed)
modifiers = FunctionMember._parse_modifiers(modifiers_str)
return (arguments, modifiers)
@@ -0,0 +1,3 @@
class test::Base {
protected void hello();
}
@@ -0,0 +1,17 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
namespace test {
class Base {
protected:
void hello();
};
} // namespace test
@@ -0,0 +1,3 @@
class test::Base {
protected static void hello();
}
@@ -0,0 +1,17 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
namespace test {
class Base {
protected:
static void hello();
};
} // namespace test
@@ -0,0 +1,23 @@
class test::Clss {
public virtual void fn16() = 0;
public void fn0(int32_t arg1);
public void fn1(int32_t arg1, int32_t arg2);
public void fn2(std::function< int32_t(int32_t)> arg1);
public void fn3(std::function< int32_t(int32_t)> arg1, std::function< int32_t(int32_t, int32_t)> arg2);
public void fn4(std::map< std::string, int > m);
public void fn5(std::unordered_map< K, std::vector< V > > m);
public void fn6(std::tuple< int, float, std::string > t);
public void fn7(std::vector< std::vector< std::pair< int, int > > > v);
public void fn8(std::map< K, std::function< void(A, B)> > m);
public void fn9(int(*)(int, int) callback);
public void fn10(void(*)(const char *, size_t) handler);
public void fn11(int(*(*)(int))(double) fp);
public void fn12(int x = 5, std::string s = "default");
public void fn13(std::function< void()> f = nullptr);
public void fn14(std::vector< int > v = {1, 2, 3});
public void fn15() noexcept;
public void fn17() = default;
public void fn18() = delete;
public void fn19() final;
public void fn20() override final;
}
@@ -0,0 +1,37 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
namespace test {
class Clss {
public:
void fn0(int32_t arg1);
void fn1(int32_t arg1, int32_t arg2);
void fn2(std::function<int32_t(int32_t)> arg1);
void fn3(std::function<int32_t(int32_t)> arg1, std::function<int32_t(int32_t, int32_t)> arg2);
void fn4(std::map<std::string, int> m);
void fn5(std::unordered_map<K, std::vector<V>> m);
void fn6(std::tuple<int, float, std::string> t);
void fn7(std::vector<std::vector<std::pair<int, int>>> v);
void fn8(std::map<K, std::function<void(A, B)>> m);
void fn9(int (*callback)(int, int));
void fn10(void (*handler)(const char *, size_t));
void fn11(int (*(*fp)(int))(double));
void fn12(int x = 5, std::string s = "default");
void fn13(std::function<void()> f = nullptr);
void fn14(std::vector<int> v = {1, 2, 3});
void fn15() noexcept;
void fn16() = 0;
void fn17() = default;
void fn18() = delete;
void fn19() final;
void fn20() final override;
};
} // namespace test
@@ -0,0 +1,13 @@
class test::Clss {
public Clss();
public const int constFn();
public const int constOverrideFn() override;
public const int testFnConst() const;
public const int testOverrideFnConst() const override;
public int fn();
public int overrideFn() override;
public virtual const int constVirtualFn();
public virtual const int testVirtualFnConst() const;
public virtual int virtualFn();
public virtual ~Clss();
}
@@ -0,0 +1,30 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
namespace test {
class Clss {
public:
Clss();
virtual ~Clss();
int fn();
const int constFn();
const int testFnConst() const;
virtual int virtualFn();
virtual const int constVirtualFn();
virtual const int testVirtualFnConst() const;
int overrideFn() override;
const int constOverrideFn() override;
const int testOverrideFnConst() const override;
};
} // namespace test
@@ -0,0 +1,3 @@
class test::Base {
public void hello();
}
@@ -0,0 +1,17 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
namespace test {
class Base {
public:
void hello();
};
} // namespace test
@@ -0,0 +1,3 @@
class test::Base {
public static void hello();
}
@@ -0,0 +1,17 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
namespace test {
class Base {
public:
static void hello();
};
} // namespace test
@@ -0,0 +1 @@
void test::helloWorld();
@@ -0,0 +1,14 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
namespace test {
void helloWorld();
} // namespace test
@@ -0,0 +1,3 @@
struct test::TestStruct {
public void test();
}
@@ -0,0 +1,17 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
namespace test {
struct TestStruct {
public:
void test();
};
} // namespace test
@@ -0,0 +1,5 @@
union test::MethodUnion {
public float floatValue;
public int32_t getInt() const;
public int32_t intValue;
}
@@ -0,0 +1,22 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <cstdint>
namespace test {
union MethodUnion {
public:
int32_t intValue;
float floatValue;
int32_t getInt() const;
};
} // namespace test
@@ -0,0 +1,14 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
namespace test {
static void helloWorld();
} // namespace test
+387
View File
@@ -0,0 +1,387 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Unit tests for FunctionMember.parse_arg_string()"""
import unittest
from ..parser import FunctionMember, FunctionModifiers
class TestParseArgString(unittest.TestCase):
"""Test cases for parsing C++ function argument strings."""
# =========================================================================
# Basic cases
# =========================================================================
def test_empty_args(self):
"""Empty parentheses"""
args, mods = FunctionMember.parse_arg_string("()")
self.assertEqual(args, [])
self.assertEqual(mods, FunctionModifiers())
def test_single_simple_arg(self):
"""Single argument: int x"""
args, mods = FunctionMember.parse_arg_string("(int x)")
self.assertEqual(args, [("int", "x", None)])
def test_multiple_simple_args(self):
"""Multiple arguments: int x, float y"""
args, mods = FunctionMember.parse_arg_string("(int x, float y)")
self.assertEqual(args, [("int", "x", None), ("float", "y", None)])
def test_void_arg(self):
"""void with no name"""
args, mods = FunctionMember.parse_arg_string("(void)")
self.assertEqual(args, [("void", "", None)])
# =========================================================================
# Modifiers: const, override, final
# =========================================================================
def test_const_modifier(self):
"""() const"""
args, mods = FunctionMember.parse_arg_string("() const")
self.assertTrue(mods.is_const)
self.assertFalse(mods.is_override)
def test_override_modifier(self):
"""() override"""
args, mods = FunctionMember.parse_arg_string("() override")
self.assertTrue(mods.is_override)
self.assertFalse(mods.is_const)
def test_const_override(self):
"""() const override"""
args, mods = FunctionMember.parse_arg_string("() const override")
self.assertTrue(mods.is_const)
self.assertTrue(mods.is_override)
def test_override_const(self):
"""() override const - reversed order"""
args, mods = FunctionMember.parse_arg_string("() override const")
self.assertTrue(mods.is_const)
self.assertTrue(mods.is_override)
def test_final_modifier(self):
"""() final"""
args, mods = FunctionMember.parse_arg_string("() final")
self.assertTrue(mods.is_final)
def test_override_final(self):
"""() override final"""
args, mods = FunctionMember.parse_arg_string("() override final")
self.assertTrue(mods.is_override)
self.assertTrue(mods.is_final)
def test_const_override_final(self):
"""() const override final"""
args, mods = FunctionMember.parse_arg_string("() const override final")
self.assertTrue(mods.is_const)
self.assertTrue(mods.is_override)
self.assertTrue(mods.is_final)
# =========================================================================
# Modifiers: noexcept
# =========================================================================
def test_noexcept(self):
"""() noexcept"""
args, mods = FunctionMember.parse_arg_string("() noexcept")
self.assertTrue(mods.is_noexcept)
self.assertIsNone(mods.noexcept_expr)
def test_noexcept_true(self):
"""() noexcept(true)"""
args, mods = FunctionMember.parse_arg_string("() noexcept(true)")
self.assertTrue(mods.is_noexcept)
self.assertEqual(mods.noexcept_expr, "true")
def test_noexcept_false(self):
"""() noexcept(false)"""
args, mods = FunctionMember.parse_arg_string("() noexcept(false)")
self.assertTrue(mods.is_noexcept)
self.assertEqual(mods.noexcept_expr, "false")
def test_noexcept_expr(self):
"""() noexcept(noexcept(other()))"""
args, mods = FunctionMember.parse_arg_string("() noexcept(noexcept(other()))")
self.assertTrue(mods.is_noexcept)
self.assertEqual(mods.noexcept_expr, "noexcept(other())")
def test_const_noexcept(self):
"""() const noexcept"""
args, mods = FunctionMember.parse_arg_string("() const noexcept")
self.assertTrue(mods.is_const)
self.assertTrue(mods.is_noexcept)
# =========================================================================
# Modifiers: = 0, = default, = delete
# =========================================================================
def test_pure_virtual(self):
"""() = 0"""
args, mods = FunctionMember.parse_arg_string("() = 0")
self.assertTrue(mods.is_pure_virtual)
def test_default(self):
"""() = default"""
args, mods = FunctionMember.parse_arg_string("() = default")
self.assertTrue(mods.is_default)
def test_delete(self):
"""() = delete"""
args, mods = FunctionMember.parse_arg_string("() = delete")
self.assertTrue(mods.is_delete)
def test_const_pure_virtual(self):
"""() const = 0"""
args, mods = FunctionMember.parse_arg_string("() const = 0")
self.assertTrue(mods.is_const)
self.assertTrue(mods.is_pure_virtual)
def test_noexcept_default(self):
"""() noexcept = default"""
args, mods = FunctionMember.parse_arg_string("() noexcept = default")
self.assertTrue(mods.is_noexcept)
self.assertTrue(mods.is_default)
# =========================================================================
# Complex types: templates with commas
# =========================================================================
def test_std_map(self):
"""std::map<K, V> with comma inside template"""
args, mods = FunctionMember.parse_arg_string("(std::map<std::string, int> m)")
self.assertEqual(args, [("std::map<std::string, int>", "m", None)])
def test_std_unordered_map_nested(self):
"""std::unordered_map<K, std::vector<V>>"""
args, mods = FunctionMember.parse_arg_string(
"(std::unordered_map<K, std::vector<V>> m)"
)
self.assertEqual(args, [("std::unordered_map<K, std::vector<V>>", "m", None)])
def test_std_tuple(self):
"""std::tuple<int, float, std::string>"""
args, mods = FunctionMember.parse_arg_string(
"(std::tuple<int, float, std::string> t)"
)
self.assertEqual(args, [("std::tuple<int, float, std::string>", "t", None)])
def test_deeply_nested_templates(self):
"""std::vector<std::vector<std::pair<int, int>>>"""
args, mods = FunctionMember.parse_arg_string(
"(std::vector<std::vector<std::pair<int, int>>> v)"
)
self.assertEqual(
args,
[("std::vector<std::vector<std::pair<int, int>>>", "v", None)],
)
# =========================================================================
# Complex types: std::function with nested parens
# =========================================================================
def test_std_function_simple(self):
"""std::function<void()>"""
args, mods = FunctionMember.parse_arg_string("(std::function<void()> f)")
self.assertEqual(args, [("std::function<void()>", "f", None)])
def test_std_function_with_args(self):
"""std::function<int(int, int)>"""
args, mods = FunctionMember.parse_arg_string("(std::function<int(int, int)> f)")
self.assertEqual(args, [("std::function<int(int, int)>", "f", None)])
def test_std_function_complex(self):
"""std::function<void(const std::string&, size_t)>"""
args, mods = FunctionMember.parse_arg_string(
"(std::function<void(const std::string&, size_t)> callback)"
)
self.assertEqual(
args,
[
(
"std::function<void(const std::string&, size_t)>",
"callback",
None,
)
],
)
def test_multiple_std_function_args(self):
"""Multiple std::function args"""
args, mods = FunctionMember.parse_arg_string(
"(std::function<int(int)> f, std::function<void(A, B)> g)"
)
self.assertEqual(
args,
[
("std::function<int(int)>", "f", None),
("std::function<void(A, B)>", "g", None),
],
)
def test_map_with_function_value(self):
"""std::map<K, std::function<void(A, B)>>"""
args, mods = FunctionMember.parse_arg_string(
"(std::map<K, std::function<void(A, B)>> m)"
)
self.assertEqual(args, [("std::map<K, std::function<void(A, B)>>", "m", None)])
# =========================================================================
# Function pointers
# =========================================================================
def test_function_pointer_simple(self):
"""int (*callback)(int, int)"""
args, mods = FunctionMember.parse_arg_string("(int (*callback)(int, int))")
self.assertEqual(args, [("int (*)(int, int)", "callback", None)])
def test_function_pointer_void(self):
"""void (*handler)(const char*, size_t)"""
args, mods = FunctionMember.parse_arg_string(
"(void (*handler)(const char*, size_t))"
)
self.assertEqual(args, [("void (*)(const char*, size_t)", "handler", None)])
def test_function_pointer_no_args(self):
"""void (*fn)()"""
args, mods = FunctionMember.parse_arg_string("(void (*fn)())")
self.assertEqual(args, [("void (*)()", "fn", None)])
# =========================================================================
# Pointer to member function
# =========================================================================
def test_pointer_to_member(self):
"""void (Class::*method)(int, int)"""
args, mods = FunctionMember.parse_arg_string(
"(void (Class::*method)(int, int))"
)
self.assertEqual(args, [("void (Class::*)(int, int)", "method", None)])
def test_pointer_to_member_const(self):
"""int (Foo::*getter)() const - note: const after () is part of member fn signature"""
args, mods = FunctionMember.parse_arg_string("(int (Foo::*getter)() const)")
# The "const" here is part of the argument type, not a method modifier
self.assertEqual(args, [("int (Foo::*)() const", "getter", None)])
# =========================================================================
# Reference to array / pointer to array
# =========================================================================
def test_reference_to_array(self):
"""int (&arr)[10]"""
args, mods = FunctionMember.parse_arg_string("(int (&arr)[10])")
self.assertEqual(args, [("int (&)[10]", "arr", None)])
def test_pointer_to_array(self):
"""int (*arr)[10]"""
args, mods = FunctionMember.parse_arg_string("(int (*arr)[10])")
self.assertEqual(args, [("int (*)[10]", "arr", None)])
# =========================================================================
# Default arguments
# =========================================================================
def test_default_int(self):
"""int x = 5"""
args, mods = FunctionMember.parse_arg_string("(int x = 5)")
self.assertEqual(args, [("int", "x", "5")])
def test_default_string(self):
"""std::string s = "default\" """
args, mods = FunctionMember.parse_arg_string('(std::string s = "default")')
self.assertEqual(args, [("std::string", "s", '"default"')])
def test_default_nullptr(self):
"""std::function<void()> f = nullptr"""
args, mods = FunctionMember.parse_arg_string(
"(std::function<void()> f = nullptr)"
)
self.assertEqual(args, [("std::function<void()>", "f", "nullptr")])
def test_default_brace_initializer(self):
"""std::vector<int> v = {1, 2, 3}"""
args, mods = FunctionMember.parse_arg_string("(std::vector<int> v = {1, 2, 3})")
self.assertEqual(args, [("std::vector<int>", "v", "{1, 2, 3}")])
def test_multiple_defaults(self):
"""int x = 5, std::string s = "test\" """
args, mods = FunctionMember.parse_arg_string(
'(int x = 5, std::string s = "test")'
)
self.assertEqual(
args,
[("int", "x", "5"), ("std::string", "s", '"test"')],
)
def test_default_template_with_comma(self):
"""std::map<int, int> m = {}"""
args, mods = FunctionMember.parse_arg_string("(std::map<int, int> m = {})")
self.assertEqual(args, [("std::map<int, int>", "m", "{}")])
# =========================================================================
# Complex CV-qualifiers
# =========================================================================
def test_const_ref(self):
"""const std::string& s"""
args, mods = FunctionMember.parse_arg_string("(const std::string& s)")
self.assertEqual(args, [("const std::string&", "s", None)])
def test_const_ptr_const_ref(self):
"""const int* const& ptr"""
args, mods = FunctionMember.parse_arg_string("(const int* const& ptr)")
self.assertEqual(args, [("const int* const&", "ptr", None)])
def test_shared_ptr_const(self):
"""const std::shared_ptr<const Foo>& p"""
args, mods = FunctionMember.parse_arg_string(
"(const std::shared_ptr<const Foo>& p)"
)
self.assertEqual(args, [("const std::shared_ptr<const Foo>&", "p", None)])
# =========================================================================
# Mixed complex cases
# =========================================================================
def test_mixed_args_with_modifiers(self):
"""Multiple complex args with const override"""
args, mods = FunctionMember.parse_arg_string(
"(std::map<K, V> m, std::function<void(A, B)> f) const override"
)
self.assertEqual(
args,
[
("std::map<K, V>", "m", None),
("std::function<void(A, B)>", "f", None),
],
)
self.assertTrue(mods.is_const)
self.assertTrue(mods.is_override)
def test_full_complex_signature(self):
"""Complex signature with everything"""
args, mods = FunctionMember.parse_arg_string(
"(const std::vector<int>& v, "
"std::function<int(int, int)> f = nullptr) const noexcept override"
)
self.assertEqual(
args,
[
("const std::vector<int>&", "v", None),
("std::function<int(int, int)>", "f", "nullptr"),
],
)
self.assertTrue(mods.is_const)
self.assertTrue(mods.is_noexcept)
self.assertTrue(mods.is_override)
if __name__ == "__main__":
unittest.main()