aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/src/xtext/ContentAssistService.ts
blob: ac8ab36a9ca11642065c419cf262871442925a92 (plain) (blame)
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
 * SPDX-FileCopyrightText: 2021-2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import type {
  Completion,
  CompletionContext,
  CompletionResult,
} from '@codemirror/autocomplete';
import { syntaxTree } from '@codemirror/language';
import type { Transaction } from '@codemirror/state';
import escapeStringRegexp from 'escape-string-regexp';

import { implicitCompletion } from '../language/props';
import getLogger from '../utils/getLogger';

import type UpdateService from './UpdateService';
import type { ContentAssistEntry } from './xtextServiceResults';

const PROPOSALS_LIMIT = 1000;

const IDENTIFIER_REGEXP_STR = '[a-zA-Z0-9_]*';

const HIGH_PRIORITY_KEYWORDS = ['<->', '->', '==>'];

const log = getLogger('xtext.ContentAssistService');

interface IFoundToken {
  from: number;

  to: number;

  implicitCompletion: boolean;

  text: string;
}

function findToken({ pos, state }: CompletionContext): IFoundToken | undefined {
  const token = syntaxTree(state).resolveInner(pos, -1);
  const { from } = token;
  if (from > pos) {
    // We haven't found the token we want to complete.
    // Complete with an empty prefix from `pos` instead.
    // The other `return undefined;` lines also handle this condition.
    return undefined;
  }
  // We look at the text at the beginning of the token.
  // For QualifiedName tokens right before a comment, this may be a comment token.
  const endIndex = token.firstChild?.from ?? token.to;
  if (pos > endIndex) {
    return undefined;
  }
  const text = state.sliceDoc(from, endIndex).trimEnd();
  // Due to parser error recovery, we may get spurious whitespace
  // at the end of the token.
  const to = from + text.length;
  if (to > endIndex) {
    return undefined;
  }
  if (from > pos || endIndex < pos) {
    // We haven't found the token we want to complete.
    // Complete with an empty prefix from `pos` instead.
    return undefined;
  }
  return {
    from,
    to,
    implicitCompletion: token.type.prop(implicitCompletion) || false,
    text,
  };
}

function shouldCompleteImplicitly(
  token: IFoundToken | undefined,
  context: CompletionContext,
): boolean {
  return (
    token !== undefined &&
    token.implicitCompletion &&
    context.pos - token.from >= 2
  );
}

function computeSpan(prefix: string, entryCount: number): RegExp {
  const escapedPrefix = escapeStringRegexp(prefix);
  if (entryCount < PROPOSALS_LIMIT) {
    // Proposals with the current prefix fit the proposals limit.
    // We can filter client side as long as the current prefix is preserved.
    return new RegExp(`^${escapedPrefix}${IDENTIFIER_REGEXP_STR}$`);
  }
  // The current prefix overflows the proposals limits,
  // so we have to fetch the completions again on the next keypress.
  // Hopefully, it'll return a shorter list and we'll be able to filter client side.
  return new RegExp(`^${escapedPrefix}$`);
}

function createCompletion(entry: ContentAssistEntry): Completion {
  let boost: number;
  switch (entry.kind) {
    case 'KEYWORD':
      // Some hard-to-type operators should be on top.
      boost = HIGH_PRIORITY_KEYWORDS.includes(entry.proposal) ? 10 : -99;
      break;
    case 'TEXT':
    case 'SNIPPET':
      boost = -90;
      break;
    default:
      {
        // Penalize qualified names (vs available unqualified names).
        const extraSegments = entry.proposal.match(/::/g)?.length || 0;
        boost = Math.max(-5 * extraSegments, -50);
      }
      break;
  }
  const completion: Completion = {
    label: entry.proposal,
    type: entry.kind?.toLowerCase(),
    boost,
  };
  if (entry.documentation !== undefined) {
    completion.info = entry.documentation;
  }
  if (entry.description !== undefined) {
    completion.detail = entry.description;
  }
  return completion;
}

export default class ContentAssistService {
  private lastCompletion: CompletionResult | undefined;

  constructor(private readonly updateService: UpdateService) {}

