csharp.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /**
  2. * C# Framework Resolver
  3. *
  4. * Handles ASP.NET Core, ASP.NET MVC, and common C# patterns.
  5. */
  6. import { Node } from '../../types';
  7. import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
  8. import { stripCommentsForRegex } from '../strip-comments';
  9. export const aspnetResolver: FrameworkResolver = {
  10. name: 'aspnet',
  11. languages: ['csharp'],
  12. detect(context: ResolutionContext): boolean {
  13. // Check for .csproj files with ASP.NET references
  14. const allFiles = context.getAllFiles();
  15. for (const file of allFiles) {
  16. if (file.endsWith('.csproj')) {
  17. const content = context.readFile(file);
  18. if (content && (
  19. content.includes('Microsoft.AspNetCore') ||
  20. content.includes('Microsoft.NET.Sdk.Web') ||
  21. content.includes('System.Web.Mvc')
  22. )) {
  23. return true;
  24. }
  25. }
  26. }
  27. // Check for Program.cs with WebApplication
  28. const programCs = context.readFile('Program.cs');
  29. if (programCs && (
  30. programCs.includes('WebApplication') ||
  31. programCs.includes('CreateHostBuilder') ||
  32. programCs.includes('UseStartup')
  33. )) {
  34. return true;
  35. }
  36. // Check for Startup.cs (ASP.NET Core signature)
  37. if (context.fileExists('Startup.cs')) {
  38. return true;
  39. }
  40. // Check for Controllers directory
  41. return allFiles.some((f) => f.includes('/Controllers/') && f.endsWith('Controller.cs'));
  42. },
  43. resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null {
  44. // Pattern 1: Controller references
  45. if (ref.referenceName.endsWith('Controller')) {
  46. const result = resolveByNameAndKind(ref.referenceName, CLASS_KINDS, CONTROLLER_DIRS, context);
  47. if (result) {
  48. return {
  49. original: ref,
  50. targetNodeId: result,
  51. confidence: 0.85,
  52. resolvedBy: 'framework',
  53. };
  54. }
  55. }
  56. // Pattern 2: Service references (dependency injection)
  57. if (ref.referenceName.endsWith('Service') || ref.referenceName.startsWith('I') && ref.referenceName.length > 1) {
  58. const result = resolveByNameAndKind(ref.referenceName, SERVICE_KINDS, SERVICE_DIRS, context);
  59. if (result) {
  60. return {
  61. original: ref,
  62. targetNodeId: result,
  63. confidence: 0.85,
  64. resolvedBy: 'framework',
  65. };
  66. }
  67. }
  68. // Pattern 3: Repository references
  69. if (ref.referenceName.endsWith('Repository')) {
  70. const result = resolveByNameAndKind(ref.referenceName, SERVICE_KINDS, REPO_DIRS, context);
  71. if (result) {
  72. return {
  73. original: ref,
  74. targetNodeId: result,
  75. confidence: 0.85,
  76. resolvedBy: 'framework',
  77. };
  78. }
  79. }
  80. // Pattern 4: Model/Entity references
  81. if (/^[A-Z][a-zA-Z]+$/.test(ref.referenceName)) {
  82. const result = resolveByNameAndKind(ref.referenceName, CLASS_KINDS, MODEL_DIRS, context);
  83. if (result) {
  84. return {
  85. original: ref,
  86. targetNodeId: result,
  87. confidence: 0.7,
  88. resolvedBy: 'framework',
  89. };
  90. }
  91. }
  92. // Pattern 5: ViewModel references
  93. if (ref.referenceName.endsWith('ViewModel') || ref.referenceName.endsWith('Dto')) {
  94. const result = resolveByNameAndKind(ref.referenceName, CLASS_KINDS, VIEWMODEL_DIRS, context);
  95. if (result) {
  96. return {
  97. original: ref,
  98. targetNodeId: result,
  99. confidence: 0.8,
  100. resolvedBy: 'framework',
  101. };
  102. }
  103. }
  104. return null;
  105. },
  106. extract(filePath, content) {
  107. if (!filePath.endsWith('.cs')) return { nodes: [], references: [] };
  108. const nodes: Node[] = [];
  109. const references: UnresolvedRef[] = [];
  110. const now = Date.now();
  111. const safe = stripCommentsForRegex(content, 'csharp');
  112. // [HttpGet("path")], [HttpPost("path")], etc.
  113. const attrRegex = /\[(HttpGet|HttpPost|HttpPut|HttpPatch|HttpDelete)\s*\(\s*"([^"]+)"\s*\)\]/g;
  114. let match: RegExpExecArray | null;
  115. while ((match = attrRegex.exec(safe)) !== null) {
  116. const [, verb, routePath] = match;
  117. const method = verb!.replace(/^Http/, '').toUpperCase();
  118. const line = safe.slice(0, match.index).split('\n').length;
  119. const routeNode: Node = {
  120. id: `route:${filePath}:${line}:${method}:${routePath}`,
  121. kind: 'route',
  122. name: `${method} ${routePath}`,
  123. qualifiedName: `${filePath}::route:${routePath}`,
  124. filePath,
  125. startLine: line,
  126. endLine: line,
  127. startColumn: 0,
  128. endColumn: match[0].length,
  129. language: 'csharp',
  130. updatedAt: now,
  131. };
  132. nodes.push(routeNode);
  133. // Capture the next method declaration
  134. const tail = safe.slice(match.index + match[0].length);
  135. const methodMatch = tail.match(/(?:public|private|protected|internal)\s+[\w<>,\s\[\]]+?\s+(\w+)\s*\(/);
  136. if (methodMatch) {
  137. references.push({
  138. fromNodeId: routeNode.id,
  139. referenceName: methodMatch[1]!,
  140. referenceKind: 'references',
  141. line,
  142. column: 0,
  143. filePath,
  144. language: 'csharp',
  145. });
  146. }
  147. }
  148. // Minimal APIs: app.MapGet("/path", handler)
  149. const minimalRegex = /\.Map(Get|Post|Put|Patch|Delete)\s*\(\s*"([^"]+)"\s*,\s*([^,)]+)/g;
  150. while ((match = minimalRegex.exec(safe)) !== null) {
  151. const [, verb, routePath, handlerExpr] = match;
  152. const method = verb!.toUpperCase();
  153. const line = safe.slice(0, match.index).split('\n').length;
  154. const routeNode: Node = {
  155. id: `route:${filePath}:${line}:${method}:${routePath}`,
  156. kind: 'route',
  157. name: `${method} ${routePath}`,
  158. qualifiedName: `${filePath}::route:${routePath}`,
  159. filePath,
  160. startLine: line,
  161. endLine: line,
  162. startColumn: 0,
  163. endColumn: match[0].length,
  164. language: 'csharp',
  165. updatedAt: now,
  166. };
  167. nodes.push(routeNode);
  168. const handlerName = extractCSharpTailIdent(handlerExpr!);
  169. if (handlerName) {
  170. references.push({
  171. fromNodeId: routeNode.id,
  172. referenceName: handlerName,
  173. referenceKind: 'references',
  174. line,
  175. column: 0,
  176. filePath,
  177. language: 'csharp',
  178. });
  179. }
  180. }
  181. return { nodes, references };
  182. },
  183. };
  184. /** Extract last identifier from an expression like `MyService.Handler` or `Handler`. */
  185. function extractCSharpTailIdent(expr: string): string | null {
  186. const cleaned = expr.trim().replace(/\s+/g, '');
  187. const m = cleaned.match(/(?:\.|^)([A-Za-z_][A-Za-z0-9_]*)$/);
  188. return m ? m[1]! : null;
  189. }
  190. // Directory patterns
  191. const CONTROLLER_DIRS = ['/Controllers/'];
  192. const SERVICE_DIRS = ['/Services/', '/Service/', '/Application/'];
  193. const REPO_DIRS = ['/Repositories/', '/Repository/', '/Data/', '/Infrastructure/'];
  194. const MODEL_DIRS = ['/Models/', '/Model/', '/Entities/', '/Entity/', '/Domain/'];
  195. const VIEWMODEL_DIRS = ['/ViewModels/', '/ViewModel/', '/DTOs/', '/Dto/'];
  196. const CLASS_KINDS = new Set(['class']);
  197. const SERVICE_KINDS = new Set(['class', 'interface']);
  198. /**
  199. * Resolve a symbol by name using indexed queries instead of scanning all files.
  200. */
  201. function resolveByNameAndKind(
  202. name: string,
  203. kinds: Set<string>,
  204. preferredDirPatterns: string[],
  205. context: ResolutionContext,
  206. ): string | null {
  207. const candidates = context.getNodesByName(name);
  208. if (candidates.length === 0) return null;
  209. const kindFiltered = candidates.filter((n) => kinds.has(n.kind));
  210. if (kindFiltered.length === 0) return null;
  211. // Prefer candidates in framework-conventional directories
  212. const preferred = kindFiltered.filter((n) =>
  213. preferredDirPatterns.some((d) => n.filePath.includes(d))
  214. );
  215. if (preferred.length > 0) return preferred[0]!.id;
  216. // Fall back to any match
  217. return kindFiltered[0]!.id;
  218. }