-
Notifications
You must be signed in to change notification settings - Fork 8
/
yamlParser.ts
322 lines (248 loc) · 9.41 KB
/
yamlParser.ts
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
'use strict';
import { JSONDocument, ASTNode, ErrorCode, BooleanASTNode, NullASTNode, ArrayASTNode, NumberASTNode, ObjectASTNode, PropertyASTNode, StringASTNode, IError, IApplicableSchema } from 'vscode-json-languageservice/lib/parser/jsonParser';
import { JSONSchema } from 'vscode-json-languageservice/lib/jsonSchema';
import * as nls from 'vscode-nls';
const localize = nls.loadMessageBundle();
import * as Yaml from 'yaml-ast-parser'
import { Kind } from 'yaml-ast-parser'
import { getLineStartPositions, getPosition } from '../documentPositionCalculator'
export class SingleYAMLDocument extends JSONDocument {
private lines;
constructor(lines: number[]) {
super({disallowComments: false, ignoreDanglingComma: true});
this.lines = lines;
}
// TODO: This is complicated, messy and probably buggy
// It should be re-written.
// To get the correct behavior, it probably needs to be aware of
// the type of the nodes it is processing since there are no delimiters
// like in JSON. (ie. so it correctly returns 'object' vs 'property')
public getNodeFromOffsetEndInclusive(offset: number): ASTNode {
if (!this.root) {
return;
}
if (offset < this.root.start || offset > this.root.end) {
// We somehow are completely outside the document
// This is unexpected
console.log("Attempting to resolve node outside of document")
return null;
}
const children = this.root.getChildNodes()
function* sliding2(nodes: ASTNode[]) {
var i = 0;
while (i < nodes.length) {
yield [nodes[i], (i === nodes.length) ? null : nodes[i + 1]]
i++;
}
}
const onLaterLine = (offset: number, node: ASTNode) => {
const { line: actualLine } = getPosition(offset, this.lines)
const { line: nodeEndLine } = getPosition(node.end, this.lines)
return actualLine > nodeEndLine;
}
let findNode = (nodes: ASTNode[]): ASTNode => {
if (nodes.length === 0) {
return null;
}
var gen = sliding2(nodes);
let result: IteratorResult<ASTNode[]> = { done: false, value: undefined }
for (let [first, second] of gen) {
const end = (second) ? second.start : first.parent.end
if (offset >= first.start && offset < end) {
const children = first.getChildNodes();
const foundChild = findNode(children)
if (foundChild) {
if (foundChild['isKey'] && foundChild.end < offset) {
return foundChild.parent;
}
if (foundChild.type === "null") {
return null;
}
}
if (!foundChild && onLaterLine(offset, first)) {
return this.getNodeByIndent(this.lines, offset, this.root)
}
return foundChild || first;
}
}
return null;
}
return findNode(children) || this.root;
}
public getNodeFromOffset(offset: number): ASTNode {
return this.getNodeFromOffsetEndInclusive(offset);
}
private getNodeByIndent = (lines: number[], offset: number, node: ASTNode) => {
const { line, column: indent } = getPosition(offset, this.lines)
const children = node.getChildNodes()
function findNode(children) {
for (var idx = 0; idx < children.length; idx++) {
var child = children[idx];
const { line: childLine, column: childCol } = getPosition(child.start, lines);
if (childCol > indent) {
return null;
}
const newChildren = child.getChildNodes()
const foundNode = findNode(newChildren)
if (foundNode) {
return foundNode;
}
// We have the right indentation, need to return based on line
if (childLine == line) {
return child;
}
if (childLine > line) {
// Get previous
(idx - 1) >= 0 ? children[idx - 1] : child;
}
// Else continue loop to try next element
}
// Special case, we found the correct
return children[children.length - 1]
}
return findNode(children) || node
}
}
function recursivelyBuildAst(parent: ASTNode, node: Yaml.YAMLNode): ASTNode {
if (!node) {
return;
}
switch (node.kind) {
case Yaml.Kind.MAP: {
const instance = <Yaml.YamlMap>node;
const result = new ObjectASTNode(parent, null, node.startPosition, node.endPosition)
result.addProperty
for (const mapping of instance.mappings) {
result.addProperty(<PropertyASTNode>recursivelyBuildAst(result, mapping))
}
return result;
}
case Yaml.Kind.MAPPING: {
const instance = <Yaml.YAMLMapping>node;
const key = instance.key;
// Technically, this is an arbitrary node in YAML
// I doubt we would get a better string representation by parsing it
const keyNode = new StringASTNode(null, null, true, key.startPosition, key.endPosition);
keyNode.value = key.value;
const result = new PropertyASTNode(parent, keyNode)
result.end = instance.endPosition
const valueNode = (instance.value) ? recursivelyBuildAst(result, instance.value) : new NullASTNode(parent, key.value, instance.endPosition, instance.endPosition)
valueNode.location = key.value
result.setValue(valueNode)
return result;
}
case Yaml.Kind.SEQ: {
const instance = <Yaml.YAMLSequence>node;
const result = new ArrayASTNode(parent, null, instance.startPosition, instance.endPosition);
let count = 0;
for (const item of instance.items) {
if (item === null && count === instance.items.length - 1) {
break;
}
// Be aware of https://github.com/nodeca/js-yaml/issues/321
// Cannot simply work around it here because we need to know if we are in Flow or Block
var itemNode = (item === null) ? new NullASTNode(parent, null, instance.endPosition, instance.endPosition) : recursivelyBuildAst(result, item);
itemNode.location = count++;
result.addItem(itemNode);
}
return result;
}
case Yaml.Kind.SCALAR: {
const instance = <Yaml.YAMLScalar>node;
const type = Yaml.determineScalarType(instance)
// The name is set either by the sequence or the mapping case.
const name = null;
const value = instance.value;
switch (type) {
case Yaml.ScalarType.null: {
return new NullASTNode(parent, name, instance.startPosition, instance.endPosition);
}
case Yaml.ScalarType.bool: {
return new BooleanASTNode(parent, name, Yaml.parseYamlBoolean(value), node.startPosition, node.endPosition)
}
case Yaml.ScalarType.int: {
const result = new NumberASTNode(parent, name, node.startPosition, node.endPosition);
result.value = Yaml.parseYamlInteger(value);
result.isInteger = true;
return result;
}
case Yaml.ScalarType.float: {
const result = new NumberASTNode(parent, name, node.startPosition, node.endPosition);
result.value = Yaml.parseYamlFloat(value);
result.isInteger = false;
return result;
}
case Yaml.ScalarType.string: {
const result = new StringASTNode(parent, name, false, node.startPosition, node.endPosition);
result.value = node.value;
return result;
}
}
break;
}
case Yaml.Kind.ANCHOR_REF: {
const instance = (<Yaml.YAMLAnchorReference>node).value
return recursivelyBuildAst(parent, instance) ||
new NullASTNode(parent, null, node.startPosition, node.endPosition);
}
case Yaml.Kind.INCLUDE_REF: {
// Issue Warning
console.log("Unsupported feature, node kind: " + node.kind);
break;
}
}
}
function convertError(e: Yaml.YAMLException) {
// Subtract 2 because \n\0 is added by the parser (see loader.ts/loadDocuments)
const bufferLength = e.mark.buffer.length - 2;
// TODO determine correct positioning.
return { message: `${e.message}`, location: { start: Math.min(e.mark.position, bufferLength - 1), end: bufferLength, code: ErrorCode.Undefined } }
}
function createJSONDocument(yamlDoc: Yaml.YAMLNode, startPositions: number[]){
let _doc = new SingleYAMLDocument(startPositions);
_doc.root = recursivelyBuildAst(null, yamlDoc)
if (!_doc.root) {
// TODO: When this is true, consider not pushing the other errors.
_doc.errors.push({ message: localize('Invalid symbol', 'Expected a YAML object, array or literal'), code: ErrorCode.Undefined, location: { start: yamlDoc.startPosition, end: yamlDoc.endPosition } });
}
const duplicateKeyReason = 'duplicate key'
const errors = yamlDoc.errors.filter(e => e.reason !== duplicateKeyReason && !e.isWarning).map(e => convertError(e))
const warnings = yamlDoc.errors.filter(e => e.reason === duplicateKeyReason || e.isWarning).map(e => convertError(e))
errors.forEach(e => _doc.errors.push(e));
warnings.forEach(e => _doc.warnings.push(e));
return _doc;
}
export class YAMLDocument {
public documents: JSONDocument[]
constructor(documents: JSONDocument[]){
this.documents = documents;
}
get errors(): IError[]{
return (<IError[]>[]).concat(...this.documents.map(d => d.errors))
}
get warnings(): IError[]{
return (<IError[]>[]).concat(...this.documents.map(d => d.warnings))
}
public getNodeFromOffset(offset: number): ASTNode {
// Depends on the documents being sorted
for (let element of this.documents) {
if (offset <= element.root.end) {
return element.getNodeFromOffset(offset)
}
}
return undefined;
}
public validate(schema: JSONSchema, matchingSchemas: IApplicableSchema[] = null, offset: number = -1): void {
this.documents.forEach(doc => {
doc.validate(schema, matchingSchemas, offset)
});
}
}
export function parse(text: string): YAMLDocument {
const startPositions = getLineStartPositions(text)
// This is documented to return a YAMLNode even though the
// typing only returns a YAMLDocument
const yamlDocs = []
Yaml.loadAll(text, doc => yamlDocs.push(doc), {})
return new YAMLDocument(yamlDocs.map(doc => createJSONDocument(doc, startPositions)));
}