All files / src/providers InlayHintsProvider.ts

83.2% Statements 104/125
70.51% Branches 55/78
100% Functions 12/12
86.53% Lines 90/104

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 24914x 1x                           11x             11x 11x 11x   11x 11x 11x   11x                               11x 11x         11x     11x 2x 2x 2x     2x 2x   2x     2x 3x 4x 3x 3x   3x   3x 3x   3x         3x     3x       11x                               11x 11x   11x     11x 2x 2x 2x     1x 1x 1x 1x 1x   1x 8x 8x 8x 1x     7x                                             1x 1x 1x 1x 1x 1x 1x         1x 1x       11x                               11x 11x   11x     11x 8x 8x 8x   7x 7x 7x   7x         7x     7x     11x                 2x 2x           3x 9x 3x 1x 1x 1x 1x       7x 6x 6x 5x 3x 2x 1x        
// src/providers/InlayHintsProvider.ts
import * as vscode from 'vscode';
import type { CacheManager } from '../cache/CacheManager';
import type { ModelDefinition } from '../types';
 
// ─── Inlay Hints Provider ─────────────────────────────────────────────────
 
/**
 * Renders ghost-text hints for:
 * 1. factory()->create([...]) — shows $fillable field types
 * 2. route() — shows required parameter names
 * 3. config() — shows inferred value type
 * 4. env() — shows the actual env value (masked if secret)
 */
export class LaravelInlayHintsProvider implements vscode.InlayHintsProvider {
  constructor(private readonly cache: CacheManager) {}
 
  provideInlayHints(
    document: vscode.TextDocument,
    range: vscode.Range,
    _token: vscode.CancellationToken
  ): vscode.InlayHint[] {
    const hints: vscode.InlayHint[] = [];
    const text = document.getText(range);
    const offset = document.offsetAt(range.start);
 
    hints.push(...this.provideFactoryHints(document, text, offset));
    hints.push(...this.provideRouteParamHints(document, text, offset));
    hints.push(...this.provideConfigHints(document, text, offset));
 
    return hints;
  }
 
  // ─── Factory Inlay Hints ──────────────────────────────────────────────
 
