Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(rosetta): support declare statements #3044

Merged
merged 5 commits into from
Oct 11, 2021
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
46 changes: 46 additions & 0 deletions packages/jsii-rosetta/lib/jsii/jsii-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import * as ts from 'typescript';

import { BuiltInType, builtInTypeName, mapElementType } from '../typescript/types';

// eslint-disable-next-line prettier/prettier
export type JsiiType =
| { kind: 'unknown' }
| { kind: 'error'; message: string }
| { kind: 'map'; elementType: JsiiType }
| { kind: 'list'; elementType: JsiiType }
| { kind: 'namedType'; name: string }
| { kind: 'builtIn'; builtIn: BuiltInType };

export function determineJsiiType(typeChecker: ts.TypeChecker, type: ts.Type): JsiiType {
// this means the snippet didn't have enough info for the TypeScript compiler to figure out the type -
// so, just render the fallback
if ((type as any).intrinsicName === 'error') {
return { kind: 'unknown' };
}

type = type.getNonNullableType();

if (type.isUnion() || type.isIntersection()) {
return { kind: 'error', message: 'Type unions or intersections are not supported in examples' };
}

const mapValuesType = mapElementType(type, typeChecker);
if (mapValuesType) {
return { kind: 'map', elementType: determineJsiiType(typeChecker, mapValuesType) };
}

// User-defined or aliased type
if (type.aliasSymbol) {
return { kind: 'namedType', name: type.aliasSymbol.name };
}
if (type.symbol) {
return { kind: 'namedType', name: type.symbol.name };
}

const typeScriptBuiltInType = builtInTypeName(type);
if (!typeScriptBuiltInType) {
return { kind: 'unknown' };
}

return { kind: 'builtIn', builtIn: typeScriptBuiltInType };
}
95 changes: 44 additions & 51 deletions packages/jsii-rosetta/lib/languages/csharp.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as ts from 'typescript';

import { determineJsiiType, JsiiType } from '../jsii/jsii-types';
import { jsiiTargetParam } from '../jsii/packages';
import { OTree, NO_SYNTAX } from '../o-tree';
import { AstRenderer, nimpl } from '../renderer';
Expand All @@ -13,14 +14,7 @@ import {
privatePropertyNames,
} from '../typescript/ast-utils';
import { ImportStatement } from '../typescript/imports';
import {
builtInTypeName,
typeContainsUndefined,
parameterAcceptsUndefined,
mapElementType,
inferMapElementType,
firstTypeInUnion,
} from '../typescript/types';
import { typeContainsUndefined, parameterAcceptsUndefined, inferMapElementType } from '../typescript/types';
import { flat, partition, setExtend } from '../util';
import { DefaultVisitor } from './default';
import { TargetLanguage } from './target-language';
Expand Down Expand Up @@ -541,15 +535,24 @@ export class CSharpVisitor extends DefaultVisitor<CSharpLanguageContext> {
}

