|
| 1 | +part of code_builder; |
| 2 | + |
| 3 | +/// Determines an [Identifier] deppending on where it appears. |
| 4 | +/// |
| 5 | +/// __Example use__: |
| 6 | +/// void useContext(Scope scope) { |
| 7 | +/// // Prints Identifier "i1.Foo" |
| 8 | +/// print(scope.getIdentifier('Foo', 'package:foo/foo.dart'); |
| 9 | +/// |
| 10 | +/// // Prints Identifier "i1.Bar" |
| 11 | +/// print(scope.getIdentifier('Bar', 'package:foo/foo.dart'); |
| 12 | +/// |
| 13 | +/// // Prints Identifier "i2.Baz" |
| 14 | +/// print(scope.getIdentifier('Baz', 'package:bar/bar.dart'); |
| 15 | +/// } |
| 16 | +abstract class Scope { |
| 17 | + /// Create a default scope context. |
| 18 | + /// |
| 19 | + /// Actual implementation is _not_ guaranteed, only that all import prefixes |
| 20 | + /// will be unique in a given scope (actual implementation may be naive). |
| 21 | + factory Scope() = _IncrementingScope; |
| 22 | + |
| 23 | + /// Create a context that does _not_ apply any scoping. |
| 24 | + factory Scope.identity() = _IdentityScope; |
| 25 | + |
| 26 | + /// Given a [symbol] and its known [importUri], return an [Identifier]. |
| 27 | + Identifier getIdentifier(String symbol, String importUri); |
| 28 | + |
| 29 | + /// Returns a list of all imports needed to resolve identifiers. |
| 30 | + Iterable<ImportBuilder> getImports(); |
| 31 | +} |
| 32 | + |
| 33 | +class _IdentityScope implements Scope { |
| 34 | + final Set<String> _imports = new Set<String>(); |
| 35 | + |
| 36 | + @override |
| 37 | + Identifier getIdentifier(String symbol, String import) { |
| 38 | + _imports.add(import); |
| 39 | + return _stringId(symbol); |
| 40 | + } |
| 41 | + |
| 42 | + @override |
| 43 | + Iterable<ImportBuilder> getImports() { |
| 44 | + return _imports.map/*<ImportBuilder*/((i) => new ImportBuilder(i)); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +class _IncrementingScope implements Scope { |
| 49 | + final Map<String, int> _imports = <String, int>{}; |
| 50 | + |
| 51 | + int _counter = 0; |
| 52 | + |
| 53 | + @override |
| 54 | + Identifier getIdentifier(String symbol, String import) { |
| 55 | + var newId = _imports.putIfAbsent(import, () => ++_counter); |
| 56 | + return new PrefixedIdentifier(_stringId('_i$newId'), |
| 57 | + new Token(TokenType.PERIOD, 0), _stringId(symbol)); |
| 58 | + } |
| 59 | + |
| 60 | + @override |
| 61 | + Iterable<ImportBuilder> getImports() { |
| 62 | + return _imports.keys.map/*<ImportBuilder*/( |
| 63 | + (i) => new ImportBuilder(i, as: '_i${_imports[i]}')); |
| 64 | + } |
| 65 | +} |
0 commit comments