0
# Code Generation
1
2
Specialized output generation system that converts AST nodes into optimized JavaScript code. The output system supports multiple JavaScript versions, formatting options, and advanced optimization features.
3
4
## Capabilities
5
6
### Output Stream
7
8
Core output stream class that manages JavaScript code generation with formatting and indentation.
9
10
```javascript { .api }
11
/**
12
* Output stream for JavaScript code generation
13
*/
14
class OutputStream {
15
constructor(options: OutputOptions);
16
17
/** Print text to the output stream */
18
print(text: string): void;
19
20
/** Print text with a space separator */
21
space(): void;
22
23
/** Print an indented block */
24
with_indent(body: () => void): void;
25
26
/** Print text with parentheses if needed */
27
with_parens(body: () => void): void;
28
29
/** Print a comma-separated list */
30
with_commas(elements: any[], printer: (element: any) => void): void;
31
32
/** Print a block statement with braces */
33
with_block(body: () => void): void;
34
35
/** Get the complete generated output */
36
get(): string;
37
38
/** Get the complete generated output (alias for get) */
39
toString(): string;
40
41
/** Current indentation level */
42
indentation(): number;
43
44
/** Current line number */
45
current_line(): number;
46
47
/** Current column position */
48
current_col(): number;
49
}
50
51
interface OutputOptions {
52
/** Generate formatted, readable JavaScript (default: true) */
53
beautify?: boolean;
54
55
/** Wrap output in private scope function wrapper (default: true) */
56
private_scope?: boolean;
57
58
/** Exclude base library functions from output (default: false) */
59
omit_baselib?: boolean;
60
61
/** Target JavaScript version: 5 or 6 (default: 5) */
62
js_version?: number;
63
64
/** Preserve docstrings as __doc__ attributes (default: false) */
65
keep_docstrings?: boolean;
66
67
/** Remove assert statements from output (default: false) */
68
discard_asserts?: boolean;
69
70
/** Cache directory for compiled modules */
71
module_cache_dir?: string;
72
73
/** Pre-loaded base library code */
74
baselib_plain?: string;
75
76
/** Comment preservation strategy */
77
comments?: boolean | Function;
78
79
/** Semicolon insertion policy */
80
semicolons?: boolean;
81
82
/** Preserve line numbers from source */
83
preserve_line?: boolean;
84
85
/** Beautification options */
86
beautify_options?: BeautifyOptions;
87
}
88
89
interface BeautifyOptions {
90
/** Indent string (default: " ") */
91
indent_start?: number;
92
93
/** Indent increment (default: 4) */
94
indent_level?: number;
95
96
/** Quote style for strings */
97
quote_keys?: boolean;
98
99
/** Space after colon in objects */
100
space_colon?: boolean;
101
102
/** ASCII output only */
103
ascii_only?: boolean;
104
105
/** Inline script safety */
106
inline_script?: boolean;
107
108
/** Width for line breaks */
109
width?: number;
110
111
/** Maximum line length */
112
max_line_len?: number;
113
}
114
```
115
116
**Usage Examples:**
117
118
```javascript
119
const { create_compiler } = require("rapydscript-ng");
120
const RapydScript = create_compiler();
121
122
// Basic output generation
123
const ast = RapydScript.parse("def hello(): print('Hello')");
124
const output = new RapydScript.OutputStream({
125
beautify: true,
126
js_version: 5
127
});
128
ast.print(output);
129
console.log(output.get());
130
131
// Minified output
132
const minified = new RapydScript.OutputStream({
133
beautify: false,
134
semicolons: true
135
});
136
ast.print(minified);
137
console.log(minified.get());
138
139
// ES6 output with preserved docstrings
140
const es6Output = new RapydScript.OutputStream({
141
beautify: true,
142
js_version: 6,
143
keep_docstrings: true,
144
private_scope: false
145
});
146
```
147
148
### Code Generation Options
149
150
Advanced configuration for controlling JavaScript output characteristics.
151
152
```javascript { .api }
153
/**
154
* JavaScript version-specific features
155
*/
156
interface JSVersionFeatures {
157
/** Use ES6 arrow functions */
158
arrow_functions: boolean;
159
160
/** Use ES6 template literals */
161
template_literals: boolean;
162
163
/** Use ES6 const/let declarations */
164
block_scoped_vars: boolean;
165
166
/** Use ES6 for...of loops */
167
for_of_loops: boolean;
168
169
/** Use ES6 destructuring */
170
destructuring: boolean;
171
172
/** Use ES6 classes */
173
native_classes: boolean;
174
175
/** Use ES6 generators */
176
native_generators: boolean;
177
178
/** Use ES6 iterators */
179
native_iterators: boolean;
180
}
181
182
/**
183
* Comment preservation strategies
184
*/
185
interface CommentOptions {
186
/** Preserve all comments */
187
all?: boolean;
188
189
/** Preserve license/copyright comments */
190
license?: boolean;
191
192
/** Custom filter function */
193
filter?: (comment: AST_Token, type: string) => boolean;
194
}
195
```
196
197
### Base Library Integration
198
199
Control how Python runtime functions are included in the output.
200
201
```javascript { .api }
202
/**
203
* Base library inclusion options
204
*/
205
interface BaseLibOptions {
206
/** Include complete base library */
207
complete?: boolean;
208
209
/** Include only used functions */
210
minimal?: boolean;
211
212
/** External base library reference */
213
external?: string;
214
215
/** Inline base library functions */
216
inline?: boolean;
217
}
218
219
/**
220
* Python built-in functions available in base library
221
*/
222
interface PythonBuiltins {
223
// Type conversion
224
int: (value: any, base?: number) => number;
225
float: (value: any) => number;
226
bool: (value: any) => boolean;
227
str: (value: any) => string;
228
229
// Container functions
230
len: (obj: any) => number;
231
range: (start: number, stop?: number, step?: number) => Iterator;
232
enumerate: (iterable: any, start?: number) => Iterator;
233
zip: (...iterables: any[]) => Iterator;
234
235
// Higher-order functions
236
map: (func: Function, ...iterables: any[]) => Iterator;
237
filter: (func: Function, iterable: any) => Iterator;
238
sorted: (iterable: any, key?: Function, reverse?: boolean) => any[];
239
240
// Object introspection
241
isinstance: (obj: any, class_or_tuple: any) => boolean;
242
hasattr: (obj: any, name: string) => boolean;
243
getattr: (obj: any, name: string, default?: any) => any;
244
setattr: (obj: any, name: string, value: any) => void;
245
}
246
```
247
248
### Module System Output
249
250
Control how RapydScript's module system is compiled to JavaScript.
251
252
```javascript { .api }
253
/**
254
* Module output options
255
*/
256
interface ModuleOptions {
257
/** Module system format */
258
format?: 'commonjs' | 'amd' | 'umd' | 'iife' | 'es6';
259
260
/** External dependencies */
261
externals?: {[name: string]: string};
262
263
/** Module name for UMD/IIFE formats */
264
name?: string;
265
266
/** Global variable mapping */
267
globals?: {[name: string]: string};
268
}
269
270
/**
271
* Import resolution configuration
272
*/
273
interface ImportOptions {
274
/** Import search paths */
275
paths?: string[];
276
277
/** Module aliases */
278
alias?: {[name: string]: string};
279
280
/** File extensions to try */
281
extensions?: string[];
282
283
/** Main file names to try */
284
main_files?: string[];
285
}
286
```
287
288
### Output Generation Process
289
290
The complete output generation workflow with all available options.
291
292
```javascript { .api }
293
/**
294
* Complete output generation workflow
295
*/
296
function generateJavaScript(
297
sourceCode: string,
298
options: CompilationOptions
299
): CompilationResult;
300
301
interface CompilationOptions extends ParseOptions, OutputOptions {
302
/** Source filename */
303
filename?: string;
304
305
/** Include source maps */
306
source_map?: boolean;
307
308
/** Source map options */
309
source_map_options?: SourceMapOptions;
310
311
/** Optimization level */
312
optimize?: number;
313
314
/** Dead code elimination */
315
dead_code?: boolean;
316
317
/** Variable renaming/mangling */
318
mangle?: boolean;
319
}
320
321
interface CompilationResult {
322
/** Generated JavaScript code */
323
code: string;
324
325
/** Source map (if requested) */
326
map?: string;
327
328
/** Compilation warnings */
329
warnings: Warning[];
330
331
/** Import dependencies */
332
dependencies: string[];
333
334
/** Generated AST */
335
ast: AST_Toplevel;
336
}
337
338
interface SourceMapOptions {
339
/** Source map filename */
340
filename?: string;
341
342
/** Include sources content */
343
include_sources?: boolean;
344
345
/** Source root URL */
346
source_root?: string;
347
}
348
```
349
350
### Advanced Output Features
351
352
Specialized output generation for specific use cases.
353
354
```javascript { .api }
355
/**
356
* Conditional compilation support
357
*/
358
interface ConditionalOptions {
359
/** Compile-time constants */
360
defines?: {[name: string]: any};
361
362
/** Feature flags */
363
features?: string[];
364
365
/** Debug mode */
366
debug?: boolean;
367
368
/** Production mode optimizations */
369
production?: boolean;
370
}
371
372
/**
373
* Runtime profiling and debugging
374
*/
375
interface DebuggingOptions {
376
/** Include runtime profiling hooks */
377
profile?: boolean;
378
379
/** Include debugging information */
380
debug_info?: boolean;
381
382
/** Line number preservation */
383
line_numbers?: boolean;
384
385
/** Function name preservation */
386
function_names?: boolean;
387
}
388
```
389
390
### Usage Examples
391
392
**Complete Compilation Workflow:**
393
394
```javascript
395
const { create_compiler } = require("rapydscript-ng");
396
const RapydScript = create_compiler();
397
398
// Advanced compilation with all options
399
function compileRapydScript(sourceCode, filename) {
400
try {
401
// Parse with full options
402
const ast = RapydScript.parse(sourceCode, {
403
filename: filename,
404
basedir: path.dirname(filename),
405
libdir: '/usr/local/lib/rapydscript/lib',
406
import_dirs: ['./modules', './vendor'],
407
discard_asserts: process.env.NODE_ENV === 'production'
408
});
409
410
// Generate optimized output
411
const output = new RapydScript.OutputStream({
412
beautify: process.env.NODE_ENV !== 'production',
413
private_scope: true,
414
js_version: 6,
415
keep_docstrings: process.env.NODE_ENV !== 'production',
416
discard_asserts: process.env.NODE_ENV === 'production',
417
comments: process.env.NODE_ENV !== 'production',
418
semicolons: true,
419
beautify_options: {
420
indent_level: 2,
421
max_line_len: 120,
422
space_colon: true
423
}
424
});
425
426
ast.print(output);
427
428
return {
429
code: output.get(),
430
ast: ast,
431
success: true
432
};
433
434
} catch (error) {
435
return {
436
error: error.message,
437
success: false
438
};
439
}
440
}
441
```
442
443
**Custom Output Formatting:**
444
445
```javascript
446
// Create custom output stream with specific formatting
447
const customOutput = new RapydScript.OutputStream({
448
beautify: true,
449
beautify_options: {
450
indent_level: 8, // 8-space indentation
451
quote_keys: true, // Always quote object keys
452
space_colon: false, // No space after colons
453
ascii_only: true, // ASCII-only output
454
max_line_len: 80 // 80-character line limit
455
},
456
comments: function(node, comment) {
457
// Only preserve comments containing 'TODO' or 'FIXME'
458
return /TODO|FIXME/i.test(comment.value);
459
}
460
});
461
```
462
463
**ES6-Specific Output:**
464
465
```javascript
466
// Generate modern ES6 JavaScript
467
const es6Output = new RapydScript.OutputStream({
468
js_version: 6,
469
beautify: true,
470
private_scope: false, // Use ES6 modules instead
471
beautify_options: {
472
indent_level: 2,
473
space_colon: true
474
}
475
});
476
477
// The output will use:
478
// - Arrow functions instead of function expressions
479
// - const/let instead of var
480
// - Template literals instead of string concatenation
481
// - Native classes instead of function constructors
482
// - for...of loops instead of array iteration
483
```