mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Add basic test cases and parser implementation (#55641)
Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/55641 Changelog: [Internal] Adds basic implementation of C++ API snapshot generation and snapshot tests covering the functionality. Reviewed By: cipolleschi Differential Revision: D90987176 fbshipit-source-id: 4243b054f98af49d49e8ce174999b44196ed3444
This commit is contained in:
1 parent
a65d8848f2
commit
25e402587a
61 files changed
+4302
-164
No files matched your search
+1
-1
@@ -2401,7 +2401,7 @@ ENABLE_PREPROCESSING = YES
|
||||
# The default value is: NO.
|
||||
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
|
||||
|
||||
MACRO_EXPANSION = NO
|
||||
MACRO_EXPANSION = YES
|
||||
|
||||
# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
|
||||
# the macro expansion is limited to the macros specified with the PREDEFINED and
|
||||
@@ -0,0 +1 @@
|
||||
api/xml
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* 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 facebook {
|
||||
|
||||
namespace react {
|
||||
|
||||
enum class Enum {
|
||||
A,
|
||||
B,
|
||||
};
|
||||
|
||||
void test(react::Enum e = Enum::A);
|
||||
|
||||
} // namespace react
|
||||
|
||||
} // namespace facebook
|
||||
@@ -1,140 +0,0 @@
|
||||
# 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.
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
from doxmlparser import index
|
||||
|
||||
DOXYGEN_CONFIG_FILE = ".doxygen.config.generated"
|
||||
|
||||
|
||||
def _get_repo_root() -> str:
|
||||
"""Get the repository root via git."""
|
||||
result = subprocess.run(
|
||||
["git", "rev-parse", "--show-toplevel"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(
|
||||
f"Could not determine repo root via 'git rev-parse': {result.stderr}"
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def get_react_native_dir() -> str:
|
||||
"""
|
||||
Get the path to the react-native package directory.
|
||||
|
||||
This function handles two execution contexts:
|
||||
1. Buck execution: Uses REACT_NATIVE_DIR env var + git repo root
|
||||
2. Direct Python invocation: Uses __file__ relative path
|
||||
"""
|
||||
react_native_dir = os.environ.get("REACT_NATIVE_DIR")
|
||||
if react_native_dir:
|
||||
return os.path.join(_get_repo_root(), react_native_dir)
|
||||
|
||||
# Use realpath to resolve symlinks — in Buck's link-tree, __file__
|
||||
# is a symlink back to the source tree, so this gives the correct
|
||||
# source location for relative path resolution.
|
||||
script_dir = os.path.dirname(os.path.realpath(__file__))
|
||||
return os.path.normpath(
|
||||
os.path.join(
|
||||
script_dir, # scripts/cxx-api/
|
||||
"..", # scripts/
|
||||
"..", # react-native-github/
|
||||
"packages",
|
||||
"react-native",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def build_doxygen_config(
|
||||
directory: str,
|
||||
include_directories: list[str] | None = None,
|
||||
exclude_patterns: list[str] | None = None,
|
||||
definitions: dict[str, str | int] | None = None,
|
||||
) -> None:
|
||||
if include_directories is None:
|
||||
include_directories = []
|
||||
if exclude_patterns is None:
|
||||
exclude_patterns = []
|
||||
if definitions is None:
|
||||
definitions = {}
|
||||
|
||||
include_directories_str = " ".join(include_directories)
|
||||
exclude_patterns_str = "\\\n".join(exclude_patterns)
|
||||
if len(exclude_patterns) > 0:
|
||||
exclude_patterns_str = f"\\\n{exclude_patterns_str}"
|
||||
|
||||
definitions_str = " ".join([f"{key}={value}" for key, value in definitions.items()])
|
||||
|
||||
# read the template file
|
||||
with open(os.path.join(directory, ".doxygen.config.template")) as f:
|
||||
template = f.read()
|
||||
|
||||
# replace the placeholder with the actual path
|
||||
config = (
|
||||
template.replace("${ADDITIONAL_INPUTS}", include_directories_str)
|
||||
.replace("${ADDITIONAL_EXCLUDE_PATTERNS}", exclude_patterns_str)
|
||||
.replace("${PREDEFINED}", definitions_str)
|
||||
)
|
||||
|
||||
# write the config file
|
||||
with open(os.path.join(directory, DOXYGEN_CONFIG_FILE), "w") as f:
|
||||
f.write(config)
|
||||
|
||||
|
||||
def build_snapshot(xml_dir) -> str:
|
||||
"""
|
||||
TODO
|
||||
"""
|
||||
index_path = os.path.join(xml_dir, "index.xml")
|
||||
if not os.path.exists(index_path):
|
||||
print(f"Doxygen entry point not found at {index_path}")
|
||||
|
||||
root = index.parse(index_path)
|
||||
|
||||
for comp in root.compound:
|
||||
print(comp.kind)
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Define the path to the ReactCommon directory
|
||||
react_native_dir = get_react_native_dir()
|
||||
|
||||
# If there is already an output directory, delete it
|
||||
if os.path.exists(os.path.join(react_native_dir, "api")):
|
||||
print("Deleting existing output directory")
|
||||
subprocess.run(["rm", "-rf", os.path.join(react_native_dir, "api")])
|
||||
|
||||
# Generate the Doxygen config file
|
||||
print("Generating Doxygen config file")
|
||||
build_doxygen_config(
|
||||
react_native_dir,
|
||||
include_directories=["ReactAndroid"],
|
||||
exclude_patterns=["*/ios/*"],
|
||||
definitions={"RN_SERIALIZABLE_STATE": 1},
|
||||
)
|
||||
|
||||
print("Running Doxygen")
|
||||
|
||||
# Run doxygen with the config file
|
||||
result = subprocess.run(
|
||||
["doxygen", DOXYGEN_CONFIG_FILE],
|
||||
cwd=react_native_dir,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
# Check the result
|
||||
if result.returncode != 0:
|
||||
print(f"Error: {result.stderr}")
|
||||
else:
|
||||
print("Success")
|
||||
build_snapshot(os.path.join(react_native_dir, "api", "xml"))
|
||||
@@ -0,0 +1,9 @@
|
||||
# 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.
|
||||
|
||||
from .main import build_snapshot
|
||||
from .path_utils import get_repo_root
|
||||
|
||||
__all__ = ["build_snapshot", "get_repo_root"]
|
||||
@@ -0,0 +1,119 @@
|
||||
# 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.
|
||||
|
||||
"""
|
||||
Entry point for running the parser package as a script.
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
from .main import build_snapshot
|
||||
from .path_utils import get_react_native_dir
|
||||
|
||||
DOXYGEN_CONFIG_FILE = ".doxygen.config.generated"
|
||||
|
||||
RUN_ON_REACT_NATIVE = False
|
||||
|
||||
|
||||
def build_doxygen_config(
|
||||
directory: str,
|
||||
include_directories: list[str] = None,
|
||||
exclude_patterns: list[str] = None,
|
||||
definitions: dict[str, str | int] = None,
|
||||
) -> None:
|
||||
if include_directories is None:
|
||||
include_directories = []
|
||||
if exclude_patterns is None:
|
||||
exclude_patterns = []
|
||||
if definitions is None:
|
||||
definitions = {}
|
||||
|
||||
include_directories_str = " ".join(include_directories)
|
||||
exclude_patterns_str = "\\\n".join(exclude_patterns)
|
||||
if len(exclude_patterns) > 0:
|
||||
exclude_patterns_str = f"\\\n{exclude_patterns_str}"
|
||||
|
||||
definitions_str = " ".join(
|
||||
[
|
||||
f'{key}="{value}"' if isinstance(value, str) else f"{key}={value}"
|
||||
for key, value in definitions.items()
|
||||
]
|
||||
)
|
||||
|
||||
# read the template file
|
||||
with open(os.path.join(directory, ".doxygen.config.template")) as f:
|
||||
template = f.read()
|
||||
|
||||
# replace the placeholder with the actual path
|
||||
config = (
|
||||
template.replace("${ADDITIONAL_INPUTS}", include_directories_str)
|
||||
.replace("${ADDITIONAL_EXCLUDE_PATTERNS}", exclude_patterns_str)
|
||||
.replace("${PREDEFINED}", definitions_str)
|
||||
)
|
||||
|
||||
# write the config file
|
||||
with open(os.path.join(directory, DOXYGEN_CONFIG_FILE), "w") as f:
|
||||
f.write(config)
|
||||
|
||||
|
||||
def main():
|
||||
# Define the path to the react-native directory
|
||||
react_native_dir = (
|
||||
f"{get_react_native_dir()}/packages/react-native"
|
||||
if RUN_ON_REACT_NATIVE
|
||||
else f"{get_react_native_dir()}/scripts/cxx-api/manual_test"
|
||||
)
|
||||
print(f"Running in directory: {react_native_dir}")
|
||||
|
||||
# If there is already an output directory, delete it
|
||||
if os.path.exists(os.path.join(react_native_dir, "api")):
|
||||
print("Deleting existing output directory")
|
||||
subprocess.run(["rm", "-rf", os.path.join(react_native_dir, "api")])
|
||||
|
||||
# Generate the Doxygen config file
|
||||
print("Generating Doxygen config file")
|
||||
if RUN_ON_REACT_NATIVE:
|
||||
build_doxygen_config(
|
||||
react_native_dir,
|
||||
include_directories=["ReactAndroid"],
|
||||
exclude_patterns=["*/platform/ios/*"],
|
||||
definitions={"RN_SERIALIZABLE_STATE": 1},
|
||||
)
|
||||
else:
|
||||
build_doxygen_config(react_native_dir)
|
||||
|
||||
print("Running Doxygen")
|
||||
|
||||
# Run doxygen with the config file
|
||||
result = subprocess.run(
|
||||
["doxygen", DOXYGEN_CONFIG_FILE],
|
||||
cwd=react_native_dir,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
# Delete the Doxygen config file
|
||||
print("Deleting Doxygen config file")
|
||||
subprocess.run(["rm", DOXYGEN_CONFIG_FILE], cwd=react_native_dir)
|
||||
|
||||
# Check the result
|
||||
if result.returncode != 0:
|
||||
print(f"Doxygen finished with error: {result.stderr}")
|
||||
else:
|
||||
print("Doxygen finished successfully")
|
||||
|
||||
if RUN_ON_REACT_NATIVE:
|
||||
# build snapshot, convert to string, and save to file
|
||||
snapshot = build_snapshot(os.path.join(react_native_dir, "api", "xml"))
|
||||
snapshot_string = snapshot.to_string()
|
||||
with open(os.path.join(react_native_dir, "api", "snapshot.api"), "w") as f:
|
||||
f.write(snapshot_string)
|
||||
else:
|
||||
build_snapshot(os.path.join(react_native_dir, "api", "xml")).print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,250 @@
|
||||
# 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.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pprint import pprint
|
||||
|
||||
from doxmlparser import compound, index
|
||||
|
||||
from .member import VariableMember
|
||||
from .scope import StructLikeScopeKind
|
||||
from .snapshot import Snapshot
|
||||
|
||||
|
||||
def resolve_ref_text_name(type_def: compound.refTextType) -> str:
|
||||
if hasattr(type_def, "content_") and type_def.content_:
|
||||
name = ""
|
||||
for part in type_def.content_:
|
||||
if part.category == 1: # MixedContainer.CategoryText
|
||||
name += part.value
|
||||
elif part.category == 3: # MixedContainer.CategoryComplex (ref element)
|
||||
if hasattr(part.value, "get_valueOf_"):
|
||||
name += part.value.get_valueOf_()
|
||||
elif hasattr(part.value, "valueOf_"):
|
||||
name += part.value.valueOf_
|
||||
else:
|
||||
name += str(part.value)
|
||||
return name
|
||||
|
||||
if type_def.ref:
|
||||
return type_def.ref[0].get_valueOf_()
|
||||
|
||||
return type_def.get_valueOf_()
|
||||
|
||||
|
||||
def resolve_linked_text_name(type_def: compound.linkedTextType) -> str:
|
||||
name = ""
|
||||
|
||||
for part in type_def.content_:
|
||||
if part.category == 1: # MixedContainer.CategoryText
|
||||
name += part.value
|
||||
elif part.category == 3: # MixedContainer.CategoryComplex (ref element)
|
||||
# For ref elements, get the text content
|
||||
if hasattr(part.value, "get_valueOf_"):
|
||||
name += part.value.get_valueOf_()
|
||||
elif hasattr(part.value, "valueOf_"):
|
||||
name += part.value.valueOf_
|
||||
else:
|
||||
name += str(part.value)
|
||||
|
||||
# literal initializers keep "=" sign
|
||||
if name.startswith("="):
|
||||
name = name[1:]
|
||||
|
||||
return name.strip()
|
||||
|
||||
|
||||
def get_base_classes(
|
||||
compound_object: compound.CompounddefType,
|
||||
) -> [StructLikeScopeKind.Base]:
|
||||
"""
|
||||
Get the base classes of a compound object.
|
||||
"""
|
||||
base_classes = []
|
||||
if compound_object.basecompoundref:
|
||||
for base in compound_object.basecompoundref:
|
||||
# base is a compoundRefType with:
|
||||
# - refid: reference ID to the base class definition
|
||||
# - prot: protection level (public, protected, private)
|
||||
# - virt: virtual inheritance (non-virtual, virtual, pure-virtual)
|
||||
# - valueOf_: the name of the base class
|
||||
base_name = base.valueOf_
|
||||
base_prot = base.prot
|
||||
base_virt = base.virt
|
||||
base_refid = base.refid
|
||||
|
||||
if base_prot == "private":
|
||||
# Ignore private base classes
|
||||
continue
|
||||
|
||||
base_classes.append(
|
||||
StructLikeScopeKind.Base(
|
||||
base_name,
|
||||
base_prot,
|
||||
base_virt == "virtual",
|
||||
base_refid,
|
||||
)
|
||||
)
|
||||
return base_classes
|
||||
|
||||
|
||||
def get_variable_member(
|
||||
member_def: compound.MemberdefType,
|
||||
visibility: str,
|
||||
is_static: bool = False,
|
||||
) -> VariableMember:
|
||||
"""
|
||||
Get the variable member from a member definition.
|
||||
"""
|
||||
variable_name = member_def.get_name()
|
||||
|
||||
if len(variable_name) == 0:
|
||||
# Ignore anonymous variables
|
||||
return None
|
||||
|
||||
variable_type = resolve_ref_text_name(member_def.get_type()).strip()
|
||||
variable_value = None
|
||||
variable_definition = member_def.definition
|
||||
variable_argstring = member_def.get_argsstring()
|
||||
|
||||
is_constexpr = member_def.constexpr == "yes"
|
||||
is_mutable = member_def.mutable == "yes"
|
||||
|
||||
if is_constexpr and variable_type.find("constexpr") != -1:
|
||||
variable_type = variable_type.replace("constexpr", "").strip()
|
||||
|
||||
is_const = variable_type.startswith("const")
|
||||
if is_const:
|
||||
variable_type = variable_type[5:].strip()
|
||||
|
||||
if member_def.initializer is not None:
|
||||
variable_value = resolve_linked_text_name(member_def.initializer)
|
||||
|
||||
return VariableMember(
|
||||
variable_name,
|
||||
variable_type,
|
||||
visibility,
|
||||
is_const,
|
||||
is_static,
|
||||
is_constexpr,
|
||||
is_mutable,
|
||||
variable_value,
|
||||
variable_definition,
|
||||
variable_argstring,
|
||||
)
|
||||
|
||||
|
||||
def build_snapshot(xml_dir: str) -> Snapshot:
|
||||
"""
|
||||
Reads the Doxygen XML output and builds a snapshot of the C++ API.
|
||||
"""
|
||||
index_path = os.path.join(xml_dir, "index.xml")
|
||||
if not os.path.exists(index_path):
|
||||
raise RuntimeError(f"Doxygen entry point not found at {index_path}")
|
||||
|
||||
root = index.parse(index_path, silence=True)
|
||||
snapshot = Snapshot()
|
||||
|
||||
for entry in root.compound:
|
||||
detail_file = os.path.join(xml_dir, f"{entry.refid}.xml")
|
||||
if not os.path.exists(detail_file):
|
||||
print(f"Detail file not found at {detail_file}")
|
||||
continue
|
||||
|
||||
doxygen_object = compound.parse(detail_file, silence=True)
|
||||
|
||||
for compound_object in doxygen_object.compounddef:
|
||||
# classes and structs are represented by the same scope with a different kind
|
||||
if (
|
||||
compound_object.kind == "class"
|
||||
or compound_object.kind == "struct"
|
||||
or compound_object.kind == "union"
|
||||
):
|
||||
class_scope = (
|
||||
snapshot.create_struct_like(
|
||||
compound_object.compoundname, StructLikeScopeKind.Type.CLASS
|
||||
)
|
||||
if compound_object.kind == "class"
|
||||
else snapshot.create_struct_like(
|
||||
compound_object.compoundname, StructLikeScopeKind.Type.STRUCT
|
||||
)
|
||||
if compound_object.kind == "struct"
|
||||
else snapshot.create_struct_like(
|
||||
compound_object.compoundname, StructLikeScopeKind.Type.UNION
|
||||
)
|
||||
)
|
||||
|
||||
class_scope.kind.add_base(get_base_classes(compound_object))
|
||||
class_scope.location = compound_object.location.file
|
||||
|
||||
for section_def in compound_object.sectiondef:
|
||||
kind = section_def.kind
|
||||
parts = kind.split("-")
|
||||
visibility = parts[0]
|
||||
is_static = "static" in parts
|
||||
member_type = parts[-1]
|
||||
|
||||
if visibility == "private":
|
||||
pass
|
||||
elif visibility in ("public", "protected"):
|
||||
if member_type == "attrib":
|
||||
for member_def in section_def.memberdef:
|
||||
if member_def.kind == "variable":
|
||||
class_scope.add_member(
|
||||
get_variable_member(
|
||||
member_def, visibility, is_static
|
||||
)
|
||||
)
|
||||
else:
|
||||
print(
|
||||
f"Unknown class section kind: {kind} in {compound_object.location.file}"
|
||||
)
|
||||
elif visibility == "friend":
|
||||
# Ignore friend declarations, they are not meaningful for the public API surface
|
||||
pass
|
||||
elif visibility == "property":
|
||||
print(
|
||||
f"Property not supported: {compound_object.compoundname} in {compound_object.location.file}"
|
||||
)
|
||||
else:
|
||||
print(
|
||||
f"Unknown class visibility: {visibility} in {compound_object.location.file}"
|
||||
)
|
||||
elif compound_object.kind == "namespace":
|
||||
namespace_scope = snapshot.create_or_get_namespace(
|
||||
compound_object.compoundname
|
||||
)
|
||||
|
||||
namespace_scope.location = compound_object.location.file
|
||||
|
||||
for section_def in compound_object.sectiondef:
|
||||
if section_def.kind == "var":
|
||||
for variable_def in section_def.memberdef:
|
||||
is_static = variable_def.static == "yes"
|
||||
namespace_scope.add_member(
|
||||
get_variable_member(variable_def, "public", is_static)
|
||||
)
|
||||
else:
|
||||
print(
|
||||
f"Unknown section kind: {section_def.kind} in {compound_object.location.file}"
|
||||
)
|
||||
elif compound_object.kind == "file":
|
||||
pass
|
||||
elif compound_object.kind == "dir":
|
||||
pass
|
||||
elif compound_object.kind == "category":
|
||||
print(f"Category not supported: {compound_object.compoundname}")
|
||||
elif compound_object.kind == "page":
|
||||
# Contains deprecation info
|
||||
pass
|
||||
elif compound_object.kind == "protocol":
|
||||
print(f"Protocol not supported: {compound_object.compoundname}")
|
||||
else:
|
||||
print(f"Unknown compound kind: {compound_object.kind}")
|
||||
|
||||
snapshot.finish()
|
||||
return snapshot
|
||||
@@ -0,0 +1,111 @@
|
||||
# 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.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .scope import Scope
|
||||
|
||||
|
||||
class Member(ABC):
|
||||
def __init__(self, name: str, visibility: str) -> None:
|
||||
self.name: str = name
|
||||
self.visibility: str = visibility
|
||||
|
||||
@abstractmethod
|
||||
def to_string(
|
||||
self,
|
||||
indent: int = 0,
|
||||
qualification: str | None = None,
|
||||
hide_visibility: bool = False,
|
||||
) -> str:
|
||||
pass
|
||||
|
||||
def close(self, scope: Scope):
|
||||
pass
|
||||
|
||||
def _get_qualified_name(self, qualification: str | None):
|
||||
return f"{qualification}::{self.name}" if qualification else self.name
|
||||
|
||||
|
||||
class VariableMember(Member):
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
type: str,
|
||||
visibility: str,
|
||||
is_const: bool,
|
||||
is_static: bool,
|
||||
is_constexpr: bool,
|
||||
is_mutable: bool,
|
||||
value: str | None,
|
||||
definition: str,
|
||||
argstring: str | None = None,
|
||||
) -> None:
|
||||
super().__init__(name, visibility)
|
||||
self.type: str = type
|
||||
self.value: str | None = value
|
||||
self.is_const: bool = is_const
|
||||
self.is_static: bool = is_static
|
||||
self.is_constexpr: bool = is_constexpr
|
||||
self.is_mutable: bool = is_mutable
|
||||
self.definition: str = definition
|
||||
self.argstring: str | None = argstring
|
||||
|
||||
def close(self, scope: Scope):
|
||||
# TODO: handle unqualified references
|
||||
pass
|
||||
|
||||
def _is_function_pointer(self) -> bool:
|
||||
"""Check if this variable is a function pointer type."""
|
||||
return self.argstring is not None and self.argstring.startswith(")(")
|
||||
|
||||
def to_string(
|
||||
self,
|
||||
indent: int = 0,
|
||||
qualification: str | None = None,
|
||||
hide_visibility: bool = False,
|
||||
) -> str:
|
||||
name = self._get_qualified_name(qualification)
|
||||
|
||||
result = " " * indent
|
||||
|
||||
if not hide_visibility:
|
||||
result += self.visibility + " "
|
||||
|
||||
if self.is_static:
|
||||
result += "static "
|
||||
|
||||
if self.is_constexpr:
|
||||
result += "constexpr "
|
||||
|
||||
if self.is_const and not self.is_constexpr:
|
||||
result += "const "
|
||||
|
||||
if self.is_mutable:
|
||||
result += "mutable "
|
||||
|
||||
if self._is_function_pointer():
|
||||
# Function pointer types: argstring is ")(args...)"
|
||||
# If type already contains "(*", e.g. "void *(*" or "void(*", use directly
|
||||
# Otherwise add "(*" to form proper function pointer syntax
|
||||
if "(*" in self.type:
|
||||
result += f"{self.type}{name}{self.argstring}"
|
||||
else:
|
||||
result += f"{self.type} (*{name}{self.argstring}"
|
||||
else:
|
||||
result += f"{self.type} {name}"
|
||||
|
||||
if self.value is not None and (self.is_const or self.is_constexpr):
|
||||
result += f" = {self.value}"
|
||||
|
||||
result += ";"
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,47 @@
|
||||
# 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.
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
|
||||
def get_repo_root() -> str:
|
||||
"""Get the repository root via git."""
|
||||
result = subprocess.run(
|
||||
["git", "rev-parse", "--show-toplevel"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(
|
||||
f"Could not determine repo root via 'git rev-parse': {result.stderr}"
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def get_react_native_dir() -> str:
|
||||
"""
|
||||
Get the path to the react-native package directory.
|
||||
|
||||
This function handles two execution contexts:
|
||||
1. Buck execution: Uses REACT_NATIVE_DIR env var + git repo root
|
||||
2. Direct Python invocation: Uses __file__ relative path
|
||||
"""
|
||||
react_native_dir = os.environ.get("REACT_NATIVE_DIR")
|
||||
if react_native_dir:
|
||||
return os.path.join(get_repo_root(), react_native_dir)
|
||||
|
||||
# Use realpath to resolve symlinks — in Buck's link-tree, __file__
|
||||
# is a symlink back to the source tree, so this gives the correct
|
||||
# source location for relative path resolution.
|
||||
script_dir = os.path.dirname(os.path.realpath(__file__))
|
||||
return os.path.normpath(
|
||||
os.path.join(
|
||||
script_dir, # scripts/cxx-api/parser/
|
||||
"..", # scripts/cxx-api/
|
||||
"..", # scripts/
|
||||
"..", # react-native-github/
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,183 @@
|
||||
# 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.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from enum import Enum
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
from natsort import natsorted
|
||||
|
||||
from .member import Member
|
||||
from .utils import parse_qualified_path
|
||||
|
||||
|
||||
class ScopeKind(ABC):
|
||||
def __init__(self, name) -> None:
|
||||
self.name: str = name
|
||||
|
||||
@abstractmethod
|
||||
def to_string(self, scope: Scope) -> str:
|
||||
pass
|
||||
|
||||
def print_scope(self, scope: Scope) -> None:
|
||||
print(self.to_string(scope))
|
||||
|
||||
|
||||
class StructLikeScopeKind(ScopeKind):
|
||||
class Base:
|
||||
def __init__(
|
||||
self, name: str, protection: str, virtual: bool, refid: str
|
||||
) -> None:
|
||||
self.name: str = name
|
||||
self.protection: str = protection
|
||||
self.virtual: bool = virtual
|
||||
self.refid: str = refid
|
||||
|
||||
class Type(Enum):
|
||||
CLASS = "class"
|
||||
STRUCT = "struct"
|
||||
UNION = "union"
|
||||
|
||||
def __init__(self, type: Type) -> None:
|
||||
super().__init__(type.value)
|
||||
|
||||
self.base_classes: [StructLikeScopeKind.Base] = []
|
||||
|
||||
def add_base(
|
||||
self, base: StructLikeScopeKind.Base | [StructLikeScopeKind.Base]
|
||||
) -> None:
|
||||
if isinstance(base, list):
|
||||
for b in base:
|
||||
self.base_classes.append(b)
|
||||
else:
|
||||
self.base_classes.append(base)
|
||||
|
||||
def to_string(self, scope: Scope) -> str:
|
||||
result = ""
|
||||
|
||||
bases = []
|
||||
for base in self.base_classes:
|
||||
base_text = [base.protection]
|
||||
if base.virtual:
|
||||
base_text.append("virtual")
|
||||
base_text.append(base.name)
|
||||
bases.append(" ".join(base_text))
|
||||
|
||||
inheritance_string = " : " + ", ".join(bases) if bases else ""
|
||||
|
||||
result += f"{self.name} {scope.get_qualified_name()}{inheritance_string} {{"
|
||||
|
||||
stringified_members = []
|
||||
for member in scope.get_members():
|
||||
stringified_members.append(member.to_string(2))
|
||||
stringified_members = natsorted(stringified_members)
|
||||
result += ("\n" if len(stringified_members) > 0 else "") + "\n".join(
|
||||
stringified_members
|
||||
)
|
||||
|
||||
result += "\n}"
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class NamespaceScopeKind(ScopeKind):
|
||||
def __init__(self) -> None:
|
||||
super().__init__("namespace")
|
||||
|
||||
def to_string(self, scope: Scope) -> str:
|
||||
qualification = scope.get_qualified_name()
|
||||
|
||||
result = []
|
||||
for member in scope.get_members():
|
||||
result.append(member.to_string(0, qualification, hide_visibility=True))
|
||||
|
||||
result = natsorted(result)
|
||||
return "\n".join(result)
|
||||
|
||||
|
||||
class TemporaryScopeKind(ScopeKind):
|
||||
def __init__(self) -> None:
|
||||
super().__init__("temporary")
|
||||
|
||||
def to_string(self, scope: Scope) -> str:
|
||||
raise RuntimeError("Temporary scope should not be printed")
|
||||
|
||||
|
||||
ScopeKindT = TypeVar("ScopeKindT", bound=ScopeKind)
|
||||
|
||||
|
||||
class Scope(Generic[ScopeKindT]):
|
||||
def __init__(self, kind: ScopeKindT, name: str | None = None) -> None:
|
||||
self.name: str | None = name
|
||||
self.kind: ScopeKindT = kind
|
||||
self.parent_scope: Scope | None = None
|
||||
self.inner_scopes: dict[str, Scope] = {}
|
||||
self._members: list[Member] = []
|
||||
self.location: str | None = None
|
||||
|
||||
def get_qualified_name(self) -> str:
|
||||
"""
|
||||
Get the qualified name of the scope.
|
||||
"""
|
||||
path = []
|
||||
current_scope = self
|
||||
while current_scope is not None:
|
||||
if current_scope.name is not None:
|
||||
path.append(current_scope.name)
|
||||
current_scope = current_scope.parent_scope
|
||||
path.reverse()
|
||||
return "::".join(path)
|
||||
|
||||
def _get_base_name(self, name: str) -> str:
|
||||
"""Strip template arguments from a name for scope lookup."""
|
||||
angle_idx = name.find("<")
|
||||
return name[:angle_idx] if angle_idx != -1 else name
|
||||
|
||||
def add_member(self, member: Member | None) -> None:
|
||||
"""
|
||||
Add a member to the scope.
|
||||
"""
|
||||
if member is None:
|
||||
return
|
||||
self._members.append(member)
|
||||
|
||||
def get_members(self) -> list[Member]:
|
||||
"""
|
||||
Get all members of the scope.
|
||||
"""
|
||||
return self._members
|
||||
|
||||
def close(self) -> None:
|
||||
"""
|
||||
Close the scope by setting the kind of all temporary scopes.
|
||||
"""
|
||||
for member in self.get_members():
|
||||
member.close(self)
|
||||
|
||||
for _, inner_scope in self.inner_scopes.items():
|
||||
inner_scope.close()
|
||||
|
||||
def to_string(self) -> str:
|
||||
"""
|
||||
Get the string representation of the scope.
|
||||
"""
|
||||
result = [self.kind.to_string(self)]
|
||||
|
||||
for _, inner_scope in sorted(
|
||||
filter(lambda x: x[0] is not None, self.inner_scopes.items()),
|
||||
key=lambda x: x[0],
|
||||
):
|
||||
result.append(inner_scope.to_string())
|
||||
|
||||
result = natsorted(result)
|
||||
return "\n\n".join(result).strip()
|
||||
|
||||
def print(self):
|
||||
"""
|
||||
Print a scope and its contents.
|
||||
"""
|
||||
print(self.to_string())
|
||||
@@ -0,0 +1,108 @@
|
||||
# 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.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .scope import NamespaceScopeKind, Scope, StructLikeScopeKind, TemporaryScopeKind
|
||||
from .utils import parse_qualified_path
|
||||
|
||||
|
||||
class Snapshot:
|
||||
def __init__(self) -> None:
|
||||
self.root_scope: Scope = Scope(NamespaceScopeKind())
|
||||
|
||||
def ensure_scope(self, scope_path: list[str]) -> Scope:
|
||||
"""
|
||||
Ensure that a scope exists in the snapshot, creating it if necessary.
|
||||
"""
|
||||
current_scope = self.root_scope
|
||||
for name in scope_path:
|
||||
if name not in current_scope.inner_scopes:
|
||||
new_scope = Scope(TemporaryScopeKind(), name)
|
||||
new_scope.parent_scope = current_scope
|
||||
current_scope.inner_scopes[name] = new_scope
|
||||
current_scope = current_scope.inner_scopes[name]
|
||||
return current_scope
|
||||
|
||||
def create_struct_like(
|
||||
self, qualified_name: str, type: StructLikeScopeKind.Type
|
||||
) -> Scope[StructLikeScopeKind]:
|
||||
"""
|
||||
Create a class in the snapshot.
|
||||
"""
|
||||
path = parse_qualified_path(qualified_name)
|
||||
scope_path = path[0:-1]
|
||||
scope_name = path[-1]
|
||||
current_scope = self.ensure_scope(scope_path)
|
||||
|
||||
if scope_name in current_scope.inner_scopes:
|
||||
scope = current_scope.inner_scopes[scope_name]
|
||||
if scope.kind.name == "temporary":
|
||||
scope.kind = StructLikeScopeKind(type)
|
||||
else:
|
||||
raise RuntimeError(
|
||||
f"Identifier {scope_name} already exists in scope {current_scope.name}"
|
||||
)
|
||||
return scope
|
||||
else:
|
||||
new_scope = Scope(StructLikeScopeKind(type), scope_name)
|
||||
new_scope.parent_scope = current_scope
|
||||
current_scope.inner_scopes[scope_name] = new_scope
|
||||
return new_scope
|
||||
|
||||
def create_or_get_namespace(self, qualified_name: str) -> Scope[NamespaceScopeKind]:
|
||||
"""
|
||||
Create a namespace in the snapshot.
|
||||
"""
|
||||
path = parse_qualified_path(qualified_name)
|
||||
scope_path = path[0:-1]
|
||||
namespace_name = path[-1] if len(path) > 0 else None
|
||||
current_scope = self.ensure_scope(scope_path)
|
||||
|
||||
if namespace_name in current_scope.inner_scopes:
|
||||
scope = current_scope.inner_scopes[namespace_name]
|
||||
if scope.kind.name == "temporary":
|
||||
scope.kind = NamespaceScopeKind()
|
||||
elif scope.kind.name == "namespace":
|
||||
return scope
|
||||
else:
|
||||
raise RuntimeError(
|
||||
f"Identifier {namespace_name} already exists in scope {current_scope.name} with kind {scope.kind.name}"
|
||||
)
|
||||
return scope
|
||||
else:
|
||||
new_scope = Scope(NamespaceScopeKind(), namespace_name)
|
||||
new_scope.parent_scope = current_scope
|
||||
current_scope.inner_scopes[namespace_name] = new_scope
|
||||
return new_scope
|
||||
|
||||
def _ensure_scope_is_defined(self, scope: Scope) -> None:
|
||||
"""
|
||||
Ensure that a scope is defined in the snapshot.
|
||||
"""
|
||||
if scope.kind.name == "temporary":
|
||||
raise RuntimeError(f"Scope {scope.name} is not defined in the snapshot")
|
||||
|
||||
for inner_scope in scope.inner_scopes.values():
|
||||
self._ensure_scope_is_defined(inner_scope)
|
||||
|
||||
def finish(self) -> None:
|
||||
"""
|
||||
Finish the snapshot by setting the kind of all temporary scopes.
|
||||
"""
|
||||
self._ensure_scope_is_defined(self.root_scope)
|
||||
self.root_scope.close()
|
||||
|
||||
def to_string(self) -> str:
|
||||
"""
|
||||
Get the string representation of the snapshot.
|
||||
"""
|
||||
return self.root_scope.to_string()
|
||||
|
||||
def print(self) -> None:
|
||||
"""
|
||||
Print the snapshot.
|
||||
"""
|
||||
self.root_scope.print()
|
||||
@@ -0,0 +1,63 @@
|
||||
# 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.
|
||||
|
||||
|
||||
def parse_qualified_path(path: str) -> list[str]:
|
||||
"""
|
||||
Parse a qualified path into a list of names.
|
||||
|
||||
Handles template syntax correctly by not splitting on "::" inside
|
||||
angle brackets. For example:
|
||||
- "std::vector<std::string>::test" -> ["std", "vector<std::string>", "test"]
|
||||
- "ns::Foo<A, B>::Bar" -> ["ns", "Foo<A, B>", "Bar"]
|
||||
|
||||
Also handles edge cases:
|
||||
- Comparison operators inside parentheses: "std::enable_if<(N > 0)>::type"
|
||||
- Arrow operators: "decltype(ptr->member)::type"
|
||||
- Bitshift operators: "std::integral_constant<int, (1 >> 2)>::value"
|
||||
"""
|
||||
result = []
|
||||
current = ""
|
||||
angle_depth = 0
|
||||
paren_depth = 0
|
||||
i = 0
|
||||
|
||||
while i < len(path):
|
||||
char = path[i]
|
||||
|
||||
if char == "(":
|
||||
paren_depth += 1
|
||||
current += char
|
||||
i += 1
|
||||
elif char == ")":
|
||||
paren_depth -= 1
|
||||
current += char
|
||||
i += 1
|
||||
elif char == "<" and paren_depth == 0:
|
||||
angle_depth += 1
|
||||
current += char
|
||||
i += 1
|
||||
elif char == ">" and paren_depth == 0:
|
||||
# Check for arrow operator "->" which should not affect angle_depth
|
||||
if i > 0 and path[i - 1] == "-":
|
||||
current += char
|
||||
i += 1
|
||||
else:
|
||||
angle_depth -= 1
|
||||
current += char
|
||||
i += 1
|
||||
elif path[i : i + 2] == "::" and angle_depth == 0 and paren_depth == 0:
|
||||
if current:
|
||||
result.append(current)
|
||||
current = ""
|
||||
i += 2
|
||||
else:
|
||||
current += char
|
||||
i += 1
|
||||
|
||||
if current:
|
||||
result.append(current)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,4 @@
|
||||
# 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.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
||||
class test::Base {
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,5 @@
|
||||
class test::Base {
|
||||
}
|
||||
|
||||
class test::Derived : public test::Base {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* 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 {};
|
||||
|
||||
class Derived : public Base {};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,3 @@
|
||||
class test::Base {
|
||||
protected int value;
|
||||
}
|
||||
@@ -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:
|
||||
int value;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
class test::Base {
|
||||
protected static int value;
|
||||
}
|
||||
@@ -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 int value;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,3 @@
|
||||
class test::Base {
|
||||
public const int value;
|
||||
}
|
||||
@@ -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:
|
||||
const int value;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
class test::Clss {
|
||||
public constexpr int value1 = 1;
|
||||
public constexpr int value2 = 1;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* 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:
|
||||
constexpr int value1 = 1;
|
||||
int constexpr value2 = 1;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,3 @@
|
||||
class test::Base {
|
||||
public int value;
|
||||
}
|
||||
@@ -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:
|
||||
int value;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
class test::Base {
|
||||
public const int value = 1;
|
||||
}
|
||||
+17
@@ -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:
|
||||
const int value = 1;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
class test::Base {
|
||||
public int value;
|
||||
}
|
||||
@@ -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:
|
||||
int value = 1;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,3 @@
|
||||
class test::Base {
|
||||
public static int value;
|
||||
}
|
||||
@@ -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 int value;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,5 @@
|
||||
class test::Base {
|
||||
}
|
||||
|
||||
class test::Derived : public virtual test::Base {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* 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 {};
|
||||
|
||||
class Derived : public virtual Base {};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,6 @@
|
||||
class test::Outer {
|
||||
}
|
||||
|
||||
struct test::Outer::InnerStruct {
|
||||
public bool value;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* 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 Outer {
|
||||
public:
|
||||
struct InnerStruct {
|
||||
bool value;
|
||||
};
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,5 @@
|
||||
struct test::FunctionPointers {
|
||||
public int(*withReturn)(double, float);
|
||||
public void *(*returnsPointer)(const char *);
|
||||
public void(*simple)(int);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* 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 FunctionPointers {
|
||||
void (*simple)(int);
|
||||
int (*withReturn)(double, float);
|
||||
void *(*returnsPointer)(const char *);
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,2 @@
|
||||
struct test::nested::NestedStruct {
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* 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 {
|
||||
|
||||
namespace nested {
|
||||
|
||||
struct NestedStruct {};
|
||||
|
||||
} // namespace nested
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,2 @@
|
||||
union test::EmptyUnion {
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/*
|
||||
* 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 {
|
||||
|
||||
union EmptyUnion {
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,4 @@
|
||||
union test::DataUnion {
|
||||
public float floatValue;
|
||||
public int32_t intValue;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* 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 DataUnion {
|
||||
int32_t intValue;
|
||||
float floatValue;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,4 @@
|
||||
union test::StaticUnion {
|
||||
public int intValue;
|
||||
public static int count;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
* 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 {
|
||||
|
||||
union StaticUnion {
|
||||
public:
|
||||
int intValue;
|
||||
|
||||
static int count;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,2 @@
|
||||
class test::Clss {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* 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 {
|
||||
bool isEnabled;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,5 @@
|
||||
class test::Base {
|
||||
}
|
||||
|
||||
class test::Derived {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* 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 {};
|
||||
|
||||
class Derived : private Base {};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,2 @@
|
||||
class test::Clss {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* 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 {
|
||||
static bool isEnabled;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,2 @@
|
||||
struct test::Strct {
|
||||
}
|
||||
@@ -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 Strct {
|
||||
private:
|
||||
bool isEnabled;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -0,0 +1,3 @@
|
||||
union test::PrivateUnion {
|
||||
public float publicValue;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* 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 {
|
||||
|
||||
union PrivateUnion {
|
||||
private:
|
||||
int secretValue;
|
||||
|
||||
public:
|
||||
float publicValue;
|
||||
};
|
||||
|
||||
} // namespace test
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
@@ -14,17 +14,17 @@ from importlib.abc import Traversable
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from .parser import build_snapshot
|
||||
from ..parser import build_snapshot, get_repo_root
|
||||
|
||||
|
||||
def _resource_root() -> Traversable:
|
||||
"""Get the root directory containing test cases.
|
||||
"""Get the root directory containing test case snapshots.
|
||||
|
||||
Resources are included directly via glob(["tests/**/*"]) in BUCK.
|
||||
Files are mapped at their original paths (e.g., tests/test1/...).
|
||||
Resources are included directly via glob(["tests/snapshots/**/*"]) in BUCK.
|
||||
Files are mapped at their original paths (e.g., tests/snapshots/test1/...).
|
||||
"""
|
||||
pkg_root = ir.files(__package__ if __package__ else "__main__")
|
||||
return pkg_root / "tests"
|
||||
return pkg_root / "snapshots"
|
||||
|
||||
|
||||
def _iter_case_dirs(root: Traversable) -> Iterable[Traversable]:
|
||||
@@ -61,8 +61,8 @@ def _generate_doxygen_api(case_dir_path: str, doxygen_config_path: str) -> None:
|
||||
raise RuntimeError(f"Doxygen failed: {result.stderr}")
|
||||
|
||||
|
||||
def _get_source_tests_dir() -> Path:
|
||||
"""Get the actual source directory for tests (for writing snapshots).
|
||||
def _get_source_snapshots_dir() -> Path:
|
||||
"""Get the actual source directory for snapshots (for writing snapshots).
|
||||
|
||||
This finds the original source directory, not the packaged resources.
|
||||
Used when UPDATE_SNAPSHOT=1 to write new snapshots.
|
||||
@@ -71,13 +71,21 @@ def _get_source_tests_dir() -> Path:
|
||||
if not source_tests_path:
|
||||
raise RuntimeError("SOURCE_TESTS_PATH environment variable is not set")
|
||||
|
||||
from .parser import _get_repo_root
|
||||
|
||||
return Path(_get_repo_root()) / source_tests_path
|
||||
return Path(get_repo_root()) / source_tests_path
|
||||
|
||||
|
||||
def _make_case_test(case_dir: Traversable, tests_root: Traversable):
|
||||
"""Create a test method for a specific test case directory."""
|
||||
"""Create a test method for a specific test case directory.
|
||||
|
||||
Snapshot update workflow:
|
||||
To regenerate snapshots, set UPDATE_SNAPSHOT=1 env
|
||||
NOTE: plain ``UPDATE_SNAPSHOT=1 buck2 test ...`` does NOT work
|
||||
because Buck2 does not forward shell environment variables to
|
||||
test processes.
|
||||
|
||||
When a test case directory has no snapshot.api in the source tree
|
||||
the snapshot is generated automatically on the first run.
|
||||
"""
|
||||
|
||||
def _test(self: unittest.TestCase) -> None:
|
||||
update = os.environ.get("UPDATE_SNAPSHOT") == "1"
|
||||
@@ -94,20 +102,39 @@ def _make_case_test(case_dir: Traversable, tests_root: Traversable):
|
||||
# Parse the generated XML
|
||||
xml_dir = case_dir_path / "api" / "xml"
|
||||
snapshot = build_snapshot(str(xml_dir))
|
||||
got_snapshot = snapshot.rstrip() + "\n"
|
||||
got_snapshot = snapshot.to_string().rstrip() + "\n"
|
||||
|
||||
expected_snapshot_path = case_dir_path / "snapshot.api"
|
||||
# Resolve the source-tree snapshot path (for writing)
|
||||
try:
|
||||
source_snapshots_dir = _get_source_snapshots_dir()
|
||||
source_snapshot_path = (
|
||||
source_snapshots_dir / case_dir.name / "snapshot.api"
|
||||
)
|
||||
except RuntimeError:
|
||||
source_snapshot_path = None
|
||||
|
||||
# For writing snapshots, use the actual source directory
|
||||
# when updating, otherwise use the packaged resource
|
||||
if update or not expected_snapshot_path.exists():
|
||||
# Write to actual source directory
|
||||
source_tests_dir = _get_source_tests_dir()
|
||||
source_snapshot_path = source_tests_dir / case_dir.name / "snapshot.api"
|
||||
source_snapshot_path.write_text(got_snapshot)
|
||||
print(f"Updated snapshot: {source_snapshot_path}")
|
||||
# Update mode: write the snapshot and pass unconditionally
|
||||
if update:
|
||||
if source_snapshot_path is not None:
|
||||
source_snapshot_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
source_snapshot_path.write_text(got_snapshot)
|
||||
print(f"Updated snapshot: {source_snapshot_path}")
|
||||
return
|
||||
|
||||
# Auto-generate when no snapshot exists in the source tree yet
|
||||
if source_snapshot_path is not None and not source_snapshot_path.exists():
|
||||
source_snapshot_path.write_text(got_snapshot)
|
||||
print(f"Created snapshot: {source_snapshot_path}")
|
||||
return
|
||||
|
||||
# Normal mode: compare against the packaged snapshot
|
||||
expected_snapshot_path = case_dir_path / "snapshot.api"
|
||||
if not expected_snapshot_path.exists():
|
||||
self.fail(
|
||||
f"{case_dir.name}: no snapshot.api found; "
|
||||
f"run with --test-env UPDATE_SNAPSHOT=1 to generate"
|
||||
)
|
||||
|
||||
expected_snapshot = expected_snapshot_path.read_text()
|
||||
_assert_text_equal_with_diff(
|
||||
self, expected_snapshot, got_snapshot, case=case_dir.name
|
||||
Reference in new issue
Block a user