My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/*
* Copyright 2010 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.javascript.jscomp;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.javascript.jscomp.CompilerOptions.AliasTransformation;
import com.google.javascript.jscomp.CompilerOptions.AliasTransformationHandler;
import com.google.javascript.jscomp.Scope.Var;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.SourcePosition;
import com.google.javascript.rhino.Token;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.annotation.Nullable;

/**
* Process aliases in goog.scope blocks.
*
* goog.scope(function() {
* var dom = goog.dom;
* var DIV = dom.TagName.DIV;
*
* dom.createElement(DIV);
* });
*
* should become
*
* goog.dom.createElement(goog.dom.TagName.DIV);
*
* @author robbyw@google.com (Robby Walker)
*/
class ScopedAliases implements HotSwapCompilerPass {
/** Name used to denote an scoped function block used for aliasing. */
static final String SCOPING_METHOD_NAME = "goog.scope";

private final AbstractCompiler compiler;
private final PreprocessorSymbolTable preprocessorSymbolTable;
private final AliasTransformationHandler transformationHandler;

// Errors
static final DiagnosticType GOOG_SCOPE_USED_IMPROPERLY = DiagnosticType.error(
"JSC_GOOG_SCOPE_USED_IMPROPERLY",
"The call to goog.scope must be alone in a single statement.");

static final DiagnosticType GOOG_SCOPE_HAS_BAD_PARAMETERS =
DiagnosticType.error(
"JSC_GOOG_SCOPE_HAS_BAD_PARAMETERS",
"The call to goog.scope must take only a single parameter. It must" +
" be an anonymous function that itself takes no parameters.");

static final DiagnosticType GOOG_SCOPE_REFERENCES_THIS = DiagnosticType.error(
"JSC_GOOG_SCOPE_REFERENCES_THIS",
"The body of a goog.scope function cannot reference 'this'.");

static final DiagnosticType GOOG_SCOPE_USES_RETURN = DiagnosticType.error(
"JSC_GOOG_SCOPE_USES_RETURN",
"The body of a goog.scope function cannot use 'return'.");

static final DiagnosticType GOOG_SCOPE_USES_THROW = DiagnosticType.error(
"JSC_GOOG_SCOPE_USES_THROW",
"The body of a goog.scope function cannot use 'throw'.");

static final DiagnosticType GOOG_SCOPE_ALIAS_REDEFINED = DiagnosticType.error(
"JSC_GOOG_SCOPE_ALIAS_REDEFINED",
"The alias {0} is assigned a value more than once.");

static final DiagnosticType GOOG_SCOPE_NON_ALIAS_LOCAL = DiagnosticType.error(
"JSC_GOOG_SCOPE_NON_ALIAS_LOCAL",
"The local variable {0} is in a goog.scope and is not an alias.");

ScopedAliases(AbstractCompiler compiler,
@Nullable PreprocessorSymbolTable preprocessorSymbolTable,
AliasTransformationHandler transformationHandler) {
this.compiler = compiler;
this.preprocessorSymbolTable = preprocessorSymbolTable;
this.transformationHandler = transformationHandler;
}

@Override
public void process(Node externs, Node root) {
hotSwapScript(root, null);
}

@Override
public void hotSwapScript(Node root, Node originalRoot) {
Traversal traversal = new Traversal();
NodeTraversal.traverse(compiler, root, traversal);

if (!traversal.hasErrors()) {

// Apply the aliases.
for (AliasUsage aliasUsage : traversal.getAliasUsages()) {
aliasUsage.applyAlias();
}

// Remove the alias definitions.
for (Node aliasDefinition : traversal.getAliasDefinitionsInOrder()) {
if (aliasDefinition.getParent().isVar() &&
aliasDefinition.getParent().hasOneChild()) {
aliasDefinition.getParent().detachFromParent();
} else {
aliasDefinition.detachFromParent();
}
}

// Collapse the scopes.
for (Node scopeCall : traversal.getScopeCalls()) {
Node expressionWithScopeCall = scopeCall.getParent();
Node scopeClosureBlock = scopeCall.getLastChild().getLastChild();
scopeClosureBlock.detachFromParent();
expressionWithScopeCall.getParent().replaceChild(
expressionWithScopeCall,
scopeClosureBlock);
NodeUtil.tryMergeBlock(scopeClosureBlock);
}

if (traversal.getAliasUsages().size() > 0 ||
traversal.getAliasDefinitionsInOrder().size() > 0 ||
traversal.getScopeCalls().size() > 0) {
compiler.reportCodeChange();
}
}
}

private interface AliasUsage {
public void applyAlias();
}

private class AliasedNode implements AliasUsage {
private final Node aliasReference;

private final Node aliasDefinition;

AliasedNode(Node aliasReference, Node aliasDefinition) {
this.aliasReference = aliasReference;
this.aliasDefinition = aliasDefinition;
}

@Override
public void applyAlias() {
aliasReference.getParent().replaceChild(
aliasReference, aliasDefinition.cloneTree());
}
}

private class AliasedTypeNode implements AliasUsage {
private final Node aliasReference;

private final String correctedType;

AliasedTypeNode(Node aliasReference, String correctedType) {
this.aliasReference = aliasReference;
this.correctedType = correctedType;
}

@Override
public void applyAlias() {
aliasReference.setString(correctedType);
}
}


private class Traversal implements NodeTraversal.ScopedCallback {
// The job of this class is to collect these three data sets.

// The order of this list determines the order that aliases are applied.
private final List<Node> aliasDefinitionsInOrder = Lists.newArrayList();

private final List<Node> scopeCalls = Lists.newArrayList();

private final List<AliasUsage> aliasUsages = Lists.newArrayList();

// This map is temporary and cleared for each scope.
private final Map<String, Var> aliases = Maps.newHashMap();

private boolean hasErrors = false;

private AliasTransformation transformation = null;

Collection<Node> getAliasDefinitionsInOrder() {
return aliasDefinitionsInOrder;
}

private List<AliasUsage> getAliasUsages() {
return aliasUsages;
}

List<Node> getScopeCalls() {
return scopeCalls;
}

boolean hasErrors() {
return hasErrors;
}

private boolean isCallToScopeMethod(Node n) {
return n.isCall() &&
SCOPING_METHOD_NAME.equals(n.getFirstChild().getQualifiedName());
}

@Override
public void enterScope(NodeTraversal t) {
Node n = t.getCurrentNode().getParent();
if (n != null && isCallToScopeMethod(n)) {
transformation = transformationHandler.logAliasTransformation(
n.getSourceFileName(), getSourceRegion(n));
findAliases(t);
}
}

@Override
public void exitScope(NodeTraversal t) {
if (t.getScopeDepth() == 2) {
aliases.clear();
transformation = null;
}
}

@Override
public final boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
if (n.isFunction() && t.inGlobalScope()) {
// Do not traverse in to functions except for goog.scope functions.
if (parent == null || !isCallToScopeMethod(parent)) {
return false;
}
}
return true;
}

private SourcePosition<AliasTransformation> getSourceRegion(Node n) {
Node testNode = n;
Node next = null;
for (; next != null || testNode.isScript();) {
next = testNode.getNext();
testNode = testNode.getParent();
}

int endLine = next == null ? Integer.MAX_VALUE : next.getLineno();
int endChar = next == null ? Integer.MAX_VALUE : next.getCharno();
SourcePosition<AliasTransformation> pos =
new SourcePosition<AliasTransformation>() {};
pos.setPositionInformation(
n.getLineno(), n.getCharno(), endLine, endChar);
return pos;
}

private void report(NodeTraversal t, Node n, DiagnosticType error,
String... arguments) {
compiler.report(t.makeError(n, error, arguments));
hasErrors = true;
}

private void findAliases(NodeTraversal t) {
Scope scope = t.getScope();
for (Var v : scope.getVarIterable()) {
Node n = v.getNode();
int type = n.getType();
Node parent = n.getParent();
if (parent.isVar() &&
n.hasChildren() && n.getFirstChild().isQualifiedName()) {
String name = n.getString();
Var aliasVar = scope.getVar(name);
aliases.put(name, aliasVar);

String qualifiedName =
aliasVar.getInitialValue().getQualifiedName();
transformation.addAlias(name, qualifiedName);
} else if (v.isBleedingFunction()) {
// Bleeding functions already get a BAD_PARAMETERS error, so just
// do nothing.
} else if (parent.getType() == Token.LP) {
// Parameters of the scope function also get a BAD_PARAMETERS
// error.
} else {
// TODO(robbyw): Support using locals for private variables.
report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());
}
}
}

