1 /* Pretty-print input source by emitting parse tree back as syntax.
2 * with no flags: pretty-printed source
3 * with -m: minified source with line breaks
4 * with -mm: minified source without line breaks
5 * with -s: s-expression syntax tree
6 */
7
8 #include <stdio.h>
9
10 #include "jsi.h"
11 #include "jsparse.h"
12
js_ppstring(js_State * J,const char * filename,const char * source,int minify)13 static void js_ppstring(js_State *J, const char *filename, const char *source, int minify)
14 {
15 js_Ast *P;
16 if (js_try(J)) {
17 jsP_freeparse(J);
18 js_throw(J);
19 }
20 P = jsP_parse(J, filename, source);
21 if (minify > 2)
22 jsP_dumplist(J, P);
23 else
24 jsP_dumpsyntax(J, P, minify);
25 jsP_freeparse(J);
26 js_endtry(J);
27 }
28
js_ppfile(js_State * J,const char * filename,int minify)29 void js_ppfile(js_State *J, const char *filename, int minify)
30 {
31 FILE *f;
32 char *s;
33 int n, t;
34
35 f = fopen(filename, "rb");
36 if (!f) {
37 js_error(J, "cannot open file: '%s'", filename);
38 }
39
40 if (fseek(f, 0, SEEK_END) < 0) {
41 fclose(f);
42 js_error(J, "cannot seek in file: '%s'", filename);
43 }
44
45 n = ftell(f);
46 if (n < 0) {
47 fclose(f);
48 js_error(J, "cannot tell in file: '%s'", filename);
49 }
50
51 if (fseek(f, 0, SEEK_SET) < 0) {
52 fclose(f);
53 js_error(J, "cannot seek in file: '%s'", filename);
54 }
55
56 s = js_malloc(J, n + 1); /* add space for string terminator */
57 if (!s) {
58 fclose(f);
59 js_error(J, "cannot allocate storage for file contents: '%s'", filename);
60 }
61
62 t = fread(s, 1, (size_t)n, f);
63 if (t != n) {
64 js_free(J, s);
65 fclose(f);
66 js_error(J, "cannot read data from file: '%s'", filename);
67 }
68
69 s[n] = 0; /* zero-terminate string containing file data */
70
71 if (js_try(J)) {
72 js_free(J, s);
73 fclose(f);
74 js_throw(J);
75 }
76
77 js_ppstring(J, filename, s, minify);
78
79 js_free(J, s);
80 fclose(f);
81 js_endtry(J);
82 }
83
84 int
main(int argc,char ** argv)85 main(int argc, char **argv)
86 {
87 js_State *J;
88 int minify = 0;
89 int i;
90
91 J = js_newstate(NULL, NULL, 0);
92
93 for (i = 1; i < argc; ++i) {
94 if (!strcmp(argv[i], "-m"))
95 minify = 1;
96 else if (!strcmp(argv[i], "-mm"))
97 minify = 2;
98 else if (!strcmp(argv[i], "-s"))
99 minify = 3;
100 else {
101 if (js_try(J)) {
102 js_report(J, js_trystring(J, -1, "Error"));
103 js_pop(J, 1);
104 continue;
105 }
106 js_ppfile(J, argv[i], minify);
107 js_endtry(J);
108 }
109 }
110
111 js_gc(J, 0);
112 js_freestate(J);
113
114 return 0;
115 }
116