Created
May 6, 2017 15:58
-
-
Save YetAnotherMinion/a6c696e078d94f8a94cec0d5af7dad9e to your computer and use it in GitHub Desktop.
Tree shaking POC for Elm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import re | |
import string | |
expressions = [] | |
# elm produces nice output where each complete top level expression starts with | |
# a line with zero indentation and continues up until the next line with zero | |
# indentation | |
current_expression = { "type": "other", "body": [] } | |
inside_var = False | |
# collect the entire program into a single string for full text search | |
body = "" | |
# identify each top level variable name | |
global_bindings = [] | |
for line in sys.stdin.readlines(): | |
body += line | |
if re.match("^var", line): | |
expressions.append(current_expression) | |
match = re.match("^var\s([^=\s]+)\s=", line) | |
var = None | |
if match: | |
var = match.group(1) | |
global_bindings.append(var) | |
current_expression = { "type": "var", "binding": var, "body": [ line ] } | |
inside_var = True | |
else: | |
if inside_var: | |
# check for termination of the var | |
if re.match("^\s+", line) or re.match(".*;\s*$", line): | |
current_expression["body"].append(line) | |
else: | |
inside_var = False | |
expressions.append(current_expression) | |
current_expression = { "type": "other", "body": [ line ] } | |
else: | |
current_expression["body"].append(line) | |
# the last expression ends at the end of the document | |
expressions.append(current_expression) | |
shake_off = set() | |
for var in global_bindings: | |
if string.count(body, var) == 1: | |
shake_off.add(var) | |
for expr in expressions: | |
if expr["type"] == "var": | |
if expr["binding"] and expr["binding"] in shake_off: | |
for line in expr["body"]: | |
sys.stdout.write("//" + line) | |
else: | |
for line in expr["body"]: | |
sys.stdout.write(line) | |
else: | |
for line in expr["body"]: | |
sys.stdout.write(line) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that the script as written only comments out the code it shakes off so you can visually inspect what it thinks is not needed. Don't be surprised if the size of the output increases if you run this script unmodified.