Skip to content

Commit

Permalink
chore(rosetta): change how python shows declared types and include mo…
Browse files Browse the repository at this point in the history
…dule name (#3317)

Currently, Python type declarations are rendered as such:

```python
# get_book_handler is of type Function
# get_book_integration is of type LambdaIntegration


get_book_integration = apigateway.LambdaIntegration(get_book_handler,
    content_handling=apigateway.ContentHandling.CONVERT_TO_TEXT,  # convert to base64
    credentials_passthrough=True
)
```

This PR adds information on what module the type came from (if possible), and changes the way these type declarations are shown:

```python
# get_book_handler: lambda.Function
# get_book_integration: apigateway.LambdaIntegration


get_book_integration = apigateway.LambdaIntegration(get_book_handler,
    content_handling=apigateway.ContentHandling.CONVERT_TO_TEXT,  # convert to base64
    credentials_passthrough=True
)
```

---

By submitting this pull request, I confirm that my contribution is made under the terms of the [Apache 2.0 license].

[Apache 2.0 license]: https://www.apache.org/licenses/LICENSE-2.0
  • Loading branch information
kaizencc authored Jan 5, 2022
1 parent 215f3c4 commit d34881c
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 11 deletions.
15 changes: 8 additions & 7 deletions packages/jsii-rosetta/lib/languages/python.ts
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@ export class PythonVisitor extends DefaultVisitor<PythonLanguageContext> {
(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), ': ', renderedType], []);
}

return new OTree([context.convert(node.name), ' = ', context.convert(node.initializer)], [], {
Expand Down Expand Up @@ -731,21 +731,22 @@ export class PythonVisitor extends DefaultVisitor<PythonLanguageContext> {
renderer.report(owningNode, jsiiType.message);
return fallback;
case 'map':
return `dictionary of string to ${doRender(jsiiType.elementType)}`;
return `Dict[str, ${doRender(jsiiType.elementType)}]`;
case 'list':
return `list of ${doRender(jsiiType.elementType)}`;
return `List[${doRender(jsiiType.elementType)}]`;
case 'namedType':
return jsiiType.name;
// in this case, the fallback will hold more information than jsiiType.name
return fallback;
case 'builtIn':
switch (jsiiType.builtIn) {
case 'boolean':
return 'boolean';
return 'bool';
case 'number':
return 'number';
case 'string':
return 'string';
return 'str';
case 'any':
return 'object';
return 'Any';
default:
return jsiiType.builtIn;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/jsii-rosetta/test/jsii-imports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,7 @@ const DEFAULT_CSHARP_CODE = [
];

/**
* Verify the Java output. All expected Java outputs look the same.
* Verify the output in the given language. All expected outputs look the same.
*/
function expectTranslation(trans: TranslatedSnippet, lang: TargetLanguage, expected: string[]) {
expect(trans.get(lang)?.source.split('\n')).toEqual(expected);
Expand Down
38 changes: 37 additions & 1 deletion packages/jsii-rosetta/test/translate.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { SnippetTranslator, TypeScriptSnippet, PythonVisitor } from '../lib';
import { SnippetTranslator, TypeScriptSnippet, PythonVisitor, TargetLanguage } from '../lib';
import { VisualizeAstVisitor } from '../lib/languages/visualize';
import { snippetKey } from '../lib/tablets/key';
import { TestJsiiModule, DUMMY_JSII_CONFIG } from './testutil';

const location = {
api: { api: 'moduleReadme', moduleFqn: '@aws-cdk/aws-apigateway' },
Expand Down Expand Up @@ -182,3 +183,38 @@ test('refuse to translate object literal with function member in shorthand prope
}),
);
});

test('declarations are translated correctly in all jsii languages', async () => {
// Create an assembly in a temp directory
const assembly = await TestJsiiModule.fromSource(
{
'index.ts': `
export class ClassA {
public someMethod() {
}
}
export class ClassB {
public anotherMethod() {
}
}
`,
},
{
name: 'my_assembly',
jsii: DUMMY_JSII_CONFIG,
},
);
try {
const ts = assembly.translateHere(
["import * as masm from 'my_assembly';", 'declare const classA: masm.ClassA;'].join('\n'),
);

expect(ts.get(TargetLanguage.PYTHON)?.source).toEqual(
['import example_test_demo as masm', '# class_a: masm.ClassA'].join('\n'),
);
expect(ts.get(TargetLanguage.JAVA)?.source).toEqual(['import example.test.demo.*;', 'ClassA classA;'].join('\n'));
expect(ts.get(TargetLanguage.CSHARP)?.source).toEqual(['using Example.Test.Demo;', 'ClassA classA;'].join('\n'));
} finally {
await assembly.cleanup();
}
});
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# array is of type list of string
# array: List[str]

print(array[3])
Original file line number Diff line number Diff line change
@@ -1 +1 @@
# variable is of type Type
# variable: Type

0 comments on commit d34881c

Please sign in to comment.