mirror of
https://github.com/colbymchenry/codegraph.git
synced 2026-10-17 05:07:37 +08:00
fix(cpp): a bare call in a gtest TEST_F or TEST_P body reaches the fixture's method (#2537)
The index holds a gtest `TEST_F(Fixture, Name)` / `TEST_P` body as a function named `TEST_F`; gtest makes it a method of a class derived from `Fixture`. #2533 gave such a body the fixture's data members (cppTestFixture), not its methods. rocksdb's tests call `DBTestBase`'s `Put(…)`, `Flush()`, `Key(i)` and `NewIterator(…)` bare, and those calls were guessed by name, often reaching a namesake in another class at 0.4 (`ColumnFamilyTestBase::Put`); `auto iter = NewIterator(…)` gave `iter` no type, so `iter->SeekToFirst()` reached the nested `MemTableRep::Iterator`. - cppImplicitThisMethod is #2479's lookup, taken out of matchCppImplicitThisCall: the caller's class, its bases, the classes around it, with cppTestFixture as the owner of a gtest body. matchCppImplicitThisCall keeps the local-shadowing check for the link. - cppExpressionType types a bare call by the same lookup, as on `this`, instead of the class's first declaration. Of two classes sharing a name in different test files it reads the caller's own, and in a template a dependent base a using-declaration names still counts, as before (protobuf's `using RepeatedFieldWrapper<T>::MutableRepeatedField;`). `this` in a gtest body points to the fixture. - A `->` call on a value of a type from outside the project no longer takes the type's last name for the class it is in (isCppArrowThroughOutsideType); the name strategies decide. matchCppDeclaredTypeCall steps aside for `->` on a value before #2532's outside-type check, so typing JsonTest's `auto m = ToProto<Any>(…)` (an `absl::StatusOr<Any>`) had sent `m->value()` to protobuf's own `hpb::StatusOr::value` at 0.9. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -103,6 +103,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
- In C++, a call on a data member of the calling method's class, like `versions_->GetColumnFamilySet()` in facebook/rocksdb's `db_impl_write.cc`, now links to the method of the member's type wherever the class is declared. Before, only the call's own file and the header of the same name were read for the member, and RocksDB declares `DBImpl` in `db_impl.h` while its methods are spread over `db_impl_write.cc`, `db_impl_compaction_flush.cc`, `db_impl_open.cc` and more, so such calls were guessed by the member's name. A member declared below an inline method that uses it, one a base class declares, and, in a gtest `TEST_F` or `TEST_P` body, one of the test's fixture, like RocksDB's `db_`, are found the same way, and a member of a class nested in the caller's class is no longer taken for the caller's own. A call on a member of a standard-library type, like `std::atomic<bool> shutting_down_`, no longer links to a project method that only shares the method's name. Re-index C++ projects after upgrading.
|
||||
- In C++, a variable, parameter or member whose declaration puts a qualifier or an annotation around its name is now read for its type, so calls on it link to the declared class's methods: a `const` after the `*` or `&`, like facebook/rocksdb's `Iterator* const iter = iter_guard.get();` or google/leveldb's `Env* const env_;`, a type written before its `const`, like `Slice const& key`, a nullability annotation after the `*`, like protocolbuffers/protobuf's `io::EpsCopyOutputStream* PROTOBUF_NONNULL stream`, and a thread-safety annotation after the name, like LevelDB's `MemTable* imm_ GUARDED_BY(mutex_);`. Before, such a declaration was skipped, or the annotation was taken for its type, so the call took the type of an earlier variable of the same name or was guessed by the method's name: RocksDB's `iter->SeekToFirst()` reached the unrelated `ArenaWrappedDBIter`, and LevelDB's `env_->NewWritableFile(…)` reached `InMemoryEnv`. Re-index C++ projects after upgrading.
|
||||
- In C++, a call on a name a structured binding declares now links to the method of the type C++ gives it. That covers a range-based `for` over pairs or a map, like facebook/rocksdb's `for (auto& [cfh, iter] : cfh_iter_pairs_) { iter->Valid(); }`, and a declaration like protocolbuffers/protobuf's `auto [dst_ext, is_new] = Insert(…);`. A call on what a `std::function` or another function wrapper returns, like `create_iterator()->Valid()` on a `std::function<Iterator*()>`, links the same way, and so does a call on a class member whose type is written on the line above its name. Before, these calls were guessed by the method's name, and calls on a library container declared that way, like a `std::priority_queue` member's `pop()`, reached a project class's method of that name. Re-index C++ projects after upgrading.
|
||||
- In C++, a call written without a receiver in a gtest `TEST_F` or `TEST_P` body now links to the test fixture's method, its own or one it inherits, as C++ finds it: facebook/rocksdb's tests call `DBTestBase`'s `Put(…)`, `Flush()` and `NewIterator(…)` this way. A variable such a call initializes, like `auto iter = NewIterator(…)`, takes the type the method returns, so `iter->SeekToFirst()` reaches the iterator class. Before, those calls were guessed by name and often reached a namesake in another class, like RocksDB's `ColumnFamilyTestBase::Put` or protocolbuffers/protobuf's `EncodeDecodeTest::ExpectNoErrors`, and `iter->SeekToFirst()` reached the unrelated `MemTableRep::Iterator`. A `->` call on a value of a type from outside the project, like protobuf's `m->value()` on an `absl::StatusOr<Any>`, no longer links to a class of the project that shares the type's name, like protobuf's own `hpb::StatusOr`. Re-index C++ projects after upgrading.
|
||||
- Framework support now switches on when an app's `package.json` sits three or more folders deep, as with an ASP.NET solution's Angular or React app in `src/Web/ClientApp/`, or a React app in a workspace folder like `web/ui/mantine-ui/`. Before, only the project root and the first two folder levels were read, so frameworks such as Angular, React Router, Vue Router, SvelteKit and TanStack Router could go undetected there: an Angular app's routes, its `routerLink` and `router.navigate(…)` navigation and its template's event bindings were missing, so a handler used only from a `(click)` binding had no callers, and a React app's `navigate('/login')` calls didn't reach their route. Re-index projects laid out this way after upgrading.
|
||||
- In a repository that mixes languages, a web framework's naming conventions now link only code written in that framework's own languages. Before, Express's also linked Go and Python code: in etcd a Go method's `*zap.Logger` result type linked to the method itself, and in Harbor a Python `self.jaeger.validate()` call linked to another class's `validate`. Links that cross languages on purpose, like React Native and Expo native modules, Swift and Objective-C, Drupal's `routing.yml`, SvelteKit's `$lib/…` imports in `.ts` files and a Razor page's `@model`, are unchanged.
|
||||
- In C and C++, a call written from the global scope, like `::leveldb::RepairDB(…)` or `::hpb::CreateMessage(…)`, now links to the function of exactly that name, and one through a namespace alias, like protobuf's `::_pbi::…` calls, to the function in the aliased namespace. Before, these calls were dropped unless the repository also held Swift and Objective-C files, and even then a name spelled out in full, like `::google::protobuf::internal::TSanWrite(…)`, linked to nothing, while `::operator delete(…)` linked to one class's own `operator delete`. A global call never links to a function or method of the same name inside a namespace or class, such as a wrapper `open()` that calls the C library's `::open(…)`, and `::std::…` and `::testing::…` calls stay unlinked unless that library's source is part of your project. Re-index C and C++ projects after upgrading.
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
/**
|
||||
* A bare call in a gtest `TEST_F(Fixture, Name)` or `TEST_P` body reaches
|
||||
* the fixture's method.
|
||||
*
|
||||
* The index holds such a body as a function named `TEST_F`, but gtest makes
|
||||
* it a method of a class it derives from `Fixture`, declared where the
|
||||
* `TEST_F` is. C++ looks a name the body calls up in that class, then in the
|
||||
* fixture and the classes it derives from, before the namespace. Since PR
|
||||
* #2533 the fixture's data members were found that way (`db_->Put(…)`); its
|
||||
* methods were not, so in facebook/rocksdb `Put(…)`, `Flush()` and `auto iter
|
||||
* = NewIterator(…)` — methods of `DBTestBase` — were guessed by name, and
|
||||
* `iter->SeekToFirst()` reached the nested `MemTableRep::Iterator`.
|
||||
*
|
||||
* A guess can land on the right method by a shared word, so these tests
|
||||
* check the confidence, not only the target.
|
||||
*/
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import { CodeGraph } from '../src';
|
||||
import type { Node } from '../src/types';
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function indexed(files: Record<string, string>): Promise<CodeGraph> {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-cpp-fixture-'));
|
||||
roots.push(root);
|
||||
for (const [rel, content] of Object.entries(files)) {
|
||||
fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, rel), content);
|
||||
}
|
||||
return CodeGraph.init(root, { index: true });
|
||||
}
|
||||
|
||||
/** The function or method `qualifiedName`, the one in `file` when given. */
|
||||
function callable(cg: CodeGraph, qualifiedName: string, file?: string): Node {
|
||||
const node = [...cg.getNodesByKind('method'), ...cg.getNodesByKind('function')].find(
|
||||
(n) => n.qualifiedName === qualifiedName && (file === undefined || n.filePath === file),
|
||||
);
|
||||
if (!node) throw new Error(`no function or method ${qualifiedName}`);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** `calls` callees of a function or method, as `qualifiedName @confidence`, one per call site. */
|
||||
function calls(cg: CodeGraph, caller: string, file?: string): string[] {
|
||||
return cg
|
||||
.getCallees(callable(cg, caller, file).id)
|
||||
.filter((r) => r.edge.kind === 'calls')
|
||||
.map((r) => `${r.node.qualifiedName} @${(r.edge.metadata as { confidence?: number } | undefined)?.confidence}`)
|
||||
.sort();
|
||||
}
|
||||
|
||||
/** `calls` callees as `qualifiedName by resolvedBy`. */
|
||||
function resolvers(cg: CodeGraph, caller: string): string[] {
|
||||
return cg
|
||||
.getCallees(callable(cg, caller).id)
|
||||
.filter((r) => r.edge.kind === 'calls')
|
||||
.map((r) => `${r.node.qualifiedName} by ${(r.edge.metadata as { resolvedBy?: string } | undefined)?.resolvedBy}`)
|
||||
.sort();
|
||||
}
|
||||
|
||||
const lines = (...text: string[]): string => [...text, ''].join('\n');
|
||||
|
||||
/** rocksdb's public iterator, the nested namesake, and the test fixture base, trimmed. */
|
||||
const ROCKSDB = {
|
||||
'include/rocksdb/iterator.h': lines(
|
||||
'namespace rocksdb {',
|
||||
'class IteratorBase {',
|
||||
' public:',
|
||||
' virtual void SeekToFirst() = 0;',
|
||||
' virtual bool Valid() const = 0;',
|
||||
'};',
|
||||
'class Iterator : public IteratorBase {};',
|
||||
'} // namespace rocksdb',
|
||||
),
|
||||
'db/db_test_util.h': lines(
|
||||
'#include "include/rocksdb/iterator.h"',
|
||||
'namespace rocksdb {',
|
||||
'class DBTestBase {',
|
||||
' public:',
|
||||
' Iterator* NewIterator();',
|
||||
' void Put(int key);',
|
||||
' void Flush();',
|
||||
'};',
|
||||
'} // namespace rocksdb',
|
||||
),
|
||||
// As in rocksdb, the fixture base's methods are defined out of line.
|
||||
'db/db_test_util.cc': lines(
|
||||
'#include "db/db_test_util.h"',
|
||||
'namespace rocksdb {',
|
||||
'Iterator* DBTestBase::NewIterator() { return nullptr; }',
|
||||
'void DBTestBase::Put(int key) {}',
|
||||
'void DBTestBase::Flush() {}',
|
||||
'} // namespace rocksdb',
|
||||
),
|
||||
};
|
||||
|
||||
/** Namesakes beside the tests, which a guess by name prefers. */
|
||||
const NAMESAKES = lines(
|
||||
'class MemTableRep {',
|
||||
' public:',
|
||||
' class Iterator {',
|
||||
' public:',
|
||||
' void SeekToFirst() {}',
|
||||
' bool Valid() const { return false; }',
|
||||
' };',
|
||||
' Iterator* NewIterator() { return nullptr; }',
|
||||
'};',
|
||||
'class WriteBatch {',
|
||||
' public:',
|
||||
' void Put(int key) {}',
|
||||
' void Flush() {}',
|
||||
'};',
|
||||
);
|
||||
|
||||
describe('C++ bare calls in gtest TEST_F / TEST_P bodies', () => {
|
||||
it("reaches the fixture's own and inherited methods", async () => {
|
||||
const cg = await indexed({
|
||||
...ROCKSDB,
|
||||
'db/db_basic_test.cc': lines(
|
||||
'#include "db/db_test_util.h"',
|
||||
'namespace rocksdb {',
|
||||
NAMESAKES,
|
||||
'class DBBasicTest : public DBTestBase {',
|
||||
' public:',
|
||||
' void Reopen() {}',
|
||||
'};',
|
||||
'TEST_F(DBBasicTest, PutFlush) {',
|
||||
' Put(1);',
|
||||
' Flush();',
|
||||
' Reopen();',
|
||||
'}',
|
||||
'} // namespace rocksdb',
|
||||
),
|
||||
});
|
||||
try {
|
||||
expect(calls(cg, 'rocksdb::TEST_F')).toEqual([
|
||||
'rocksdb::DBBasicTest::Reopen @0.9',
|
||||
'rocksdb::DBTestBase::Flush @0.9',
|
||||
'rocksdb::DBTestBase::Put @0.9',
|
||||
]);
|
||||
} finally {
|
||||
cg.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('types `auto iter = NewIterator()` from the fixture\'s method', async () => {
|
||||
const cg = await indexed({
|
||||
...ROCKSDB,
|
||||
'db/db_iterator_test.cc': lines(
|
||||
'#include "db/db_test_util.h"',
|
||||
'namespace rocksdb {',
|
||||
NAMESAKES,
|
||||
'class DBIteratorTest : public DBTestBase {};',
|
||||
'TEST_F(DBIteratorTest, IterSeekToFirst) {',
|
||||
' auto iter = NewIterator();',
|
||||
' iter->SeekToFirst();',
|
||||
' if (iter->Valid()) {}',
|
||||
'}',
|
||||
'} // namespace rocksdb',
|
||||
),
|
||||
});
|
||||
try {
|
||||
expect(calls(cg, 'rocksdb::TEST_F')).toEqual([
|
||||
'rocksdb::DBTestBase::NewIterator @0.9',
|
||||
'rocksdb::IteratorBase::SeekToFirst @0.9',
|
||||
'rocksdb::IteratorBase::Valid @0.9',
|
||||
]);
|
||||
} finally {
|
||||
cg.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('does the same in a TEST_P body, and on `this->`', async () => {
|
||||
const cg = await indexed({
|
||||
...ROCKSDB,
|
||||
'db/db_param_test.cc': lines(
|
||||
'#include "db/db_test_util.h"',
|
||||
'namespace rocksdb {',
|
||||
NAMESAKES,
|
||||
'class DBParamTest : public DBTestBase {};',
|
||||
'TEST_P(DBParamTest, Write) {',
|
||||
' this->Put(2);',
|
||||
' Flush();',
|
||||
' auto it = this->NewIterator();',
|
||||
' it->SeekToFirst();',
|
||||
'}',
|
||||
'} // namespace rocksdb',
|
||||
),
|
||||
});
|
||||
try {
|
||||
expect(calls(cg, 'rocksdb::TEST_P')).toEqual([
|
||||
'rocksdb::DBTestBase::Flush @0.9',
|
||||
'rocksdb::DBTestBase::NewIterator @0.9',
|
||||
'rocksdb::DBTestBase::Put @0.9',
|
||||
'rocksdb::IteratorBase::SeekToFirst @0.9',
|
||||
]);
|
||||
} finally {
|
||||
cg.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('uses the fixture declared in the test\'s own file, of two sharing its name', async () => {
|
||||
const cg = await indexed({
|
||||
...ROCKSDB,
|
||||
'db/other_test_util.h': lines(
|
||||
'namespace rocksdb {',
|
||||
NAMESAKES,
|
||||
'class OtherTestBase {',
|
||||
' public:',
|
||||
' MemTableRep::Iterator* NewIterator() { return nullptr; }',
|
||||
'};',
|
||||
'} // namespace rocksdb',
|
||||
),
|
||||
'db/a_test.cc': lines(
|
||||
'#include "db/other_test_util.h"',
|
||||
'namespace rocksdb {',
|
||||
'class SharedTest : public OtherTestBase {};',
|
||||
'} // namespace rocksdb',
|
||||
),
|
||||
'db/b_test.cc': lines(
|
||||
'#include "db/db_test_util.h"',
|
||||
'namespace rocksdb {',
|
||||
'class SharedTest : public DBTestBase {};',
|
||||
'TEST_F(SharedTest, Seek) {',
|
||||
' auto iter = NewIterator();',
|
||||
' iter->SeekToFirst();',
|
||||
'}',
|
||||
'} // namespace rocksdb',
|
||||
),
|
||||
});
|
||||
try {
|
||||
expect(calls(cg, 'rocksdb::TEST_F', 'db/b_test.cc')).toEqual([
|
||||
'rocksdb::DBTestBase::NewIterator @0.9',
|
||||
'rocksdb::IteratorBase::SeekToFirst @0.9',
|
||||
]);
|
||||
} finally {
|
||||
cg.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("types a method's bare call on what the inherited method returns, past a nested class's parameter of its name", async () => {
|
||||
// leveldb's SpecialEnv: a class declared in the method takes a `target`
|
||||
// parameter, which is no local the bare `target()` calls.
|
||||
const cg = await indexed({
|
||||
'db/db_test.cc': lines(
|
||||
'namespace leveldb {',
|
||||
'class Env {',
|
||||
' public:',
|
||||
' virtual int NewRandomAccessFile() { return 0; }',
|
||||
'};',
|
||||
'class EnvWrapper : public Env {',
|
||||
' public:',
|
||||
' Env* target() const { return target_; }',
|
||||
' private:',
|
||||
' Env* target_;',
|
||||
'};',
|
||||
'class SpecialEnv : public EnvWrapper {',
|
||||
' public:',
|
||||
' int NewRandomAccessFile() override {',
|
||||
' class CountingFile {',
|
||||
' public:',
|
||||
' explicit CountingFile(Env* target) : target_(target) {}',
|
||||
' private:',
|
||||
' Env* target_;',
|
||||
' };',
|
||||
' return target()->NewRandomAccessFile();',
|
||||
' }',
|
||||
'};',
|
||||
'} // namespace leveldb',
|
||||
),
|
||||
});
|
||||
try {
|
||||
expect(calls(cg, 'leveldb::SpecialEnv::NewRandomAccessFile')).toContain('leveldb::Env::NewRandomAccessFile @0.85');
|
||||
} finally {
|
||||
cg.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("types a template's bare call into a base it names with a using-declaration", async () => {
|
||||
// protobuf's RepeatedFieldPrimitiveAccessor: `MutableRepeatedField` is
|
||||
// its dependent base's, brought in by `using RepeatedFieldWrapper<T>::MutableRepeatedField;`.
|
||||
const cg = await indexed({
|
||||
'src/google/protobuf/reflection_internal.h': lines(
|
||||
'namespace google {',
|
||||
'namespace protobuf {',
|
||||
'template <typename T>',
|
||||
'class RepeatedField {',
|
||||
' public:',
|
||||
' void Swap(RepeatedField* other) {}',
|
||||
'};',
|
||||
'template <typename T>',
|
||||
'class RepeatedFieldWrapper {',
|
||||
' public:',
|
||||
' RepeatedField<T>* MutableRepeatedField(void* data) const { return nullptr; }',
|
||||
'};',
|
||||
'template <typename T>',
|
||||
'class RepeatedFieldPrimitiveAccessor final : public RepeatedFieldWrapper<T> {',
|
||||
' using RepeatedFieldWrapper<T>::MutableRepeatedField;',
|
||||
' public:',
|
||||
' void Swap(void* data, void* other_data) const {',
|
||||
' MutableRepeatedField(data)->Swap(MutableRepeatedField(other_data));',
|
||||
' }',
|
||||
'};',
|
||||
'} // namespace protobuf',
|
||||
'} // namespace google',
|
||||
),
|
||||
});
|
||||
try {
|
||||
expect(calls(cg, 'google::protobuf::RepeatedFieldPrimitiveAccessor::Swap')).toContain('google::protobuf::RepeatedField::Swap @0.85');
|
||||
} finally {
|
||||
cg.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("gives `->` on a value of a type from outside the project no project class sharing the type's name", async () => {
|
||||
// protobuf's JsonTest: `ToProto<Any>(…)` returns an `absl::StatusOr<Any>`,
|
||||
// whose `->` reaches the `Any` it holds, not protobuf's own `hpb::StatusOr`.
|
||||
const cg = await indexed({
|
||||
'hpb/status.h': lines(
|
||||
'namespace hpb {',
|
||||
'template <typename T>',
|
||||
'class StatusOr {',
|
||||
' public:',
|
||||
' T& value() { return value_; }',
|
||||
' private:',
|
||||
' T value_;',
|
||||
'};',
|
||||
'} // namespace hpb',
|
||||
),
|
||||
'src/google/protobuf/json/json_test.cc': lines(
|
||||
'#include "hpb/status.h"',
|
||||
'namespace google {',
|
||||
'namespace protobuf {',
|
||||
'namespace json {',
|
||||
'class JsonTest {',
|
||||
' protected:',
|
||||
' template <typename Proto>',
|
||||
' absl::StatusOr<Proto> ToProto(absl::string_view json) { return Proto(); }',
|
||||
'};',
|
||||
'TEST_P(JsonTest, Any) {',
|
||||
' auto m = ToProto<Any>("{}");',
|
||||
' m->value();',
|
||||
'}',
|
||||
'void Parsed(absl::StatusOr<Any> parsed) {',
|
||||
' parsed->value();',
|
||||
'}',
|
||||
'} // namespace json',
|
||||
'} // namespace protobuf',
|
||||
'} // namespace google',
|
||||
),
|
||||
});
|
||||
try {
|
||||
// (The name strategies still decide, as for any receiver of an unknown type;
|
||||
// in this small project the one `value` is that one.)
|
||||
expect(calls(cg, 'google::protobuf::json::TEST_P')).not.toContain('hpb::StatusOr::value @0.9');
|
||||
expect(calls(cg, 'google::protobuf::json::Parsed')).not.toContain('hpb::StatusOr::value @0.9');
|
||||
} finally {
|
||||
cg.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves a TEST body, which has no fixture, to the name strategies', async () => {
|
||||
const cg = await indexed({
|
||||
...ROCKSDB,
|
||||
'db/db_plain_test.cc': lines(
|
||||
'#include "db/db_test_util.h"',
|
||||
'namespace rocksdb {',
|
||||
'class DBPlainTest : public DBTestBase {};',
|
||||
'TEST(DBPlainTest, Plain) {',
|
||||
' Put(1);',
|
||||
'}',
|
||||
'} // namespace rocksdb',
|
||||
),
|
||||
});
|
||||
try {
|
||||
expect(resolvers(cg, 'rocksdb::TEST')).not.toContain('rocksdb::DBTestBase::Put by instance-method');
|
||||
} finally {
|
||||
cg.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('calls a local of the name the body declares, not the fixture\'s method', async () => {
|
||||
const cg = await indexed({
|
||||
...ROCKSDB,
|
||||
'db/db_local_test.cc': lines(
|
||||
'#include "db/db_test_util.h"',
|
||||
'namespace rocksdb {',
|
||||
'class DBLocalTest : public DBTestBase {};',
|
||||
'TEST_F(DBLocalTest, Local) {',
|
||||
' auto Put = [](int key) {};',
|
||||
' Put(1);',
|
||||
'}',
|
||||
'} // namespace rocksdb',
|
||||
),
|
||||
});
|
||||
try {
|
||||
expect(resolvers(cg, 'rocksdb::TEST_F')).not.toContain('rocksdb::DBTestBase::Put by instance-method');
|
||||
} finally {
|
||||
cg.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -9496,8 +9496,11 @@ function cppExpressionType(expr: string, at: UnresolvedRef, context: ResolutionC
|
||||
if (!caller) return null;
|
||||
// What the calling function writes is looked up from inside it.
|
||||
const callers = { scope: caller.qualifiedName, file: at.filePath, line: at.line, parameters: cppTemplateParameters(caller, context) };
|
||||
const owner = cppMemberOwner(caller, context);
|
||||
if (text === 'this') return owner ? { ...callers, text: `${owner}*` } : null;
|
||||
if (text === 'this') {
|
||||
// (A gtest `TEST_F` body's object is of a class derived from its fixture.)
|
||||
const owner = cppMemberOwner(caller, context) ?? cppTestFixture(caller, at, context);
|
||||
return owner ? { ...callers, text: `${owner}*` } : null;
|
||||
}
|
||||
const name = /^(?:this\s*->\s*)?([A-Za-z_]\w*)$/.exec(text);
|
||||
if (name) {
|
||||
const decl: CppReceiverDeclaration = {};
|
||||
@@ -9545,10 +9548,14 @@ function cppExpressionType(expr: string, at: UnresolvedRef, context: ResolutionC
|
||||
}
|
||||
if (!/^(?:[A-Za-z_]\w*\s*::\s*)*[A-Za-z_]\w*(?:\s*<[\s\S]*>)?$/.test(callee)) return null;
|
||||
const spelled = stripCppTemplateArguments(callee).replace(/\s+/g, '');
|
||||
// `NewIterator(…)` in a method: its class's own or inherited method first.
|
||||
const ownClass = owner && !spelled.includes('::') ? cppClassDecls(owner, context)[0] : undefined;
|
||||
const own = ownClass ? cppMethodsOf(ownClass, spelled, at, context) : [];
|
||||
if (own.length > 0) return cppReturnTypeOf(own, context);
|
||||
// `NewIterator(…)` in a method, or in a gtest body: what the method of its
|
||||
// class, or of a class it derives from, returns (cppImplicitThisMethod),
|
||||
// before anything outside. It is looked up as on `this`: in a template, a
|
||||
// bare call into a base that depends on its parameters compiles only
|
||||
// through a using-declaration, like protobuf's `using
|
||||
// RepeatedFieldWrapper<T>::MutableRepeatedField;`.
|
||||
const own = spelled.includes('::') ? undefined : cppImplicitThisMethod(spelled, 'this', caller, at, context);
|
||||
if (own) return cppReturnTypeOf([own], context);
|
||||
// `f(…)`, `ns::f(…)`, `Class::f(…)`: looked up from the caller outwards.
|
||||
for (const scope of cppScopesWithin(cppParentScope(caller.qualifiedName))) {
|
||||
const fns = context.getNodesByQualifiedName(scope ? `${scope}::${spelled}` : spelled).filter(isCppFunctionNode);
|
||||
@@ -10017,6 +10024,23 @@ function matchCppDeclaredTypeCall(
|
||||
return cppLacksMethod(found.node, context) ? null : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is a C++ `->` call on `receiver` made on a value — not a pointer — of a
|
||||
* type from outside the project that nothing the file sees declares
|
||||
* (isCppOutsideQualifiedType)? Its `operator->` hands the call to a type the
|
||||
* declared one only wraps (`absl::StatusOr<Any>`'s `Any`), so the declared
|
||||
* type's last name names no class the method is in. (A standard smart
|
||||
* pointer or optional is matchCppHeldTypeCall's.)
|
||||
*/
|
||||
function isCppArrowThroughOutsideType(receiver: string, decl: CppReceiverDeclaration, ref: UnresolvedRef, context: ResolutionContext): boolean {
|
||||
if (!decl.callers || decl.shadowed || !decl.raw || decl.pointer || decl.aliased) return false;
|
||||
if (cppMemberOperator(receiver, ref, context) !== '->' || isCppLibraryType(decl.raw, context)) return false;
|
||||
const caller = context.getNodeById?.(ref.fromNodeId);
|
||||
if (!caller) return false;
|
||||
const site = decl.declared ?? cppCallSite(caller, ref, context);
|
||||
return cppClassWritten(decl.raw, site, ref, context) === undefined && isCppOutsideQualifiedType(decl.raw, site, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the C++ type `raw`, which nothing the file sees declares, written under
|
||||
* a namespace the project declares no type in — `absl::Status`,
|
||||
@@ -10148,16 +10172,33 @@ function matchCppImplicitThisCall(ref: UnresolvedRef, context: ResolutionContext
|
||||
const receiver = cppImplicitReceiver(ref, context);
|
||||
if (receiver === null) return undefined;
|
||||
const caller = context.getNodeById?.(ref.fromNodeId);
|
||||
const owner = caller ? cppMemberOwner(caller, context) : null;
|
||||
if (!caller || owner === null) return undefined;
|
||||
if (!caller) return undefined;
|
||||
const found = cppImplicitThisMethod(name, receiver, caller, ref, context);
|
||||
// (A recursive call names the function itself, which no local shadows.)
|
||||
if (!found || (receiver === 'bare' && name !== caller.name && isCppLocalName(name, caller, ref, context))) return undefined;
|
||||
return { original: ref, targetNodeId: found.id, confidence: 0.9, resolvedBy: 'instance-method' };
|
||||
}
|
||||
|
||||
/**
|
||||
* The method a C++ call of `name` written with no receiver, or on `this`,
|
||||
* reaches from `caller` by C++ lookup (matchCppImplicitThisCall): of the
|
||||
* caller's class, a class it derives from, or one it is nested in. A gtest
|
||||
* `TEST_F(Fixture, …)` or `TEST_P` body is a method of a class gtest derives
|
||||
* from `Fixture`, so the fixture's methods are its own: rocksdb's tests call
|
||||
* `DBTestBase`'s `Put(…)` and `NewIterator(…)` bare. Undefined when the
|
||||
* caller is no member function, or no class on the way has a method of that
|
||||
* name in the index. (Whether a local of the caller's shadows it is the
|
||||
* caller's to ask.)
|
||||
*/
|
||||
function cppImplicitThisMethod(name: string, receiver: 'bare' | 'this', caller: Node, ref: UnresolvedRef, context: ResolutionContext): Node | undefined {
|
||||
const owner = cppMemberOwner(caller, context) ?? cppTestFixture(caller, ref, context);
|
||||
if (owner === null) return undefined;
|
||||
let found: Node | null | undefined = null;
|
||||
for (const scope of cppEnclosingClasses(owner, caller, context)) {
|
||||
found = cppScopeMethod(scope, name, receiver, ref, context);
|
||||
if (found !== null || receiver === 'this') break;
|
||||
}
|
||||
// (A recursive call names the function itself, which no local shadows.)
|
||||
if (!found || (receiver === 'bare' && name !== caller.name && isCppLocalName(name, caller, ref, context))) return undefined;
|
||||
return { original: ref, targetNodeId: found.id, confidence: 0.9, resolvedBy: 'instance-method' };
|
||||
return found ?? undefined;
|
||||
}
|
||||
|
||||
/** `this->` / `(*this).` before a member's name, with a `template` keyword after it. */
|
||||
@@ -12555,6 +12596,11 @@ export function matchMethodCall(
|
||||
const declared = nmTimedT('mc-cppdecl', ref, () =>
|
||||
matchCppDeclaredTypeCall(objectOrClass!, methodName!, cppDecl, ref, context));
|
||||
if (declared !== undefined) return declared;
|
||||
// `->` on a value of a type from outside the project reaches what its
|
||||
// `operator->` returns, which the type's last name doesn't name:
|
||||
// protobuf's `absl::StatusOr<Any> m; m->value()` is no member of the
|
||||
// project's own `hpb::StatusOr`. The name strategies decide.
|
||||
if (inferredType && isCppArrowThroughOutsideType(objectOrClass!, cppDecl, ref, context)) inferredType = null;
|
||||
}
|
||||
// A pytest test's parameter is what its fixture returns: flaskbb's
|
||||
// `cli_runner.invoke(…)` is click's `CliRunner`, not the project's one `invoke`.
|
||||
|
||||
Reference in New Issue
Block a user