aboutsummaryrefslogtreecommitdiffstats
path: root/language-web/src/main/js/xtext/ContentAssistService.ts
blob: 917898649e855c2e6980b47c0c835512d5b542a3 (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
import type {
  Completion,
  CompletionContext,
  CompletionResult,
} from '@codemirror/autocomplete';
import type { ChangeSet, Transaction } from '@codemirror/state';

import { getLogger } from '../logging';
import type { UpdateService } from './UpdateService';

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

export class ContentAssistService {
  updateService: UpdateService;

  lastCompletion: CompletionResult | null = null;

  constructor(updateService: UpdateService) {
    this.updateService = updateService;
  }

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

  async contentAssist(context: CompletionContext): Promise<CompletionResult> {
    const tokenBefore = context.tokenBefore(['QualifiedName']);
    let range: { from: number, to: number };
    let selection: { selectionStart?: number, selectionEnd?: number };
    if (tokenBefore === null) {
      if (!context.explicit) {
        return {
          from: context.pos,
          options: [],
        };
      }
      range = {
        from: context.pos,
        to: context.pos,
      };
      selection = {};
    } else {
      range = {
        from: tokenBefore.from,
        to: tokenBefore.to,
      };
      selection = {
        selectionStart: tokenBefore.from,
        selectionEnd: tokenBefore.to,
      };
    }
    if (!context.explicit && this.shouldReturnCachedCompletion(tokenBefore)) {
      log.trace('Returning cached completion result');
      // Postcondition of `shouldReturnCachedCompletion`: `lastCompletion !== null`
      return {
        ...this.lastCompletion as CompletionResult,
        ...range,
      };
    }
    this.lastCompletion = null;
    const entries = await this.updateService.fetchContentAssist({
      resource: this.updateService.resourceName,
      serviceType: 'assist',
      caretOffset: context.pos,
      ...selection,
    }, context);
    if (context.aborted) {
      return {
        ...range,
        options: [],
      };
    }
    const options: Completion[] = [];
    entries.forEach((entry) => {
      options.push({
        label: entry.proposal,
        detail: entry.description,
        info: entry.documentation,
        type: entry.kind?.toLowerCase(),
        boost: entry.kind === 'KEYWORD' ? -90 : 0,
      });
    });
    log.debug('Fetched', options.length, 'completions from server');
    this.lastCompletion = {
      ...range,
      options,
      span: /^[a-zA-Z0-9_:]*$/,
    };
    return this.lastCompletion;
  }

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

  private shouldInvalidateCachedCompletion(changes: ChangeSet) {
    if (changes.empty || this.lastCompletion === null) {
      return false;
    }
    const { from: lastFrom, to: lastTo } = this.lastCompletion;
    if (!lastTo) {
      return true;
    }
    const [transformedFrom, transformedTo] = this.mapRangeInclusive(lastFrom, lastTo);
    let invalidate = false;
    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];
  }
}