summaryrefslogtreecommitdiff
path: root/module/language/javascript/simplify.scm
blob: a26b7fd2ee3eab29646a6a4c19813c1b16ddbb0c (plain)
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
(define-module (language javascript simplify)
  #:use-module (language javascript)
  #:use-module (ice-9 match)
  #:use-module ((srfi srfi-1) #:select (fold-right))
  #:export (flatten-blocks))

(define (flatten-blocks exp)
  (define (flatten exp rest)
    (match exp
      (($ block statements)
       (fold-right flatten rest statements))
      (else
       (cons (flatten-exp exp) rest))))
  (define (flatten-block stmts)
    (fold-right flatten '() stmts))
  (define (flatten-exp exp)
    (match exp
      (($ assign id exp)
       (make-assign id (flatten-exp exp)))
      (($ const c) exp)
      (($ new exp)
       (make-new (flatten-exp exp)))
      (($ return exp)
       (make-return (flatten-exp exp)))
      (($ id name) exp)
      (($ var id exp)
       (make-var id (flatten-exp exp)))
      (($ refine id field)
       (make-refine (flatten-exp id)
                    (flatten-exp field)))
      (($ binop op arg1 arg2)
       (make-binop op
                   (flatten-exp arg1)
                   (flatten-exp arg2)))
      (($ function args body)
       (make-function args (flatten-block body)))
      (($ block statements)
       (maybe-make-block (flatten-block statements)))
      (($ branch test then else)
       (make-branch (flatten-exp test)
                    (flatten-block then)
                    (flatten-block else)))
      (($ call function args)
       (make-call (flatten-exp function)
                  (map flatten-exp args)))

      (($ ternary test then else)
       (make-ternary (flatten-exp test)
                     (flatten-exp then)
                     (flatten-exp else)))
      (($ prefix op exp)
       (make-prefix op (flatten-exp exp)))
      ))
  (define (maybe-make-block exp)
    (match exp
      ((exp) exp)
      (exps (make-block exps))))
  (maybe-make-block (flatten exp '())))