|
14 | 14 | import keyword |
15 | 15 | import types |
16 | 16 |
|
| 17 | +from java2python.lang import tokens |
| 18 | + |
17 | 19 |
|
18 | 20 | def invalidPythonNames(): |
19 | 21 | """ Creates a list of valid Java identifiers that are invalid in Python. """ |
@@ -55,6 +57,38 @@ def syntaxSafeFloatLiteral(node, config): |
55 | 57 | node.token.text = value |
56 | 58 |
|
57 | 59 |
|
| 60 | +def lengthToLen(node, config): |
| 61 | + """ Transforms expressions like 'value.length()' to 'len(value)'. |
| 62 | +
|
| 63 | + This method changes AST branches like this: |
| 64 | +
|
| 65 | + METHOD_CALL [start=45, stop=49] |
| 66 | + DOT . [line=4, start=45, stop=47] |
| 67 | + IDENT foo [line=4, start=45] |
| 68 | + IDENT length [line=4, start=47] |
| 69 | + ARGUMENT_LIST [line=4, start=48, stop=49] |
| 70 | +
|
| 71 | + Into branches like this: |
| 72 | +
|
| 73 | + IDENT len(foo) [line=4, start=45] |
| 74 | +
|
| 75 | + Notice that the resulting IDENT node text is invalid. We can't use a |
| 76 | + METHOD_CALL token because those are always bound to a class or instance. |
| 77 | + It would be best to add a new token type, and that option will be explored |
| 78 | + if we run into this problem again. |
| 79 | +
|
| 80 | + """ |
| 81 | + dot = node.parent |
| 82 | + method = dot.parent |
| 83 | + |
| 84 | + ident = dot.firstChildOfType(tokens.IDENT) |
| 85 | + ident.token.text = 'len({})'.format(ident.text) |
| 86 | + |
| 87 | + expr = method.parent |
| 88 | + expr.children.remove(method) |
| 89 | + expr.addChild(ident) |
| 90 | + |
| 91 | + |
58 | 92 | def typeSub(node, config): |
59 | 93 | """ Maps specific, well-known Java types to their Python counterparts. |
60 | 94 |
|
|
0 commit comments