lib.rs 7.7 KB

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