OLD | NEW |
| (Empty) |
1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 library computer.occurrences; | |
6 | |
7 import 'dart:collection'; | |
8 | |
9 import 'package:analysis_server/src/protocol_server.dart' as protocol; | |
10 import 'package:analyzer/src/generated/ast.dart'; | |
11 import 'package:analyzer/src/generated/element.dart'; | |
12 | |
13 /** | |
14 * A computer for elements occurrences in a Dart [CompilationUnit]. | |
15 */ | |
16 class DartUnitOccurrencesComputer { | |
17 final CompilationUnit _unit; | |
18 | |
19 final Map<Element, List<int>> _elementsOffsets = | |
20 new HashMap<Element, List<int>>(); | |
21 | |
22 DartUnitOccurrencesComputer(this._unit); | |
23 | |
24 /** | |
25 * Returns the computed occurrences, not `null`. | |
26 */ | |
27 List<protocol.Occurrences> compute() { | |
28 _unit.accept(new _DartUnitOccurrencesComputerVisitor(this)); | |
29 List<protocol.Occurrences> occurrences = <protocol.Occurrences>[]; | |
30 _elementsOffsets.forEach((engineElement, offsets) { | |
31 var serverElement = protocol.newElement_fromEngine(engineElement); | |
32 var length = engineElement.displayName.length; | |
33 occurrences.add(new protocol.Occurrences(serverElement, offsets, length)); | |
34 }); | |
35 return occurrences; | |
36 } | |
37 | |
38 void _addOccurrence(Element element, int offset) { | |
39 element = _canonicalizeElement(element); | |
40 if (element == null || element == DynamicElementImpl.instance) { | |
41 return; | |
42 } | |
43 List<int> offsets = _elementsOffsets[element]; | |
44 if (offsets == null) { | |
45 offsets = <int>[]; | |
46 _elementsOffsets[element] = offsets; | |
47 } | |
48 offsets.add(offset); | |
49 } | |
50 | |
51 Element _canonicalizeElement(Element element) { | |
52 if (element is FieldFormalParameterElement) { | |
53 element = (element as FieldFormalParameterElement).field; | |
54 } | |
55 if (element is PropertyAccessorElement) { | |
56 element = (element as PropertyAccessorElement).variable; | |
57 } | |
58 if (element is Member) { | |
59 element = (element as Member).baseElement; | |
60 } | |
61 return element; | |
62 } | |
63 } | |
64 | |
65 class _DartUnitOccurrencesComputerVisitor extends RecursiveAstVisitor { | |
66 final DartUnitOccurrencesComputer computer; | |
67 | |
68 _DartUnitOccurrencesComputerVisitor(this.computer); | |
69 | |
70 @override | |
71 visitSimpleIdentifier(SimpleIdentifier node) { | |
72 Element element = node.bestElement; | |
73 if (element != null) { | |
74 computer._addOccurrence(element, node.offset); | |
75 } | |
76 return super.visitSimpleIdentifier(node); | |
77 } | |
78 } | |
OLD | NEW |