INRIA / INRIA/spoon

Add method to `SourcePosition` for creating sub-positions

Open
#5,264 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
2k
Forks
392
Avg merge
11h 24m
Merged PRs (30d)
36

Description

### Motivation

Some Methods on spoon elements return a `String` instead of an element with a source position, like for example `CtStatement::getLabel`. It is undesireable to use the entire position including the label, when only the label is of interest. (there are other examples as well, like arrays... -_-)

My solution is to locate the label in the source code from spoon and calculate the correct offsets, then create a new source position with it:

```java
int start = matcher.start();
int length = matcher.end() - start;

return ctElement.getFactory().createSourcePosition(
position.getCompilationUnit(),
position.getSourceStart() + start,
position.getSourceStart() + start + length,
position.getCompilationUnit().getLineSeparatorPositions()
);
```

I do not feel confident about the correctness of the code (not sure what `getLineSeparatorPositions` is).

### Suggestion
One could make this easier by providing a new method for `SourcePosition` that does create a sub-position with the correct compilation unit and file set:
```java
interface SourcePosition {
default SourcePosition range(int start, int end) {
return ctElement.getFactory().createSourcePosition(
this.getCompilationUnit(),
this.getSourceStart() + start,
this.getSourceStart() + start + (end - start),
this.getCompilationUnit().getLineSeparatorPositions()
);
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.