public variableDeclaration(node: ts.VariableDeclaration, renderer: CSharpRenderer): OTree {
let fallback = 'var';
if (node.type) {
fallback = node.type.getText();
}

const type =
(node.type && renderer.typeOfType(node.type)) ||
(node.initializer && renderer.typeOfExpression(node.initializer));

let renderedType = this.renderType(node, type, false, 'var', renderer);
let renderedType = this.renderType(node, type, false, fallback, renderer);
if (renderedType === 'object') {
renderedType = 'var';
}

if (!node.initializer) {
return new OTree([renderedType, ' ', renderer.convert(node.name), ';'], []);
}

return new OTree(
[
renderedType,
Expand Down Expand Up @@ -623,18 +626,39 @@ export class CSharpVisitor extends DefaultVisitor<CSharpLanguageContext> {
return fallback;
}

const nonUnionType = firstTypeInUnion(renderer.typeChecker, type);
if (!nonUnionType) {
renderer.report(typeNode, 'Type unions in examples are not supported for csharp');
return '...';
}

const mappedTo = mapElementType(nonUnionType, renderer);
if (mappedTo) {
return `IDictionary<string, ${this.renderType(typeNode, mappedTo, questionMark, 'object', renderer)}>`;
const renderedType = doRender(determineJsiiType(renderer.typeChecker, type));

const suffix = questionMark || typeContainsUndefined(type) ? '?' : '';

return renderedType + suffix;

// eslint-disable-next-line consistent-return
function doRender(jsiiType: JsiiType): string {
switch (jsiiType.kind) {
case 'unknown':
return fallback;
case 'error':
renderer.report(typeNode, jsiiType.message);
return fallback;
case 'map':
return `IDictionary<string, ${doRender(jsiiType.elementType)}>`;
case 'list':
return `${doRender(jsiiType.elementType)}[]`;
case 'namedType':
return jsiiType.name;
case 'builtIn':
switch (jsiiType.builtIn) {
case 'boolean':
return 'boolean';
case 'number':
return 'int';
case 'string':
return 'string';
case 'any':
return 'object';
}
}
}

return typeNameFromType(nonUnionType, fallback) + (typeContainsUndefined(type) || questionMark ? '?' : '');
}

private classHeritage(node: ts.ClassDeclaration | ts.InterfaceDeclaration, renderer: CSharpRenderer) {
Expand All @@ -646,37 +670,6 @@ export class CSharpVisitor extends DefaultVisitor<CSharpLanguageContext> {
}
}

function typeNameFromType(type: ts.Type, fallback: string): string {
// User-defined or aliased type
if (type.aliasSymbol) {
return type.aliasSymbol.name;
}
if (type.symbol) {
return type.symbol.name;
}

const builtIn = builtInTypeName(type);
// *really* any OR we don't know what type it is
if (builtIn === 'any') {
return fallback;
}

return csharpTypeName(builtIn);
}

function csharpTypeName(jsTypeName: string | undefined): string {
if (jsTypeName === undefined) {
return 'void';
}
switch (jsTypeName) {
case 'number':
return 'int';
case 'any':
return 'object';
}
return jsTypeName;
}

/**
* Uppercase the first letter
*/
Expand Down
2 changes: 1 addition & 1 deletion packages/jsii-rosetta/lib/languages/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export abstract class DefaultVisitor<C> implements AstHandler<C> {
if (isKnownStruct) {
return this.knownStructObjectLiteralExpression(node, type!, context);
}
return this.keyValueObjectLiteralExpression(node, type && mapElementType(type, context), context);
return this.keyValueObjectLiteralExpression(node, type && mapElementType(type, context.typeChecker), context);
}

public unknownTypeObjectLiteralExpression(node: ts.ObjectLiteralExpression, context: AstRenderer<C>): OTree {
Expand Down
95 changes: 41 additions & 54 deletions packages/jsii-rosetta/lib/languages/java.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
import * as ts from 'typescript';

import { determineJsiiType, JsiiType } from '../jsii/jsii-types';
import { isStructType } from '../jsii/jsii-utils';
import { jsiiTargetParam } from '../jsii/packages';
import { TargetLanguage } from '../languages/target-language';
import { OTree, NO_SYNTAX } from '../o-tree';
import { AstRenderer } from '../renderer';
import { isReadOnly, matchAst, nodeOfType, quoteStringLiteral, visibility } from '../typescript/ast-utils';
import { ImportStatement } from '../typescript/imports';
import {
builtInTypeName,
mapElementType,
isEnumAccess,
isStaticReadonlyAccess,
firstTypeInUnion,
} from '../typescript/types';
import { isEnumAccess, isStaticReadonlyAccess } from '../typescript/types';
import { DefaultVisitor } from './default';

interface JavaContext {
Expand Down Expand Up @@ -274,11 +269,19 @@ export class JavaVisitor extends DefaultVisitor<JavaContext> {
}

public variableDeclaration(node: ts.VariableDeclaration, renderer: JavaRenderer): OTree {
let fallback = 'Object';
if (node.type) {
fallback = node.type.getText();
}
const type =
(node.type && renderer.typeOfType(node.type)) ||
(node.initializer && renderer.typeOfExpression(node.initializer));

const renderedType = type ? this.renderType(node, type, renderer, 'Object') : 'Object';
const renderedType = type ? this.renderType(node, type, renderer, fallback) : fallback;

if (!node.initializer) {
return new OTree([renderedType, ' ', renderer.convert(node.name), ';'], []);
}

return new OTree(
[
Expand Down Expand Up @@ -662,52 +665,36 @@ export class JavaVisitor extends DefaultVisitor<JavaContext> {
}

private renderType(owningNode: ts.Node, type: ts.Type, renderer: JavaRenderer, fallback: string): string {
// this means the snippet didn't have enough info for the TypeScript compiler to figure out the type -
// so, just render the fallback
if ((type as any).intrinsicName === 'error') {
return fallback;
}

const nonUnionType = firstTypeInUnion(renderer.typeChecker, type);
if (!nonUnionType) {
renderer.report(owningNode, 'Type unions in examples are not supported for java');
return fallback;
}

const mapValuesType = mapElementType(nonUnionType, renderer);
if (mapValuesType) {
return `Map<String, ${this.renderType(
owningNode,
mapValuesType,
renderer.updateContext({ requiresReferenceType: true }),
'Object',
)}>`;
}

// User-defined or aliased type
if (type.aliasSymbol) {
return type.aliasSymbol.name;
}
if (type.symbol) {
return type.symbol.name;
}

const typeScriptBuiltInType = builtInTypeName(nonUnionType);
if (!typeScriptBuiltInType) {
return fallback;
}

switch (typeScriptBuiltInType) {
case 'boolean':
return renderer.currentContext.requiresReferenceType ? 'Boolean' : 'boolean';
case 'number':
return 'Number';
case 'string':
return 'String';
case 'any':
return 'Object';
default:
return typeScriptBuiltInType;
return doRender(determineJsiiType(renderer.typeChecker, type), false);

// eslint-disable-next-line consistent-return
function doRender(jsiiType: JsiiType, requiresReferenceType: boolean): string {
switch (jsiiType.kind) {
case 'unknown':
return fallback;
case 'error':
renderer.report(owningNode, jsiiType.message);
return fallback;
case 'map':
return `Map<String, ${doRender(jsiiType.elementType, true)}>`;
case 'list':
return `${doRender(jsiiType.elementType, true)}[]`;
case 'namedType':
return jsiiType.name;
case 'builtIn':
switch (jsiiType.builtIn) {
case 'boolean':
return requiresReferenceType ? 'Boolean' : 'boolean';
case 'number':
return 'Number';
case 'string':
return 'String';
case 'any':
return 'Object';
default:
return jsiiType.builtIn;
}
}
}
}

Expand Down
54 changes: 54 additions & 0 deletions packages/jsii-rosetta/lib/languages/python.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as ts from 'typescript';

import { determineJsiiType, JsiiType } from '../jsii/jsii-types';
import { isStructType, propertiesOfStruct, StructProperty, structPropertyAcceptsUndefined } from '../jsii/jsii-utils';
import { jsiiTargetParam } from '../jsii/packages';
import { TargetLanguage } from '../languages/target-language';
Expand Down Expand Up @@ -418,6 +419,20 @@ export class PythonVisitor extends DefaultVisitor<PythonLanguageContext> {
}

public variableDeclaration(node: ts.VariableDeclaration, context: PythonVisitorContext): OTree {
let fallback = 'object';
if (node.type) {
fallback = node.type.getText();
}

if (!node.initializer) {
const type =
(node.type && context.typeOfType(node.type)) ||
(node.initializer && context.typeOfExpression(node.initializer));

const renderedType = type ? this.renderType(node, type, context, fallback) : fallback;
return new OTree(['# ', context.convert(node.name), ' is of type ', renderedType], []);
}

return new OTree([context.convert(node.name), ' = ', context.convert(node.initializer)], [], {
canBreakLine: true,
});
Expand Down Expand Up @@ -627,6 +642,45 @@ export class PythonVisitor extends DefaultVisitor<PythonLanguageContext> {

return new OTree([], converted, { separator: ', ', indent: 4 });
}

/**
* Render a type.
*
* Not usually a thing in Python, but useful for declared variables.
*/
private renderType(owningNode: ts.Node, type: ts.Type, renderer: PythonVisitorContext, fallback: string): string {
return doRender(determineJsiiType(renderer.typeChecker, type));

// eslint-disable-next-line consistent-return
function doRender(jsiiType: JsiiType): string {
switch (jsiiType.kind) {
case 'unknown':
return fallback;
case 'error':
renderer.report(owningNode, jsiiType.message);
return fallback;
case 'map':
return `dictionary of string to ${doRender(jsiiType.elementType)}`;
case 'list':
return `list of ${doRender(jsiiType.elementType)}`;
case 'namedType':
return jsiiType.name;
case 'builtIn':
switch (jsiiType.builtIn) {
case 'boolean':
return 'boolean';
case 'number':
return 'number';
case 'string':
return 'string';
case 'any':
return 'object';
default:
return jsiiType.builtIn;
}
}
}
}
}

function mangleIdentifier(originalIdentifier: string) {
Expand Down
Loading