Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 3 additions & 12 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [

{
"name": "Launch C# Compiler",
"type": "node",
Expand All @@ -20,14 +19,12 @@
"ts-node/register"
],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"smartStep": false,
"internalConsoleOptions": "openOnSessionStart",
"env": {
"TS_NODE_PROJECT": "tsconfig.build-csharp.json"
}
},

{
"name": "Launch Kotlin Compiler",
"type": "node",
Expand All @@ -43,14 +40,12 @@
"ts-node/register"
],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"smartStep": false,
"internalConsoleOptions": "openOnSessionStart",
"env": {
"TS_NODE_PROJECT": "tsconfig.build-kotlin.json"
}
},

{
"name": "Launch TypeScript Generator",
"type": "node",
Expand All @@ -66,14 +61,12 @@
"ts-node/register"
],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"smartStep": false,
"internalConsoleOptions": "openOnSessionStart",
"env": {
"TS_NODE_PROJECT": "tsconfig.build-csharp.json"
}
},

{
"name": "Launch JavaScript Compiler",
"type": "node",
Expand All @@ -83,11 +76,9 @@
"runtimeExecutable": "npm.cmd"
},
"runtimeArgs": [
"run-script",
"build",
"--inspect-brk=5858"
],
"port": 5858
"run",
"build"
]
}
]
}
3 changes: 0 additions & 3 deletions src.compiler/BuilderHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,6 @@ function findNode(node: ts.Node, kind: ts.SyntaxKind): ts.Node | null {
return null;
}

export function addNewLines(stmts: ts.Statement[]) {
return stmts.map(stmt => ts.addSyntheticTrailingComment(stmt, ts.SyntaxKind.SingleLineCommentTrivia, '', true));
}
export function getTypeWithNullableInfo(
checker: ts.TypeChecker,
node: ts.TypeNode | undefined,
Expand Down
21 changes: 12 additions & 9 deletions src.compiler/TranspilerBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default function (emitters: Emitter[], handleErrors: boolean = false) {
};

const parsedCommandLine = ts.getParsedCommandLineOfConfigFile(commandLine.options.project!, commandLine.options, parseConfigFileHost, /*extendedConfigCache*/ undefined, commandLine.watchOptions)!;
const pretty = !!ts.sys.writeOutputIsTTY && ts.sys.writeOutputIsTTY();
const pretty = !!ts.sys.writeOutputIsTTY?.();
if (pretty) {
reportDiagnostic = createDiagnosticReporter(true);
}
Expand All @@ -51,14 +51,17 @@ export default function (emitters: Emitter[], handleErrors: boolean = false) {
host: ts.createCompilerHost(parsedCommandLine.options),
});

const allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
const configFileParsingDiagnosticsLength = allDiagnostics.length;
allDiagnostics.push(...program.getSyntacticDiagnostics());

if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
allDiagnostics.push(...program.getOptionsDiagnostics());
allDiagnostics.push(...program.getGlobalDiagnostics());
allDiagnostics.push(...program.getSemanticDiagnostics());
let allDiagnostics: ts.Diagnostic[] = [];
if (handleErrors) {
allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
const syntacticDiagnostics = program.getSyntacticDiagnostics();
if (syntacticDiagnostics.length) {
allDiagnostics.push(...syntacticDiagnostics);
} else {
allDiagnostics.push(...program.getOptionsDiagnostics());
allDiagnostics.push(...program.getGlobalDiagnostics());
allDiagnostics.push(...program.getSemanticDiagnostics());
}
}

program.getTypeChecker();
Expand Down
22 changes: 10 additions & 12 deletions src.compiler/typescript/AlphaTabGenerator.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as ts from 'typescript';
import cloneEmit from './CloneEmitter';
import { GENERATED_FILE_HEADER } from './EmitterBase';
import serializerEmit from './SerializerEmitter';
import transpiler from '../TranspilerBase';
import * as path from 'path';
import * as fs from 'fs';

transpiler([{
Expand All @@ -11,18 +11,16 @@ transpiler([{
}, {
name: 'Serializer',
emit: serializerEmit
}]);
}], false);

