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

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

Issue 194813007: Add codegen support in smoke (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 6 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 | Annotate | Revision Log
OLDNEW
(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;
Jennifer Messerly 2014/03/17 22:38:48 is this all intended as public api? SmokeCodeGener
Siggi Cherem (dart-lang) 2014/03/18 01:52:29 Yes. SmokeCodeGenerator will be heavily used exte
12
13 import 'dart:collection' show SplayTreeMap; // To keep generated code sorted.
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 /// * [generateImports] returns a list of imports directives,
21 /// * [generateTopLevelDeclarations] returns additional declarations used to
22 /// represent mixin classes by name in the generated code.
23 /// * [generateInitCall] returns 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 /// Names used as getters via smoke.
31 List<String> _getters = [];
Jennifer Messerly 2014/03/17 22:38:48 final here & below?
Siggi Cherem (dart-lang) 2014/03/18 01:52:29 Done.
32
33 /// Names used as setters via smoke.
34 List<String> _setters = [];
35
36 /// Subclass relations needed to run smoke queries.
37 Map<TypeIdentifier, TypeIdentifier> _parents =
Jennifer Messerly 2014/03/17 22:38:48 does it work to just say "final _parents" here ins
Siggi Cherem (dart-lang) 2014/03/18 01:52:29 Done.
38 new SplayTreeMap<TypeIdentifier, TypeIdentifier>();
39
40 /// Declarations requested via `smoke.getDeclaration or `smoke.query`.
41 Map<TypeIdentifier, Map<String, _DeclarationCode>> _declarations =
42 new SplayTreeMap<TypeIdentifier, Map<String, _DeclarationCode>>();
43
44 /// Names that are used both as strings and symbols.
45 List<String> _names = [];
46
47 /// Prefixes associated with imported libraries.
48 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 /// Returns a list of imports that are needed for the code returned by
123 /// [generateInitCall].
124 List<String> generateImports() {
125 var imports = []..addAll(DEFAULT_IMPORTS);
126 _libraryPrefix.forEach((url, prefix) {
127 imports.add("import '$url' as $prefix;");
128 });
129 return imports;
130 }
131
132 /// Returns a top-level declarations that are used by the code in
133 /// [generateInitCall]. These are typically declarations of empty classes that
134 /// are then used as placeholder for mixin superclasses.
135 String generateTopLevelDeclarations() {
Jennifer Messerly 2014/03/17 22:38:48 hmmm, I wonder if these should be methods that acc
Siggi Cherem (dart-lang) 2014/03/18 01:52:29 good idea, done.
136 var types = new Set()
137 ..addAll(_parents.keys)
138 ..addAll(_parents.values)
139 ..addAll(_declarations.keys)
140 ..addAll(_declarations.values.expand(
141 (m) => m.values.map((d) => d.type)))
142 ..removeWhere((t) => t.importUrl != null);
143 final sb = new StringBuffer();
144 for (var type in types) {
145 sb.write('abstract class ${type.name} {}');
146 if (type.comment != null) sb.write(' // ${type.comment}');
147 sb.writeln();
148 }
149 return sb.toString();
150 }
151
152 /// Returns code that will initialize smoke's static configuration. For
153 /// example, the code might be of the form:
154 ///
155 /// useGeneratedCode(new StaticConfiguration(
156 /// getters: {
157 /// #i: (o) => o.i,
158 /// ...
159 /// names: {
160 /// #i: "i",
161 /// }));
162 ///
163 /// The optional [indent] argument is used for formatting purposes. All
164 /// entries in each map (getters, setters, names, declarations, parents) are
165 /// sorted alphabetically.
166 ///
167 /// **Note**: this code assumes that imports returned by [generateImports] and
168 /// top-level declarations from [generateTopLevelDeclarations] are included in
169 /// the same library where this code will live.
170 String generateInitCall([int indent = 2]) {
171 final spaces = new List.filled(indent, ' ').join('');
172 var args = {};
173
174 if (_getters.isNotEmpty) {
175 args['getters'] = (_getters..sort()).map((n) => '#$n: (o) => o.$n');
176 }
177 if (_setters.isNotEmpty) {
178 args['setters'] = (_setters..sort()).map(
179 (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..sort()).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;
Jennifer Messerly 2014/03/17 22:38:48 final for these fields?
Siggi Cherem (dart-lang) 2014/03/18 01:52:29 Done.
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;
Jennifer Messerly 2014/03/17 22:38:48 doc comment?
Siggi Cherem (dart-lang) 2014/03/18 01:52:29 Done.
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"`.
Jennifer Messerly 2014/03/17 22:38:48 maybe explain that it will be normalized
Siggi Cherem (dart-lang) 2014/03/18 01:52:29 Done.
299 factory ConstExpression.string(String string) {
300 var value = string.replaceAll(r'\', r'\\').replaceAll('\'', '\\\'');
Jennifer Messerly 2014/03/17 22:38:48 for second replace, maybe write it as: .replaceAl
Siggi Cherem (dart-lang) 2014/03/18 01:52:29 Done.
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 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698