aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/src/xtext/ValidationService.ts
blob: 1a896db3bd63c1324f67986a2588d9bd6607a578 (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
/*
 * SPDX-FileCopyrightText: 2021-2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import type { Diagnostic } from '@codemirror/lint';

import type EditorStore from '../editor/EditorStore';

import type UpdateService from './UpdateService';
import { Issue, ValidationResult } from './xtextServiceResults';

export default class ValidationService {
  constructor(
    private readonly store: EditorStore,
    private readonly updateService: UpdateService,
  ) {}

  private lastValidationIssues: Issue[] = [];

  private lastSemanticsIssues: Issue[] = [];

  onPush(push: unknown): void {
    ({ issues: this.lastValidationIssues } = ValidationResult.parse(push));
    this.lastSemanticsIssues = [];
    this.updateDiagnostics();
    if (
      this.lastValidationIssues.some(({ severity }) => severity === 'error')
    ) {
      this.store.analysisCompleted(true);
    }
  }

  onDisconnect(): void {
    this.store.updateDiagnostics([]);
    this.lastValidationIssues = [];
    this.lastSemanticsIssues = [];
  }

  setSemanticsIssues(issues: Issue[]): void {
    this.lastSemanticsIssues = issues;
    this.updateDiagnostics();
  }

  private updateDiagnostics(): void {
    const allChanges = this.updateService.computeChangesSinceLastUpdate();
    const diagnostics: Diagnostic[] = [];
    function createDiagnostic({
      offset,
      length,
      severity,
      description,
    }: Issue): void {
      if (severity === 'ignore') {
        return;
      }
      diagnostics.push({
        from: allChanges.mapPos(offset),
        to: allChanges.mapPos(offset + length),
        severity,
        message: description,
      });
    }
    this.lastValidationIssues.forEach(createDiagnostic);
    this.lastSemanticsIssues.forEach(createDiagnostic);
    this.store.updateDiagnostics(diagnostics);
  }
}