csharp.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. // ASP.NET signatures in controller/entrypoint SOURCE — covers feature-folder
  41. // apps with no `/Controllers/` dir and a subdir `Program.cs` that the
  42. // root-only checks above miss (e.g. realworld: Features/*/FooController.cs).
  43. // `.csproj` often isn't in the indexed source set, so source-scan is the
  44. // reliable signal.
  45. for (const file of allFiles) {
  46. if (!/(?:Controller|Program|Startup)\.cs$/.test(file)) continue;
  47. const c = context.readFile(file);
  48. if (c && (
  49. /\[(?:ApiController|Route|Http(?:Get|Post|Put|Patch|Delete))\b/.test(c) ||
  50. c.includes('ControllerBase') || c.includes(': Controller') ||
  51. c.includes('MapControllers') || c.includes('WebApplication') ||
  52. c.includes('Microsoft.AspNetCore')
  53. )) return true;
  54. }
  55. return false;
  56. },
  57. resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null {
  58. // Pattern 1: Controller references
  59. if (ref.referenceName.endsWith('Controller')) {
  60. const result = resolveByNameAndKind(ref.referenceName, CLASS_KINDS, CONTROLLER_DIRS, context);
  61. if (result) {
  62. return {
  63. original: ref,
  64. targetNodeId: result,
  65. confidence: 0.85,
  66. resolvedBy: 'framework',
  67. };
  68. }
  69. }
  70. // Pattern 2: Service references (dependency injection)
  71. if (ref.referenceName.endsWith('Service') || ref.referenceName.startsWith('I') && ref.referenceName.length > 1) {
  72. const result = resolveByNameAndKind(ref.referenceName, SERVICE_KINDS, SERVICE_DIRS, context);
  73. if (result) {
  74. return {
  75. original: ref,
  76. targetNodeId: result,
  77. confidence: 0.85,
  78. resolvedBy: 'framework',
  79. };
  80. }
  81. }
  82. // Pattern 3: Repository references
  83. if (ref.referenceName.endsWith('Repository')) {
  84. const result = resolveByNameAndKind(ref.referenceName, SERVICE_KINDS, REPO_DIRS, context);
  85. if (result) {
  86. return {
  87. original: ref,
  88. targetNodeId: result,
  89. confidence: 0.85,
  90. resolvedBy: 'framework',
  91. };
  92. }
  93. }
  94. // Pattern 4: Model/Entity references
  95. if (/^[A-Z][a-zA-Z]+$/.test(ref.referenceName)) {
  96. const result = resolveByNameAndKind(ref.referenceName, CLASS_KINDS, MODEL_DIRS, context);
  97. if (result) {
  98. return {
  99. original: ref,
  100. targetNodeId: result,
  101. confidence: 0.7,
  102. resolvedBy: 'framework',
  103. };
  104. }
  105. }
  106. // Pattern 5: ViewModel references
  107. if (ref.referenceName.endsWith('ViewModel') || ref.referenceName.endsWith('Dto')) {
  108. const result = resolveByNameAndKind(ref.referenceName, CLASS_KINDS, VIEWMODEL_DIRS, context);
  109. if (result) {
  110. return {
  111. original: ref,
  112. targetNodeId: result,
  113. confidence: 0.8,
  114. resolvedBy: 'framework',
  115. };
  116. }
  117. }
  118. return null;
  119. },
  120. extract(filePath, content) {
  121. if (!filePath.endsWith('.cs')) return { nodes: [], references: [] };
  122. const nodes: Node[] = [];
  123. const references: UnresolvedRef[] = [];
  124. const now = Date.now();
  125. const safe = stripCommentsForRegex(content, 'csharp');
  126. // Class-level [Route("api/[controller]")] prefix — joined onto each action.
  127. let classPrefix = '';
  128. const cls = /\[Route\s*\(\s*"([^"]+)"[^)]*\)\]\s*(?:\[[^\]]*\]\s*)*(?:public\s+|sealed\s+|abstract\s+|partial\s+)*class\b/.exec(safe);
  129. if (cls) classPrefix = cls[1]!;
  130. // [HttpGet], [HttpGet("path")], [HttpPost("path", Name="x")] — BARE or with a
  131. // path. (The old regex required a string, so bare attributes — with the route
  132. // on the class [Route] — were missed; eShopOnWeb was 24 bare / 2 string.)
  133. const attrRegex = /\[(HttpGet|HttpPost|HttpPut|HttpPatch|HttpDelete)(?:\s*\(\s*"([^"]+)"[^)]*\))?\s*\]/g;
  134. let match: RegExpExecArray | null;
  135. while ((match = attrRegex.exec(safe)) !== null) {
  136. const verb = match[1]!;
  137. const method = verb.replace(/^Http/, '').toUpperCase();
  138. const routePath = joinCsPath(classPrefix, match[2] || '');
  139. const line = safe.slice(0, match.index).split('\n').length;
  140. const routeNode: Node = {
  141. id: `route:${filePath}:${line}:${method}:${routePath}`,
  142. kind: 'route',
  143. name: `${method} ${routePath}`,
  144. qualifiedName: `${filePath}::route:${routePath}`,
  145. filePath,
  146. startLine: line,
  147. endLine: line,
  148. startColumn: 0,
  149. endColumn: match[0].length,
  150. language: 'csharp',
  151. updatedAt: now,
  152. };
  153. nodes.push(routeNode);
  154. // Next method declaration (skip stacked attributes; C# puts the return type
  155. // before the name). Bounded so we don't grab a far one.
  156. const tail = safe.slice(match.index + match[0].length, match.index + match[0].length + 600);
  157. const methodMatch = tail.match(/(?:public|private|protected|internal)\s+[\w<>,\s\[\]?.]+?\s+(\w+)\s*\(/);
  158. if (methodMatch) {
  159. references.push({
  160. fromNodeId: routeNode.id,
  161. referenceName: methodMatch[1]!,
  162. referenceKind: 'references',
  163. line,
  164. column: 0,
  165. filePath,
  166. language: 'csharp',
  167. });
  168. }
  169. }
  170. // Minimal APIs: app.MapGet("/path", handler)
  171. const minimalRegex = /\.Map(Get|Post|Put|Patch|Delete)\s*\(\s*"([^"]+)"\s*,\s*([^,)]+)/g;
  172. while ((match = minimalRegex.exec(safe)) !== null) {
  173. const [, verb, routePath, handlerExpr] = match;
  174. const method = verb!.toUpperCase();
  175. const line = safe.slice(0, match.index).split('\n').length;
  176. const routeNode: Node = {
  177. id: `route:${filePath}:${line}:${method}:${routePath}`,
  178. kind: 'route',
  179. name: `${method} ${routePath}`,
  180. qualifiedName: `${filePath}::route:${routePath}`,
  181. filePath,
  182. startLine: line,
  183. endLine: line,
  184. startColumn: 0,
  185. endColumn: match[0].length,
  186. language: 'csharp',
  187. updatedAt: now,
  188. };
  189. nodes.push(routeNode);
  190. const handlerName = extractCSharpTailIdent(handlerExpr!);
  191. if (handlerName) {
  192. references.push({
  193. fromNodeId: routeNode.id,
  194. referenceName: handlerName,
  195. referenceKind: 'references',
  196. line,
  197. column: 0,
  198. filePath,
  199. language: 'csharp',
  200. });
  201. }
  202. }
  203. return { nodes, references };
  204. },
  205. };
  206. /** Join a class-level [Route] prefix and an action's path into one normalized `/path`. */
  207. function joinCsPath(prefix: string, sub: string): string {
  208. const parts = [prefix, sub].map((p) => p.replace(/^\/+|\/+$/g, '')).filter(Boolean);
  209. return '/' + parts.join('/');
  210. }
  211. /** Extract last identifier from an expression like `MyService.Handler` or `Handler`. */
  212. function extractCSharpTailIdent(expr: string): string | null {
  213. const cleaned = expr.trim().replace(/\s+/g, '');
  214. const m = cleaned.match(/(?:\.|^)([A-Za-z_][A-Za-z0-9_]*)$/);
  215. return m ? m[1]! : null;
  216. }
  217. // Directory patterns
  218. const CONTROLLER_DIRS = ['/Controllers/'];
  219. const SERVICE_DIRS = ['/Services/', '/Service/', '/Application/'];
  220. const REPO_DIRS = ['/Repositories/', '/Repository/', '/Data/', '/Infrastructure/'];
  221. const MODEL_DIRS = ['/Models/', '/Model/', '/Entities/', '/Entity/', '/Domain/'];
  222. const VIEWMODEL_DIRS = ['/ViewModels/', '/ViewModel/', '/DTOs/', '/Dto/'];
  223. const CLASS_KINDS = new Set(['class']);
  224. const SERVICE_KINDS = new Set(['class', 'interface']);
  225. /**
  226. * Resolve a symbol by name using indexed queries instead of scanning all files.
  227. */
  228. function resolveByNameAndKind(
  229. name: string,
  230. kinds: Set<string>,
  231. preferredDirPatterns: string[],
  232. context: ResolutionContext,
  233. ): string | null {
  234. const candidates = context.getNodesByName(name);
  235. if (candidates.length === 0) return null;
  236. const kindFiltered = candidates.filter((n) => kinds.has(n.kind));
  237. if (kindFiltered.length === 0) return null;
  238. // Prefer candidates in framework-conventional directories
  239. const preferred = kindFiltered.filter((n) =>
  240. preferredDirPatterns.some((d) => n.filePath.includes(d))
  241. );
  242. if (preferred.length > 0) return preferred[0]!.id;
  243. // Fall back to any match
  244. return kindFiltered[0]!.id;
  245. }