  onTransaction(transaction: Transaction): void {
    if (this.shouldInvalidateCachedCompletion(transaction)) {
      this.lastCompletion = undefined;
    }
  }

  async contentAssist(context: CompletionContext): Promise<CompletionResult> {
    if (!this.updateService.opened) {
      this.lastCompletion = undefined;
      return {
        from: context.pos,
        options: [],
      };
    }
    const tokenBefore = findToken(context);
    if (!context.explicit && !shouldCompleteImplicitly(tokenBefore, context)) {
      return {
        from: context.pos,
        options: [],
      };
    }
    let range: { from: number; to: number };
    let prefix = '';
    if (tokenBefore === undefined) {
      range = {
        from: context.pos,
        to: context.pos,
      };
      prefix = '';
    } else {
      range = {
        from: tokenBefore.from,
        to: tokenBefore.to,
      };
      const prefixLength = context.pos - tokenBefore.from;
      if (prefixLength > 0) {
        prefix = tokenBefore.text.substring(0, context.pos - tokenBefore.from);
      }
    }
    if (!context.explicit && this.shouldReturnCachedCompletion(tokenBefore)) {
      if (this.lastCompletion === undefined) {
        throw new Error(
          'There is no cached completion, but we want to return it',
        );
      }
      log.trace('Returning cached completion result');
      return {
        ...this.lastCompletion,
        ...range,
      };
    }
    this.lastCompletion = undefined;
    const entries = await this.updateService.fetchContentAssist(
      {
        caretOffset: context.pos,
        proposalsLimit: PROPOSALS_LIMIT,
      },
      context,
    );
    if (context.aborted) {
      return {
        ...range,
        options: [],
      };
    }
    const options: Completion[] = [];
    entries.forEach((entry) => {
      if (prefix === entry.prefix) {
        // Xtext will generate completions that do not complete the current token,
        // e.g., `(` after trying to complete an indetifier,
        // but we ignore those, since CodeMirror won't filter for them anyways.
        options.push(createCompletion(entry));
      }
    });
    log.debug('Fetched', options.length, 'completions from server');
    this.lastCompletion = {
      ...range,
      options,
      validFor: computeSpan(prefix, entries.length),
    };
    return this.lastCompletion;
  }

  private shouldReturnCachedCompletion(
    token: { from: number; to: number; text: string } | undefined,
  ): boolean {
    if (token === undefined || this.lastCompletion === undefined) {
      return false;
    }
    const { from, to, text } = token;
    const { from: lastFrom, to: lastTo, validFor } = this.lastCompletion;
    if (!lastTo) {
      return true;
    }
    const [transformedFrom, transformedTo] = this.mapRangeInclusive(
      lastFrom,
      lastTo,
    );
    return (
      from >= transformedFrom &&
      to <= transformedTo &&
      validFor instanceof RegExp &&
      validFor.exec(text) !== null
    );
  }

  private shouldInvalidateCachedCompletion(transaction: Transaction): boolean {
    if (!transaction.docChanged || this.lastCompletion === undefined) {
      return false;
    }
    const { from: lastFrom, to: lastTo } = this.lastCompletion;
    if (lastTo === undefined) {
      return true;
    }
    let transformedFrom: number;
    let transformedTo: number;
    try {
      [transformedFrom, transformedTo] = this.mapRangeInclusive(
        lastFrom,
        lastTo,
      );
    } catch (error) {
      if (error instanceof RangeError) {
        log.debug('Invalidating cache due to invalid range', error);
        return true;
      }
      throw error;
    }
    let invalidate = false;
    transaction.changes.iterChangedRanges((fromA, toA) => {
      if (fromA < transformedFrom || toA > transformedTo) {
        invalidate = true;
      }
    });
    return invalidate;
  }

  private mapRangeInclusive(
    lastFrom: number,
    lastTo: number,
  ): [number, number] {
    const changes = this.updateService.computeChangesSinceLastUpdate();
    const transformedFrom = changes.mapPos(lastFrom);
    const transformedTo = changes.mapPos(lastTo, 1);
    return [transformedFrom, transformedTo];
  }
}