cincheo / jsweet

A Java to JavaScript transpiler.
http://www.jsweet.org
Other
1.46k stars 160 forks source link

Problems when accessing elements from a tree #575

Closed renaudpawlak closed 4 years ago

renaudpawlak commented 4 years ago

This is not a PR to be merged at this point. It demonstrates issues related to accessing a model element / type from a tree. In the public API, this access can only be contextual (basically you need the compilation unit tree to get the tree path before accessing the element).

However, JSweet v2 implementation was not contextual because it used the sym and type fields in JCTree to access the elements. This leads to a complicated refactoring because in some cases (see the test of this PR), JSweet tries to access elements of trees that don't belong to the current compilation units (typically in case of overloads, but I believe it is the case when injecting default methods too).

In order to make the test pass, I had to introduce a reflection hack, which sucks but allows the getElement to work even when the compilation unit is not right. It would be possible to make it work, however when I see the complexity of the utility methods right now, I believe that it would be worth discussing other strategies.

lgrignon commented 4 years ago

This is the main remaining problem. The only other alternative I glimpse is maintaining a map of Tree => CompilationUnit for special cases, but this seems dubious. There would be a lot of cases to handle (default methods, overloads, ...), and it would be hard to get the actual compilation unit for a tree (for instance if we register a default method tree's compilation unit, its body statements would not benefit this mapping, and javac tree API is not easily traversable without a TreePath ... which requires a CompilationUnit ... 🤯)

TL;DR The hack seems the most effective solution to setup for now as a fallback. Indeed, we can sense that java tree API is directed toward TreePaths, CompilationUnit context, and we should try to stick to it as much as we can, but the transpiler historically uses some advanced and tricky features which drives us to this conclusion.