1 | 'use strict';
|
2 | const util = require('util');
|
3 | const _ = require('lodash');
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | function getLine(html, node) {
|
16 | if (!node) {
|
17 | return {line: 1, col: 1};
|
18 | }
|
19 | const linesUntil = html.substring(0, node.startIndex).split('\n');
|
20 | return {line: linesUntil.length, col: linesUntil[linesUntil.length - 1].length + 1};
|
21 | }
|
22 |
|
23 | function norm(n) {
|
24 | return n === undefined ? -1 : n;
|
25 | }
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | class RTCodeError extends Error {
|
36 | constructor(message, startOffset, endOffset, line, column) {
|
37 | super();
|
38 | Error.captureStackTrace(this, RTCodeError);
|
39 | this.name = 'RTCodeError';
|
40 | this.message = message || '';
|
41 | this.index = norm(startOffset);
|
42 | this.startOffset = norm(startOffset);
|
43 | this.endOffset = norm(endOffset);
|
44 | this.line = norm(line);
|
45 | this.column = norm(column);
|
46 | }
|
47 | }
|
48 |
|
49 |
|
50 |
|
51 |
|
52 | RTCodeError.build = buildError;
|
53 | RTCodeError.norm = norm;
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 | function buildFormat(context, node, msg, args) {
|
63 | return buildError(context, node, util.format.apply(this, [msg].concat(args)));
|
64 | }
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 | RTCodeError.buildFormat = _.rest(buildFormat, 3);
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 | function buildError(context, node, msg) {
|
82 | const loc = getNodeLoc(context, node);
|
83 | return new RTCodeError(msg, loc.start, loc.end, loc.pos.line, loc.pos.col);
|
84 | }
|
85 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 |
|
91 | function getNodeLoc(context, node) {
|
92 | const start = node.startIndex;
|
93 | const pos = getLine(context.html, node);
|
94 | let end;
|
95 | if (node.data) {
|
96 | end = start + node.data.length;
|
97 | } else if (node.next) {
|
98 | end = node.next.startIndex;
|
99 | } else {
|
100 | end = context.html.length;
|
101 | }
|
102 | return {
|
103 | pos,
|
104 | start,
|
105 | end
|
106 | };
|
107 | }
|
108 |
|
109 | module.exports = {
|
110 | RTCodeError,
|
111 | getNodeLoc
|
112 | };
|