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): incorrect transliteration for selective imports #3508

Merged
merged 3 commits into from
May 6, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/jsii-pacmak/lib/targets/go/documentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ export class Documentation {
}
}

public emitReadme(moduleFqn: string, readme: string, directory: string) {
const goReadme = this.rosetta.translateSnippetsInMarkdown({ api: 'moduleReadme', moduleFqn }, readme, TargetLanguage.GO, false);

const readmeFile = `${directory}/README.md`;
this.code.openFile(readmeFile);
for (const line of goReadme.split('\n')) {
this.code.line(line);
}
this.code.closeFile(readmeFile);
}

private emitComment(text = '') {
const lines = text.trim().split('\n');

Expand Down
31 changes: 13 additions & 18 deletions packages/jsii-pacmak/lib/targets/go/package.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CodeMaker } from 'codemaker';
import { Assembly, Type, Submodule as JsiiSubmodule } from 'jsii-reflect';
import { Assembly, ModuleLike as JsiiModuleLike, Type, Submodule as JsiiSubmodule } from 'jsii-reflect';
import { basename, dirname, join } from 'path';
import * as semver from 'semver';

Expand Down Expand Up @@ -42,10 +42,10 @@ export abstract class Package {
public readonly types: GoType[];

private readonly embeddedTypes = new Map<string, EmbeddedType>();
private readonly readmeFile?: ReadmeFile;

public constructor(
private readonly typeSpec: readonly Type[],
private readonly submoduleSpec: readonly JsiiSubmodule[],
private readonly jsiiModule: JsiiModuleLike,
public readonly packageName: string,
public readonly filePath: string,
public readonly moduleName: string,
Expand All @@ -56,11 +56,11 @@ export abstract class Package {
this.directory = filePath;
this.file = `${this.directory}/${packageName}.go`;
this.root = root ?? this;
this.submodules = this.submoduleSpec.map(
this.submodules = this.jsiiModule.submodules.map(
(sm) => new InternalPackage(this.root, this, sm),
);

this.types = this.typeSpec.map((type: Type): GoType => {
this.types = this.jsiiModule.types.map((type: Type): GoType => {
if (type.isInterfaceType() && type.datatype) {
return new Struct(this, type);
} else if (type.isInterfaceType()) {
Expand All @@ -74,6 +74,10 @@ export abstract class Package {
`Type: ${type.name} with kind ${type.kind} is not a supported type`,
);
});

if (this.jsiiModule.readme?.markdown) {
this.readmeFile = new ReadmeFile(this.jsiiModule.fqn, this.jsiiModule.readme.markdown, this.directory);
}
}

/*
Expand Down Expand Up @@ -121,6 +125,8 @@ export abstract class Package {
this.emitTypes(context);
code.closeFile(this.file);

this.readmeFile?.emit(context);

this.emitGoInitFunction(context);
this.emitSubmodules(context);

Expand Down Expand Up @@ -318,7 +324,6 @@ export abstract class Package {
export class RootPackage extends Package {
public readonly assembly: Assembly;
public readonly version: string;
private readonly readme?: ReadmeFile;
private readonly versionFile: VersionFile;

// This cache of root packages is shared across all root packages derived created by this one (via dependencies).
Expand All @@ -335,8 +340,7 @@ export class RootPackage extends Package {
const version = `${assembly.version}${goConfig.versionSuffix ?? ''}`;

super(
assembly.types,
assembly.submodules,
assembly,
packageName,
filePath,
moduleName,
Expand All @@ -349,19 +353,11 @@ export class RootPackage extends Package {
this.assembly = assembly;
this.version = version;
this.versionFile = new VersionFile(this.version);

if (this.assembly.readme?.markdown) {
this.readme = new ReadmeFile(
this.packageName,
this.assembly.readme.markdown,
);
}
}

public emit(context: EmitContext): void {
super.emit(context);
this.emitJsiiPackage(context);
this.readme?.emit(context);

this.emitGomod(context.code);
this.versionFile.emit(context.code);
Expand Down Expand Up @@ -518,8 +514,7 @@ export class InternalPackage extends Package {
parent === root ? packageName : `${parent.filePath}/${packageName}`;

super(
assembly.types,
assembly.submodules,
assembly,
packageName,
filePath,
root.moduleName,
Expand Down
38 changes: 5 additions & 33 deletions packages/jsii-pacmak/lib/targets/go/readme-file.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,16 @@
import { join } from 'path';

import { EmitContext } from './emit-context';
// import { Translation } from 'jsii-rosetta';
// import { INCOMPLETE_DISCLAIMER_COMPILING, INCOMPLETE_DISCLAIMER_NONCOMPILING } from '..';

export class ReadmeFile {
public constructor(
private readonly packageName: string,
private readonly document: string,
private readonly directory: string,
) {}

public emit({ code /*, rosetta */ }: EmitContext) {
const nameParts = this.packageName.split('.');
const file = join(
...nameParts.slice(0, nameParts.length - 11),
'README.md',
);

code.openFile(file);
const translated = this.document; // rosetta.translateSnippetsInMarkdown(this.document, 'go', prependDisclaimer);
for (const line of translated.split('\n')) {
code.line(line);
}
code.closeFile(file);
}

/*
function prependDisclaimer(translation: Translation) {
const source = addDisclaimerIfNeeded();
return { language: translation.language, source };

function addDisclaimerIfNeeded(): string {
if (translation.didCompile && INCOMPLETE_DISCLAIMER_COMPILING) {
return `// ${INCOMPLETE_DISCLAIMER_COMPILING}\n\n${translation.source}`;
}
if (!translation.didCompile && INCOMPLETE_DISCLAIMER_NONCOMPILING) {
return `// ${INCOMPLETE_DISCLAIMER_NONCOMPILING}\n\n${translation.source}`;
}
return translation.source;
public emit({ documenter }: EmitContext) {
if (!this.document) {
return;
}
documenter.emitReadme(this.packageName, this.document, this.directory)
}
*/
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

79 changes: 55 additions & 24 deletions packages/jsii-rosetta/lib/languages/go.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { analyzeObjectLiteral, determineJsiiType, JsiiType, ObjectLiteralStruct
import { OTree } from '../o-tree';
import { AstRenderer } from '../renderer';
import { isExported, isPublic, isPrivate, isReadOnly, isStatic } from '../typescript/ast-utils';
import { ImportStatement } from '../typescript/imports';
import { analyzeImportDeclaration, ImportStatement } from '../typescript/imports';
import {
determineReturnType,
inferMapElementType,
Expand Down Expand Up @@ -156,6 +156,32 @@ export class GoVisitor extends DefaultVisitor<GoLanguageContext> {

public identifier(node: ts.Identifier | ts.StringLiteral | ts.NoSubstitutionTemplateLiteral, renderer: GoRenderer) {
const symbol = renderer.typeChecker.getSymbolAtLocation(node);

// If the identifier corresponds to a renamed imported symbol, we need to use the original symbol name, qualified
// with the import package name, since Go does not allow generalized symbol aliasing (we *could* alias types, but
// not static functions or constructors).
const declaration = symbol?.valueDeclaration ?? symbol?.declarations?.[0];
if (declaration && ts.isImportSpecifier(declaration)) {
const importInfo = analyzeImportDeclaration(declaration.parent.parent.parent, renderer);
const packageName =
importInfo.moduleSymbol?.sourceAssembly?.packageJson.jsii?.targets?.go?.packageName ??
this.goName(importInfo.packageName, renderer, undefined);

const importedSymbol = declaration.propertyName
? renderer.typeChecker.getSymbolAtLocation(declaration.propertyName)
: symbol;
// Note: imported members are (by nature) always exported by the module they are imported from.
return new OTree([
packageName,
'.',
this.goName(
(declaration.propertyName ?? declaration.name).text,
renderer.updateContext({ isExported: true }),
importedSymbol,
),
]);
}

return new OTree([this.goName(node.text, renderer, symbol)]);
}

Expand All @@ -174,6 +200,26 @@ export class GoVisitor extends DefaultVisitor<GoLanguageContext> {

function determineClassName(this: GoVisitor, expr: ts.Expression): { classNamespace?: OTree; className: string } {
if (ts.isIdentifier(expr)) {
// Imported names are referred to by the original (i.e: exported) name, qualified with the source module's go
// package name.
const symbol = renderer.typeChecker.getSymbolAtLocation(expr);
const declaration = symbol?.valueDeclaration ?? symbol?.declarations?.[0];
if (declaration && ts.isImportSpecifier(declaration)) {
const importInfo = analyzeImportDeclaration(declaration.parent.parent.parent, renderer);
const packageName =
importInfo.moduleSymbol?.sourceAssembly?.packageJson.jsii?.targets?.go?.packageName ??
this.goName(importInfo.packageName, renderer, undefined);

return {
classNamespace: new OTree([packageName]),
className: this.goName(
(declaration.propertyName ?? declaration.name).text,
renderer.updateContext({ isExported: true }),
symbol,
),
};
}

return { className: ucFirst(expr.text) };
}
if (ts.isPropertyAccessExpression(expr)) {
Expand Down Expand Up @@ -761,34 +807,19 @@ export class GoVisitor extends DefaultVisitor<GoLanguageContext> {
: `github.com/aws-samples/dummy/${packageName}`;

if (node.imports.import === 'full') {
return new OTree(['import ', this.goName(node.imports.alias, renderer, undefined), ' "', moduleName, '"']);
}

// We'll just create local type aliases for all imported types. This is not very go-idiomatic, but simplifies things elsewhere...
const elements = node.imports.elements
.filter((element) => element.importedSymbol?.symbolType === 'type')
.map(
(element) =>
new OTree(['type ', element.alias ?? element.sourceName, ' ', packageName, '.', element.sourceName]),
);

const submodules = node.imports.elements
.filter((element) => element.importedSymbol?.symbolType === 'module')
.map(
(element) =>
new OTree(['import ', element.alias ?? element.sourceName, ' "', moduleName, '/', element.sourceName, '"']),
return new OTree(
['import ', this.goName(node.imports.alias, renderer, undefined), ' "', moduleName, '"'],
undefined,
{ canBreakLine: true },
);
}

if (elements.length === 0 && submodules.length === 0) {
if (node.imports.elements.length === 0) {
// This is a blank import (for side-effects only)
return new OTree(['import _ "', moduleName, '"']);
return new OTree(['import _ "', moduleName, '"'], undefined, { canBreakLine: true });
}

const mainImport = new OTree(['import ', packageName, ' "', moduleName, '"'], elements, {
canBreakLine: true,
separator: '\n',
});
return new OTree([mainImport, ...submodules]);
return new OTree(['import "', moduleName, '"'], undefined, { canBreakLine: true });
}

public variableDeclaration(node: ts.VariableDeclaration, renderer: AstRenderer<GoLanguageContext>): OTree {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
using Aws.Cdk.Lib;
using Constructs;
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import cdk "github.com/aws-samples/dummy/awscdklib"
import "github.com/aws-samples/dummy/constructs"
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import aws.cdk.lib.*;
import constructs.Construct;
import constructs.IConstruct;
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import aws_cdk_lib as cdk
from constructs import Construct, IConstruct
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import * as cdk from 'aws-cdk-lib';
import { Construct, IConstruct } from 'constructs';