Skip to content

Instantly share code, notes, and snippets.

@DoctorGester
Created June 28, 2019 21:39
Show Gist options
  • Save DoctorGester/a27f34aed347708f267e516bf95e6c8f to your computer and use it in GitHub Desktop.
Save DoctorGester/a27f34aed347708f267e516bf95e6c8f to your computer and use it in GitHub Desktop.
function process_node(node: ts.Node): ts.Node | undefined {
if (node.kind == ts.SyntaxKind.CallExpression) {
const call = node as ts.CallExpression;
const signature = checker.getResolvedSignature(call);
const decl = signature.declaration;
if (!decl) return;
if (decl.kind == ts.SyntaxKind.FunctionDeclaration && decl.name.escapedText == "enum_to_string") {
const argument = call.arguments[0];
const type = checker.getTypeAtLocation(argument);
const flags = type.getFlags();
if ((flags & ts.TypeFlags.UnionOrIntersection) != 0) {
const inline_function_argument_name = "value";
let case_clauses;
if ((flags & ts.TypeFlags.EnumLike) != 0) {
const enum_decl = type.getSymbol().valueDeclaration as ts.EnumDeclaration;
case_clauses = enum_decl.members.map(member => {
return ts.createCaseClause(ts.createLiteral(parseInt(member.initializer.getText())), [
ts.createReturn(ts.createStringLiteral(member.name.getText()))
]);
});
} else {
const union = type as ts.UnionOrIntersectionType;
case_clauses = union.types.map(type => {
const value = (type as ts.LiteralType).value;
return ts.createCaseClause(ts.createLiteral(value), [
ts.createReturn(ts.createStringLiteral(type.getSymbol().getEscapedName().toString()))
]);
});
}
const switch_expression = ts.createSwitch(ts.createIdentifier(inline_function_argument_name), ts.createCaseBlock(case_clauses));
const code_block = ts.createBlock([
switch_expression
]);
const arrow_function = ts.createArrowFunction(
undefined,
undefined,
[
ts.createParameter(undefined, undefined, undefined, inline_function_argument_name)
],
undefined,
undefined,
code_block
);
return ts.createCall(arrow_function, undefined, [argument]);
} /*else if (ts.isEnumMember(symbol.valueDeclaration)) {
return ts.createStringLiteral(symbol.valueDeclaration.name.getText());
} */else {
error_out(argument,"Unsupported argument");
}
}
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment