lib.rs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. //! codegraph-kernel — native extraction kernel (napi-rs).
  2. //!
  3. //! Replaces ONLY the parse+extract walk inside the parse workers, behind the
  4. //! existing `ExtractionResult` contract. Input `(filePath, content, language)`
  5. //! per file; output flat typed buffers — one boundary crossing per file.
  6. //! Everything downstream (resolution, synthesis, frameworks, MCP) is
  7. //! untouched and consumes the decoded result exactly as before.
  8. //!
  9. //! Calls are synchronous by design: the existing `ParseWorkerPool` workers
  10. //! already parallelize per-file, so each worker thread drives its own kernel
  11. //! call (do NOT rebuild the pool on the Rust side — see the migration plan §3).
  12. //!
  13. //! Per-language extraction lives in a dedicated walker module (tsjs/ for
  14. //! typescript/tsx/javascript/jsx) that mirrors the TS extractor for behavioral
  15. //! parity — verified by scripts/kernel-parity.mjs and the §5 gate.
  16. #![deny(clippy::all)]
  17. mod buffers;
  18. mod ccpp;
  19. mod cfnptr;
  20. mod csharp;
  21. mod docstring;
  22. mod ids;
  23. mod go;
  24. mod java;
  25. mod kotlin;
  26. mod langs;
  27. mod php;
  28. mod rlang;
  29. mod ruby;
  30. mod rustlang;
  31. mod swift;
  32. mod textutil;
  33. mod python;
  34. mod tsjs;
  35. use napi::bindgen_prelude::*;
  36. use napi_derive::napi;
  37. /// The five flat tables for one file. See buffers.rs for the byte layout;
  38. /// `src/extraction/kernel/layout.ts` is the TS mirror.
  39. #[napi(object)]
  40. pub struct ExtractBuffers {
  41. pub meta: Buffer,
  42. pub nodes: Buffer,
  43. pub edges: Buffer,
  44. pub refs: Buffer,
  45. pub arena: Buffer,
  46. }
  47. /// Wire-contract description — the TS loader verifies this against
  48. /// src/types.ts before routing anything to the kernel, so an out-of-date
  49. /// `.node` degrades to the wasm path instead of mis-decoding.
  50. #[napi(object)]
  51. pub struct ContractInfo {
  52. pub abi_version: u32,
  53. pub kernel_version: String,
  54. pub node_kinds: Vec<String>,
  55. pub edge_kinds: Vec<String>,
  56. /// Languages this binary can extract (routing is still TS-side policy).
  57. pub languages: Vec<String>,
  58. }
  59. /// Grammar identity for the grammar-source-parity gate: the wasm grammar and
  60. /// the native grammar must expose identical node-kind/field tables, or
  61. /// kernel-vs-fallback routing would be non-deterministic.
  62. #[napi(object)]
  63. pub struct GrammarInfo {
  64. pub abi_version: u32,
  65. pub node_kind_count: u32,
  66. pub field_count: u32,
  67. pub node_kinds: Vec<String>,
  68. pub field_names: Vec<String>,
  69. }
  70. #[napi]
  71. pub fn contract_info() -> ContractInfo {
  72. ContractInfo {
  73. abi_version: buffers::KERNEL_ABI_VERSION as u32,
  74. kernel_version: env!("CARGO_PKG_VERSION").to_string(),
  75. node_kinds: buffers::NODE_KINDS.iter().map(|s| s.to_string()).collect(),
  76. edge_kinds: buffers::EDGE_KINDS.iter().map(|s| s.to_string()).collect(),
  77. languages: langs::LANGUAGES.iter().map(|s| s.to_string()).collect(),
  78. }
  79. }
  80. #[napi]
  81. pub fn grammar_info(language: String) -> Option<GrammarInfo> {
  82. let lang = langs::grammar_for(&language)?;
  83. let node_kind_count = lang.node_kind_count();
  84. let field_count = lang.field_count();
  85. let node_kinds = (0..node_kind_count)
  86. .map(|i| lang.node_kind_for_id(i as u16).unwrap_or("").to_string())
  87. .collect();
  88. // Field ids are 1-based in tree-sitter.
  89. let field_names = (1..=field_count)
  90. .map(|i| lang.field_name_for_id(i as u16).unwrap_or("").to_string())
  91. .collect();
  92. Some(GrammarInfo {
  93. abi_version: lang.abi_version() as u32,
  94. node_kind_count: node_kind_count as u32,
  95. field_count: field_count as u32,
  96. node_kinds,
  97. field_names,
  98. })
  99. }
  100. /// One struct node's extent for the cFnPtr sweep (mirror of the TS caller's
  101. /// `{ id, startLine, endLine }`, with `endLine ?? startLine` applied TS-side).
  102. #[napi(object)]
  103. pub struct CfnptrStructIn {
  104. pub id: String,
  105. pub start_line: u32,
  106. pub end_line: u32,
  107. }
  108. #[napi(object)]
  109. pub struct CfnptrFileIn {
  110. /// RAW file text, exactly as the resolver's readFile returned it.
  111. pub text: String,
  112. pub structs: Vec<CfnptrStructIn>,
  113. }
  114. #[napi(object)]
  115. pub struct CfnptrField {
  116. pub name: String,
  117. pub index: u32,
  118. pub ptr: bool,
  119. #[napi(js_name = "type")]
  120. pub ty: String,
  121. }
  122. #[napi(object)]
  123. pub struct CfnptrStructOut {
  124. pub id: String,
  125. pub parsed: bool,
  126. pub fields: Vec<CfnptrField>,
  127. }
  128. /// The cFnPtr extraction-sweep facts for one file — see cfnptr.rs (and the
  129. /// TS synthesizer's `FileFacts`) for field semantics.
  130. #[napi(object)]
  131. pub struct CfnptrFacts {
  132. pub fn_ptr_typedefs: Vec<String>,
  133. pub fn_type_typedefs: Vec<String>,
  134. pub structs: Vec<CfnptrStructOut>,
  135. pub inline_ptr: bool,
  136. pub inline_types: Vec<String>,
  137. pub inline_tags: Vec<String>,
  138. pub init_tokens: Vec<String>,
  139. pub array_elems: Vec<String>,
  140. pub alias_names: Vec<String>,
  141. pub d_pairs: Vec<String>,
  142. pub dispatch_fields: Vec<String>,
  143. pub array_dispatch_names: Vec<String>,
  144. pub includes: Vec<String>,
  145. }
  146. /// Batched cFnPtr extraction sweep (task #5 step 2): one call scans a batch
  147. /// of files and returns their collected facts, amortizing the NAPI boundary.
  148. /// Feature-detected by the TS loader — absent on older binaries, where the
  149. /// synthesizer keeps its JS sweep.
  150. #[napi]
  151. pub fn cfnptr_scan_files(files: Vec<CfnptrFileIn>) -> Vec<CfnptrFacts> {
  152. files
  153. .into_iter()
  154. .map(|f| {
  155. let structs: Vec<cfnptr::StructExtent> = f
  156. .structs
  157. .into_iter()
  158. .map(|s| cfnptr::StructExtent { id: s.id, start_line: s.start_line, end_line: s.end_line })
  159. .collect();
  160. let facts = cfnptr::scan_file(&f.text, &structs);
  161. CfnptrFacts {
  162. fn_ptr_typedefs: facts.fn_ptr_typedefs,
  163. fn_type_typedefs: facts.fn_type_typedefs,
  164. structs: facts
  165. .structs
  166. .into_iter()
  167. .map(|s| CfnptrStructOut {
  168. id: s.id,
  169. parsed: s.parsed,
  170. fields: s
  171. .fields
  172. .into_iter()
  173. .map(|fl| CfnptrField { name: fl.name, index: fl.index, ptr: fl.ptr, ty: fl.ty })
  174. .collect(),
  175. })
  176. .collect(),
  177. inline_ptr: facts.inline_ptr,
  178. inline_types: facts.inline_types,
  179. inline_tags: facts.inline_tags,
  180. init_tokens: facts.init_tokens,
  181. array_elems: facts.array_elems,
  182. alias_names: facts.alias_names,
  183. d_pairs: facts.d_pairs,
  184. dispatch_fields: facts.dispatch_fields,
  185. array_dispatch_names: facts.array_dispatch_names,
  186. includes: facts.includes,
  187. }
  188. })
  189. .collect()
  190. }
  191. /// Debug/differential hook: the native `stripCommentsForRegex(text, 'c')`.
  192. /// Exists so the strip differential oracle can pin the Rust stripper against
  193. /// the TS reference directly.
  194. #[napi]
  195. pub fn cfnptr_strip_c(text: String) -> String {
  196. String::from_utf8_lossy(&cfnptr::strip_c(text.as_bytes())).into_owned()
  197. }
  198. #[napi]
  199. pub fn extract_file(file_path: String, content: String, language: String) -> Result<ExtractBuffers> {
  200. let out = match language.as_str() {
  201. "java" => java::extract(&file_path, &content).map_err(Error::from_reason)?,
  202. "python" => python::extract(&file_path, &content).map_err(Error::from_reason)?,
  203. "go" => go::extract(&file_path, &content).map_err(Error::from_reason)?,
  204. "c" | "cpp" => ccpp::extract(&file_path, &content, &language).map_err(Error::from_reason)?,
  205. "rust" => rustlang::extract(&file_path, &content).map_err(Error::from_reason)?,
  206. "csharp" => csharp::extract(&file_path, &content).map_err(Error::from_reason)?,
  207. "ruby" => ruby::extract(&file_path, &content).map_err(Error::from_reason)?,
  208. "php" => php::extract(&file_path, &content).map_err(Error::from_reason)?,
  209. "swift" => swift::extract(&file_path, &content).map_err(Error::from_reason)?,
  210. "kotlin" => kotlin::extract(&file_path, &content).map_err(Error::from_reason)?,
  211. "r" => rlang::extract(&file_path, &content).map_err(Error::from_reason)?,
  212. _ => tsjs::extract(&file_path, &content, &language).map_err(Error::from_reason)?,
  213. };
  214. Ok(ExtractBuffers {
  215. meta: out.meta.into(),
  216. nodes: out.nodes.into(),
  217. edges: out.edges.into(),
  218. refs: out.refs.into(),
  219. arena: out.arena.into(),
  220. })
  221. }