javascript - Closure Compiler: @enum, property collapsing and JSC_UNSAFE_NAMESPACE -


initial situation

i have following code:

var ns = {};  // namespace  ns.myenum = {     foo: 1,     bar: 2 };  var extendedns = object.create(ns);  extendedns.myalert = function (x) { alert(x); };  extendedns.myalert(extendedns.myenum.foo); 

it compiles command (no warnings or errors):

java -jar compiler-20150609.jar --js test.js --compilation_level advanced --warning_level verbose 

question 1

according docs jsc_unsafe_namespace, think advanced optimisations may replace ns.myenum ns$myenum, , remove ns.

so why compiler not raise warning line?

var extendedns = object.create(ns); 

isn't unsafe reference namespace ns? shouldn't compiler warn: "incomplete alias created namespace ns"?

@enum type breaks compiled output

i mark ns.myenum enum:

/**  * @enum {number}  */ ns.myenum = {     foo: 1,     bar: 2 }; 

according this old answer, "the compiler expects collapse enum value single variables". think compiler may collapse ns.myenum to:

ns$myenum$foo = 1; ns$myenum$bar = 2; 

the compiler raises warning:

warning - incomplete alias created namespace ns var extendedns = object.create(ns);                                ^ 

i think understand why: advanced optimisations may have removed ns after collapsing enum's values.

the compiled output indeed broken:

var = object.create({}); a.a = function() {   alert(a.c.b);      // a.c.b doesn't exist, runtime error occur }; a.a(); 

question 2

i add @nocollapse tag enum ("denotes property should not collapsed compiler variable. if annotate property object @nocollapse, properties remain uncollapsed."):

/**  * @enum {number}  * @nocollapse  */ ns.myenum = {     foo: 1,     bar: 2 }; 

the compiled output valid code:

var = object.create({c:{a:1, f:2}}); a.b = function() {   alert(a.c.a);      // a.c.a exist }; a.b(); 

but compiler still raises jsc_unsafe_namespace warning:

warning - incomplete alias created namespace ns var extended = object.create(ns);                              ^ 

why? there tag need add ns.myenum prevent warning?

(note: i'd prefer not @suppress warning. i'd understand , fix cause of warning.)

the core issue comes down fact traditionally, @enum properties have been collapsed - warning when @enum annotation added code broken (and in first example).

@nocollapse block enum collapsing , warning incorrectly emitted when annotation present. can file bug if wish, low priority issue.

in general case, enums designed used more constants , using them proto object not intended/supported behavior.

the rules , cases surrounding property collapsing complex. best way understand them through unit tests see specific patterns trigger warning.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -