-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathhbs-parser.js
More file actions
92 lines (81 loc) · 2.4 KB
/
hbs-parser.js
File metadata and controls
92 lines (81 loc) · 2.4 KB
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
import * as eslintScope from 'eslint-scope';
import DocumentLines from '../utils/document.js';
import { processGlimmerTemplate, buildGlimmerVisitorKeys } from './transforms.js';
// Constant: Program + all Glimmer node types. Computed once at module load.
const hbsVisitorKeys = { Program: ['body'], ...buildGlimmerVisitorKeys() };
/**
* implements https://eslint.org/docs/latest/extend/custom-parsers
* for Handlebars (.hbs) template files.
*
* The entire file is treated as a Glimmer template.
* All locals not defined in the template are assumed to be defined
* (no no-undef errors for template identifiers).
*/
/**
* @type {import('eslint').ParserModule}
*/
export const meta = {
name: 'ember-eslint-parser/hbs',
version: '*',
};
export function parseForESLint(code, options) {
const filePath = (options && options.filePath) || '<hbs>';
const codeLines = new DocumentLines(code);
let result;
try {
result = processGlimmerTemplate({
templateContent: code,
codeLines,
templateRange: [0, code.length],
});
} catch (e) {
// Transform glimmer parse error to ESLint-compatible error
const loc = e.location || (e.hash && e.hash.loc);
if (loc && loc.start) {
const err = Object.assign(new SyntaxError(e.message), {
lineNumber: loc.start.line,
column: loc.start.column,
index: codeLines.positionToOffset(loc.start),
fileName: filePath,
});
throw err;
}
throw e;
}
const { ast: templateNode, comments } = result;
// Wrap in a synthetic Program node (required by ESLint)
const program = {
type: 'Program',
body: [templateNode],
tokens: templateNode.tokens,
comments,
range: [0, code.length],
start: 0,
end: code.length,
loc: {
start: { line: 1, column: 0 },
end: codeLines.offsetToPosition(code.length),
},
};
// Build visitor keys: Program + all Glimmer node types
const visitorKeys = hbsVisitorKeys;
// Create an empty scope manager.
// For HBS, all locals are assumed to be defined at runtime,
// so we don't track variable references (no no-undef errors).
const scopeManager = eslintScope.analyze(
{
type: 'Program',
body: [],
range: [0, code.length],
loc: program.loc,
},
{ range: true }
);
return {
ast: program,
scopeManager,
visitorKeys,
services: {},
};
}
export default { meta, parseForESLint };