Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(76)

Side by Side Diff: pkg/compiler/lib/src/js_backend/minify_namer.dart

Issue 707793002: Use field names that are unique only wrt. the inheritance chain in minified mode. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Comments Created 6 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | tests/compiler/dart2js_extra/many_fields_test.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a 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. 3 // BSD-style license that can be found in the LICENSE file.
4 4
5 part of js_backend; 5 part of js_backend;
6 6
7 /** 7 /**
8 * Assigns JavaScript identifiers to Dart variables, class-names and members. 8 * Assigns JavaScript identifiers to Dart variables, class-names and members.
9 */ 9 */
10 class MinifyNamer extends Namer { 10 class MinifyNamer extends Namer {
11 MinifyNamer(Compiler compiler) : super(compiler) { 11 MinifyNamer(Compiler compiler) : super(compiler) {
12 reserveBackendNames(); 12 reserveBackendNames();
13 fieldRegistry = new _FieldNamingRegistry(this);
13 } 14 }
14 15
15 String get isolateName => 'I'; 16 String get isolateName => 'I';
16 String get isolatePropertiesName => 'p'; 17 String get isolatePropertiesName => 'p';
17 bool get shouldMinify => true; 18 bool get shouldMinify => true;
18 19
19 final String getterPrefix = 'g'; 20 final String getterPrefix = 'g';
20 final String setterPrefix = 's'; 21 final String setterPrefix = 's';
21 final String callPrefix = ''; // this will create function names $<n> 22 final String callPrefix = ''; // this will create function names $<n>
22 23
23 static const ALPHABET_CHARACTERS = 52; // a-zA-Z. 24 final ALPHABET_CHARACTERS = 52; // a-zA-Z.
24 static const ALPHANUMERIC_CHARACTERS = 62; // a-zA-Z0-9. 25 final ALPHANUMERIC_CHARACTERS = 62; // a-zA-Z0-9.
26
27 _FieldNamingRegistry fieldRegistry;
25 28
26 // You can pass an invalid identifier to this and unlike its non-minifying 29 // You can pass an invalid identifier to this and unlike its non-minifying
27 // counterpart it will never return the proposedName as the new fresh name. 30 // counterpart it will never return the proposedName as the new fresh name.
28 String getFreshName(String proposedName, 31 String getFreshName(String proposedName,
29 Set<String> usedNames, 32 Set<String> usedNames,
30 Map<String, String> suggestedNames, 33 Map<String, String> suggestedNames,
31 {bool ensureSafe: true}) { 34 {bool ensureSafe: true}) {
32 var freshName; 35 var freshName;
33 var suggestion = suggestedNames[proposedName]; 36 var suggestion = suggestedNames[proposedName];
34 if (suggestion != null && !usedNames.contains(suggestion)) { 37 if (suggestion != null && !usedNames.contains(suggestion)) {
35 freshName = suggestion; 38 freshName = suggestion;
36 } else { 39 } else {
37 freshName = _getUnusedName(proposedName, usedNames); 40 freshName = _getUnusedName(proposedName, usedNames);
38 } 41 }
39 usedNames.add(freshName); 42 usedNames.add(freshName);
40 return freshName; 43 return freshName;
41 } 44 }
42 45
43 String getClosureVariableName(String name, int id) { 46 String getClosureVariableName(String name, int id) {
44 if (id < ALPHABET_CHARACTERS) { 47 if (id < ALPHABET_CHARACTERS) {
45 return new String.fromCharCodes([_letterNumber(id)]); 48 return new String.fromCharCodes([_letterNumber(id)]);
46 } 49 }
47 return "${getMappedInstanceName('closure')}_$id"; 50 return "${getMappedInstanceName('closure')}_$id";
48 } 51 }
49 52
53 // From issue 7554. These should not be used on objects (as instance
54 // variables) because they clash with names from the DOM. However, it is
55 // OK to use them as fields, as we only access fields directly if we know
56 // the receiver type.
57 static const _reservedNativeProperties = const <String>[
58 'Q', 'a', 'b', 'c', 'd', 'e', 'f', 'r', 'x', 'y', 'z',
59 // 2-letter:
60 'ch', 'cx', 'cy', 'db', 'dx', 'dy', 'fr', 'fx', 'fy', 'go', 'id', 'k1',
61 'k2', 'k3', 'k4', 'r1', 'r2', 'rx', 'ry', 'x1', 'x2', 'y1', 'y2',
62 // 3-letter:
63 'add', 'all', 'alt', 'arc', 'CCW', 'cmp', 'dir', 'end', 'get', 'in1',
64 'in2', 'INT', 'key', 'log', 'low', 'm11', 'm12', 'm13', 'm14', 'm21',
65 'm22', 'm23', 'm24', 'm31', 'm32', 'm33', 'm34', 'm41', 'm42', 'm43',
66 'm44', 'max', 'min', 'now', 'ONE', 'put', 'red', 'rel', 'rev', 'RGB',
67 'sdp', 'set', 'src', 'tag', 'top', 'uid', 'uri', 'url', 'URL',
68 // 4-letter:
69 'abbr', 'atob', 'Attr', 'axes', 'axis', 'back', 'BACK', 'beta', 'bias',
70 'Blob', 'blue', 'blur', 'BLUR', 'body', 'BOOL', 'BOTH', 'btoa', 'BYTE',
71 'cite', 'clip', 'code', 'cols', 'cues', 'data', 'DECR', 'DONE', 'face',
72 'file', 'File', 'fill', 'find', 'font', 'form', 'gain', 'hash', 'head',
73 'high', 'hint', 'host', 'href', 'HRTF', 'IDLE', 'INCR', 'info', 'INIT',
74 'isId', 'item', 'KEEP', 'kind', 'knee', 'lang', 'left', 'LESS', 'line',
75 'link', 'list', 'load', 'loop', 'mode', 'name', 'Node', 'None', 'NONE',
76 'only', 'open', 'OPEN', 'ping', 'play', 'port', 'rect', 'Rect', 'refX',
77 'refY', 'RGBA', 'root', 'rows', 'save', 'seed', 'seek', 'self', 'send',
78 'show', 'SINE', 'size', 'span', 'stat', 'step', 'stop', 'tags', 'text',
79 'Text', 'time', 'type', 'view', 'warn', 'wrap', 'ZERO'];
80
50 void reserveBackendNames() { 81 void reserveBackendNames() {
51 // From issue 7554. These should not be used on objects (as instance 82 for (var name in _reservedNativeProperties) {
52 // variables) because they clash with names from the DOM.
53 const reservedNativeProperties = const <String>[
54 'Q', 'a', 'b', 'c', 'd', 'e', 'f', 'r', 'x', 'y', 'z',
55 // 2-letter:
56 'ch', 'cx', 'cy', 'db', 'dx', 'dy', 'fr', 'fx', 'fy', 'go', 'id', 'k1',
57 'k2', 'k3', 'k4', 'r1', 'r2', 'rx', 'ry', 'x1', 'x2', 'y1', 'y2',
58 // 3-letter:
59 'add', 'all', 'alt', 'arc', 'CCW', 'cmp', 'dir', 'end', 'get', 'in1',
60 'in2', 'INT', 'key', 'log', 'low', 'm11', 'm12', 'm13', 'm14', 'm21',
61 'm22', 'm23', 'm24', 'm31', 'm32', 'm33', 'm34', 'm41', 'm42', 'm43',
62 'm44', 'max', 'min', 'now', 'ONE', 'put', 'red', 'rel', 'rev', 'RGB',
63 'sdp', 'set', 'src', 'tag', 'top', 'uid', 'uri', 'url', 'URL',
64 // 4-letter:
65 'abbr', 'atob', 'Attr', 'axes', 'axis', 'back', 'BACK', 'beta', 'bias',
66 'Blob', 'blue', 'blur', 'BLUR', 'body', 'BOOL', 'BOTH', 'btoa', 'BYTE',
67 'cite', 'clip', 'code', 'cols', 'cues', 'data', 'DECR', 'DONE', 'face',
68 'file', 'File', 'fill', 'find', 'font', 'form', 'gain', 'hash', 'head',
69 'high', 'hint', 'host', 'href', 'HRTF', 'IDLE', 'INCR', 'info', 'INIT',
70 'isId', 'item', 'KEEP', 'kind', 'knee', 'lang', 'left', 'LESS', 'line',
71 'link', 'list', 'load', 'loop', 'mode', 'name', 'Node', 'None', 'NONE',
72 'only', 'open', 'OPEN', 'ping', 'play', 'port', 'rect', 'Rect', 'refX',
73 'refY', 'RGBA', 'root', 'rows', 'save', 'seed', 'seek', 'self', 'send',
74 'show', 'SINE', 'size', 'span', 'stat', 'step', 'stop', 'tags', 'text',
75 'Text', 'time', 'type', 'view', 'warn', 'wrap', 'ZERO'];
76
77 for (var name in reservedNativeProperties) {
78 if (name.length < 2) { 83 if (name.length < 2) {
79 instanceNameMap[name] = name; 84 instanceNameMap[name] = name;
80 } 85 }
81 usedInstanceNames.add(name); 86 usedInstanceNames.add(name);
82 // Getter and setter names are autogenerated by prepending 'g' and 's' to 87 // Getter and setter names are autogenerated by prepending 'g' and 's' to
83 // field names. Therefore there are some field names we don't want to 88 // field names. Therefore there are some field names we don't want to
84 // use. It is implicit in the next line that the banned prefix is 89 // use. It is implicit in the next line that the banned prefix is
85 // only one character. 90 // only one character.
86 if (_hasBannedPrefix(name)) usedInstanceNames.add(name.substring(1)); 91 if (_hasBannedPrefix(name)) usedInstanceNames.add(name.substring(1));
87 } 92 }
(...skipping 127 matching lines...) Expand 10 before | Expand all | Expand 10 after
215 return $A + x - 26; 220 return $A + x - 26;
216 } 221 }
217 222
218 int _alphaNumericNumber(int x) { 223 int _alphaNumericNumber(int x) {
219 if (x >= ALPHANUMERIC_CHARACTERS) x %= ALPHANUMERIC_CHARACTERS; 224 if (x >= ALPHANUMERIC_CHARACTERS) x %= ALPHANUMERIC_CHARACTERS;
220 if (x < 26) return $a + x; 225 if (x < 26) return $a + x;
221 if (x < 52) return $A + x - 26; 226 if (x < 52) return $A + x - 26;
222 return $0 + x - 52; 227 return $0 + x - 52;
223 } 228 }
224 229
225 } 230 String instanceFieldPropertyName(Element element) {
231 if (element.hasFixedBackendName) {
232 return element.fixedBackendName;
233 }
234
235 _FieldNamingScope names;
236 if (element is BoxFieldElement) {
237 names = new _FieldNamingScope.forBox(element.box, fieldRegistry);
238 } else {
239 ClassElement cls = element is ClosureFieldElement
240 ? element.closureClass : element.enclosingClass;
241 names = new _FieldNamingScope.forClass(cls, compiler.world,
242 fieldRegistry);
243 }
244
245 // The inheritance scope based naming did not yield a name. For instance,
246 // this could be because the field belongs to a mixin.
247 if (!names.containsField(element)) {
248 return super.instanceFieldPropertyName(element);
249 }
250
251 return names[element];
252 }
253 }
254
255 /**
256 * Encapsulates the global state of field naming.
257 */
258 class _FieldNamingRegistry {
259 final MinifyNamer namer;
260
261 final Map<Entity, _FieldNamingScope> scopes =
262 new Map<Entity, _FieldNamingScope>();
263
264 final Map<Entity, String> globalNames = new Map<Entity, String>();
265
266 int globalCount = 0;
267
268 final List<String> nameStore = new List<String>();
269
270 _FieldNamingRegistry(this.namer);
271
272 String getName(int count) {
273 if (count >= nameStore.length) {
274 // The namer usually does not use certain names as they clash with
275 // existing properties on JS objects (see [_reservedNativeProperties]).
276 // However, some of them are really short and safe to use for fields.
277 // Thus, we shortcut the namer to use those first.
278 if (count < MinifyNamer._reservedNativeProperties.length &&
279 MinifyNamer._reservedNativeProperties[count].length <= 2) {
280 nameStore.add(MinifyNamer._reservedNativeProperties[count]);
281 } else {
282 nameStore.add(namer.getFreshName("field$count",
283 namer.usedInstanceNames, namer.suggestedInstanceNames,
284 ensureSafe: true));
285 }
286 }
287
288 return nameStore[count];
289 }
290 }
291
292 /**
293 * A [_FieldNamingScope] encodes a node in the inheritance tree of the current
294 * class hierarchy. The root node typically is the node corresponding to the
295 * `Object` class. It is used to assign a unique name to each field of a class.
296 * Unique here means unique wrt. all fields along the path back to the root.
297 * This is achieved at construction time via the [_fieldNameCounter] field that counts the
298 * number of fields on the path to the root node that have been encountered so
299 * far.
300 *
301 * Obviously, this only works if no fields are added to a parent node after its
302 * children have added their first field.
303 */
304 class _FieldNamingScope {
305 final _FieldNamingScope superScope;
306 final Entity container;
307 final Map<Element, String> names = new Maplet<Element, String>();
308 final _FieldNamingRegistry registry;
309
310 /// Naming counter used for fields of ordinary classes.
311 int _fieldNameCounter;
312
313 /// The number of fields along the superclass chain that use inheritance
314 /// based naming, including the ones allocated for this scope.
315 int get inheritanceBasedFieldNameCounter => _fieldNameCounter;
316
317 /// The number of locally used fields. Depending on the naming source
318 /// (e.g. inheritance based or globally unique for mixixns) this
319 /// might be different from [inheritanceBasedFieldNameCounter].
320 int get _localFieldNameCounter => _fieldNameCounter;
321 void set _localFieldNameCounter(int val) { _fieldNameCounter = val; }
322
323 factory _FieldNamingScope.forClass(ClassElement cls, ClassWorld world,
324 _FieldNamingRegistry registry) {
325 _FieldNamingScope result = registry.scopes[cls];
326 if (result != null) return result;
327
328 if (world.isUsedAsMixin(cls)) {
329 result = new _MixinFieldNamingScope.mixin(cls, registry);
330 } else {
331 if (cls.superclass == null) {
332 result = new _FieldNamingScope.rootScope(cls, registry);
333 } else {
334 _FieldNamingScope superScope = new _FieldNamingScope.forClass(
335 cls.superclass, world, registry);
336 if (cls.isMixinApplication) {
337 result = new _MixinFieldNamingScope.mixedIn(cls, superScope,
338 registry);
339 } else {
340 result = new _FieldNamingScope.inherit(cls, superScope, registry);
341 }
342 }
343 }
344
345 cls.forEachInstanceField((cls, field) => result.add(field));
346
347 registry.scopes[cls] = result;
348 return result;
349 }
350
351 factory _FieldNamingScope.forBox(Local box, _FieldNamingRegistry registry) {
352 return registry.scopes.putIfAbsent(box,
353 () => new _BoxFieldNamingScope(box, registry));
354 }
355
356 _FieldNamingScope.rootScope(this.container, this.registry)
357 : superScope = null,
358 _fieldNameCounter = 0;
359
360 _FieldNamingScope.inherit(this.container, this.superScope, this.registry) {
361 _fieldNameCounter = superScope.inheritanceBasedFieldNameCounter;
362 }
363
364 /**
365 * Checks whether [name] is already used in the current scope chain.
366 */
367 _isNameUnused(String name) {
368 return !names.values.contains(name) &&
369 ((superScope == null) || superScope._isNameUnused(name));
370 }
371
372 String _nextName() => registry.getName(_localFieldNameCounter++);
373
374 String operator[](Element field) {
375 String name = names[field];
376 if (name == null && superScope != null) return superScope[field];
377 return name;
378 }
379
380 void add(Element field) {
381 if (names.containsKey(field)) return;
382
383 String value = _nextName();
384 assert(invariant(field, _isNameUnused(value)));
385 names[field] = value;
386 }
387
388 bool containsField(Element field) => names.containsKey(field);
389 }
390
391 /**
392 * Field names for mixins have two constraints: They need to be unique in the
393 * hierarchy of each application of a mixin and they need to be the same for
394 * all applications of a mixin. To achieve this, we use global naming for
395 * mixins from the same name pool as fields and add a `$` at the end to ensure
396 * they do not collide with normal field names. The `$` sign is typically used
397 * as a separator between method names and argument counts and does not appear
398 * in generated names themselves.
399 */
400 class _MixinFieldNamingScope extends _FieldNamingScope {
401 int get _localFieldNameCounter => registry.globalCount;
402 void set _localFieldNameCounter(int val) { registry.globalCount = val; }
403
404 Map<Element, String> get names => registry.globalNames;
405
406 _MixinFieldNamingScope.mixin(ClassElement cls, _FieldNamingRegistry registry)
407 : super.rootScope(cls, registry);
408
409 _MixinFieldNamingScope.mixedIn(MixinApplicationElement container,
410 _FieldNamingScope superScope, _FieldNamingRegistry registry)
411 : super.inherit(container, superScope, registry);
412
413 String _nextName() {
414 var proposed = super._nextName();
415 return proposed + r'$';
416 }
417 }
418
419 /**
420 * [BoxFieldElement] fields work differently in that they do not belong to an
421 * actual class but an anonymous box associated to a [Local]. As there is no
422 * inheritance chain, we do not need to compute fields a priori but can assign
423 * names on the fly.
424 */
425 class _BoxFieldNamingScope extends _FieldNamingScope {
426 _BoxFieldNamingScope(Local box, _FieldNamingRegistry registry) :
427 super.rootScope(box, registry);
428
429 bool containsField(_) => true;
430
431 String operator[](Element field) {
432 if (!names.containsKey(field)) add(field);
433 return names[field];
434 }
435 }
OLDNEW
« no previous file with comments | « no previous file | tests/compiler/dart2js_extra/many_fields_test.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698