// Write version file
import { version } from '../../package.json';
const fileHandle = fs.openSync('src/generated/VersionInfo.ts', 'w');
fs.writeSync(fileHandle, '// <auto-generated>\n');
fs.writeSync(fileHandle, '// This code was auto-generated.\n');
fs.writeSync(fileHandle, '// Changes to this file may cause incorrect behavior and will be lost if\n');
fs.writeSync(fileHandle, '// the code is regenerated.\n');
fs.writeSync(fileHandle, '// </auto-generated>\n');
fs.writeSync(fileHandle, 'export class VersionInfo {\n');
fs.writeSync(fileHandle, ` public static readonly version:string = '${version}';\n`);
fs.writeSync(fileHandle, ` public static readonly date:string = '${new Date().toISOString()}';\n`);
fs.writeSync(fileHandle, '}\n');
ts.sys.exit(ts.ExitStatus.Success);
fs.writeSync(fileHandle, `\
${GENERATED_FILE_HEADER}
export class VersionInfo {
public static readonly version: string = '${version}';
public static readonly date: string = '${new Date().toISOString()}';
}
`);
ts.sys.exit(ts.ExitStatus.Success);
10 changes: 4 additions & 6 deletions src.compiler/typescript/CloneEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import * as path from 'path';
import * as ts from 'typescript';
import createEmitter from './EmitterBase';
import { addNewLines } from '../BuilderHelpers';
import { getTypeWithNullableInfo, unwrapArrayItemType } from '../BuilderHelpers';

function removeExtension(fileName: string) {
Expand Down Expand Up @@ -137,7 +136,7 @@ function generateClonePropertyStatements(
]
)
)
])
], true)
)
];

Expand All @@ -154,7 +153,7 @@ function generateClonePropertyStatements(
ts.factory.createIdentifier('original'),
propertyName
),
ts.factory.createBlock(loopItems),
ts.factory.createBlock(loopItems, true),
undefined
)
);
Expand Down Expand Up @@ -255,7 +254,7 @@ function generateCloneBody(
}, new Array<ts.Statement>());

return ts.factory.createBlock(
addNewLines([
[
// const clone = new Type();
ts.factory.createVariableStatement(
undefined,
Expand All @@ -274,8 +273,7 @@ function generateCloneBody(
...bodyStatements,
// return json;
ts.factory.createReturnStatement(ts.factory.createIdentifier('clone'))
])
);
], true);
}