private void validateScopeCall(NodeTraversal t, Node n, Node parent) {
if (preprocessorSymbolTable != null) {
preprocessorSymbolTable.addReference(n.getFirstChild());
}
if (!parent.isExprResult()) {
report(t, n, GOOG_SCOPE_USED_IMPROPERLY);
}
if (n.getChildCount() != 2) {
// The goog.scope call should have exactly 1 parameter. The first
// child is the "goog.scope" and the second should be the parameter.
report(t, n, GOOG_SCOPE_HAS_BAD_PARAMETERS);
} else {
Node anonymousFnNode = n.getChildAtIndex(1);
if (!anonymousFnNode.isFunction() ||
NodeUtil.getFunctionName(anonymousFnNode) != null ||
NodeUtil.getFunctionParameters(anonymousFnNode).hasChildren()) {
report(t, anonymousFnNode, GOOG_SCOPE_HAS_BAD_PARAMETERS);
} else {
scopeCalls.add(n);
}
}
}

@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (isCallToScopeMethod(n)) {
validateScopeCall(t, n, n.getParent());
}

if (t.getScopeDepth() < 2) {
return;
}

int type = n.getType();
Var aliasVar = null;
if (type == Token.NAME) {
String name = n.getString();
Var lexicalVar = t.getScope().getVar(n.getString());
if (lexicalVar != null && lexicalVar == aliases.get(name)) {
aliasVar = lexicalVar;
}
}

