graphlore-engine 0.5.79__tar.gz → 0.5.80__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/Cargo.lock +1 -1
  2. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/Cargo.toml +1 -1
  3. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/PKG-INFO +3 -3
  4. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/README.md +2 -2
  5. graphlore_engine-0.5.80/python/graphlore_engine/__init__.py +27 -0
  6. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/python/graphlore_engine/__main__.py +5 -2
  7. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/python/graphlore_engine/_native.pyi +1 -1
  8. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/cache.rs +68 -24
  9. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/community/leiden.rs +30 -12
  10. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/community/mod.rs +510 -55
  11. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/coupling.rs +12 -8
  12. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/docs/markdown.rs +9 -7
  13. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/facts.rs +35 -4
  14. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/generic.rs +114 -66
  15. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/graph/assemble.rs +6 -1
  16. graphlore_engine-0.5.80/src/graph/links.rs +241 -0
  17. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/graph/mod.rs +1 -0
  18. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/graph/write.rs +2 -2
  19. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/http/csharp.rs +43 -35
  20. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/http/ecma.rs +76 -87
  21. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/http/go.rs +35 -35
  22. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/http/jvm.rs +46 -41
  23. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/http/mod.rs +14 -11
  24. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/http/php.rs +38 -48
  25. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/http/python.rs +37 -36
  26. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/http/ruby.rs +22 -20
  27. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/http/rust.rs +24 -17
  28. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/c_family.rs +23 -20
  29. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/csharp.rs +41 -26
  30. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/ecma.rs +114 -111
  31. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/go.rs +23 -23
  32. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/java.rs +16 -14
  33. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/kotlin.rs +34 -28
  34. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/mod.rs +12 -2
  35. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/php.rs +19 -17
  36. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/python.rs +145 -42
  37. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/ruby.rs +40 -36
  38. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/rust.rs +37 -36
  39. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/scala.rs +19 -16
  40. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lang/swift.rs +28 -28
  41. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/lib.rs +309 -71
  42. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/parse.rs +216 -22
  43. graphlore_engine-0.5.80/src/py.rs +163 -0
  44. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/refs.rs +2684 -840
  45. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/report.rs +19 -0
  46. graphlore_engine-0.5.80/src/resolve/decl.rs +271 -0
  47. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/resolve/http.rs +62 -5
  48. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/resolve/mod.rs +3089 -963
  49. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/resolve/modules.rs +89 -40
  50. graphlore_engine-0.5.80/src/resolve/reuse.rs +162 -0
  51. graphlore_engine-0.5.80/src/resolve/trace.rs +795 -0
  52. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/resources.rs +20 -20
  53. graphlore_engine-0.5.80/src/search.rs +281 -0
  54. graphlore_engine-0.5.80/src/search_digits.rs +98 -0
  55. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/state.rs +171 -56
  56. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/walk.rs +192 -18
  57. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/tests/build_fixture.rs +29 -5
  58. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/tests/edges_golden.rs +839 -4
  59. graphlore_engine-0.5.80/tests/incremental.rs +380 -0
  60. graphlore_engine-0.5.80/tests/search_kernel.rs +81 -0
  61. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/tests/spans_golden.rs +65 -1
  62. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/tests/tracked.rs +54 -0
  63. graphlore_engine-0.5.80/tests/workspace.rs +322 -0
  64. graphlore_engine-0.5.79/python/graphlore_engine/__init__.py +0 -21
  65. graphlore_engine-0.5.79/src/py.rs +0 -85
  66. graphlore_engine-0.5.79/tests/incremental.rs +0 -133
  67. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/LICENSE +0 -0
  68. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/examples/dump.rs +0 -0
  69. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/examples/facts.rs +0 -0
  70. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/examples/sexp.rs +0 -0
  71. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/pyproject.toml +0 -0
  72. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/python/graphlore_engine/py.typed +0 -0
  73. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/rustfmt.toml +0 -0
  74. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/docs/link.rs +0 -0
  75. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/docs/mod.rs +0 -0
  76. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/docs/rst.rs +0 -0
  77. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/graph/ids.rs +0 -0
  78. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/src/versions.rs +0 -0
  79. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/tests/dispatch_golden.rs +0 -0
  80. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/tests/docs_golden.rs +0 -0
  81. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/tests/grammars_load.rs +0 -0
  82. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/tests/http_golden.rs +0 -0
  83. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/tests/resources_golden.rs +0 -0
  84. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/tests/state_golden.rs +0 -0
  85. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/tests/unresolved.rs +0 -0
  86. {graphlore_engine-0.5.79 → graphlore_engine-0.5.80}/tests/versions.rs +0 -0
