SimpleIdentifiier doesn't resolve staticElement

24 views
Skip to first unread message

Brett Sutton

unread,
Nov 20, 2023, 12:35:36 AM11/20/23
to Dart Analyzer Discussion
I'm trying to write an obfuscator for dart code.

Yes, I know the --obfuscate switch on the flutter compiler but this obfuscator is for source code.

The problem I have is that for each token I need to identify if it is externally or internally defined. If the token is externally defined then I shouldn't obfuscate the token as that will break things.

I'm using the GeneralizingAstVisitor to visit each node.

My problem is with the 'visitSimpleIdentifier' method.
I've mostly been able to rely on the staticElement to determine what package/library a token hails from but with the vistSimpleIdentifier the staticElement is null.

My code is fully resolved (my first attempt wasn't and staticElement was null everywhere).

The particular code that is giving me trouble is:
import 'dart:io';

void test() {
Directory.current = Directory.current.path;
}


The node 'Directory.current' causes the following elements to be visited:

```
- AssignmentExpression Director.current = xxx
     - PrefixedIdentifier  - Diretcory.current
           - SimpleIdentifier - current
```
When the `SimpleIdentifier` is visited I need to determine if `current` comes from a local package. In this case it doesn't so I shouldn't rename it.

So how do identify that 'current' is from a local package when staticElement is null.

I note that@brianwilkerson stated:
> It shouldn't. Assuming that you're working with a resolved AST, these identifiers (`SimpleIdentifier` everywhere except at declaration sites) should have a non-null `staticElement`. You can ask that element for its `library` (a `LibraryElement`). All of that information is already computed; you're just accessing data stored in fields.

This seems to go against what I'm seeing.

I'm using  analyzer: ^6.0.0




Brett Sutton

unread,
Nov 20, 2023, 1:16:59 AM11/20/23
to Dart Analyzer Discussion, Brett Sutton
I've had a chat on the discord and now understand that staticElement can't be set in an assignment.

I have some code that works in a least my small set of samples but I believe it won't handle everything.



/// If [node] is part of an assignment then we return
/// the library it belongs to.
Element? ifAssignment(SimpleIdentifier node) {
var parent = node.parent;
while (parent != null) {
if (parent case final AssignmentExpression assignment) {
if (node == assignment.leftHandSide ||
node.parent == assignment.leftHandSide) {
return assignment.writeElement?.library;
}
// TODO: apparently readElement has nothing to do with rhs
if (node.parent == assignment.rightHandSide) {
return assignment.readElement?.library;
}
}
parent = parent.parent;
}
return null;
}
Reply all
Reply to author
Forward
0 new messages