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 import 'package:smoke/src/common.dart' show compareLists, compareMaps; |
| 16 |
| 17 /// Collects the necessary information and generates code to initialize a |
| 18 /// `StaticConfiguration`. After setting up the generator by calling |
| 19 /// [addGetter], [addSetter], [addSymbol], and [addDeclaration], you can |
| 20 /// retrieve the generated code using the following three methods: |
| 21 /// |
| 22 /// * [writeImports] writes a list of imports directives, |
| 23 /// * [writeTopLevelDeclarations] writes additional declarations used to |
| 24 /// represent mixin classes by name in the generated code. |
| 25 /// * [writeInitCall] writes the actual code that allocates the static |
| 26 /// configuration. |
| 27 /// |
| 28 /// You'd need to include all three in your generated code, since the |
| 29 /// initialization code refers to symbols that are only available from the |
| 30 /// generated imports or the generated top-level declarations. |
| 31 class SmokeCodeGenerator { |
| 32 // Note: we use SplayTreeSet/Map here and below to keep generated code sorted. |
| 33 /// Names used as getters via smoke. |
| 34 final Set<String> _getters = new SplayTreeSet(); |
| 35 |
| 36 /// Names used as setters via smoke. |
| 37 final Set<String> _setters = new SplayTreeSet(); |
| 38 |
| 39 /// Subclass relations needed to run smoke queries. |
| 40 final Map<TypeIdentifier, TypeIdentifier> _parents = new SplayTreeMap(); |
| 41 |
| 42 /// Declarations requested via `smoke.getDeclaration or `smoke.query`. |
| 43 final Map<TypeIdentifier, Map<String, _DeclarationCode>> _declarations = |
| 44 new SplayTreeMap(); |
| 45 |
| 46 /// Names that are used both as strings and symbols. |
| 47 final Set<String> _names = new SplayTreeSet(); |
| 48 |
| 49 /// Prefixes associated with imported libraries. |
| 50 final Map<String, String> _libraryPrefix = {}; |
| 51 |
| 52 /// Register that [name] is used as a getter in the code. |
| 53 void addGetter(String name) { _getters.add(name); } |
| 54 |
| 55 /// Register that [name] is used as a setter in the code. |
| 56 void addSetter(String name) { _setters.add(name); } |
| 57 |
| 58 /// Register that [name] might be needed as a symbol. |
| 59 void addSymbol(String name) { _names.add(name); } |
| 60 |
| 61 int _mixins = 0; |
| 62 |
| 63 /// Creates a new type to represent a mixin. Use [comment] to help users |
| 64 /// figure out what mixin is being represented. |
| 65 TypeIdentifier createMixinType([String comment = '']) => |
| 66 new TypeIdentifier(null, '_M${_mixins++}', comment); |
| 67 |
| 68 /// Register that we care to know that [child] extends [parent]. |
| 69 void addParent(TypeIdentifier child, TypeIdentifier parent) { |
| 70 var existing = _parents[child]; |
| 71 if (existing != null) { |
| 72 if (existing == parent) return; |
| 73 throw new StateError('$child already has a different parent associated' |
| 74 '($existing instead of $parent)'); |
| 75 } |
| 76 _addLibrary(child.importUrl); |
| 77 _addLibrary(parent.importUrl); |
| 78 _parents[child] = parent; |
| 79 } |
| 80 |
| 81 /// Register a declaration of a field, property, or method. Note that one and |
| 82 /// only one of [isField], [isMethod], or [isProperty] should be set at a |
| 83 /// given time. |
| 84 void addDeclaration(TypeIdentifier cls, String name, TypeIdentifier type, |
| 85 {bool isField: false, bool isProperty: false, bool isMethod: false, |
| 86 bool isFinal: false, bool isStatic: false, |
| 87 List<ConstExpression> annotations: const []}) { |
| 88 final count = (isField ? 1 : 0) + (isProperty ? 1 : 0) + (isMethod ? 1 : 0); |
| 89 if (count != 1) { |
| 90 throw new ArgumentError('Declaration must be one (and only one) of the ' |
| 91 'following: a field, a property, or a method.'); |
| 92 } |
| 93 var kind = isField ? 'FIELD' : isProperty ? 'PROPERTY' : 'METHOD'; |
| 94 _declarations.putIfAbsent(cls, |
| 95 () => new SplayTreeMap<String, _DeclarationCode>()); |
| 96 _addLibrary(cls.importUrl); |
| 97 var map = _declarations[cls]; |
| 98 |
| 99 for (var exp in annotations) { |
| 100 for (var lib in exp.librariesUsed) { |
| 101 _addLibrary(lib); |
| 102 } |
| 103 } |
| 104 |
| 105 _addLibrary(type.importUrl); |
| 106 var decl = new _DeclarationCode(name, type, kind, isFinal, isStatic, |
| 107 annotations); |
| 108 if (map.containsKey(name) && map[name] != decl) { |
| 109 throw new StateError('$type.$name already has a different declaration' |
| 110 ' (${map[name]} instead of $decl).'); |
| 111 } |
| 112 map[name] = decl; |
| 113 } |
| 114 |
| 115 /// Register that we might try to read declarations of [type], even if no |
| 116 /// declaration exists. This informs the smoke system that querying for a |
| 117 /// member in this class might be intentional and not an error. |
| 118 void addEmptyDeclaration(TypeIdentifier type) { |
| 119 _addLibrary(type.importUrl); |
| 120 _declarations.putIfAbsent(type, |
| 121 () => new SplayTreeMap<String, _DeclarationCode>()); |
| 122 } |
| 123 |
| 124 /// Writes to [buffer] a line for each import that is needed by the generated |
| 125 /// code. The code added by [writeInitCall] depends on these imports. |
| 126 void writeImports(StringBuffer buffer) { |
| 127 DEFAULT_IMPORTS.forEach((i) => buffer.writeln(i)); |
| 128 _libraryPrefix.forEach((url, prefix) { |
| 129 buffer.writeln("import '$url' as $prefix;"); |
| 130 }); |
| 131 } |
| 132 |
| 133 /// Writes to [buffer] top-level declarations that are used by the code |
| 134 /// generated in [writeInitCall]. These are typically declarations of empty |
| 135 /// classes that are then used as placeholders for mixin superclasses. |
| 136 void writeTopLevelDeclarations(StringBuffer buffer) { |
| 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 for (var type in types) { |
| 145 buffer.write('abstract class ${type.name} {}'); |
| 146 if (type.comment != null) buffer.write(' // ${type.comment}'); |
| 147 buffer.writeln(); |
| 148 } |
| 149 } |
| 150 |
| 151 /// Appends to [buffer] code that will initialize smoke's static |
| 152 /// configuration. For example, the code might be of the form: |
| 153 /// |
| 154 /// useGeneratedCode(new StaticConfiguration( |
| 155 /// getters: { |
| 156 /// #i: (o) => o.i, |
| 157 /// ... |
| 158 /// names: { |
| 159 /// #i: "i", |
| 160 /// })); |
| 161 /// |
| 162 /// The optional [indent] argument is used for formatting purposes. All |
| 163 /// entries in each map (getters, setters, names, declarations, parents) are |
| 164 /// sorted alphabetically. |
| 165 /// |
| 166 /// **Note**: this code assumes that imports from [writeImports] and top-level |
| 167 /// declarations from [writeTopLevelDeclarations] are included in the same |
| 168 /// library where this code will live. |
| 169 void writeInitCall(StringBuffer buffer, [int indent = 2]) { |
| 170 final spaces = new List.filled(indent, ' ').join(''); |
| 171 var args = {}; |
| 172 |
| 173 if (_getters.isNotEmpty) { |
| 174 args['getters'] = _getters.map((n) => '#$n: (o) => o.$n'); |
| 175 } |
| 176 if (_setters.isNotEmpty) { |
| 177 args['setters'] = _setters.map((n) => '#$n: (o, v) { o.$n = v; }'); |
| 178 } |
| 179 |
| 180 if (_parents.isNotEmpty) { |
| 181 var parentsMap = []; |
| 182 _parents.forEach((child, parent) { |
| 183 var parent = _parents[child]; |
| 184 parentsMap.add('${child.asCode(_libraryPrefix)}: ' |
| 185 '${parent.asCode(_libraryPrefix)}'); |
| 186 }); |
| 187 args['parents'] = parentsMap; |
| 188 } |
| 189 |
| 190 if (_declarations.isNotEmpty) { |
| 191 var declarations = []; |
| 192 _declarations.forEach((type, members) { |
| 193 final sb = new StringBuffer() |
| 194 ..write(type.asCode(_libraryPrefix)) |
| 195 ..write(': '); |
| 196 if (members.isEmpty) { |
| 197 sb.write('const {}'); |
| 198 } else { |
| 199 sb.write('{\n'); |
| 200 members.forEach((name, decl) { |
| 201 var decl = members[name].asCode(_libraryPrefix); |
| 202 sb.write('$spaces #$name: $decl,\n'); |
| 203 }); |
| 204 sb.write('$spaces }'); |
| 205 } |
| 206 declarations.add(sb.toString()); |
| 207 }); |
| 208 args['declarations'] = declarations; |
| 209 } |
| 210 |
| 211 if (_names.isNotEmpty) { |
| 212 args['names'] = _names.map((n) => "#$n: '$n'"); |
| 213 } |
| 214 |
| 215 buffer..write(spaces) |
| 216 ..writeln('useGeneratedCode(new StaticConfiguration(') |
| 217 ..write('$spaces checkedMode: false'); |
| 218 |
| 219 args.forEach((name, mapContents) { |
| 220 buffer.writeln(','); |
| 221 // TODO(sigmund): use const map when Type can be keys (dartbug.com/17123) |
| 222 buffer.writeln('$spaces $name: {'); |
| 223 for (var entry in mapContents) { |
| 224 buffer.writeln('$spaces $entry,'); |
| 225 } |
| 226 buffer.write('$spaces }'); |
| 227 }); |
| 228 buffer.writeln('));'); |
| 229 } |
| 230 |
| 231 /// Adds a library that needs to be imported. |
| 232 void _addLibrary(String url) { |
| 233 if (url == null || url == 'dart:core') return; |
| 234 _libraryPrefix.putIfAbsent(url, () => 'smoke_${_libraryPrefix.length}'); |
| 235 } |
| 236 } |
| 237 |
| 238 /// Information used to generate code that allocates a `Declaration` object. |
| 239 class _DeclarationCode extends ConstExpression { |
| 240 final String name; |
| 241 final TypeIdentifier type; |
| 242 final String kind; |
| 243 final bool isFinal; |
| 244 final bool isStatic; |
| 245 final List<ConstExpression> annotations; |
| 246 |
| 247 _DeclarationCode(this.name, this.type, this.kind, this.isFinal, this.isStatic, |
| 248 this.annotations); |
| 249 |
| 250 List<String> get librariesUsed => [] |
| 251 ..addAll(type.librariesUsed) |
| 252 ..addAll(annotations.expand((a) => a.librariesUsed)); |
| 253 |
| 254 String asCode(Map<String, String> libraryPrefixes) { |
| 255 var sb = new StringBuffer(); |
| 256 sb.write("const Declaration(#$name, ${type.asCode(libraryPrefixes)}"); |
| 257 if (kind != 'FIELD') sb.write(', kind: $kind'); |
| 258 if (isFinal) sb.write(', isFinal: true'); |
| 259 if (isStatic) sb.write(', isStatic: true'); |
| 260 if (annotations != null && annotations.isNotEmpty) { |
| 261 sb.write(', annotations: const ['); |
| 262 bool first = true; |
| 263 for (var e in annotations) { |
| 264 if (!first) sb.write(', '); |
| 265 first = false; |
| 266 sb.write(e.asCode(libraryPrefixes)); |
| 267 } |
| 268 sb.write(']'); |
| 269 } |
| 270 sb.write(')'); |
| 271 return sb.toString(); |
| 272 } |
| 273 |
| 274 String toString() => |
| 275 '(decl: $type.$name - $kind, $isFinal, $isStatic, $annotations)'; |
| 276 operator== (other) => other is _DeclarationCode && name == other.name && |
| 277 type == other.type && kind == other.kind && isFinal == other.isFinal && |
| 278 isStatic == other.isStatic && |
| 279 compareLists(annotations, other.annotations); |
| 280 int get hashCode => name.hashCode + (31 * type.hashCode); |
| 281 } |
| 282 |
| 283 /// A constant expression that can be used as an annotation. |
| 284 abstract class ConstExpression { |
| 285 |
| 286 /// Returns the library URLs that needs to be imported for this |
| 287 /// [ConstExpression] to be a valid annotation. |
| 288 List<String> get librariesUsed; |
| 289 |
| 290 /// Return a string representation of the code in this expression. |
| 291 /// [libraryPrefixes] describes what prefix has been associated with each |
| 292 /// import url mentioned in [libraryUsed]. |
| 293 String asCode(Map<String, String> libraryPrefixes); |
| 294 |
| 295 ConstExpression(); |
| 296 |
| 297 /// Create a string expression of the form `'string'`, where [string] is |
| 298 /// normalized so we can correctly wrap it in single quotes. |
| 299 factory ConstExpression.string(String string) { |
| 300 var value = string.replaceAll(r'\', r'\\').replaceAll(r"'", r"\'"); |
| 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 ]; |
OLD | NEW |