Chromium Code Reviews| 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 to generate code that can initialize the `StaticConfiguration` in | |
| 6 /// `package:smoke/static.dart`. | |
| 7 /// | |
| 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 | |
| 10 /// `smoke.codegen.recorder` library. | |
| 11 library smoke.codegen.generator; | |
| 12 | |
| 13 // We use SplayTreeSet/Map to keep generated code sorted. | |
|
Jennifer Messerly
2014/03/17 22:38:48
maybe move this comment down to where they're used
Siggi Cherem (dart-lang)
2014/03/18 01:52:29
Done. I moved it down to the first occurrence (the
| |
| 14 import 'dart:collection' show SplayTreeMap, SplayTreeSet; | |
| 15 | |
| 16 /// Collects the necessary information and generates code to initialize a | |
| 17 /// `StaticConfiguration`. After setting up the generator by calling | |
| 18 /// [addGetter], [addSetter], [addSymbol], and [addDeclaration], you can | |
| 19 /// retrieve the generated code using the following three methods: | |
| 20 /// | |
| 21 /// * [generateImports] returns a list of imports directives, | |
| 22 /// * [generateTopLevelDeclarations] returns additional declarations used to | |
| 23 /// represent mixin classes by name in the generated code. | |
| 24 /// * [generateInitCall] returns the actual code that allocates the static | |
| 25 /// configuration. | |
| 26 /// | |
| 27 /// You'd need to include all three in your generated code, since the | |
| 28 /// initialization code refers to symbols that are only available from the | |
| 29 /// generated imports or the generated top-level declarations. | |
| 30 class SmokeCodeGenerator { | |
| 31 /// Names used as getters via smoke. | |
| 32 Set<String> _getters = new SplayTreeSet(); | |
| 33 | |
| 34 /// Names used as setters via smoke. | |
| 35 Set<String> _setters = new SplayTreeSet(); | |
| 36 | |
| 37 /// Subclass relations needed to run smoke queries. | |
| 38 Map<TypeIdentifier, TypeIdentifier> _parents = | |
| 39 new SplayTreeMap<TypeIdentifier, TypeIdentifier>(); | |
| 40 | |
| 41 /// Declarations requested via `smoke.getDeclaration or `smoke.query`. | |
| 42 Map<TypeIdentifier, Map<String, _DeclarationCode>> _declarations = | |
| 43 new SplayTreeMap<TypeIdentifier, Map<String, _DeclarationCode>>(); | |
| 44 | |
| 45 /// Names that are used both as strings and symbols. | |
| 46 Set<String> _names = new SplayTreeSet(); | |
| 47 | |
| 48 /// Prefixes associated with imported libraries. | |
| 49 Map<String, String> _libraryPrefix = {}; | |
| 50 | |
| 51 /// Register that [name] is used as a getter in the code. | |
| 52 void addGetter(String name) { _getters.add(name); } | |
| 53 | |
| 54 /// Register that [name] is used as a setter in the code. | |
| 55 void addSetter(String name) { _setters.add(name); } | |
| 56 | |
| 57 /// Register that [name] might be needed as a symbol. | |
| 58 void addSymbol(String name) { _names.add(name); } | |
| 59 | |
| 60 int _mixins = 0; | |
| 61 | |
| 62 /// Creates a new type to represent a mixin. Use [comment] to help users | |
| 63 /// figure out what mixin is being represented. | |
| 64 TypeIdentifier createMixinType([String comment = '']) => | |
| 65 new TypeIdentifier(null, '_M${_mixins++}', comment); | |
| 66 | |
| 67 /// Register that we care to know that [child] extends [parent]. | |
| 68 void addParent(TypeIdentifier child, TypeIdentifier parent) { | |
| 69 var existing = _parents[child]; | |
| 70 if (existing != null) { | |
| 71 if (existing == parent) return; | |
| 72 throw new StateError('$child already has a different parent associated' | |
| 73 '($existing instead of $parent)'); | |
| 74 } | |
| 75 _addLibrary(child.importUrl); | |
| 76 _addLibrary(parent.importUrl); | |
| 77 _parents[child] = parent; | |
| 78 } | |
| 79 | |
| 80 /// Register a declaration of a field, property, or method. Note that one and | |
| 81 /// only one of [isField], [isMethod], or [isProperty] should be set at a | |
| 82 /// given time. | |
| 83 void addDeclaration(TypeIdentifier cls, String name, TypeIdentifier type, | |
| 84 {bool isField: false, bool isProperty: false, bool isMethod: false, | |
| 85 bool isFinal: false, bool isStatic: false, | |
| 86 List<ConstExpression> annotations: const []}) { | |
| 87 final count = (isField ? 1 : 0) + (isProperty ? 1 : 0) + (isMethod ? 1 : 0); | |
| 88 if (count != 1) { | |
| 89 throw new ArgumentError('Declaration must be one (and only one) of the ' | |
| 90 'following: a field, a property, or a method.'); | |
| 91 } | |
| 92 var kind = isField ? 'FIELD' : isProperty ? 'PROPERTY' : 'METHOD'; | |
| 93 _declarations.putIfAbsent(cls, | |
| 94 () => new SplayTreeMap<String, _DeclarationCode>()); | |
| 95 _addLibrary(cls.importUrl); | |
| 96 var map = _declarations[cls]; | |
| 97 | |
| 98 for (var exp in annotations) { | |
| 99 for (var lib in exp.librariesUsed) { | |
| 100 _addLibrary(lib); | |
| 101 } | |
| 102 } | |
| 103 | |
| 104 _addLibrary(type.importUrl); | |
| 105 var decl = new _DeclarationCode(name, type, kind, isFinal, isStatic, | |
| 106 annotations); | |
| 107 if (map.containsKey(name) && map[name] != decl) { | |
| 108 throw new StateError('$type.$name already has a different declaration' | |
| 109 ' (${map[name]} instead of $decl).'); | |
| 110 } | |
| 111 map[name] = decl; | |
| 112 } | |
| 113 | |
| 114 /// Register that we might try to read declarations of [type], even if no | |
| 115 /// declaration exists. This informs the smoke system that querying for a | |
| 116 /// member in this class might be intentional and not an error. | |
| 117 void addEmptyDeclaration(TypeIdentifier type) { | |
| 118 _addLibrary(type.importUrl); | |
| 119 _declarations.putIfAbsent(type, | |
| 120 () => new SplayTreeMap<String, _DeclarationCode>()); | |
| 121 } | |
| 122 | |
| 123 /// Returns a list of imports that are needed for the code returned by | |
| 124 /// [generateInitCall]. | |
| 125 List<String> generateImports() { | |
| 126 var imports = []..addAll(DEFAULT_IMPORTS); | |
| 127 _libraryPrefix.forEach((url, prefix) { | |
| 128 imports.add("import '$url' as $prefix;"); | |
| 129 }); | |
| 130 return imports; | |
| 131 } | |
| 132 | |
| 133 /// Returns a top-level declarations that are used by the code in | |
| 134 /// [generateInitCall]. These are typically declarations of empty classes that | |
| 135 /// are then used as placeholder for mixin superclasses. | |
| 136 String generateTopLevelDeclarations() { | |
| 137 var types = new Set() | |
| 138 ..addAll(_parents.keys) | |
| 139 ..addAll(_parents.values) | |
| 140 ..addAll(_declarations.keys) | |
| 141 ..addAll(_declarations.values.expand( | |
| 142 (m) => m.values.map((d) => d.type))) | |
| 143 ..removeWhere((t) => t.importUrl != null); | |
| 144 final sb = new StringBuffer(); | |
| 145 for (var type in types) { | |
| 146 sb.write('abstract class ${type.name} {}'); | |
| 147 if (type.comment != null) sb.write(' // ${type.comment}'); | |
| 148 sb.writeln(); | |
| 149 } | |
| 150 return sb.toString(); | |
| 151 } | |
| 152 | |
| 153 /// Returns code that will initialize smoke's static configuration. For | |
| 154 /// example, the code might be of the form: | |
| 155 /// | |
| 156 /// useGeneratedCode(new StaticConfiguration( | |
| 157 /// getters: { | |
| 158 /// #i: (o) => o.i, | |
| 159 /// ... | |
| 160 /// names: { | |
| 161 /// #i: "i", | |
| 162 /// })); | |
| 163 /// | |
| 164 /// The optional [indent] argument is used for formatting purposes. All | |
| 165 /// entries in each map (getters, setters, names, declarations, parents) are | |
| 166 /// sorted alphabetically. | |
| 167 /// | |
| 168 /// **Note**: this code assumes that imports returned by [generateImports] and | |
| 169 /// top-level declarations from [generateTopLevelDeclarations] are included in | |
| 170 /// the same library where this code will live. | |
| 171 String generateInitCall([int indent = 2]) { | |
| 172 final spaces = new List.filled(indent, ' ').join(''); | |
| 173 var args = {}; | |
| 174 | |
| 175 if (_getters.isNotEmpty) { | |
| 176 args['getters'] = _getters.map((n) => '#$n: (o) => o.$n'); | |
| 177 } | |
| 178 if (_setters.isNotEmpty) { | |
| 179 args['setters'] = _setters.map((n) => '#$n: (o, v) { o.$n = v; }'); | |
| 180 } | |
| 181 | |
| 182 if (_parents.isNotEmpty) { | |
| 183 var parentsMap = []; | |
| 184 _parents.forEach((child, parent) { | |
| 185 var parent = _parents[child]; | |
| 186 parentsMap.add('${child.asCode(_libraryPrefix)}: ' | |
| 187 '${parent.asCode(_libraryPrefix)}'); | |
| 188 }); | |
| 189 args['parents'] = parentsMap; | |
| 190 } | |
| 191 | |
| 192 if (_declarations.isNotEmpty) { | |
| 193 var declarations = []; | |
| 194 _declarations.forEach((type, members) { | |
| 195 final sb = new StringBuffer() | |
| 196 ..write(type.asCode(_libraryPrefix)) | |
| 197 ..write(': '); | |
| 198 if (members.isEmpty) { | |
| 199 sb.write('const {}'); | |
| 200 } else { | |
| 201 sb.write('{\n'); | |
| 202 members.forEach((name, decl) { | |
| 203 var decl = members[name].asCode(_libraryPrefix); | |
| 204 sb.write('$spaces #$name: $decl,\n'); | |
| 205 }); | |
| 206 sb.write('$spaces }'); | |
| 207 } | |
| 208 declarations.add(sb.toString()); | |
| 209 }); | |
| 210 args['declarations'] = declarations; | |
| 211 } | |
| 212 | |
| 213 if (_names.isNotEmpty) { | |
| 214 args['names'] = _names.map((n) => "#$n: '$n'"); | |
| 215 } | |
| 216 | |
| 217 final sb = new StringBuffer() | |
| 218 ..write(spaces) | |
| 219 ..writeln('useGeneratedCode(new StaticConfiguration(') | |
| 220 ..write('$spaces checkedMode: false'); | |
| 221 | |
| 222 args.forEach((name, mapContents) { | |
| 223 sb.writeln(','); | |
| 224 // TODO(sigmund): use const map when Type can be keys (dartbug.com/17123) | |
| 225 sb.writeln('$spaces $name: {'); | |
| 226 for (var entry in mapContents) { | |
| 227 sb.writeln('$spaces $entry,'); | |
| 228 } | |
| 229 sb.write('$spaces }'); | |
| 230 }); | |
| 231 sb.writeln('));'); | |
| 232 return sb.toString(); | |
| 233 } | |
| 234 | |
| 235 /// Adds a library that needs to be imported. | |
| 236 void _addLibrary(String url) { | |
| 237 if (url == null || url == 'dart:core') return; | |
| 238 _libraryPrefix.putIfAbsent(url, () => 'smoke_${_libraryPrefix.length}'); | |
| 239 } | |
| 240 } | |
| 241 | |
| 242 /// Information used to generate code that allocates a `Declaration` object. | |
| 243 class _DeclarationCode extends ConstExpression { | |
| 244 String name; | |
| 245 TypeIdentifier type; | |
| 246 String kind; | |
| 247 bool isFinal; | |
| 248 bool isStatic; | |
| 249 List<ConstExpression> annotations; | |
| 250 | |
| 251 _DeclarationCode(this.name, this.type, this.kind, this.isFinal, this.isStatic, | |
| 252 this.annotations); | |
| 253 | |
| 254 List<String> get librariesUsed => [] | |
| 255 ..addAll(type.librariesUsed) | |
| 256 ..addAll(annotations.expand((a) => a.librariesUsed)); | |
| 257 | |
| 258 String asCode(Map<String, String> libraryPrefixes) { | |
| 259 var sb = new StringBuffer(); | |
| 260 sb.write("const Declaration(#$name, ${type.asCode(libraryPrefixes)}"); | |
| 261 if (kind != 'FIELD') sb.write(', kind: $kind'); | |
| 262 if (isFinal) sb.write(', isFinal: true'); | |
| 263 if (isStatic) sb.write(', isStatic: true'); | |
| 264 if (annotations != null && annotations.isNotEmpty) { | |
| 265 sb.write(', annotations: const ['); | |
| 266 bool first = true; | |
| 267 for (var e in annotations) { | |
| 268 if (!first) sb.write(', '); | |
| 269 first = false; | |
| 270 sb.write(e.asCode(libraryPrefixes)); | |
| 271 } | |
| 272 sb.write(']'); | |
| 273 } | |
| 274 sb.write(')'); | |
| 275 return sb.toString(); | |
| 276 } | |
| 277 | |
| 278 String toString() => | |
| 279 '(decl: $type.$name - $kind, $isFinal, $isStatic, $annotations)'; | |
| 280 operator== (other) => other is _DeclarationCode && name == other.name && | |
| 281 type == other.type && kind == other.kind && isFinal == other.isFinal && | |
| 282 isStatic == other.isStatic && | |
| 283 _compareLists(annotations, other.annotations); | |
| 284 int get hashCode => name.hashCode + (31 * type.hashCode); | |
| 285 } | |
| 286 | |
| 287 /// A constant expression that can be used as an annotation. | |
| 288 abstract class ConstExpression { | |
| 289 | |
| 290 List<String> get librariesUsed; | |
| 291 | |
| 292 /// Return a string representation of the code in this expression. | |
| 293 /// [libraryPrefixes] describes what prefix has been associated | |
| 294 String asCode(Map<String, String> libraryPrefixes); | |
| 295 | |
| 296 ConstExpression(); | |
| 297 | |
| 298 /// Create a string expression of the form `"string"`. | |
| 299 factory ConstExpression.string(String string) { | |
| 300 var value = string.replaceAll(r'\', r'\\').replaceAll('\'', '\\\''); | |
| 301 return new CodeAsConstExpression("'$value'"); | |
| 302 } | |
| 303 | |
| 304 /// Create an expression of the form `prefix.variable_name`. | |
| 305 factory ConstExpression.identifier(String importUrl, String name) => | |
| 306 new TopLevelIdentifier(importUrl, name); | |
| 307 | |
| 308 /// Create an expression of the form `prefix.Constructor(v1, v2, p3: v3)`. | |
| 309 factory ConstExpression.constructor(String importUrl, String name, | |
| 310 List<ConstExpression> positionalArgs, | |
| 311 Map<String, ConstExpression> namedArgs) => | |
| 312 new ConstructorExpression(importUrl, name, positionalArgs, namedArgs); | |
| 313 } | |
| 314 | |
| 315 /// A constant expression written as a String. Used when the code is self | |
| 316 /// contained and it doesn't depend on any imported libraries. | |
| 317 class CodeAsConstExpression extends ConstExpression { | |
| 318 String code; | |
| 319 List<String> get librariesUsed => const []; | |
| 320 | |
| 321 CodeAsConstExpression(this.code); | |
| 322 | |
| 323 String asCode(Map<String, String> libraryPrefixes) => code; | |
| 324 | |
| 325 String toString() => '(code: $code)'; | |
| 326 operator== (other) => other is CodeAsConstExpression && code == other.code; | |
| 327 int get hashCode => code.hashCode; | |
| 328 } | |
| 329 | |
| 330 /// Describes a reference to some symbol that is exported from a library. This | |
| 331 /// is typically used to refer to a type or a top-level variable from that | |
| 332 /// library. | |
| 333 class TopLevelIdentifier extends ConstExpression { | |
| 334 final String importUrl; | |
| 335 final String name; | |
| 336 TopLevelIdentifier(this.importUrl, this.name); | |
| 337 | |
| 338 List<String> get librariesUsed => [importUrl]; | |
| 339 String asCode(Map<String, String> libraryPrefixes) { | |
| 340 if (importUrl == 'dart:core' || importUrl == null) return name; | |
| 341 return '${libraryPrefixes[importUrl]}.$name'; | |
| 342 } | |
| 343 | |
| 344 String toString() => '(identifier: $importUrl, $name)'; | |
| 345 operator== (other) => other is TopLevelIdentifier && name == other.name | |
| 346 && importUrl == other.importUrl; | |
| 347 int get hashCode => 31 * importUrl.hashCode + name.hashCode; | |
| 348 } | |
| 349 | |
| 350 /// Represents an expression that invokes a const constructor. | |
| 351 class ConstructorExpression extends ConstExpression { | |
| 352 final String importUrl; | |
| 353 final String name; | |
| 354 final List<ConstExpression> positionalArgs; | |
| 355 final Map<String, ConstExpression> namedArgs; | |
| 356 ConstructorExpression(this.importUrl, this.name, this.positionalArgs, | |
| 357 this.namedArgs); | |
| 358 | |
| 359 List<String> get librariesUsed => [importUrl] | |
| 360 ..addAll(positionalArgs.expand((e) => e.librariesUsed)) | |
| 361 ..addAll(namedArgs.values.expand((e) => e.librariesUsed)); | |
| 362 | |
| 363 String asCode(Map<String, String> libraryPrefixes) { | |
| 364 var sb = new StringBuffer(); | |
| 365 sb.write('const '); | |
| 366 if (importUrl != 'dart:core' && importUrl != null) { | |
| 367 sb.write('${libraryPrefixes[importUrl]}.'); | |
| 368 } | |
| 369 sb.write('$name('); | |
| 370 bool first = true; | |
| 371 for (var e in positionalArgs) { | |
| 372 if (!first) sb.write(', '); | |
| 373 first = false; | |
| 374 sb.write(e.asCode(libraryPrefixes)); | |
| 375 } | |
| 376 namedArgs.forEach((name, value) { | |
| 377 if (!first) sb.write(', '); | |
| 378 first = false; | |
| 379 sb.write('$name: '); | |
| 380 sb.write(value.asCode(libraryPrefixes)); | |
| 381 }); | |
| 382 sb.write(')'); | |
| 383 return sb.toString(); | |
| 384 } | |
| 385 | |
| 386 String toString() => '(ctor: $importUrl, $name, $positionalArgs, $namedArgs)'; | |
| 387 operator== (other) => other is ConstructorExpression && name == other.name | |
| 388 && importUrl == other.importUrl && | |
| 389 _compareLists(positionalArgs, other.positionalArgs) && | |
| 390 _compareMaps(namedArgs, other.namedArgs); | |
| 391 int get hashCode => 31 * importUrl.hashCode + name.hashCode; | |
| 392 } | |
| 393 | |
| 394 | |
| 395 /// Describes a type identifier, with the library URL where the type is defined. | |
| 396 // TODO(sigmund): consider adding support for imprecise TypeIdentifiers, which | |
| 397 // may be used by tools that want to generate code without using the analyzer | |
| 398 // (they can syntactically tell the type comes from one of N imports). | |
| 399 class TypeIdentifier extends TopLevelIdentifier | |
| 400 implements Comparable<TypeIdentifier> { | |
| 401 final String comment; | |
| 402 TypeIdentifier(importUrl, typeName, [this.comment]) | |
| 403 : super(importUrl, typeName); | |
| 404 | |
| 405 // We implement [Comparable] to sort out entries in the generated code. | |
| 406 int compareTo(TypeIdentifier other) { | |
| 407 if (importUrl == null && other.importUrl != null) return 1; | |
| 408 if (importUrl != null && other.importUrl == null) return -1; | |
| 409 var c1 = importUrl == null ? 0 : importUrl.compareTo(other.importUrl); | |
| 410 return c1 != 0 ? c1 : name.compareTo(other.name); | |
| 411 } | |
| 412 | |
| 413 String toString() => '(type-identifier: $importUrl, $name, $comment)'; | |
| 414 bool operator ==(other) => other is TypeIdentifier && | |
| 415 importUrl == other.importUrl && name == other.name && | |
| 416 comment == other.comment; | |
| 417 int get hashCode => super.hashCode; | |
| 418 } | |
| 419 | |
| 420 /// Default set of imports added by [SmokeCodeGenerator]. | |
| 421 const DEFAULT_IMPORTS = const [ | |
| 422 "import 'package:smoke/smoke.dart' show Declaration, PROPERTY, METHOD;", | |
| 423 "import 'package:smoke/static.dart' show " | |
| 424 "useGeneratedCode, StaticConfiguration;", | |
| 425 ]; | |
| 426 | |
| 427 /// Shallow comparison of two lists. | |
| 428 bool _compareLists(List a, List b) { | |
| 429 if (a == null && b != null) return false; | |
| 430 if (a != null && b == null) return false; | |
| 431 if (a.length != b.length) return false; | |
| 432 for (int i = 0; i < a.length; i++) { | |
| 433 if (a[i] != b[i]) return false; | |
| 434 } | |
| 435 return true; | |
| 436 } | |
| 437 | |
| 438 /// Shallow comparison of two maps. | |
| 439 bool _compareMaps(Map a, Map b) { | |
| 440 if (a == null && b != null) return false; | |
| 441 if (a != null && b == null) return false; | |
| 442 if (a.length != b.length) return false; | |
| 443 for (var k in a.keys) { | |
| 444 if (!b.containsKey(k) || a[k] != b[k]) return false; | |
| 445 } | |
| 446 return true; | |
| 447 } | |
| OLD | NEW |