tstosc
Version:
A transpiler that convert TypeScript to SuperCollider's SCLang.
73 lines (70 loc) • 2.42 kB
JavaScript
import { writeFileSync } from 'fs';
import path, { join } from 'path';
import { convertTSSourceFileToSC, default_convert_file_option } from './ts_to_sc_convert/file_conv.js';
import { default_transpiler_option, default_generator_context } from './context.js';
import { SourceFileNotFoundError } from '../../util/error.js';
import { Result } from '../../util/Result.js';
class Generator {
program;
context;
constructor({
compiler_program,
context = default_generator_context,
transpiler_option = default_transpiler_option
}) {
this.program = compiler_program;
this.context = { ...context, compiler_program, transpiler_option };
}
/**
* Generate the SCLang result of inputted files.
*
* For now, all the files recorded in compiler program's `root_files_path` (`rootNames`)
* will be generated.
*
* @param output_path By default, current work directory.
*/
generateAll(output_path = ".") {
let outputed_file_name_index_dict = /* @__PURE__ */ new Map();
for (const f_name of this.program.getRootFileNames()) {
let output_index = outputed_file_name_index_dict.get(f_name) ?? -1;
const output_full_path = join(
output_path,
output_index >= 0 ? `${f_name}_${++output_index}` : f_name
).replace(/\.ts$/g, ".scd");
const result = this.generateFile({
name: f_name,
output_path: output_full_path
});
if (result.isErr()) {
return result;
}
outputed_file_name_index_dict.set(f_name, output_index);
}
return Result.createOk(null);
}
/**
*
* @throws `SourceFileNotFoundError` if the `name` cannot be used to get source file.
*/
generateFile({
name,
output_path = path.join(path.dirname(name), path.basename(name).replace(/\.ts$/g, ".scd")),
convertTSSourceFileToSC_option = default_convert_file_option
}) {
const source_file = this.program.getSourceFile(name);
if (source_file == void 0) {
return Result.createErr(SourceFileNotFoundError.forFile(name));
}
const converted = convertTSSourceFileToSC(source_file, this.context, convertTSSourceFileToSC_option);
if (converted.isOk()) {
writeFileSync(output_path, converted.unwrapOk().file);
return Result.createOk(null);
} else {
return Result.fromErr(converted);
}
}
getContext() {
return { ...this.context };
}
}
export { Generator };