@@ -104,7 +104,7 @@ dependencies = [
104
104
 
105
105
  [[package]]
106
106
  name = "graphlore-engine"
107
- version = "0.5.79"
107
+ version = "0.5.80"
108
108
  dependencies = [
109
109
  "bincode",
110
110
  "ignore",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "graphlore-engine"
3
- version = "0.5.79"
3
+ version = "0.5.80"
4
4
  edition = "2021"
5
5
  rust-version = "1.90"
6
6
  description = "graphlore's native code-graph extractor: tree-sitter definitions, spans and containment in 14 languages"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: graphlore-engine
3
- Version: 0.5.79
3
+ Version: 0.5.80
4
4
  Classifier: Development Status :: 4 - Beta
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: License :: OSI Approved :: MIT License
@@ -45,10 +45,10 @@ pip install graphlore-engine # prebuilt abi3 wheels: Linux (glibc, musl), m
45
45
  ```
46
46
 
47
47
  ```bash
48
- python -m graphlore_engine build /path/to/repo # writes graphify-out/graph.json
48
+ python -m graphlore_engine build /path/to/repo # writes graphlore-out/graph.json
49
49
  python -m graphlore_engine build /path/to/repo --incremental # parse only what changed
50
50
  python -m graphlore_engine build /path/to/repo --unresolved left.json # the calls left without an edge, with the reason
51
- python -m graphlore_engine cluster graphify-out/graph.json # detect its communities again
51
+ python -m graphlore_engine cluster graphlore-out/graph.json # detect its communities again
52
52
  python -m graphlore_engine spans src/app.ts # one file's definitions
53
53
  python -m graphlore_engine languages
54
54
  ```
@@ -25,10 +25,10 @@ pip install graphlore-engine # prebuilt abi3 wheels: Linux (glibc, musl), m
25
25
  ```
26
26
 
27
27
  ```bash
28
- python -m graphlore_engine build /path/to/repo # writes graphify-out/graph.json
28
+ python -m graphlore_engine build /path/to/repo # writes graphlore-out/graph.json
29
29
  python -m graphlore_engine build /path/to/repo --incremental # parse only what changed
30
30
  python -m graphlore_engine build /path/to/repo --unresolved left.json # the calls left without an edge, with the reason
31
- python -m graphlore_engine cluster graphify-out/graph.json # detect its communities again
31
+ python -m graphlore_engine cluster graphlore-out/graph.json # detect its communities again
32
32
  python -m graphlore_engine spans src/app.ts # one file's definitions
33
33
  python -m graphlore_engine languages
34
34
  ```
@@ -0,0 +1,27 @@
1
+ """graphlore's native code-graph extractor.
2
+
3
+ ``build`` walks a project and writes a graphify-compatible ``graph.json``;
4
+ ``cluster`` detects its communities again;
5
+ ``file_spans`` / ``definition_spans`` / ``file_facts`` read one file;
6
+ ``SearchKernel`` is the kernel of graphlore's built-in search (``KERNEL_ABI``).
7
+ The tree-sitter grammars are compiled in: nothing is downloaded, nothing
8
+ reaches the network.
9
+ """
10
+
11
+ from ._native import (
12
+ KERNEL_ABI,
13
+ SCHEMA_VERSION,
14
+ SearchKernel,
15
+ __version__,
16
+ build,
17
+ cluster,
18
+ definition_spans,
19
+ file_facts,
20
+ file_spans,
21
+ languages,
22
+ )
23
+
24
+ __all__ = [
25
+ "KERNEL_ABI", "SCHEMA_VERSION", "SearchKernel", "__version__", "build", "cluster",
26
+ "definition_spans", "file_facts", "file_spans", "languages",
27
+ ]
@@ -1,7 +1,7 @@
1
1
  """``python -m graphlore_engine``: the engine's command line.
2
2
 
3
3
  build ROOT [--out PATH] [--commit SHA] [--no-docs] [--out-dir-name NAME] [--incremental]
4
- [--unresolved PATH]
4
+ [--unresolved PATH] [--vendor]
5
5
  cluster GRAPH
6
6
  spans FILE [--as PATH]
7
7
  languages
@@ -30,7 +30,7 @@ def main(argv: list[str] | None = None) -> int:
30
30
  b.add_argument("--out", help="graph.json to write (default: ROOT/OUT_DIR_NAME/graph.json)")
31
31
  b.add_argument("--commit", help="value for built_at_commit")
32
32
  b.add_argument("--no-docs", action="store_true", help="skip Markdown / RST headings")
33
- b.add_argument("--out-dir-name", default="graphify-out")
33
+ b.add_argument("--out-dir-name", default="graphlore-out")
34
34
  b.add_argument("--max-file-bytes", type=int, default=2 * 1024 * 1024)
35
35
  b.add_argument("--threads", type=int)
36
36
  b.add_argument("--incremental", action="store_true",
@@ -38,6 +38,8 @@ def main(argv: list[str] | None = None) -> int:
38
38
  b.add_argument("--unresolved", metavar="PATH",
39
39
  help="also write the calls left without an edge whose name is one "
40
40
  "definition of the project, each with the reason (JSON)")
41
+ b.add_argument("--vendor", action="store_true",
42
+ help="also read a Go module's vendor/ directory (left out by default)")
41
43
  c = sub.add_parser("cluster", help="detect a graph.json's communities again")
42
44
  c.add_argument("graph")
43
45
  s = sub.add_parser("spans", help="print the definition spans of one file")
@@ -68,6 +70,7 @@ def main(argv: list[str] | None = None) -> int:
68
70
  args.root, out=out, commit=args.commit, documents=not args.no_docs,
69
71
  out_dir_name=args.out_dir_name, max_file_bytes=args.max_file_bytes,
70
72
  threads=args.threads, incremental=args.incremental, unresolved=args.unresolved,
73
+ read_vendor=args.vendor,
71
74
  )
72
75
  except RuntimeError as e:
73
76
  print(f"ERROR: {e}", file=sys.stderr)
@@ -6,7 +6,7 @@ def build(
6
6
  out: str | None = None,
7
7
  commit: str | None = None,
8
8
  documents: bool = True,
9
- out_dir_name: str = "graphify-out",
9
+ out_dir_name: str = "graphlore-out",
10
10
  max_file_bytes: int = ...,
11
11
  parse_timeout_ms: int = 10000,
12
12
  threads: int | None = None,
@@ -1,7 +1,7 @@
1
1
  //! The facts cache behind `update=True`: what each file yielded last time, keyed
2
2
  //! by its path and checked against its size, modification time and content
3
- //! hash, so an update parses only the files that changed. Resolution and
4
- //! communities always run over the whole project, so an update writes the same
3
+ //! hash, so an update parses only the files that changed. Resolution reuses
4
+ //! what it can on its own terms (`resolve/reuse.rs`); an update writes the
5
5
  //! graph a full build would.
6
6
  //!
7
7
  //! One file, `<out dir>/cache/graphlore-native.bin`, written atomically after
@@ -21,6 +21,10 @@ use serde::{Deserialize, Deserializer, Serialize};
21
21
  use crate::facts::FileFacts;
22
22
 
23
23
  pub const CACHE_DIR: &str = "cache";
24
+ /// The layout of the cached facts (`Key::format`): 2 keeps a definition's
25
+ /// byte range, which an update resolved without before; 3 keeps each file's
26
+ /// shadowed names and the hash of its facts.
27
+ pub const FORMAT: u32 = 4;
24
28
  pub const CACHE_FILE: &str = "graphlore-native.bin";
25
29
  /// A file modified this close to the cache being written may have changed
26
30
  /// again within the same timestamp: its content hash decides.
@@ -34,15 +38,23 @@ pub struct Stamp {
34
38
  pub hash: u64,
35
39
  }
36
40
 
41
+ /// What the cache keeps of a file: its stamp, its facts, the names it was
42
+ /// read with as the project's own types (`parse::shadowed`, sorted) and the
43
+ /// hash of its facts (`facts_hash`).
37
44
  #[derive(Serialize, Deserialize)]
38
- struct Entry {
39
- stamp: Stamp,
40
- facts: FileFacts,
45
+ pub struct Entry {
46
+ pub stamp: Stamp,
47
+ pub facts: FileFacts,
48
+ pub shadowed: Vec<String>,
49
+ pub facts_hash: u64,
41
50
  }
42
51
 
43
52
  /// Everything a cached fact depends on besides the file itself.
44
53
  #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
45
54
  pub struct Key {
55
+ /// The layout of what is cached, raised when it changes within an engine
56
+ /// version (`FORMAT`): a cache of another layout is not read.
57
+ pub format: u32,
46
58
  pub engine_version: String,
47
59
  pub schema_version: u32,
48
60
  pub documents: bool,
@@ -56,10 +68,11 @@ struct Stored {
56
68
  files: HashMap<String, Entry>,
57
69
  }
58
70
 
59
- /// A cache read back for one build.
71
+ /// A cache read back for one build: each entry is taken out by the read of
72
+ /// its file (no copy of the facts), once.
60
73
  pub struct Cache {
61
74
  written_ns: u64,
62
- files: HashMap<String, Entry>,
75
+ files: HashMap<String, Mutex<Option<Entry>>>,
63
76
  }
64
77
 
65
78
  fn codec() -> impl Options {
@@ -91,6 +104,28 @@ pub fn hash(bytes: &[u8]) -> u64 {
91
104
  h
92
105
  }
93
106
 
107
+ /// A hash of a file's facts as the cache writes them: what other files can
108
+ /// read of it, so that an edit that leaves the facts as they were (a comment,
109
+ /// a blank line at the end) changes no other file's resolution.
110
+ pub fn facts_hash(facts: &FileFacts) -> u64 {
111
+ struct Hasher(u64);
112
+ impl Write for Hasher {
113
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
114
+ for &b in buf {
115
+ self.0 ^= u64::from(b);
116
+ self.0 = self.0.wrapping_mul(0x0000_0100_0000_01b3);
117
+ }
118
+ Ok(buf.len())
119
+ }
120
+ fn flush(&mut self) -> std::io::Result<()> {
121
+ Ok(())
122
+ }
123
+ }
124
+ let mut h = Hasher(0xcbf2_9ce4_8422_2325);
125
+ let _ = codec().serialize_into(&mut h, facts);
126
+ h.0
127
+ }
128
+
94
129
  impl Cache {
95
130
  /// The cache at `path`, if it was written for `key`.
96
131
  pub fn load(path: &Path, key: &Key) -> Option<Cache> {
@@ -98,7 +133,8 @@ impl Cache {
98
133
  let len = file.metadata().ok()?.len();
99
134
  // bounded by the file's size: a damaged length cannot ask for more memory
100
135
  let stored: Stored = codec().with_limit(len).deserialize_from(BufReader::new(file)).ok()?;
101
- (stored.key == *key).then_some(Cache { written_ns: stored.written_ns, files: stored.files })
136
+ let files = stored.files.into_iter().map(|(k, e)| (k, Mutex::new(Some(e)))).collect();
137
+ (stored.key == *key).then_some(Cache { written_ns: stored.written_ns, files })
102
138
  }
103
139
 
104
140
  pub fn len(&self) -> usize {
@@ -111,17 +147,20 @@ impl Cache {
111
147
 
112
148
  /// The cached facts of `rel` when size and modification time say the file
113
149
  /// is unchanged (and it was not modified around the time of the cache).
114
- pub fn unchanged(&self, rel: &str, size: u64, mtime: u64) -> Option<(FileFacts, Stamp)> {
115
- let e = self.files.get(rel)?;
150
+ pub fn unchanged(&self, rel: &str, size: u64, mtime: u64) -> Option<Entry> {
151
+ let mut slot = self.files.get(rel)?.lock().unwrap_or_else(|e| e.into_inner());
152
+ let e = slot.as_ref()?;
116
153
  let settled = mtime.saturating_add(MTIME_SLACK_NS) < self.written_ns;
117
154
  (e.stamp.size == size && e.stamp.mtime_ns == mtime && mtime != 0 && settled)
118
- .then(|| (e.facts.clone(), e.stamp))
155
+ .then(|| slot.take())
156
+ .flatten()
119
157
  }
120
158
 
121
- /// The cached facts of `rel` when its content is the same.
122
- pub fn same_content(&self, rel: &str, size: u64, hash: u64) -> Option<FileFacts> {
123
- let e = self.files.get(rel)?;
124
- (e.stamp.size == size && e.stamp.hash == hash).then(|| e.facts.clone())
159
+ /// The cached entry of `rel` when its content is the same.
160
+ pub fn same_content(&self, rel: &str, size: u64, hash: u64) -> Option<Entry> {
161
+ let mut slot = self.files.get(rel)?.lock().unwrap_or_else(|e| e.into_inner());
162
+ let e = slot.as_ref()?;
163
+ (e.stamp.size == size && e.stamp.hash == hash).then(|| slot.take()).flatten()
125
164
  }
126
165
 
127
166
  /// Paths cached but not found by this build: deleted, renamed or now ignored.
@@ -132,11 +171,11 @@ impl Cache {
132
171
 
133
172
  /// Write the cache for the facts a build used; files whose parse timed out are
134
173
  /// left out, to be tried again.
135
- pub fn store(path: &Path, key: Key, facts: Vec<(FileFacts, Stamp)>) -> Result<(), String> {
136
- let files = facts
174
+ pub fn store(path: &Path, key: Key, entries: Vec<Entry>) -> Result<(), String> {
175
+ let files: HashMap<String, Entry> = entries
137
176
  .into_iter()
138
- .filter(|(f, _)| !f.parse.timed_out)
139
- .map(|(facts, stamp)| (facts.path.clone(), Entry { stamp, facts }))
177
+ .filter(|e| !e.facts.parse.timed_out)
178
+ .map(|e| (e.facts.path.clone(), e))
140
179
  .collect();
141
180
  let stored = Stored { key, written_ns: now_ns(), files };
142
181
  let dir = path.parent().ok_or("no cache directory")?;
@@ -158,13 +197,18 @@ pub fn store(path: &Path, key: Key, facts: Vec<(FileFacts, Stamp)>) -> Result<()
158
197
  /// Rebuild a `&'static str` field (a reference's `context`) from the cache:
159
198
  /// each distinct value is allocated once per process.
160
199
  pub fn static_str<'de, D: Deserializer<'de>>(d: D) -> Result<&'static str, D::Error> {
161
- static SEEN: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
162
200
  let s = String::deserialize(d)?;
201
+ Ok(intern(&s))
202
+ }
203
+
204
+ /// A `&'static str` of `s`: each distinct value is allocated once per process.
205
+ pub fn intern(s: &str) -> &'static str {
206
+ static SEEN: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
163
207
  let mut seen = SEEN.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
164
- if let Some(&known) = seen.get(s.as_str()) {
165
- return Ok(known);
208
+ if let Some(&known) = seen.get(s) {
209
+ return known;
166
210
  }
167
- let leaked: &'static str = Box::leak(s.into_boxed_str());
211
+ let leaked: &'static str = Box::leak(s.to_string().into_boxed_str());
168
212
  seen.insert(leaked);
169
- Ok(leaked)
213
+ leaked
170
214
  }
@@ -66,16 +66,26 @@ impl Graph {
66
66
 
67
67
  /// The graph induced by `nodes` (indices into `self`), re-indexed in order.
68
68
  pub fn subgraph(&self, nodes: &[usize]) -> Graph {
69
+ // (a small group of a large graph: a map, not an index of every node)
70
+ if nodes.len() * 16 < self.len() {
71
+ let index: std::collections::HashMap<usize, usize> =
72
+ nodes.iter().enumerate().map(|(k, &v)| (v, k)).collect();
73
+ return self.induced(nodes, |u| index.get(&u).copied());
74
+ }
69
75
  let mut index = vec![usize::MAX; self.len()];
70
76
  for (k, &v) in nodes.iter().enumerate() {
71
77
  index[v] = k;
72
78
  }
79
+ self.induced(nodes, |u| (index[u] != usize::MAX).then_some(index[u]))
80
+ }
81
+
82
+ fn induced(&self, nodes: &[usize], index: impl Fn(usize) -> Option<usize>) -> Graph {
73
83
  let mut g = Graph::new(nodes.len());
74
84
  for (k, &v) in nodes.iter().enumerate() {
75
85
  g.self_w[k] = self.self_w[v];
76
86
  for &(u, w) in &self.adj[v] {
77
- if index[u] != usize::MAX {
78
- g.adj[k].push((index[u], w));
87
+ if let Some(i) = index(u) {
88
+ g.adj[k].push((i, w));
79
89
  }
80
90
  }
81
91
  g.adj[k].sort_by_key(|&(u, _)| u);
@@ -103,25 +113,27 @@ pub fn leiden(g: &Graph, resolution: f64, keys: &[u64], initial: Option<&[usize]
103
113
  if n == 0 {
104
114
  return Vec::new();
105
115
  }
106
- let m2: f64 = g.strengths().iter().sum();
116
+ let mut k = g.strengths();
117
+ let m2: f64 = k.iter().sum();
107
118
  if m2 <= 0.0 {
108
119
  return (0..n).collect();
109
120
  }
110
121
  // which aggregate node each original node is part of, and the current level
122
+ // (the graph itself, borrowed, until the first aggregate)
111
123
  let mut member: Vec<usize> = (0..n).collect();
112
- let mut level = g.clone();
124
+ let mut level: std::borrow::Cow<Graph> = std::borrow::Cow::Borrowed(g);
113
125
  let mut level_keys = keys.to_vec();
114
126
  let mut part: Vec<usize> = match initial {
115
127
  Some(p) if p.len() == n => p.to_vec(),
116
128
  _ => (0..n).collect(),
117
129
  };
118
130
  for _ in 0..64 {
119
- let moved = local_moving(&level, &mut part, resolution, m2, &level_keys);
131
+ let moved = local_moving(&level, &k, &mut part, resolution, m2, &level_keys);
120
132
  let communities = renumber(&mut part);
121
133
  if !moved && communities == level.len() {
122
134
  break;
123
135
  }
124
- let mut refined = refine(&level, &part, resolution, m2, &level_keys);
136
+ let mut refined = refine(&level, &k, &part, resolution, m2, &level_keys);
125
137
  let groups = renumber(&mut refined);
126
138
  if groups == level.len() {
127
139
  // nothing merges inside the communities: one more level changes nothing
@@ -135,7 +147,8 @@ pub fn leiden(g: &Graph, resolution: f64, keys: &[u64], initial: Option<&[usize]
135
147
  start[refined[v]] = part[v];
136
148
  agg_keys[refined[v]] = agg_keys[refined[v]].min(level_keys[v]);
137
149
  }
138
- level = aggregate(&level, &refined, groups);
150
+ level = std::borrow::Cow::Owned(aggregate(&level, &refined, groups));
151
+ k = level.strengths();
139
152
  level_keys = agg_keys;
140
153
  for m in member.iter_mut() {
141
154
  *m = refined[*m];
@@ -189,9 +202,15 @@ fn renumber(part: &mut [usize]) -> usize {
189
202
  /// Leiden's fast local moving: visit nodes from a queue, move each to the
190
203
  /// neighbouring community with the largest modularity gain, and requeue the
191
204
  /// neighbours a move may now pull along. Returns whether anything moved.
192
- fn local_moving(g: &Graph, part: &mut [usize], gamma: f64, m2: f64, keys: &[u64]) -> bool {
205
+ fn local_moving(
206
+ g: &Graph,
207
+ k: &[f64],
208
+ part: &mut [usize],
209
+ gamma: f64,
210
+ m2: f64,
211
+ keys: &[u64],
212
+ ) -> bool {
193
213
  let n = g.len();
194
- let k = g.strengths();
195
214
  let mut tot = vec![0.0; n];
196
215
  for v in 0..n {
197
216
  tot[part[v]] += k[v];
@@ -260,16 +279,15 @@ fn local_moving(g: &Graph, part: &mut [usize], gamma: f64, m2: f64, keys: &[u64]
260
279
  /// Leiden's refinement: inside each community, start from singletons and merge
261
280
  /// a node that is still a singleton into the refined group it gains most by
262
281
  /// joining, when both are well connected to the rest of the community.
263
- fn refine(g: &Graph, part: &[usize], gamma: f64, m2: f64, keys: &[u64]) -> Vec<usize> {
282
+ fn refine(g: &Graph, k: &[f64], part: &[usize], gamma: f64, m2: f64, keys: &[u64]) -> Vec<usize> {
264
283
  let n = g.len();
265
- let k = g.strengths();
266
284
  let c_count = part.iter().copied().max().map_or(0, |x| x + 1);
267
285
  let mut members: Vec<Vec<usize>> = vec![Vec::new(); c_count];
268
286
  for v in 0..n {
269
287
  members[part[v]].push(v);
270
288
  }
271
289
  let mut refined: Vec<usize> = (0..n).collect();
272
- let mut tot = k.clone(); // per refined group
290
+ let mut tot = k.to_vec(); // per refined group
273
291
  let mut ext = vec![0.0; n]; // weight from a refined group to the rest of its community
274
292
  let mut single = vec![true; n];
275
293
  for v in 0..n {