  /**
   * Adds type hints for factory create/make array keys.
   *
   * factory(User::class)->create(['name' => ...])
   *                              ^^^^^^ string
   */
  private provideFactoryHints(
    document: vscode.TextDocument,
    text: string,
    offset: number
  ): vscode.InlayHint[] {
    const hints: vscode.InlayHint[] = [];
    const index = this.cache.getIndex();
 
    // Match: ModelName::factory()->create(['key' => value])
    // or: factory(ModelName::class)->create([...])
    const factoryPattern =
      /(?:(\w+)::factory\(\)|factory\((\w+)::class\))\s*->\s*(?:create|make|createMany|makeMany)\s*\(\s*\[/g;
 
    let match: RegExpExecArray | null;
    while ((match = factoryPattern.exec(text)) !== null) {
      const modelName = match[1] ?? match[2];
      const model = this.findModel(modelName, index.models);
      Iif (!model) { continue; }
 
      // Now find the array keys after this factory call
      const arrayStart = match.index + match[0].length;
      const arrayContent = text.slice(arrayStart, arrayStart + 500); // look ahead 500 chars
 
      const keyPattern = /['"]([^'"]+)['"]\s*=>/g;
      let keyMatch: RegExpExecArray | null;
 
      while ((keyMatch = keyPattern.exec(arrayContent)) !== null) {
        const fieldName = keyMatch[1];
        const col = model.columns.find((c) => c.name === fieldName);
        const cast = model.casts[fieldName];
        const phpType = cast ?? (col ? this.dbTypeToDisplay(col.type) : null);
 
        Iif (!phpType) { continue; }
 
        const hintOffset = offset + arrayStart + keyMatch.index + keyMatch[0].length;
        const hintPosition = document.positionAt(hintOffset);
 
        const hint = new vscode.InlayHint(
          hintPosition,
          `: ${phpType}`,
          vscode.InlayHintKind.Type
        );
        hint.tooltip = new vscode.MarkdownString(
          `**${fieldName}** — DB type: \`${col?.type ?? 'unknown'}\`${col?.nullable ? ', nullable' : ''}`
        );
        hints.push(hint);
      }
    }
 
    return hints;
  }
 
  // ─── Route Parameter Hints ────────────────────────────────────────────
 
  /**
   * Shows route parameter names as inlay hints.
   *
   * route('users.show', $id)
   *                     ^^^^ id:
   */
  private provideRouteParamHints(
    document: vscode.TextDocument,
    text: string,
    offset: number
  ): vscode.InlayHint[] {
    const hints: vscode.InlayHint[] = [];
    const index = this.cache.getIndex();
 
    const routeCallPattern = /\broute\s*\(\s*['"]([^'"]+)['"]\s*,\s*/g;
    let match: RegExpExecArray | null;
 
    while ((match = routeCallPattern.exec(text)) !== null) {
      const routeName = match[1];
      const route = index.routes.get(routeName);
      if (!route || route.parameters.length === 0) { continue; }
 
      // After the comma: extract positional arguments
      const afterComma = text.slice(match.index + match[0].length);
      let depth = 0;
      let argIdx = 0;
      let argStart = 0;
      let i = 0;
 
      for (; i < afterComma.length && argIdx < route.parameters.length; i++) {
        const ch = afterComma[i];
        Iif (ch === '(' || ch === '[') { depth++; }
        if (ch === ')' || ch === ']') {
          Eif (depth === 0) { break; }
          depth--;
        }
        Iif (ch === ',' && depth === 0) {
          // Hint for the next argument
          const param = route.parameters[argIdx];
          if (param) {
            const hintPos = offset + match.index + match[0].length + i + 1;
            // Skip whitespace
            const wsMatch = /^\s*/.exec(afterComma.slice(i + 1));
            const wsLen = wsMatch?.[0].length ?? 0;
            const finalPos = document.positionAt(hintPos + wsLen);
            const hint = new vscode.InlayHint(
              finalPos,
              `${param.name}: `,
              vscode.InlayHintKind.Parameter
            );
            hint.tooltip = `Route parameter: ${param.name}${param.required ? '' : ' (optional)'}`;
            hints.push(hint);
          }
          argIdx++;
          argStart = i + 1;
        }
      }
 
      // Hint for the first parameter (before any comma)
      Eif (route.parameters[0] && argStart === 0) {
        const param = route.parameters[0];
        const hintPos = offset + match.index + match[0].length;
        const wsMatch = /^\s*/.exec(afterComma);
        const wsLen = wsMatch?.[0].length ?? 0;
        const finalPos = document.positionAt(hintPos + wsLen);
        const hint = new vscode.InlayHint(
          finalPos,
          `${param.name}: `,
          vscode.InlayHintKind.Parameter
        );
        hint.tooltip = `Route parameter: ${param.name}`;
        hints.push(hint);
      }
    }
 
    return hints;
  }
 
  // ─── Config Value Hints ───────────────────────────────────────────────
 
  /**
   * Shows inferred config value type as inlay hint.
   *
   * config('app.debug')
   *         ^^^^^^^^^^^ bool
   */
  private provideConfigHints(
    document: vscode.TextDocument,
    text: string,
    offset: number
  ): vscode.InlayHint[] {
    const hints: vscode.InlayHint[] = [];
    const index = this.cache.getIndex();
 
    const configPattern = /\bconfig\s*\(\s*['"]([^'"]+)['"]/g;
    let match: RegExpExecArray | null;
 
    while ((match = configPattern.exec(text)) !== null) {
      const key = match[1];
      const configVal = index.configs.get(key);
      if (!configVal) { continue; }
 
      const phpType = this.phpTypeOf(configVal.value);
      const hintOffset = offset + match.index + match[0].length;
      const position = document.positionAt(hintOffset);
 
      const hint = new vscode.InlayHint(
        position,
        ` /* ${phpType} */`,
        vscode.InlayHintKind.Type
      );
      hint.tooltip = new vscode.MarkdownString(
        `Config \`${key}\` = \`${JSON.stringify(configVal.value)}\``
      );
      hints.push(hint);
    }
 
    return hints;
  }
 
  // ─── Helpers ──────────────────────────────────────────────────────────
 
  private findModel(
    name: string,
    models: Map<string, ModelDefinition>
  ): ModelDefinition | undefined {
    for (const [, m] of models) {
      Eif (m.className === name) { return m; }
    }
    return undefined;
  }
 
  private dbTypeToDisplay(dbType: string): string {
    const t = dbType.toLowerCase();
    if (['int', 'integer', 'bigint', 'smallint', 'tinyint'].some((x) => t.startsWith(x))) { return 'int'; }
    Iif (['float', 'double', 'decimal'].some((x) => t.startsWith(x))) { return 'float'; }
    Iif (t.startsWith('bool')) { return 'bool'; }
    Iif (t.includes('date') || t.includes('time')) { return 'Carbon'; }
    Iif (t === 'json' || t === 'jsonb') { return 'array'; }
    return 'string';
  }
 
  private phpTypeOf(value: unknown): string {
    if (value === null) { return 'null'; }
    const t = typeof value;
    if (t === 'boolean') { return 'bool'; }
    if (t === 'number') { return Number.isInteger(value) ? 'int' : 'float'; }
    if (t === 'string') { return 'string'; }
    if (Array.isArray(value)) { return 'array'; }
    Eif (t === 'object') { return 'array'; }
    return 'mixed';
  }
}