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): literal map type is rendered as __object in C sharp #3047

Merged
merged 10 commits into from
Oct 11, 2021
51 changes: 51 additions & 0 deletions packages/jsii-rosetta/lib/jsii/jsii-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
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.result === 'map') {
return {
kind: 'map',
elementType: mapValuesType.elementType
? determineJsiiType(typeChecker, mapValuesType.elementType)
: { kind: 'builtIn', builtIn: 'any' },
};
}

// 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 };
}
107 changes: 47 additions & 60 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 {
typeWithoutUndefinedUnion,
builtInTypeName,
typeContainsUndefined,
parameterAcceptsUndefined,
mapElementType,
inferMapElementType,
} 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 @@ -415,7 +409,7 @@ export class CSharpVisitor extends DefaultVisitor<CSharpLanguageContext> {
});
}
// Type information missing and from context we prefer a map
return this.keyValueObjectLiteralExpression(node, undefined, renderer);
return this.keyValueObjectLiteralExpression(node, renderer);
}

public knownStructObjectLiteralExpression(
Expand All @@ -430,15 +424,9 @@ export class CSharpVisitor extends DefaultVisitor<CSharpLanguageContext> {
});
}

public keyValueObjectLiteralExpression(
node: ts.ObjectLiteralExpression,
valueType: ts.Type | undefined,
renderer: CSharpRenderer,
): OTree {
public keyValueObjectLiteralExpression(node: ts.ObjectLiteralExpression, renderer: CSharpRenderer): OTree {
// Try to infer an element type from the elements
if (valueType === undefined) {
valueType = inferMapElementType(node.properties, renderer);
}
const valueType = inferMapElementType(node.properties, renderer.typeChecker);

return new OTree(
['new Dictionary<string, ', this.renderType(node, valueType, false, 'object', renderer), '> { '],
Expand Down Expand Up @@ -541,15 +529,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 +620,39 @@ export class CSharpVisitor extends DefaultVisitor<CSharpLanguageContext> {
return fallback;
}

const nonUnionType = typeWithoutUndefinedUnion(type);
if (!nonUnionType) {
renderer.report(typeNode, 'Type unions in examples are not supported');
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 +664,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
10 changes: 3 additions & 7 deletions packages/jsii-rosetta/lib/languages/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { OTree, NO_SYNTAX } from '../o-tree';
import { AstRenderer, AstHandler, nimpl, CommentSyntax } from '../renderer';
import { voidExpressionString } from '../typescript/ast-utils';
import { ImportStatement } from '../typescript/imports';
import { mapElementType, typeWithoutUndefinedUnion } from '../typescript/types';
import { typeWithoutUndefinedUnion } from '../typescript/types';

import { TargetLanguage } from '.';

Expand Down 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, context);
}

public unknownTypeObjectLiteralExpression(node: ts.ObjectLiteralExpression, context: AstRenderer<C>): OTree {
Expand All @@ -170,11 +170,7 @@ export abstract class DefaultVisitor<C> implements AstHandler<C> {
return this.notImplemented(node, context);
}

public keyValueObjectLiteralExpression(
node: ts.ObjectLiteralExpression,
_valueType: ts.Type | undefined,
context: AstRenderer<C>,
): OTree {
public keyValueObjectLiteralExpression(node: ts.ObjectLiteralExpression, context: AstRenderer<C>): OTree {
return this.notImplemented(node, context);
}

Expand Down
97 changes: 43 additions & 54 deletions packages/jsii-rosetta/lib/languages/java.ts
Original file line number Diff line number Diff line change
@@ -1,13 +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, typeWithoutUndefinedUnion } from '../typescript/types';
import { typeWithoutUndefinedUnion } from '../typescript/types';
import { DefaultVisitor } from './default';

interface JavaContext {
Expand Down Expand Up @@ -268,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 @@ -443,14 +452,10 @@ export class JavaVisitor extends DefaultVisitor<JavaContext> {
public unknownTypeObjectLiteralExpression(node: ts.ObjectLiteralExpression, renderer: JavaRenderer): OTree {
return renderer.currentContext.inNewExprWithObjectLiteralAsLastArg
? this.renderObjectLiteralAsBuilder(node, renderer)
: this.keyValueObjectLiteralExpression(node, undefined, renderer);
: this.keyValueObjectLiteralExpression(node, renderer);
}

public keyValueObjectLiteralExpression(
node: ts.ObjectLiteralExpression,
_valueType: ts.Type | undefined,
renderer: JavaRenderer,
): OTree {
public keyValueObjectLiteralExpression(node: ts.ObjectLiteralExpression, renderer: JavaRenderer): OTree {
return new OTree(['Map.of('], renderer.updateContext({ inKeyValueList: true }).convertAll(node.properties), {
suffix: ')',
separator: ', ',
Expand Down Expand Up @@ -648,52 +653,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 = typeWithoutUndefinedUnion(type);
if (!nonUnionType) {
renderer.report(owningNode, 'Type unions in examples are not supported');
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
Loading