Admissible argument counts of a `(params)` signature; null when it can't be read.
(signature: string | undefined)
| 29 | |
| 30 | /** Admissible argument counts of a `(params)` signature; null when it can't be read. */ |
| 31 | function constructorShape(signature: string | undefined): { min: number; max: number; key: string } | null { |
| 32 | signature = signature?.replace(/;$/, ''); |
| 33 | if (!signature?.startsWith('(') || !signature.endsWith(')')) return null; |
| 34 | const text = signature.slice(1, -1).trim(); |
| 35 | if (!text || text === 'void') return { min: 0, max: 0, key: '' }; |
| 36 | // Split on top-level commas only: `std::map<K, V>`, `int (*cb)(int, int)` |
| 37 | // and `T x = f(a, b)` all nest their commas. |
| 38 | const parts: string[] = []; |
| 39 | let start = 0; |
| 40 | let depth = 0; |
| 41 | let quote = ''; |
| 42 | for (let i = 0; i < text.length; i++) { |
| 43 | const c = text[i]!; |
| 44 | if (quote) { |
| 45 | if (c === '\\') i++; |
| 46 | else if (c === quote) quote = ''; |
| 47 | continue; |
| 48 | } |
| 49 | if (c === '"' || c === "'") { |
| 50 | quote = c; |
| 51 | continue; |
| 52 | } |
| 53 | if ('(<[{'.includes(c)) depth++; |
| 54 | if (')>]}'.includes(c)) depth--; |
| 55 | if (c === ',' && depth === 0) { |
| 56 | parts.push(text.slice(start, i)); |
| 57 | start = i + 1; |
| 58 | } |
| 59 | } |
| 60 | if (depth !== 0 || quote) return null; |
| 61 | parts.push(text.slice(start)); |
| 62 | // A comparison in a default argument would be mistaken for a `=` default |
| 63 | // or a template bracket — leave those to a compiler. |
| 64 | if (parts.some((p) => /[<>]=|==|!=/.test(p))) return null; |
| 65 | const variadic = parts.some((p) => p.includes('...')); |
| 66 | const types = parts.map((p) => { |
| 67 | let type = p.split('=')[0]!.trim(); |
| 68 | // Strip an optional parameter name, retaining unnamed built-in types |
| 69 | // (`unsigned int`, `long long`) and qualifiers. Complex declarators stay |
| 70 | // distinct unless their spelling matches; uncertainty must not merge overloads. |
| 71 | type = type.replace(/(.*[\s*&>])([A-Za-z_]\w*)$/, (whole, prefix: string, name: string) => |
| 72 | /^(?:void|bool|char|short|int|long|float|double|signed|unsigned|const|volatile)$/.test(name) |
| 73 | || /^(?:const|volatile|struct|class|enum)\s*$/.test(prefix) ? whole : prefix); |
| 74 | return type.replace(/\s+/g, ''); |
| 75 | }); |
| 76 | return { |
| 77 | key: types.join(','), |
| 78 | min: parts.filter((p) => !p.includes('=') && !p.includes('...')).length, |
| 79 | max: variadic ? Infinity : parts.length, |
| 80 | }; |
| 81 | } |
| 82 | |
| 83 | export function matchCppConstructor(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null { |
| 84 | const match = ref.referenceName.match(CONSTRUCTOR_REF); |
no test coverage detected