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

Side by Side Diff: lib/codegen/generator.dart

Issue 1016913002: pkg/smoke: support latest analyzer version and formatted code (Closed) Base URL: https://github.com/dart-lang/smoke@master
Patch Set: updates Created 5 years, 9 months 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
« no previous file with comments | « CHANGELOG.md ('k') | lib/codegen/recorder.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) 2014, the Dart project authors. Please see the AUTHORS file 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 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 /// Library to generate code that can initialize the `StaticConfiguration` in 5 /// Library to generate code that can initialize the `StaticConfiguration` in
6 /// `package:smoke/static.dart`. 6 /// `package:smoke/static.dart`.
7 /// 7 ///
8 /// This library doesn't have any specific logic to extract information from 8 /// This library doesn't have any specific logic to extract information from
9 /// Dart source code. To extract code using the analyzer, take a look at the 9 /// Dart source code. To extract code using the analyzer, take a look at the
10 /// `smoke.codegen.recorder` library. 10 /// `smoke.codegen.recorder` library.
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
46 /// Static methods used on each type. 46 /// Static methods used on each type.
47 final Map<TypeIdentifier, Set<String>> _staticMethods = new SplayTreeMap(); 47 final Map<TypeIdentifier, Set<String>> _staticMethods = new SplayTreeMap();
48 48
49 /// Names that are used both as strings and symbols. 49 /// Names that are used both as strings and symbols.
50 final Set<String> _names = new SplayTreeSet(); 50 final Set<String> _names = new SplayTreeSet();
51 51
52 /// Prefixes associated with imported libraries. 52 /// Prefixes associated with imported libraries.
53 final Map<String, String> _libraryPrefix = {}; 53 final Map<String, String> _libraryPrefix = {};
54 54
55 /// Register that [name] is used as a getter in the code. 55 /// Register that [name] is used as a getter in the code.
56 void addGetter(String name) { _getters.add(name); } 56 void addGetter(String name) {
57 _getters.add(name);
58 }
57 59
58 /// Register that [name] is used as a setter in the code. 60 /// Register that [name] is used as a setter in the code.
59 void addSetter(String name) { _setters.add(name); } 61 void addSetter(String name) {
62 _setters.add(name);
63 }
60 64
61 /// Register that [name] might be needed as a symbol. 65 /// Register that [name] might be needed as a symbol.
62 void addSymbol(String name) { _names.add(name); } 66 void addSymbol(String name) {
67 _names.add(name);
68 }
63 69
64 /// Register that `cls.name` is used as a static method in the code. 70 /// Register that `cls.name` is used as a static method in the code.
65 void addStaticMethod(TypeIdentifier cls, String name) { 71 void addStaticMethod(TypeIdentifier cls, String name) {
66 var methods = _staticMethods.putIfAbsent(cls, 72 var methods =
67 () => new SplayTreeSet<String>()); 73 _staticMethods.putIfAbsent(cls, () => new SplayTreeSet<String>());
68 _addLibrary(cls.importUrl); 74 _addLibrary(cls.importUrl);
69 methods.add(name); 75 methods.add(name);
70 } 76 }
71 77
72 int _mixins = 0; 78 int _mixins = 0;
73 79
74 /// Creates a new type to represent a mixin. Use [comment] to help users 80 /// Creates a new type to represent a mixin. Use [comment] to help users
75 /// figure out what mixin is being represented. 81 /// figure out what mixin is being represented.
76 TypeIdentifier createMixinType([String comment = '']) => 82 TypeIdentifier createMixinType([String comment = '']) =>
77 new TypeIdentifier(null, '_M${_mixins++}', comment); 83 new TypeIdentifier(null, '_M${_mixins++}', comment);
(...skipping 17 matching lines...) Expand all
95 void addDeclaration(TypeIdentifier cls, String name, TypeIdentifier type, 101 void addDeclaration(TypeIdentifier cls, String name, TypeIdentifier type,
96 {bool isField: false, bool isProperty: false, bool isMethod: false, 102 {bool isField: false, bool isProperty: false, bool isMethod: false,
97 bool isFinal: false, bool isStatic: false, 103 bool isFinal: false, bool isStatic: false,
98 List<ConstExpression> annotations: const []}) { 104 List<ConstExpression> annotations: const []}) {
99 final count = (isField ? 1 : 0) + (isProperty ? 1 : 0) + (isMethod ? 1 : 0); 105 final count = (isField ? 1 : 0) + (isProperty ? 1 : 0) + (isMethod ? 1 : 0);
100 if (count != 1) { 106 if (count != 1) {
101 throw new ArgumentError('Declaration must be one (and only one) of the ' 107 throw new ArgumentError('Declaration must be one (and only one) of the '
102 'following: a field, a property, or a method.'); 108 'following: a field, a property, or a method.');
103 } 109 }
104 var kind = isField ? 'FIELD' : isProperty ? 'PROPERTY' : 'METHOD'; 110 var kind = isField ? 'FIELD' : isProperty ? 'PROPERTY' : 'METHOD';
105 _declarations.putIfAbsent(cls, 111 _declarations.putIfAbsent(
106 () => new SplayTreeMap<String, _DeclarationCode>()); 112 cls, () => new SplayTreeMap<String, _DeclarationCode>());
107 _addLibrary(cls.importUrl); 113 _addLibrary(cls.importUrl);
108 var map = _declarations[cls]; 114 var map = _declarations[cls];
109 115
110 for (var exp in annotations) { 116 for (var exp in annotations) {
111 for (var lib in exp.librariesUsed) { 117 for (var lib in exp.librariesUsed) {
112 _addLibrary(lib); 118 _addLibrary(lib);
113 } 119 }
114 } 120 }
115 121
116 _addLibrary(type.importUrl); 122 _addLibrary(type.importUrl);
117 var decl = new _DeclarationCode(name, type, kind, isFinal, isStatic, 123 var decl =
118 annotations); 124 new _DeclarationCode(name, type, kind, isFinal, isStatic, annotations);
119 if (map.containsKey(name) && map[name] != decl) { 125 if (map.containsKey(name) && map[name] != decl) {
120 throw new StateError('$type.$name already has a different declaration' 126 throw new StateError('$type.$name already has a different declaration'
121 ' (${map[name]} instead of $decl).'); 127 ' (${map[name]} instead of $decl).');
122 } 128 }
123 map[name] = decl; 129 map[name] = decl;
124 } 130 }
125 131
126 /// Register that we might try to read declarations of [type], even if no 132 /// Register that we might try to read declarations of [type], even if no
127 /// declaration exists. This informs the smoke system that querying for a 133 /// declaration exists. This informs the smoke system that querying for a
128 /// member in this class might be intentional and not an error. 134 /// member in this class might be intentional and not an error.
129 void addEmptyDeclaration(TypeIdentifier type) { 135 void addEmptyDeclaration(TypeIdentifier type) {
130 _addLibrary(type.importUrl); 136 _addLibrary(type.importUrl);
131 _declarations.putIfAbsent(type, 137 _declarations.putIfAbsent(
132 () => new SplayTreeMap<String, _DeclarationCode>()); 138 type, () => new SplayTreeMap<String, _DeclarationCode>());
133 } 139 }
134 140
135 /// Writes to [buffer] a line for each import that is needed by the generated 141 /// Writes to [buffer] a line for each import that is needed by the generated
136 /// code. The code added by [writeStaticConfiguration] depends on these 142 /// code. The code added by [writeStaticConfiguration] depends on these
137 /// imports. 143 /// imports.
138 void writeImports(StringBuffer buffer) { 144 void writeImports(StringBuffer buffer) {
139 DEFAULT_IMPORTS.forEach((i) => buffer.writeln(i)); 145 DEFAULT_IMPORTS.forEach((i) => buffer.writeln(i));
140 _libraryPrefix.forEach((url, prefix) { 146 _libraryPrefix.forEach((url, prefix) {
141 buffer.writeln("import '$url' as $prefix;"); 147 buffer.writeln("import '$url' as $prefix;");
142 }); 148 });
143 } 149 }
144 150
145 /// Writes to [buffer] top-level declarations that are used by the code 151 /// Writes to [buffer] top-level declarations that are used by the code
146 /// generated in [writeStaticConfiguration]. These are typically declarations 152 /// generated in [writeStaticConfiguration]. These are typically declarations
147 /// of empty classes that are then used as placeholders for mixin 153 /// of empty classes that are then used as placeholders for mixin
148 /// superclasses. 154 /// superclasses.
149 void writeTopLevelDeclarations(StringBuffer buffer) { 155 void writeTopLevelDeclarations(StringBuffer buffer) {
150 var types = new Set() 156 var types = new Set()
151 ..addAll(_parents.keys) 157 ..addAll(_parents.keys)
152 ..addAll(_parents.values) 158 ..addAll(_parents.values)
153 ..addAll(_declarations.keys) 159 ..addAll(_declarations.keys)
154 ..addAll(_declarations.values.expand( 160 ..addAll(_declarations.values.expand((m) => m.values.map((d) => d.type)))
155 (m) => m.values.map((d) => d.type))) 161 ..removeWhere((t) => t.importUrl != null);
156 ..removeWhere((t) => t.importUrl != null);
157 for (var type in types) { 162 for (var type in types) {
158 buffer.write('abstract class ${type.name} {}'); 163 buffer.write('abstract class ${type.name} {}');
159 if (type.comment != null) buffer.write(' // ${type.comment}'); 164 if (type.comment != null) buffer.write(' // ${type.comment}');
160 buffer.writeln(); 165 buffer.writeln();
161 } 166 }
162 } 167 }
163 168
164 /// Appends to [buffer] code that will create smoke's static configuration. 169 /// Appends to [buffer] code that will create smoke's static configuration.
165 /// For example, the code might be of the form: 170 /// For example, the code might be of the form:
166 /// 171 ///
(...skipping 16 matching lines...) Expand all
183 /// declarations from [writeTopLevelDeclarations] are included in the same 188 /// declarations from [writeTopLevelDeclarations] are included in the same
184 /// library where this code will live. 189 /// library where this code will live.
185 void writeStaticConfiguration(StringBuffer buffer, [int indent = 2]) { 190 void writeStaticConfiguration(StringBuffer buffer, [int indent = 2]) {
186 final spaces = ' ' * (indent + 4); 191 final spaces = ' ' * (indent + 4);
187 var args = {}; 192 var args = {};
188 193
189 if (_getters.isNotEmpty) { 194 if (_getters.isNotEmpty) {
190 args['getters'] = _getters.map((n) => '${_symbol(n)}: (o) => o.$n'); 195 args['getters'] = _getters.map((n) => '${_symbol(n)}: (o) => o.$n');
191 } 196 }
192 if (_setters.isNotEmpty) { 197 if (_setters.isNotEmpty) {
193 args['setters'] = _setters.map( 198 args['setters'] =
194 (n) => '${_symbol(n)}: (o, v) { o.$n = v; }'); 199 _setters.map((n) => '${_symbol(n)}: (o, v) { o.$n = v; }');
195 } 200 }
196 201
197 if (_parents.isNotEmpty) { 202 if (_parents.isNotEmpty) {
198 var parentsMap = []; 203 var parentsMap = [];
199 _parents.forEach((child, parent) { 204 _parents.forEach((child, parent) {
200 var parent = _parents[child]; 205 var parent = _parents[child];
201 parentsMap.add('${child.asCode(_libraryPrefix)}: ' 206 parentsMap.add('${child.asCode(_libraryPrefix)}: '
202 '${parent.asCode(_libraryPrefix)}'); 207 '${parent.asCode(_libraryPrefix)}');
203 }); 208 });
204 args['parents'] = parentsMap; 209 args['parents'] = parentsMap;
205 } 210 }
206 211
207 if (_declarations.isNotEmpty) { 212 if (_declarations.isNotEmpty) {
208 var declarations = []; 213 var declarations = [];
209 _declarations.forEach((type, members) { 214 _declarations.forEach((type, members) {
210 final sb = new StringBuffer() 215 final sb = new StringBuffer()
211 ..write(type.asCode(_libraryPrefix)) 216 ..write(type.asCode(_libraryPrefix))
212 ..write(': '); 217 ..write(': ');
213 if (members.isEmpty) { 218 if (members.isEmpty) {
214 sb.write('{}'); 219 sb.write('{}');
215 } else { 220 } else {
216 sb.write('{\n'); 221 sb.write('{\n');
217 members.forEach((name, decl) { 222 members.forEach((name, decl) {
218 var decl = members[name].asCode(_libraryPrefix); 223 var decl = members[name].asCode(_libraryPrefix);
219 sb.write('${spaces} ${_symbol(name)}: $decl,\n'); 224 sb.write('${spaces} ${_symbol(name)}: $decl,\n');
220 }); 225 });
221 sb.write('${spaces} }'); 226 sb.write('${spaces} }');
222 } 227 }
223 declarations.add(sb.toString()); 228 declarations.add(sb.toString());
224 }); 229 });
225 args['declarations'] = declarations; 230 args['declarations'] = declarations;
226 } 231 }
227 232
228 if (_staticMethods.isNotEmpty) { 233 if (_staticMethods.isNotEmpty) {
229 var methods = []; 234 var methods = [];
230 _staticMethods.forEach((type, members) { 235 _staticMethods.forEach((type, members) {
231 var className = type.asCode(_libraryPrefix); 236 var className = type.asCode(_libraryPrefix);
232 final sb = new StringBuffer() 237 final sb = new StringBuffer()
233 ..write(className) 238 ..write(className)
234 ..write(': '); 239 ..write(': ');
235 if (members.isEmpty) { 240 if (members.isEmpty) {
236 sb.write('{}'); 241 sb.write('{}');
237 } else { 242 } else {
238 sb.write('{\n'); 243 sb.write('{\n');
239 for (var name in members) { 244 for (var name in members) {
240 sb.write('${spaces} ${_symbol(name)}: $className.$name,\n'); 245 sb.write('${spaces} ${_symbol(name)}: $className.$name,\n');
241 } 246 }
242 sb.write('${spaces} }'); 247 sb.write('${spaces} }');
243 } 248 }
244 methods.add(sb.toString()); 249 methods.add(sb.toString());
245 }); 250 });
246 args['staticMethods'] = methods; 251 args['staticMethods'] = methods;
247 } 252 }
248 253
249 if (_names.isNotEmpty) { 254 if (_names.isNotEmpty) {
250 args['names'] = _names.map((n) => "${_symbol(n)}: r'$n'"); 255 args['names'] = _names.map((n) => "${_symbol(n)}: r'$n'");
251 } 256 }
252 257
253 buffer..writeln('new StaticConfiguration(') 258 buffer
254 ..write('${spaces}checkedMode: false'); 259 ..writeln('new StaticConfiguration(')
260 ..write('${spaces}checkedMode: false');
255 261
256 args.forEach((name, mapContents) { 262 args.forEach((name, mapContents) {
257 buffer.writeln(','); 263 buffer.writeln(',');
258 // TODO(sigmund): use const map when Type can be keys (dartbug.com/17123) 264 // TODO(sigmund): use const map when Type can be keys (dartbug.com/17123)
259 buffer.writeln('${spaces}$name: {'); 265 buffer.writeln('${spaces}$name: {');
260 for (var entry in mapContents) { 266 for (var entry in mapContents) {
261 buffer.writeln('${spaces} $entry,'); 267 buffer.writeln('${spaces} $entry,');
262 } 268 }
263 buffer.write('${spaces}}'); 269 buffer.write('${spaces}}');
264 }); 270 });
(...skipping 13 matching lines...) Expand all
278 final TypeIdentifier type; 284 final TypeIdentifier type;
279 final String kind; 285 final String kind;
280 final bool isFinal; 286 final bool isFinal;
281 final bool isStatic; 287 final bool isStatic;
282 final List<ConstExpression> annotations; 288 final List<ConstExpression> annotations;
283 289
284 _DeclarationCode(this.name, this.type, this.kind, this.isFinal, this.isStatic, 290 _DeclarationCode(this.name, this.type, this.kind, this.isFinal, this.isStatic,
285 this.annotations); 291 this.annotations);
286 292
287 List<String> get librariesUsed => [] 293 List<String> get librariesUsed => []
288 ..addAll(type.librariesUsed) 294 ..addAll(type.librariesUsed)
289 ..addAll(annotations.expand((a) => a.librariesUsed)); 295 ..addAll(annotations.expand((a) => a.librariesUsed));
290 296
291 String asCode(Map<String, String> libraryPrefixes) { 297 String asCode(Map<String, String> libraryPrefixes) {
292 var sb = new StringBuffer(); 298 var sb = new StringBuffer();
293 sb.write('const Declaration(${_symbol(name)}, ' 299 sb.write('const Declaration(${_symbol(name)}, '
294 '${type.asCode(libraryPrefixes)}'); 300 '${type.asCode(libraryPrefixes)}');
295 if (kind != 'FIELD') sb.write(', kind: $kind'); 301 if (kind != 'FIELD') sb.write(', kind: $kind');
296 if (isFinal) sb.write(', isFinal: true'); 302 if (isFinal) sb.write(', isFinal: true');
297 if (isStatic) sb.write(', isStatic: true'); 303 if (isStatic) sb.write(', isStatic: true');
298 if (annotations != null && annotations.isNotEmpty) { 304 if (annotations != null && annotations.isNotEmpty) {
299 sb.write(', annotations: const ['); 305 sb.write(', annotations: const [');
300 bool first = true; 306 bool first = true;
301 for (var e in annotations) { 307 for (var e in annotations) {
302 if (!first) sb.write(', '); 308 if (!first) sb.write(', ');
303 first = false; 309 first = false;
304 sb.write(e.asCode(libraryPrefixes)); 310 sb.write(e.asCode(libraryPrefixes));
305 } 311 }
306 sb.write(']'); 312 sb.write(']');
307 } 313 }
308 sb.write(')'); 314 sb.write(')');
309 return sb.toString(); 315 return sb.toString();
310 } 316 }
311 317
312 String toString() => 318 String toString() =>
313 '(decl: $type.$name - $kind, $isFinal, $isStatic, $annotations)'; 319 '(decl: $type.$name - $kind, $isFinal, $isStatic, $annotations)';
314 operator== (other) => other is _DeclarationCode && name == other.name && 320 operator ==(other) => other is _DeclarationCode &&
315 type == other.type && kind == other.kind && isFinal == other.isFinal && 321 name == other.name &&
322 type == other.type &&
323 kind == other.kind &&
324 isFinal == other.isFinal &&
316 isStatic == other.isStatic && 325 isStatic == other.isStatic &&
317 compareLists(annotations, other.annotations); 326 compareLists(annotations, other.annotations);
318 int get hashCode => name.hashCode + (31 * type.hashCode); 327 int get hashCode => name.hashCode + (31 * type.hashCode);
319 } 328 }
320 329
321 /// A constant expression that can be used as an annotation. 330 /// A constant expression that can be used as an annotation.
322 abstract class ConstExpression { 331 abstract class ConstExpression {
323 332
324 /// Returns the library URLs that needs to be imported for this 333 /// Returns the library URLs that needs to be imported for this
325 /// [ConstExpression] to be a valid annotation. 334 /// [ConstExpression] to be a valid annotation.
(...skipping 12 matching lines...) Expand all
338 var value = string.replaceAll(r'\', r'\\').replaceAll(r"'", r"\'"); 347 var value = string.replaceAll(r'\', r'\\').replaceAll(r"'", r"\'");
339 return new CodeAsConstExpression("'$value'"); 348 return new CodeAsConstExpression("'$value'");
340 } 349 }
341 350
342 /// Create an expression of the form `prefix.variable_name`. 351 /// Create an expression of the form `prefix.variable_name`.
343 factory ConstExpression.identifier(String importUrl, String name) => 352 factory ConstExpression.identifier(String importUrl, String name) =>
344 new TopLevelIdentifier(importUrl, name); 353 new TopLevelIdentifier(importUrl, name);
345 354
346 /// Create an expression of the form `prefix.Constructor(v1, v2, p3: v3)`. 355 /// Create an expression of the form `prefix.Constructor(v1, v2, p3: v3)`.
347 factory ConstExpression.constructor(String importUrl, String name, 356 factory ConstExpression.constructor(String importUrl, String name,
348 List<ConstExpression> positionalArgs, 357 List<ConstExpression> positionalArgs,
349 Map<String, ConstExpression> namedArgs) => 358 Map<String, ConstExpression> namedArgs) =>
350 new ConstructorExpression(importUrl, name, positionalArgs, namedArgs); 359 new ConstructorExpression(importUrl, name, positionalArgs, namedArgs);
351 } 360 }
352 361
353 /// A constant expression written as a String. Used when the code is self 362 /// A constant expression written as a String. Used when the code is self
354 /// contained and it doesn't depend on any imported libraries. 363 /// contained and it doesn't depend on any imported libraries.
355 class CodeAsConstExpression extends ConstExpression { 364 class CodeAsConstExpression extends ConstExpression {
356 String code; 365 String code;
357 List<String> get librariesUsed => const []; 366 List<String> get librariesUsed => const [];
358 367
359 CodeAsConstExpression(this.code); 368 CodeAsConstExpression(this.code);
360 369
361 String asCode(Map<String, String> libraryPrefixes) => code; 370 String asCode(Map<String, String> libraryPrefixes) => code;
362 371
363 String toString() => '(code: $code)'; 372 String toString() => '(code: $code)';
364 operator== (other) => other is CodeAsConstExpression && code == other.code; 373 operator ==(other) => other is CodeAsConstExpression && code == other.code;
365 int get hashCode => code.hashCode; 374 int get hashCode => code.hashCode;
366 } 375 }
367 376
368 /// Describes a reference to some symbol that is exported from a library. This 377 /// Describes a reference to some symbol that is exported from a library. This
369 /// is typically used to refer to a type or a top-level variable from that 378 /// is typically used to refer to a type or a top-level variable from that
370 /// library. 379 /// library.
371 class TopLevelIdentifier extends ConstExpression { 380 class TopLevelIdentifier extends ConstExpression {
372 final String importUrl; 381 final String importUrl;
373 final String name; 382 final String name;
374 TopLevelIdentifier(this.importUrl, this.name); 383 TopLevelIdentifier(this.importUrl, this.name);
375 384
376 List<String> get librariesUsed => [importUrl]; 385 List<String> get librariesUsed => [importUrl];
377 String asCode(Map<String, String> libraryPrefixes) { 386 String asCode(Map<String, String> libraryPrefixes) {
378 if (importUrl == 'dart:core' || importUrl == null) return name; 387 if (importUrl == 'dart:core' || importUrl == null) return name;
379 return '${libraryPrefixes[importUrl]}.$name'; 388 return '${libraryPrefixes[importUrl]}.$name';
380 } 389 }
381 390
382 String toString() => '(identifier: $importUrl, $name)'; 391 String toString() => '(identifier: $importUrl, $name)';
383 operator== (other) => other is TopLevelIdentifier && name == other.name 392 operator ==(other) => other is TopLevelIdentifier &&
384 && importUrl == other.importUrl; 393 name == other.name &&
394 importUrl == other.importUrl;
385 int get hashCode => 31 * importUrl.hashCode + name.hashCode; 395 int get hashCode => 31 * importUrl.hashCode + name.hashCode;
386 } 396 }
387 397
388 /// Represents an expression that invokes a const constructor. 398 /// Represents an expression that invokes a const constructor.
389 class ConstructorExpression extends ConstExpression { 399 class ConstructorExpression extends ConstExpression {
390 final String importUrl; 400 final String importUrl;
391 final String name; 401 final String name;
392 final List<ConstExpression> positionalArgs; 402 final List<ConstExpression> positionalArgs;
393 final Map<String, ConstExpression> namedArgs; 403 final Map<String, ConstExpression> namedArgs;
394 ConstructorExpression(this.importUrl, this.name, this.positionalArgs, 404 ConstructorExpression(
395 this.namedArgs); 405 this.importUrl, this.name, this.positionalArgs, this.namedArgs);
396 406
397 List<String> get librariesUsed => [importUrl] 407 List<String> get librariesUsed => [importUrl]
398 ..addAll(positionalArgs.expand((e) => e.librariesUsed)) 408 ..addAll(positionalArgs.expand((e) => e.librariesUsed))
399 ..addAll(namedArgs.values.expand((e) => e.librariesUsed)); 409 ..addAll(namedArgs.values.expand((e) => e.librariesUsed));
400 410
401 String asCode(Map<String, String> libraryPrefixes) { 411 String asCode(Map<String, String> libraryPrefixes) {
402 var sb = new StringBuffer(); 412 var sb = new StringBuffer();
403 sb.write('const '); 413 sb.write('const ');
404 if (importUrl != 'dart:core' && importUrl != null) { 414 if (importUrl != 'dart:core' && importUrl != null) {
405 sb.write('${libraryPrefixes[importUrl]}.'); 415 sb.write('${libraryPrefixes[importUrl]}.');
406 } 416 }
407 sb.write('$name('); 417 sb.write('$name(');
408 bool first = true; 418 bool first = true;
409 for (var e in positionalArgs) { 419 for (var e in positionalArgs) {
410 if (!first) sb.write(', '); 420 if (!first) sb.write(', ');
411 first = false; 421 first = false;
412 sb.write(e.asCode(libraryPrefixes)); 422 sb.write(e.asCode(libraryPrefixes));
413 } 423 }
414 namedArgs.forEach((name, value) { 424 namedArgs.forEach((name, value) {
415 if (!first) sb.write(', '); 425 if (!first) sb.write(', ');
416 first = false; 426 first = false;
417 sb.write('$name: '); 427 sb.write('$name: ');
418 sb.write(value.asCode(libraryPrefixes)); 428 sb.write(value.asCode(libraryPrefixes));
419 }); 429 });
420 sb.write(')'); 430 sb.write(')');
421 return sb.toString(); 431 return sb.toString();
422 } 432 }
423 433
424 String toString() => '(ctor: $importUrl, $name, $positionalArgs, $namedArgs)'; 434 String toString() => '(ctor: $importUrl, $name, $positionalArgs, $namedArgs)';
425 operator== (other) => other is ConstructorExpression && name == other.name 435 operator ==(other) => other is ConstructorExpression &&
426 && importUrl == other.importUrl && 436 name == other.name &&
437 importUrl == other.importUrl &&
427 compareLists(positionalArgs, other.positionalArgs) && 438 compareLists(positionalArgs, other.positionalArgs) &&
428 compareMaps(namedArgs, other.namedArgs); 439 compareMaps(namedArgs, other.namedArgs);
429 int get hashCode => 31 * importUrl.hashCode + name.hashCode; 440 int get hashCode => 31 * importUrl.hashCode + name.hashCode;
430 } 441 }
431 442
432
433 /// Describes a type identifier, with the library URL where the type is defined. 443 /// Describes a type identifier, with the library URL where the type is defined.
434 // TODO(sigmund): consider adding support for imprecise TypeIdentifiers, which 444 // TODO(sigmund): consider adding support for imprecise TypeIdentifiers, which
435 // may be used by tools that want to generate code without using the analyzer 445 // may be used by tools that want to generate code without using the analyzer
436 // (they can syntactically tell the type comes from one of N imports). 446 // (they can syntactically tell the type comes from one of N imports).
437 class TypeIdentifier extends TopLevelIdentifier 447 class TypeIdentifier extends TopLevelIdentifier
438 implements Comparable<TypeIdentifier> { 448 implements Comparable<TypeIdentifier> {
439 final String comment; 449 final String comment;
440 TypeIdentifier(importUrl, typeName, [this.comment]) 450 TypeIdentifier(importUrl, typeName, [this.comment])
441 : super(importUrl, typeName); 451 : super(importUrl, typeName);
442 452
443 // We implement [Comparable] to sort out entries in the generated code. 453 // We implement [Comparable] to sort out entries in the generated code.
444 int compareTo(TypeIdentifier other) { 454 int compareTo(TypeIdentifier other) {
445 if (importUrl == null && other.importUrl != null) return 1; 455 if (importUrl == null && other.importUrl != null) return 1;
446 if (importUrl != null && other.importUrl == null) return -1; 456 if (importUrl != null && other.importUrl == null) return -1;
447 var c1 = importUrl == null ? 0 : importUrl.compareTo(other.importUrl); 457 var c1 = importUrl == null ? 0 : importUrl.compareTo(other.importUrl);
448 return c1 != 0 ? c1 : name.compareTo(other.name); 458 return c1 != 0 ? c1 : name.compareTo(other.name);
449 } 459 }
450 460
451 String toString() => '(type-identifier: $importUrl, $name, $comment)'; 461 String toString() => '(type-identifier: $importUrl, $name, $comment)';
452 bool operator ==(other) => other is TypeIdentifier && 462 bool operator ==(other) => other is TypeIdentifier &&
453 importUrl == other.importUrl && name == other.name && 463 importUrl == other.importUrl &&
464 name == other.name &&
454 comment == other.comment; 465 comment == other.comment;
455 int get hashCode => super.hashCode; 466 int get hashCode => super.hashCode;
456 } 467 }
457 468
458 /// Default set of imports added by [SmokeCodeGenerator]. 469 /// Default set of imports added by [SmokeCodeGenerator].
459 const DEFAULT_IMPORTS = const [ 470 const DEFAULT_IMPORTS = const [
460 "import 'package:smoke/smoke.dart' show Declaration, PROPERTY, METHOD;", 471 "import 'package:smoke/smoke.dart' show Declaration, PROPERTY, METHOD;",
461 "import 'package:smoke/static.dart' show " 472 "import 'package:smoke/static.dart' show "
462 "useGeneratedCode, StaticConfiguration;", 473 "useGeneratedCode, StaticConfiguration;",
463 ]; 474 ];
464 475
465 _symbol(String name) { 476 _symbol(String name) {
466 if (!_publicSymbolPattern.hasMatch(name)) { 477 if (!_publicSymbolPattern.hasMatch(name)) {
467 throw new StateError('invalid symbol name: "$name"'); 478 throw new StateError('invalid symbol name: "$name"');
468 } 479 }
469 return _literalSymbolPattern.hasMatch(name) 480 return _literalSymbolPattern.hasMatch(name)
470 ? '#$name' : "const Symbol('$name')"; 481 ? '#$name'
482 : "const Symbol('$name')";
471 } 483 }
472 484
473 // TODO(sigmund): is this included in some library we can import? I derived the 485 // TODO(sigmund): is this included in some library we can import? I derived the
474 // definitions below from sdk/lib/internal/symbol.dart. 486 // definitions below from sdk/lib/internal/symbol.dart.
475 487
476 /// Reserved words in Dart. 488 /// Reserved words in Dart.
477 const String _reservedWordRE = 489 const String _reservedWordRE =
478 r'(?:assert|break|c(?:a(?:se|tch)|lass|on(?:st|tinue))|d(?:efault|o)|' 490 r'(?:assert|break|c(?:a(?:se|tch)|lass|on(?:st|tinue))|d(?:efault|o)|'
479 r'e(?:lse|num|xtends)|f(?:alse|inal(?:ly)?|or)|i[fns]|n(?:ew|ull)|' 491 r'e(?:lse|num|xtends)|f(?:alse|inal(?:ly)?|or)|i[fns]|n(?:ew|ull)|'
480 r'ret(?:hrow|urn)|s(?:uper|witch)|t(?:h(?:is|row)|r(?:ue|y))|' 492 r'ret(?:hrow|urn)|s(?:uper|witch)|t(?:h(?:is|row)|r(?:ue|y))|'
481 r'v(?:ar|oid)|w(?:hile|ith))'; 493 r'v(?:ar|oid)|w(?:hile|ith))';
482 494
483 /// Public identifier: a valid identifier (not a reserved word) that doesn't 495 /// Public identifier: a valid identifier (not a reserved word) that doesn't
484 /// start with '_'. 496 /// start with '_'.
485 const String _publicIdentifierRE = 497 const String _publicIdentifierRE =
486 r'(?!' '$_reservedWordRE' r'\b(?!\$))[a-zA-Z$][\w$]*'; 498 r'(?!' '$_reservedWordRE' r'\b(?!\$))[a-zA-Z$][\w$]*';
487 499
488 /// Pattern that matches operators only. 500 /// Pattern that matches operators only.
489 final RegExp _literalSymbolPattern = new RegExp( 501 final RegExp _literalSymbolPattern =
490 '^(?:$_publicIdentifierRE(?:\$|[.](?!\$)))+?\$'); 502 new RegExp('^(?:$_publicIdentifierRE(?:\$|[.](?!\$)))+?\$');
491 503
492 /// Operator names allowed as symbols. The name of the oeprators is the same as 504 /// Operator names allowed as symbols. The name of the oeprators is the same as
493 /// the operator itself except for unary minus, where the name is "unary-". 505 /// the operator itself except for unary minus, where the name is "unary-".
494 const String _operatorRE = 506 const String _operatorRE =
495 r'(?:[\-+*/%&|^]|\[\]=?|==|~/?|<[<=]?|>[>=]?|unary-)'; 507 r'(?:[\-+*/%&|^]|\[\]=?|==|~/?|<[<=]?|>[>=]?|unary-)';
496 508
497 /// Pattern that matches public symbols. 509 /// Pattern that matches public symbols.
498 final RegExp _publicSymbolPattern = new RegExp( 510 final RegExp _publicSymbolPattern = new RegExp(
499 '^(?:$_operatorRE\$|$_publicIdentifierRE(?:=?\$|[.](?!\$)))+?\$'); 511 '^(?:$_operatorRE\$|$_publicIdentifierRE(?:=?\$|[.](?!\$)))+?\$');
OLDNEW
« no previous file with comments | « CHANGELOG.md ('k') | lib/codegen/recorder.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698