Skip to content

Add script to generate function map for static analysis tools #1436

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ file. Note that this requires `phpize` to be run for PHP 8.2 to make use
of all features. After changing a stub file, run `./build/gen_stub.php`
to regenerate the corresponding arginfo files and commit the results.

## Generating function maps for static analysis tools

PHPStan and Psalm use function maps to provide users with correct type analysis
when using this extension. To generate the function map, run the
`generate-function-map` make target. The generated map will be stored in
`scripts/functionMap.php`.

## Testing

The extension's test use the PHPT format from PHP internals. This format is
Expand Down
24 changes: 23 additions & 1 deletion Makefile.frag
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
.PHONY: coverage test-clean package package.xml format format-changed format-check
.PHONY: mv-coverage lcov-coveralls lcov-local coverage coveralls format format-changed format-check test-clean package package.xml libmongoc-version-current libmongocrypt-version-current generate-function-map

ifneq (,$(realpath $(EXTENSION_DIR)/json.so))
PHP_TEST_SHARED_EXTENSIONS := "-d" "extension=$(EXTENSION_DIR)/json.so" $(PHP_TEST_SHARED_EXTENSIONS)
Expand Down Expand Up @@ -66,3 +66,25 @@ libmongoc-version-current:

libmongocrypt-version-current:
cd src/libmongocrypt/ && python etc/calc_release_version.py > ../LIBMONGOCRYPT_VERSION_CURRENT

generate-function-map: all
@if test ! -z "$(PHP_EXECUTABLE)" && test -x "$(PHP_EXECUTABLE)"; then \
INI_FILE=`$(PHP_EXECUTABLE) -d 'display_errors=stderr' -r 'echo php_ini_loaded_file();' 2> /dev/null`; \
if test "$$INI_FILE"; then \
$(EGREP) -h -v $(PHP_DEPRECATED_DIRECTIVES_REGEX) "$$INI_FILE" > $(top_builddir)/tmp-php.ini; \
else \
echo > $(top_builddir)/tmp-php.ini; \
fi; \
INI_SCANNED_PATH=`$(PHP_EXECUTABLE) -d 'display_errors=stderr' -r '$$a = explode(",\n", trim(php_ini_scanned_files())); echo $$a[0];' 2> /dev/null`; \
if test "$$INI_SCANNED_PATH"; then \
INI_SCANNED_PATH=`$(top_srcdir)/build/shtool path -d $$INI_SCANNED_PATH`; \
$(EGREP) -h -v $(PHP_DEPRECATED_DIRECTIVES_REGEX) "$$INI_SCANNED_PATH"/*.ini >> $(top_builddir)/tmp-php.ini; \
fi; \
CC="$(CC)" \
$(PHP_EXECUTABLE) -n -c $(top_builddir)/tmp-php.ini -n -c $(top_builddir)/tmp-php.ini -d extension_dir=$(top_builddir)/modules/ $(PHP_TEST_SHARED_EXTENSIONS) $(top_srcdir)/scripts/generate-functionmap.php; \
RESULT_EXIT_CODE=$$?; \
rm $(top_builddir)/tmp-php.ini; \
exit $$RESULT_EXIT_CODE; \
else \
echo "ERROR: Cannot generate function maps without CLI sapi."; \
fi
138 changes: 138 additions & 0 deletions scripts/generate-functionmap.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
<?php

if (PHP_VERSION_ID < 80000) {
echo 'This script requires PHP 8.0 or higher';
exit(1);
}

$filename = __DIR__ . '/functionmap.php';
(new FunctionMapGenerator)->createFunctionMap($filename);
printf("Created call map in %s\n", $filename);

class FunctionMapGenerator
{
public function createFunctionMap(string $filename): void
{
$this->writeFunctionMap($filename, $this->getFunctionMap());
}

private function getFunctionMap(): array
{
$classes = array_filter(get_declared_classes(), $this->filterItems(...));
$interfaces = array_filter(get_declared_interfaces(), $this->filterItems(...));
$functions = array_filter(get_defined_functions()['internal'], $this->filterItems(...));

$functionMap = [];

// Generate call map for functions
foreach ($functions as $functionName) {
$reflectionFunction = new ReflectionFunction($functionName);
$functionMap[$reflectionFunction->getName()] = $this->getFunctionMapEntry($reflectionFunction);
}

// Generate call map for classes and interfaces
$members = array_merge($classes, $interfaces);
sort($members);

$skippedMethods = ['__set_state', '__wakeup', '__serialize', '__unserialize'];

foreach ($members as $member) {
$reflectionClass = new ReflectionClass($member);

foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
if ($method->getDeclaringClass() != $reflectionClass && $method->getName() != '__toString') {
continue;
}

if (in_array($method->getName(), $skippedMethods, true)) {
continue;
}

$methodKey = $reflectionClass->getName() . '::' . $method->getName();
$functionMap[$methodKey] = $this->getFunctionMapEntry($method);
}
}

return $functionMap;
}

private function writeFunctionMap(string $filename, array $functionMap): void
{
$lines = [];
foreach ($functionMap as $methodName => $typeInfo) {
$generatedTypeInfo = implode(
', ',
array_map(
function (string|int $key, string $value): string {
if (is_int($key)) {
return $this->removeDoubleBackslash(var_export($value, true));
}

return sprintf('%s => %s', var_export($key, true), $this->removeDoubleBackslash(var_export($value, true)));
},
array_keys($typeInfo),
array_values($typeInfo)
)
);

$lines[] = sprintf(
' %s => [%s],',
$this->removeDoubleBackslash(var_export($methodName, true)),
$generatedTypeInfo
);
}

$fileTemplate = <<<'PHP'
<?php

$mongoDBFunctionMap = [
%s
];

PHP;

file_put_contents($filename, sprintf($fileTemplate, implode("\n", $lines)));
}

private function filterItems(string $name): bool {
$namespaces = ['MongoDB\BSON\\', 'MongoDB\Driver\\'];

$name = strtolower($name);

foreach ($namespaces as $namespace) {
// Always compare lowercase names, as get_defined_functions lowercases function names by default
if (str_starts_with($name, strtolower($namespace))) {
return true;
}
}

return false;
}

private function getFunctionMapEntry(ReflectionFunctionAbstract $function): array
{
$returnType = match(true) {
$function->hasReturnType() => (string) $function->getReturnType(),
$function->hasTentativeReturnType() => (string) $function->getTentativeReturnType(),
default => 'void',
};

$functionMapEntry = [$returnType];

foreach ($function->getParameters() as $parameter) {
$parameterKey = $parameter->getName();
if ($parameter->isOptional()) {
$parameterKey .= '=';
}

$functionMapEntry[$parameterKey] = (string) $parameter->getType();
}

return $functionMapEntry;
}

private function removeDoubleBackslash(string $string): string
{
return str_replace('\\\\', '\\', $string);
}
}