function createCloneMethod(
Expand Down
73 changes: 32 additions & 41 deletions src.compiler/typescript/EmitterBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,93 +2,84 @@ import * as path from 'path';
import * as ts from 'typescript';
import * as fs from 'fs';

export default function createEmitter(jsDocMarker: string, generate: (program: ts.Program, classDeclaration: ts.ClassDeclaration) => ts.SourceFile) {

export const GENERATED_FILE_HEADER = `\
// <auto-generated>
// This code was auto-generated.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>`;

export default function createEmitter(
jsDocMarker: string,
generate: (program: ts.Program, classDeclaration: ts.ClassDeclaration) => ts.SourceFile
) {
function generateClass(program: ts.Program, classDeclaration: ts.ClassDeclaration) {
const sourceFileName = path.relative(
path.resolve(program.getCompilerOptions().baseUrl!, 'src'),
path.resolve(classDeclaration.getSourceFile().fileName)
);

const result = generate(program, classDeclaration);
const defaultClass = result.statements.filter(stmt => ts.isClassDeclaration(stmt) &&
stmt.modifiers!.find(m => m.kind === ts.SyntaxKind.ExportKeyword)
)[0] as ts.ClassDeclaration;
const defaultClass = result.statements.find(
stmt => ts.isClassDeclaration(stmt) && stmt.modifiers!.find(m => m.kind === ts.SyntaxKind.ExportKeyword)
) as ts.ClassDeclaration;

const targetFileName = path.join(
path.resolve(program.getCompilerOptions().baseUrl!),
'src/generated',
path.dirname(sourceFileName),
defaultClass.name!.text + '.ts'
`${defaultClass.name!.text}.ts`
);

fs.mkdirSync(path.dirname(targetFileName), { recursive: true });

const fileHandle = fs.openSync(targetFileName, 'w');

fs.writeSync(fileHandle, '// <auto-generated>\n');
fs.writeSync(fileHandle, '// This code was auto-generated.\n');
fs.writeSync(fileHandle, '// Changes to this file may cause incorrect behavior and will be lost if\n');
fs.writeSync(fileHandle, '// the code is regenerated.\n');
fs.writeSync(fileHandle, '// </auto-generated>\n');
fs.writeSync(fileHandle, `${GENERATED_FILE_HEADER}\n`);

const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
const printer = ts.createPrinter();
const source = printer.printNode(ts.EmitHint.Unspecified, result, result);
const servicesHost: ts.LanguageServiceHost = {
getScriptFileNames: () => [targetFileName],
getScriptVersion: fileName => result.languageVersion.toString(),
getScriptSnapshot: fileName => {
if (fileName != targetFileName) {
return undefined;
}

return ts.ScriptSnapshot.fromString(source);
},
getScriptVersion: () => result.languageVersion.toString(),
getScriptSnapshot: fileName =>
fileName === targetFileName ? ts.ScriptSnapshot.fromString(source) : undefined,
getCurrentDirectory: () => process.cwd(),
getCompilationSettings: () => program.getCompilerOptions(),
getDefaultLibFileName: options => ts.getDefaultLibFilePath(options),
fileExists: fileName => fileName === targetFileName,
readFile: fileName => fileName === targetFileName ? source : "",
readFile: fileName => (fileName === targetFileName ? source : ''),
readDirectory: ts.sys.readDirectory,
directoryExists: ts.sys.directoryExists,
getDirectories: ts.sys.getDirectories,
getDirectories: ts.sys.getDirectories
};

const languageService = ts.createLanguageService(servicesHost, ts.createDocumentRegistry());
const textChanges: ts.TextChange[] = languageService.getFormattingEditsForDocument(targetFileName, {
const formattingChanges: ts.TextChange[] = languageService.getFormattingEditsForDocument(targetFileName, {
convertTabsToSpaces: true,
insertSpaceAfterCommaDelimiter: true,
insertSpaceAfterKeywordsInControlFlowStatements: true,
insertSpaceBeforeAndAfterBinaryOperators: true,
newLineCharacter: "\n",
indentStyle: ts.IndentStyle.Smart,
indentSize: 4,
tabSize: 4,
});
textChanges.sort((a, b) => b.span.start - a.span.start);
trimTrailingWhitespace: true
} as ts.FormatCodeSettings);
formattingChanges.sort((a, b) => b.span.start - a.span.start);

let finalText = source;
for (const textChange of textChanges) {
const { span } = textChange;
finalText = finalText.slice(0, span.start) + textChange.newText
+ finalText.slice(span.start + span.length);
for (const { span: { start, length }, newText } of formattingChanges) {
finalText = `${finalText.slice(0, start)}${newText}${finalText.slice(start + length)}`;
}

finalText = finalText.replace(/\/\/ */g, '');

fs.writeSync(fileHandle, finalText);
fs.writeSync(fileHandle, '\n');

fs.closeSync(fileHandle);
}

function scanSourceFile(program: ts.Program, sourceFile: ts.SourceFile) {
sourceFile.statements.forEach(stmt => {
if (ts.isClassDeclaration(stmt)) {
const isActive = ts.getJSDocTags(stmt).find(t => t.tagName.text === jsDocMarker);
if (isActive) {
generateClass(program, stmt);
}
if (ts.isClassDeclaration(stmt) && ts.getJSDocTags(stmt).some(t => t.tagName.text === jsDocMarker)) {
generateClass(program, stmt);
Comment thread
jonaro00 marked this conversation as resolved.
}
});
}
Expand All @@ -97,5 +88,5 @@ export default function createEmitter(jsDocMarker: string, generate: (program: t
program.getRootFileNames().forEach(file => {
scanSourceFile(program, program.getSourceFile(file)!);
});
}
}
};
}
6 changes: 3 additions & 3 deletions src.compiler/typescript/Serializer.fromJson.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import * as ts from 'typescript';
import { addNewLines, createNodeFromSource, setMethodBody } from '../BuilderHelpers';
import { createNodeFromSource, setMethodBody } from '../BuilderHelpers';
import { JsonSerializable } from './Serializer.common';

function generateFromJsonBody(serializable: JsonSerializable, importer: (name: string, module: string) => void) {
importer('JsonHelper', '@src/io/JsonHelper');
return ts.factory.createBlock(addNewLines([
return ts.factory.createBlock([
createNodeFromSource<ts.IfStatement>(`if(!m) {
return;
}`, ts.SyntaxKind.IfStatement),
Expand All @@ -17,7 +17,7 @@ function generateFromJsonBody(serializable: JsonSerializable, importer: (name: s
`JsonHelper.forEach(m, (v, k) => this.setProperty(obj, k.toLowerCase(), v));`,
ts.SyntaxKind.ExpressionStatement
)
]));
], true);
}

export function createFromJsonMethod(
Expand Down
Loading