Matt Elson
Matt Elson

Reputation: 4355

How to delete useless JavaScript code using Python or Lisp

The JavaScript code is as follows:

   <script>
    a={name:"abc"};
    b={xyz:"123"};
    this.c='aaa';
    this.cc='bbb';
    d=new Date();
    var e=new Array();
    var f=false;
    this.g=123;
    this.g++;
    document.write(b.xyz+this.cc);
    </script>

Only the variables b(b={xyz:"123"};) and cc(this.cc='bbb';) are used above.

Does anyone know if there is a way to delete unused variables with Python or Lisp?

Upvotes: 1

Views: 273

Answers (3)

Kaz
Kaz

Reputation: 58598

Quick and dirty text based hack in TXR:

script.txr:

@(collect)
@prolog
@(last)
<script>
@(end)
@(collect :vars (code))
@  (block occurs)
@    (cases)
@{decl /(var )?/}@{var /[a-z]+/}=@expr
@      (trailer)
@      (skip)
@      (cases)
@        (skip)@var@(skip)
@        (bind code `@decl@var=@expr`)
@      (or)
</script>
@        (fail occurs)
@      (end)
@    (or)
@code
@    (end)
@  (end)
@(last)
</script>
@(end)
@(collect)
@epilog
@(end)
@(output)
@{prolog "\n"}
<script>
@{code "\n"}
</script>
@{epilog "\n"}
@(end)

Test case script.html:

verbatim
text
<script>
a={name:"abc"};
b={xyz:"123"};
this.c='aaa';
this.cc='bbb';
d=new Date();
var e=new Array();
var f=false;
this.g=123;
this.g++;
</script>
left
alone

Run:

$ txr script.txr script.html
verbatim
text
<script>
a={name:"abc"};
b={xyz:"123"};
this.c='aaa';
this.cc='bbb';
var e=new Array();
this.g=123;
this.g++;
</script>
left
alone

As you can see, some condensing was achieved.

Howver, the code thinks that aaa constitutes a use of the variable a. The variable e is retained because e occurs in var f=false; but you don't see that any more because that line itself is deleted since f does not occur.

If you want more than dumb text based hacks, you have to parse the Javascript. (Possible in a clear and disciplined grammar-based way in TXR also, but coding all the grammar rules is tedious.)

Upvotes: 1

Vsevolod Dyomkin
Vsevolod Dyomkin

Reputation: 9451

In Common Lisp land there's parse-js to parse JavaScript code. There's also CL-JavaScript interpreter, built on top of it, if you want to interactively evaluate JavaScript code and perform some kind of dynamic analysis. As for static analysis, there's cl-uglify-js, also built on top of parse-js - either it does dead code elimination, or you can try to modify it to do that...

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250991

Try the closure compiler to remove redundant code and useless whitespaces from javascript code: I ran your code(158 bytes) on closure compiler and I got this(89 bytes):

a={name:"abc"};b={b:"123"};this.a="bbb";d=new Date;document.write(b.b+this.a);

http://closure-compiler.appspot.com

Upvotes: 3

Related Questions