-
Notifications
You must be signed in to change notification settings - Fork 0
/
LanguageUtils.ts
873 lines (796 loc) · 30.3 KB
/
LanguageUtils.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
import {
ReferenceParams,
DocumentUri,
Location,
Range,
Position,
TextDocument,
DeclarationParams,
RenameParams,
LocationLink,
CompletionItem,
TextDocumentPositionParams,
FoldingRangeParams,
FoldingRange,
FoldingRangeKind,
WorkspaceEdit,
TextDocumentEdit,
CompletionList,
CompletionItemKind,
TextDocuments,
TextDocumentIdentifier,
TextDocumentChangeEvent,
DidChangeWatchedFilesParams,
PrepareRenameParams,
} from 'vscode-languageserver';
import * as Parser from 'web-tree-sitter';
import * as Utils from './Utils'
import * as path from 'path';
import { isNullOrUndefined } from 'util';
import { PMTextDocument } from './Documents';
import { URI } from 'vscode-uri';
export declare type FilePath = string;
/**
* A map in which a keys are the names of an imported decision graph and the values are their file paths
*/
export declare type ImportMap = Map<string, FilePath>
export enum PolicyModelsLanguage {
PolicySpace,
DecisionGraph,
ValueInference
}
/**
* An object list describing the necessary information to create an instance of a language parser
*/
export const parsersInfo =
[
{
fileExtentsions : ['dg'],
language : PolicyModelsLanguage.DecisionGraph,
wasm : 'tree-sitter-decisiongraph.wasm',
},
{
fileExtentsions : ['pspace', 'ps', 'ts'],
language : PolicyModelsLanguage.PolicySpace,
wasm : 'tree-sitter-policyspace.wasm',
},
{
fileExtentsions : ['vi'],
language : PolicyModelsLanguage.ValueInference,
wasm : 'tree-sitter-valueinference.wasm',
}
]
/**
* Returns the sum of two numbers.
*
* @param extension - the file type extension
* @returns The PolicyModelsLanguage corresponding to the provided file extension
*/
export function getLanguageByExtension(extension : string) : PolicyModelsLanguage | null {
const correspondingInfo = parsersInfo.filter(info => info.fileExtentsions.indexOf(extension) != -1)
if(!(correspondingInfo) || correspondingInfo.length == 0) return null
return correspondingInfo[0].language
}
/**
* Given an absolute path to 1st file, and a relative path to 2nd file,
* returns the path to the 2nd file
*
* @param fromAbsolutePath absolute path to 1st file
* @param toRelativePath relative path to 2nd file
* @returns absolute path to 2nd file
*/
function resolvePaths(fromAbsolutePath : FilePath, toRelativePath : FilePath) : FilePath {
let currFileDir : FilePath = path.dirname(fromAbsolutePath)
//let absolutePath : FilePath = path.resolve(currFileDir, toRelativePath)
// return absolutePath
return path.normalize(path.join(currFileDir, toRelativePath))
}
/**
* This class represents an entity found in a parse tree.
* Instances of this class are the basis of all language services.
* It holds all the necessary information to answer LSP queries.
* Entity types are listed in {@link PolicyModelEntityType}
* Entity category are listed in {@link PolicyModelEntityCategory}
*/
export class PolicyModelEntity {
/**
* The type of the entity in the file
*/
type : PolicyModelEntityType
/**
* The category of the entity in the file
*/
category : PolicyModelEntityCategory
/**
* The name of the entity in the file
*/
name : string
/**
* The file from which the entity originates.
* //An _**undefined**_ value denotes that this is either irrelevant or originates from the same file it was found
*/
source : FilePath
/**
* The Syntax node from which this entity was originated
*/
syntaxNode : Parser.SyntaxNode
/**
* The location of the this entity. (Derived from it's syntax node location)
*/
location : Location
constructor(
name : string ,
type : PolicyModelEntityType,
syntaxNode : Parser.SyntaxNode,
sourceFile : FilePath,
currentFile : FilePath,
category){
this.name = name
this.type = type
this.syntaxNode = syntaxNode
//derive location from syntax node
this.location = Utils.newLocation(
currentFile,
Utils.newRange(
Utils.point2Position(syntaxNode.startPosition),
Utils.point2Position(syntaxNode.endPosition)))
this.source = sourceFile
this.category = category
}
getType() : PolicyModelEntityType {
return this.type
}
getName() : string {
return this.name
}
getSource() : DocumentUri {
return this.source
}
setSource(uri : DocumentUri) {
this.source = uri
}
getCategory() : PolicyModelEntityCategory {
return this.category
}
}
export enum PolicyModelEntityType {
DGNode,
Slot,
SlotValue,
ValueInference,
InferencePair,
ImportGraph
}
export enum PolicyModelEntityCategory {
Declaration,
Reference,
Special,
/**
* @deprecated NO LONGER SUPPORTED
*/
FoldRange
}
/**
* Keywords for AutoComplete in Decision Graph files
*/
export const DecisionGraphKeywords : CompletionItem[] = [
{label: "todo", kind: CompletionItemKind.Keyword},
{label: "ask", kind: CompletionItemKind.Keyword},
{label: "text", kind: CompletionItemKind.Keyword},
{label: "term", kind: CompletionItemKind.Keyword},
{label: "answers", kind: CompletionItemKind.Keyword},
{label: "call", kind: CompletionItemKind.Keyword},
{label: "consider", kind: CompletionItemKind.Keyword},
{label: "slot", kind: CompletionItemKind.Keyword},
{label: "options", kind: CompletionItemKind.Keyword},
{label: "else", kind: CompletionItemKind.Keyword},
{label: "when", kind: CompletionItemKind.Keyword},
{label: "section", kind: CompletionItemKind.Keyword},
{label: "title", kind: CompletionItemKind.Keyword},
{label: "end", kind: CompletionItemKind.Keyword},
{label: "reject", kind: CompletionItemKind.Keyword},
{label: "set", kind: CompletionItemKind.Keyword},
{label: "#import", kind: CompletionItemKind.Keyword},
]
/**
* Keywords for AutoComplete in Policy Space files
*/
export const PolicySpaceKeywords : CompletionItem[] = [
{label: "TODO", kind: CompletionItemKind.Keyword},
{label: "one of", kind: CompletionItemKind.Keyword},
{label: "some of", kind: CompletionItemKind.Keyword},
{label: "consists of", kind: CompletionItemKind.Keyword},
]
/**
* Keywords for AutoComplete in Value Inference files
*/
export const ValueInferenceKeywords : CompletionItem[] = [
{label: "support", kind: CompletionItemKind.Keyword},
{label: "comply", kind: CompletionItemKind.Keyword},
]
/**
* Converts a {@link PolicyModelEntity} into a {@link CompletionItem}
*
* @param entity the entity to convert
* @param currentFile current file in which the completion item is suggested.
* Used with import map to include imported decision graph file name in completion item label
* @param importMap the import map of the current file
* @returns CompletionItem representing the provided entity.
* Null if entity should be a suggested CompletionItem
*/
export function entity2CompletionItem(entity : PolicyModelEntity, currentFile : FilePath = undefined, importMap : ImportMap = undefined) : CompletionItem | null {
let EntityType2CompletionItemKind : CompletionItemKind[] = []
EntityType2CompletionItemKind[PolicyModelEntityType.DGNode] = CompletionItemKind.Variable
EntityType2CompletionItemKind[PolicyModelEntityType.Slot] = CompletionItemKind.Enum
EntityType2CompletionItemKind[PolicyModelEntityType.SlotValue] = CompletionItemKind.Value
if(entity.getType() == PolicyModelEntityType.ImportGraph) {
return null //import entities are not suggested in autocomplete
}
let kind : CompletionItemKind = EntityType2CompletionItemKind[entity.getType()]
let prefix : string = ""
if(!isNullOrUndefined(currentFile) && !isNullOrUndefined(importMap)){
prefix =
(entity.getType() == PolicyModelEntityType.DGNode &&
[PolicyModelEntityCategory.Declaration, PolicyModelEntityCategory.Reference].indexOf(entity.getCategory()) > -1 &&
!isNullOrUndefined(entity.getSource()) &&
entity.getSource() !== currentFile && Utils.getMapKeysByValue(importMap, entity.getSource()).length > 0)
? Utils.getMapKeysByValue(importMap, entity.getSource())[0].concat(">") : ""
}
let label : string = prefix.concat(entity.getName())
let result : CompletionItem = {
label: label,
kind: kind,
}
return result
}
export function getRangeOfSyntaxNode(node : Parser.SyntaxNode) : Range {
return Utils.newRange(Utils.point2Position(node.startPosition), Utils.point2Position(node.endPosition))
}
export function getLocationOfSyntaxNode(node : Parser.SyntaxNode, uri : DocumentUri) : Location {
return {range: getRangeOfSyntaxNode(node), uri: uri}
}
export function getRangesOfSyntaxNodes(nodes : Parser.SyntaxNode[]) : Range[] {
return nodes.map(getRangeOfSyntaxNode)
}
/**
* Generator function to iterate a {@link Parser.Tree}
*
* @param root the {@link Parser.Tree} to iterate
* @param visibleRanges the range of the visible text
* @returns an {@link IterableIterator} of {@link Parser.SyntaxNode}
*/
function* nextNode(root : Parser.Tree, visibleRanges: {start: number, end: number}[] = undefined) : IterableIterator<Parser.SyntaxNode> {
function visible(x: Parser.TreeCursor, visibleRanges: {start: number, end: number}[]) {
if(visibleRanges) {
for (const { start, end } of visibleRanges) {
const overlap = x.startPosition.row <= end + 1 && start - 1 <= x.endPosition.row
if (overlap) return true
}
return false
}
return true
}
let visitedChildren = false
let cursor = root.walk()
let parents = [cursor.nodeType]
let parent
let grandparent
while (true) {
// Advance cursor
if (visitedChildren) {
if (cursor.gotoNextSibling()) {
visitedChildren = false
} else if (cursor.gotoParent()) {
parents.pop()
visitedChildren = true
continue
} else {
break
}
} else {
const parent = cursor.nodeType
if (cursor.gotoFirstChild()) {
parents.push(parent)
visitedChildren = false
} else {
visitedChildren = true
continue
}
}
// Skip nodes that are not visible
if (!visible(cursor, visibleRanges)) {
visitedChildren = true
continue
}
yield cursor.currentNode()
}
}
/**
* Get all error nodes in a {@link Parser.Tree}
*
* @param tree the {@link Parser.Tree} to iterate
* @returns an array of {@link Parser.SyntaxNode}
*/
export function getAllErrorNodes(tree : Parser.Tree) : Parser.SyntaxNode[] {
const errorNodeTypes : string[] = ["ERROR", "MISSING", "UNEXPECTED"]
let result : Parser.SyntaxNode[] = []
for (let node of nextNode(tree)) {
if(errorNodeTypes.indexOf(node.type) >= 0){
result.push(node)
}
// if(node.hasError()){
// result.push(node)
// }
}
return result
// let root : Parser.SyntaxNode = tree.walk().currentNode()
// let errors : Parser.SyntaxNode[] = root.descendantsOfType(["ERROR", "MISSING"]) //maybe also UNEXPECTED ?
// return errors
}
//****Language Specific Static Services****/
/**
* Main node type names, as returned from the {@link Parser.Tree}
* of Decision Graph language
*/
const mainNodesTypes : string[] = [
'text_sub_node',
'terms_sub_node',
'term_sub_node',
'answers_sub_node',
'answer_sub_node',
'slot_sub_node',
'consider_options_sub_node',
'consider_option_sub_node',
'else_sub_node',
'when_answer_sub_node',
'info_sub_node',
]
/**
* Sub-node type names, as returned from the {@link Parser.Tree}
* of Decision Graph language
*/
const subNodesTypes : string[] = [
'ask_node',
'continue_node',
'todo_node',
'call_node',
'reject_node',
'set_node',
'section_node',
'part_node',
'consider_node',
'when_node',
'import_node',
'end_node',
'continue_node',
]
/**
* All node type names, as returned from the {@link Parser.Tree}
* of Decision Graph language
*/
const nodeTypes : string[] = mainNodesTypes.concat(subNodesTypes)
/**
* This class is a collection of basic analysis methods of a **Decision Graph** {@link Parser.Tree}
* All the methods are static and store no information and cause no side-effects.
* They are to be called by other classes to be composed into more complex queries
*/
export class DecisionGraphServices {
/**
* creates an {@link PolicyModelEntity} from a {@link Parser.SyntaxNode}
*
* @param node the node to convert
* @param currentFile the current file from which the syntax node originated
* @param importMap the import map of the current file
* @returns the {@link PolicyModelEntity} derived from the node
*/
static createEntityFromNode(node : Parser.SyntaxNode, currentFile : FilePath, importMap : ImportMap = undefined) : PolicyModelEntity | null {
let name : string
let source : DocumentUri
let category : PolicyModelEntityCategory
switch(node.type) {
case 'node_id_value':
name = node.text
switch(node.parent.type){
case 'node_reference':
category = PolicyModelEntityCategory.Reference
let parent = node.parent
//we need to check whether the node reference also contains an imported graph reference
let graph_name_node = parent.descendantsOfType('decision_graph_name')
if(isNullOrUndefined(graph_name_node) || graph_name_node.length == 0) {
//in case there is no imported graph reference -> set the entity's source to be this file
source = currentFile
}
else {
//in case there is an imported graph reference -> set the entity's source to be the imported graph's file
source = isNullOrUndefined(importMap) ?
undefined :
importMap.get(graph_name_node[0].text.trim())
}
break;
case 'node_id':
category = PolicyModelEntityCategory.Declaration
source = currentFile
break;
}
return new PolicyModelEntity(name, PolicyModelEntityType.DGNode, node, source, currentFile, category)
case 'slot_identifier':
name = node.text
return new PolicyModelEntity(name, PolicyModelEntityType.Slot, node, undefined, currentFile, PolicyModelEntityCategory.Reference)
case 'slot_value':
name = node.text
return new PolicyModelEntity(name, PolicyModelEntityType.SlotValue, node, undefined, currentFile, PolicyModelEntityCategory.Reference)
// case 'import_node':
// name = node.descendantsOfType("decision_graph_name")[0].text.trim()
// return new PolicyModelEntity(name, PolicyModelEntityType.ImportGraph, node, undefined, uri, PolicyModelEntityCategory.Special)
default:
return null
}
}
/**
* analyzes Decision Graph {@link Parser.Tree} and returns {@link PolicyModelEntity} for all imports
* and an {@link ImportMap}
*
* @param tree the tree to analyze
* @param currentFile the current file from which the tree originated
* @returns array of {@link PolicyModelEntity} for all import nodes and an {@link ImportMap}
*/
static getAllImportsInDoc(tree : Parser.Tree, currentFile : FilePath) : {imports: PolicyModelEntity[], importMap : ImportMap} {
let importNodes : Parser.SyntaxNode[] = tree.walk().currentNode().descendantsOfType("import_node")
let imports : PolicyModelEntity[] = []
if (importNodes.length > 0) {
importNodes.forEach(imp => {
let graphname : string = imp.descendantsOfType("decision_graph_name")[0].text.trim()
let entity : PolicyModelEntity = new PolicyModelEntity(graphname, PolicyModelEntityType.ImportGraph, imp, undefined, currentFile, PolicyModelEntityCategory.Special)
imports.push(entity)
})
}
return {
imports: imports,
importMap: DecisionGraphServices.importMapFromImportEntities(imports, currentFile)
}
}
/**
* creates {@link ImportMap} from {@link PolicyModelEntity} of imports
*
* @param tree import entities
* @param currentFile the current file from which the tree originated
* @returns array of {@link PolicyModelEntity} for all import nodes and an {@link ImportMap}
*/
static importMapFromImportEntities(imports: PolicyModelEntity[], currentFile : FilePath) : ImportMap {
let importMap : ImportMap = new Map()
if (imports.length > 0) {
imports
.map(importEntity => importEntity.syntaxNode)
.filter(imp => imp.type === "import_node")
.forEach(imp => {
let filename : string = imp.descendantsOfType("file_path")[0].text.trim()
filename = resolvePaths(currentFile, filename)
let graphname : string = imp.descendantsOfType("decision_graph_name")[0].text.trim()
importMap.set(graphname, filename)
})
}
return importMap
}
/**
* returns all {@link PolicyModelEntity} from a Decision Graph {@link Parser.Tree} (and an {@link ImportMap})
*
* @param tree the tree to analyze
* @param currentFile the current file from which the tree originated
* @returns array of {@link PolicyModelEntity} and an {@link ImportMap}
*/
static getAllEntitiesInDoc(tree : Parser.Tree, currentFile : FilePath) : {entities: PolicyModelEntity[], importMap : ImportMap} {
let result : PolicyModelEntity[] = []
let importsInfo : {imports: PolicyModelEntity[], importMap : Map<string, DocumentUri>}
= DecisionGraphServices.getAllImportsInDoc(tree, currentFile)
for (let node of nextNode(tree)) {
if(nodeTypes.indexOf(node.type) > -1) {
//We no longer support folding ranges - Do nothing
//result.push(new PolicyModelEntity(node.type, PolicyModelEntityType.DGNode, node, currentFile, currentFile, PolicyModelEntityCategory.FoldRange))
}
else {
let entity = DecisionGraphServices.createEntityFromNode(node, currentFile, importsInfo.importMap)
if(!isNullOrUndefined(entity)) {
result.push(entity)
}
}
}
return {entities: result.concat(importsInfo.imports), importMap: importsInfo.importMap}
}
/**
* returns all the ranges of the **definitions** of a node in a Decision Graph {@link Parser.Tree}
*
* @param name id of the node
* @param tree the tree to analyze
* @returns a {@link Range} array in which each element in the range of a **definition** of the node
*/
static getAllDefinitionsOfNodeInDocument(name : string, tree : Parser.Tree) : Range[] {
let root : Parser.SyntaxNode = tree.walk().currentNode()
let nodeIds : Parser.SyntaxNode[] = root.descendantsOfType("node_id")
let relevantIds = nodeIds
.map(id => id.descendantsOfType("node_id_value")[0])
.filter(id => id.text === name)
return getRangesOfSyntaxNodes(relevantIds)
}
/**
* returns all the ranges of the **references** of a node in a Decision Graph {@link Parser.Tree}
*
* @param name id of the node
* @param tree the tree to analyze
* @param currentFile the current file from which the tree originated
* @param decisiongraphSource the current file from which the tree originated
* @returns a {@link Range} array in which each element in the range of a **references** of the node
*/
static getAllReferencesOfNodeInDocument(name : string, tree : Parser.Tree, currentFile : FilePath, decisiongraphSource : FilePath = undefined /*if the node is from another file*/) : Range[] {
let root : Parser.SyntaxNode = tree.walk().currentNode()
let importMap : ImportMap = DecisionGraphServices.getAllImportsInDoc(tree, currentFile).importMap
let references : Parser.SyntaxNode[] = root.descendantsOfType("node_reference")
let relevantReferences = references.filter(
ref =>
{
let importedGraphName = ref.descendantsOfType("decision_graph_name").length > 0 ? ref.descendantsOfType("decision_graph_name")[0].text.trim() : undefined
return ref.descendantsOfType("node_id_value")[0].text === name &&
(isNullOrUndefined(importedGraphName) || importedGraphName === Utils.getMapKeysByValue(importMap,decisiongraphSource)[0] )
}
).map(ref => {return ref.descendantsOfType("node_id_value")[0]})
return getRangesOfSyntaxNodes(relevantReferences)
}
/**
* returns all the ranges of the **references** of a slot in a Decision Graph {@link Parser.Tree}
*
* @param name name of the slot
* @param tree the tree to analyze
* @returns a {@link Range} array in which each element in the range of a **references** of the slot
*/
static getAllReferencesOfSlotInDocument(name : string, tree : Parser.Tree) : Range[] {
let root : Parser.SyntaxNode = tree.walk().currentNode()
let slotRefs : Parser.SyntaxNode[] = root.descendantsOfType("slot_reference")
let slotIdentifiers : Parser.SyntaxNode[] = Utils.flatten(slotRefs.map(ref => ref.descendantsOfType("slot_identifier")))
let relevant = slotIdentifiers.filter(id => id.text === name)
return getRangesOfSyntaxNodes(relevant)
}
/**
* returns all the ranges of the **references** of a slot value in a Decision Graph {@link Parser.Tree}
*
* @param name name of the slot value
* @param tree the tree to analyze
* @returns a {@link Range} array in which each element in the range of a **references** of the slot value
*/
static getAllReferencesOfSlotValueInDocument(name : string, tree : Parser.Tree) : Range[] {
let root : Parser.SyntaxNode = tree.walk().currentNode()
let slotRefs : Parser.SyntaxNode[] = root.descendantsOfType("slot_value")
let relevant = slotRefs.filter(id => id.text === name)
return getRangesOfSyntaxNodes(relevant)
}
/**
* returns all the ranges of the nodes in a Decision Graph {@link Parser.Tree}
*
* @param tree the tree to analyze
* @returns a {@link Range} array in which each element in the range of a node
*/
static getAllNodesInDocument(tree : Parser.Tree) : Range[] {
let result : Parser.SyntaxNode[] = []
for (let node of nextNode(tree)) {
if(nodeTypes.indexOf(node.type) > -1){
result.push(node)
}
}
return getRangesOfSyntaxNodes(result)
}
}
/**
* This class is a collection of basic analysis methods of a **Policy Space** {@link Parser.Tree}
* All the methods are static and store no information and cause no side-effects.
* They are to be called by other classes to be composed into more complex queries
*/
export class PolicySpaceServices {
/**
* creates an {@link PolicyModelEntity} from a {@link Parser.SyntaxNode}
*
* @param node the syntax node to convert
* @param currentFile the current file from which the syntax node originated
* @returns the {@link PolicyModelEntity} derived from the node
*/
static createEntityFromNode(node : Parser.SyntaxNode, currentFile : FilePath) : PolicyModelEntity | null {
let name : string
if(node.type === 'identifier_value') {
name = node.text
switch(node.parent.type) {
case 'identifier':
return new PolicyModelEntity(name, PolicyModelEntityType.Slot, node, currentFile, currentFile, PolicyModelEntityCategory.Declaration)
case 'compound_values':
return new PolicyModelEntity(name, PolicyModelEntityType.Slot, node, currentFile, currentFile, PolicyModelEntityCategory.Reference)
case 'slot_value':
return new PolicyModelEntity(name, PolicyModelEntityType.SlotValue, node, currentFile, currentFile, PolicyModelEntityCategory.Declaration)
default:
return null
}
}
return null
}
/**
* returns all {@link PolicyModelEntity} from a Policy Space {@link Parser.Tree}
*
* @param tree the tree to analyze
* @param currentFile the current file from which the tree originated
* @returns array of {@link PolicyModelEntity}
*/
static getAllEntitiesInDoc(tree : Parser.Tree, currentFile : FilePath) : PolicyModelEntity[] {
let result : PolicyModelEntity[] = []
for (let node of nextNode(tree)) {
if(node.type === "slot") {
//We no longer support folding ranges - Do nothing
//result.push(new PolicyModelEntity(node.type, PolicyModelEntityType.Slot, node, currentFile, currentFile, PolicyModelEntityCategory.FoldRange))
}
else {
let entity = PolicySpaceServices.createEntityFromNode(node, currentFile)
if(!isNullOrUndefined(entity)) {
result.push(entity)
}
}
}
return result
}
/**
* returns all the ranges of the **definitions** of a slot in a Policy Space {@link Parser.Tree}
*
* @param name name of the slot
* @param tree the tree to analyze
* @returns a {@link Range} array in which each element in the range of a **definitions** of the slot
*/
static getAllDefinitionsOfSlotInDocument(name : string, tree : Parser.Tree) : Range[] {
let root : Parser.SyntaxNode = tree.walk().currentNode()
let slots : Parser.SyntaxNode[] = root.descendantsOfType("slot")
let relevantSlots = slots
.map(slot => slot.children.find(child => child.type === "identifier"))
.filter(id => id && id.descendantsOfType("identifier_value")[0].text === name)
.map(id => id.descendantsOfType("identifier_value")[0])
return getRangesOfSyntaxNodes(relevantSlots)
}
/**
* returns all the ranges of the **references** of a slot in a Policy Space {@link Parser.Tree}
*
* @param name name of the slot
* @param tree the tree to analyze
* @returns a {@link Range} array in which each element in the range of a **references** of the slot
*/
static getAllReferencesOfSlotInDocument(name : string, tree : Parser.Tree) : Range[] {
let root : Parser.SyntaxNode = tree.walk().currentNode()
let identifiers : Parser.SyntaxNode[] = root.descendantsOfType("identifier_value")
let relevantIdentifiers = identifiers
.filter(id => !(id.parent.type === "identifier") && !(id.parent.type === "slot_value"))
.filter(id => id.text === name)
return getRangesOfSyntaxNodes(relevantIdentifiers)
}
/**
* returns all the ranges of the **definitions** of a slot value in a Policy Space {@link Parser.Tree}
*
* @param name name of the slot value
* @param tree the tree to analyze
* @returns a {@link Range} array in which each element in the range of a **definitions** of the slot value
*/
static getAllDefinitionsOfSlotValueInDocument(name : string, tree : Parser.Tree) : Range[] {
let root : Parser.SyntaxNode = tree.walk().currentNode()
let values : Parser.SyntaxNode[] = root.descendantsOfType("slot_value")
let relevantIdentifiers = values
.map(val => val.descendantsOfType("identifier_value")[0])
.filter(id => id.text === name)
return getRangesOfSyntaxNodes(relevantIdentifiers)
}
/**
* returns all the ranges of the nodes in a Policy Space {@link Parser.Tree}
*
* @param tree the tree to analyze
* @returns a {@link Range} array in which each element in the range of a node
*/
static getAllSlotsInDocument(tree : Parser.Tree) : Range[] {
let root : Parser.SyntaxNode = tree.walk().currentNode()
let result : Parser.SyntaxNode[] = root.descendantsOfType("slot")
return getRangesOfSyntaxNodes(result)
}
}
/**
* This class is a collection of basic analysis methods of a **Value Inference** {@link Parser.Tree}
* All the methods are static and store no information and cause no side-effects.
* They are to be called by other classes to be composed into more complex queries
*/
export class ValueInferenceServices {
/**
* creates an {@link PolicyModelEntity} from a {@link Parser.SyntaxNode}
*
* @param node the syntax node to convert
* @param currentFile the current file from which the syntax node originated
* @returns the {@link PolicyModelEntity} derived from the node
*/
static createEntityFromNode(node : Parser.SyntaxNode, currentFile : FilePath) : PolicyModelEntity | null {
let name : string
if(node.type === 'slot_identifier') {
name = node.text
switch(node.parent.type) {
case 'slot_reference':
return new PolicyModelEntity(name, PolicyModelEntityType.Slot, node, undefined, currentFile, PolicyModelEntityCategory.Reference)
case 'slot_value':
return new PolicyModelEntity(name, PolicyModelEntityType.SlotValue, node, undefined, currentFile, PolicyModelEntityCategory.Reference)
default:
return null
}
}
return null
}
/**
* returns all {@link PolicyModelEntity} from a Value Inference {@link Parser.Tree}
*
* @param tree the tree to analyze
* @param currentFile the current file from which the tree originated
* @returns array of {@link PolicyModelEntity}
*/
static getAllEntitiesInDoc(tree : Parser.Tree, currentFile : FilePath) : PolicyModelEntity[] {
let result : PolicyModelEntity[] = []
for (let node of nextNode(tree)) {
if(node.type === "value_inference") {
//We no longer support folding ranges - Do nothing
//result.push(new PolicyModelEntity(node.type , PolicyModelEntityType.ValueInference, node, currentFile, currentFile, PolicyModelEntityCategory.FoldRange))
}
else if(node.type === "inference_pair") {
//We no longer support folding ranges - Do nothing
//result.push(new PolicyModelEntity(node.type , PolicyModelEntityType.InferencePair, node, currentFile, currentFile, PolicyModelEntityCategory.FoldRange))
}
else {
let entity = ValueInferenceServices.createEntityFromNode(node, currentFile)
if(!isNullOrUndefined(entity)) {
result.push(entity)
}
}
}
return result
}
/**
* returns all the ranges of the **references** of a slot in a Value Inference {@link Parser.Tree}
*
* @param name name of the slot
* @param tree the tree to analyze
* @returns a {@link Range} array in which each element in the range of a **references** of the slot
*/
static getAllReferencesOfSlotInDocument(name : string, tree : Parser.Tree) : Range[] {
let root : Parser.SyntaxNode = tree.walk().currentNode()
let identifiers : Parser.SyntaxNode[] = Utils.flatten(root.descendantsOfType("slot_reference")
.map(id => id.descendantsOfType("slot_identifier")))
let relevantIdentifiers = identifiers.filter(ref => ref.text === name)
return getRangesOfSyntaxNodes(relevantIdentifiers)
}
/**
* returns all the ranges of the **references** of a slot value in a Policy Space {@link Parser.Tree}
*
* @param name name of the slot value
* @param tree the tree to analyze
* @returns a {@link Range} array in which each element in the range of a **references** of the slot value
*/
static getAllReferencesOfSlotValueInDocument(name : string, tree : Parser.Tree) : Range[] {
let root : Parser.SyntaxNode = tree.walk().currentNode()
let identifiers : Parser.SyntaxNode[] = root.descendantsOfType("slot_value")
.map(id => id.descendantsOfType("slot_identifier")[0])
let relevantIdentifiers = identifiers.filter(ref => ref.text === name)
return getRangesOfSyntaxNodes(relevantIdentifiers)
}
/**
* returns all the ranges of the value-inferences in a Value Inference {@link Parser.Tree}
*
* @param tree the tree to analyze
* @returns a {@link Range} array in which each element in the range of a value-inference
*/
static getAllValueInferencesInDocument(tree : Parser.Tree) : Range[] {
let root : Parser.SyntaxNode = tree.walk().currentNode()
let result : Parser.SyntaxNode[] = root.descendantsOfType("value_inference")
return getRangesOfSyntaxNodes(result)
}
/**
* returns all the ranges of the value-inferences pair in a Value Inference {@link Parser.Tree}
*
* @param tree the tree to analyze
* @returns a {@link Range} array in which each element in the range of a value-inference pair
*/
static getAllInferencePairsInDocument(tree : Parser.Tree) : Range[] {
let root : Parser.SyntaxNode = tree.walk().currentNode()
let result : Parser.SyntaxNode[] = root.descendantsOfType("inference_pair")
return getRangesOfSyntaxNodes(result)
}
}