// Validate the top-level of the goog.scope block.
if (t.getScopeDepth() == 2) {
if (aliasVar != null && NodeUtil.isLValue(n)) {
if (aliasVar.getNode() == n) {
aliasDefinitionsInOrder.add(n);

// Return early, to ensure that we don't record a definition
// twice.
return;
} else {
report(t, n, GOOG_SCOPE_ALIAS_REDEFINED, n.getString());
}
}

if (type == Token.RETURN) {
report(t, n, GOOG_SCOPE_USES_RETURN);
} else if (type == Token.THIS) {
report(t, n, GOOG_SCOPE_REFERENCES_THIS);
} else if (type == Token.THROW) {
report(t, n, GOOG_SCOPE_USES_THROW);
}
}

// Validate all descendent scopes of the goog.scope block.
if (t.getScopeDepth() >= 2) {
// Check if this name points to an alias.
if (aliasVar != null) {
// Note, to support the transitive case, it's important we don't
// clone aliasedNode here. For example,
// var g = goog; var d = g.dom; d.createElement('DIV');
// The node in aliasedNode (which is "g") will be replaced in the
// changes pass above with "goog". If we cloned here, we'd end up
// with <code>g.dom.createElement('DIV')</code>.
Node aliasedNode = aliasVar.getInitialValue();
aliasUsages.add(new AliasedNode(n, aliasedNode));
}

JSDocInfo info = n.getJSDocInfo();
if (info != null) {
for (Node node : info.getTypeNodes()) {
fixTypeNode(node);
}
}

// TODO(robbyw): Error for goog.scope not at root.
}
}

private void fixTypeNode(Node typeNode) {
if (typeNode.isString()) {
String name = typeNode.getString();
int endIndex = name.indexOf('.');
if (endIndex == -1) {
endIndex = name.length();
}
String baseName = name.substring(0, endIndex);
Var aliasVar = aliases.get(baseName);
if (aliasVar != null) {
Node aliasedNode = aliasVar.getInitialValue();
aliasUsages.add(new AliasedTypeNode(typeNode,
aliasedNode.getQualifiedName() + name.substring(endIndex)));
}
}

for (Node child = typeNode.getFirstChild(); child != null;
child = child.getNext()) {
fixTypeNode(child);
}
}
}
}

Change log

r1993 by nicksan...@google.com on May 24 (3 days ago)   Diff
Emit an error if there are dangling
functions in the goog.scope
fixes  issue 737 

R=johnlenz
DELTA=26  (7 added, 0 deleted, 19 changed)


Revision created by MOE tool
push_codebase.
MOE_MIGRATION=4853
Go to: 
Project members, sign in to write a code review

Older revisions

r1979 by johnl...@google.com on May 18, 2012   Diff
Fix various typos, spelling and
grammar errors.
Fixes  issue 734 .
Contributed by Robert Gust Bardon
...
r1702 by johnl...@google.com on Jan 4, 2012   Diff
Inline NodeUtil.isExpressionNode

R=nicksantos
DELTA=37  (0 added, 4 deleted, 33
...
r1582 by johnl...@google.com on Nov 10, 2011   Diff
Replace the bulk of the Node.getType()
== Token.XXX calls with
Node.isXXX calls.

...
All revisions of this file

File info

Size: 13743 bytes, 413 lines

File properties

svn:mime-type
text/x-java
Powered by Google Project Hosting