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