Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rename refactoring: keyword fields #444

Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
ed62e20
Extend/improve data type tests.
toinehartman Aug 16, 2024
f852237
Basic implementation of constructor field renaming.
toinehartman Aug 19, 2024
2fc4ec7
Implement basic constructor keyword fields.
toinehartman Aug 21, 2024
9ffbaff
Implement common keyword fields.
toinehartman Aug 22, 2024
fa965c1
Find nested (field) definitions as well.
toinehartman Aug 26, 2024
d2d8a7a
Fix cursor at ADT field def.
toinehartman Aug 26, 2024
98809e5
Simplify cursor calculation/preloading.
toinehartman Aug 26, 2024
f709bf0
Resolve reachable definitions in two directions.
toinehartman Aug 26, 2024
949c609
Re-use more generic field machinery.
toinehartman Aug 27, 2024
df99b82
Only rename definitions with the same role.
toinehartman Aug 28, 2024
5be976b
Fix iteration in presence of multiple definitions.
toinehartman Aug 29, 2024
0f28d3f
Support skipping cursors in multi-module tests.
toinehartman Aug 29, 2024
2a6108d
Resolve fields in data definitions.
toinehartman Aug 29, 2024
2d1bbf9
Fix existing field detection.
toinehartman Aug 29, 2024
18a18bf
Consider overloaded/reachable ADT defs only.
toinehartman Aug 30, 2024
216acc1
Find fields to rename in reachable scopes only.
toinehartman Aug 30, 2024
86a359a
Optimize repeated code and clean up.
toinehartman Aug 30, 2024
72a3202
Fix type errors.
toinehartman Sep 2, 2024
7dd59d0
Accept renaming from collection field projection.
toinehartman Sep 2, 2024
0a2ac13
Update documentation.
toinehartman Sep 2, 2024
d2ce994
Merge branch 'feature/rename-refactoring/cross-module' into feature/r…
toinehartman Sep 2, 2024
6b6c336
Clean up some more debugging artefacts.
toinehartman Sep 2, 2024
16d39b6
Merge branch 'feature/rename-refactoring/cross-module' into feature/r…
toinehartman Sep 5, 2024
fac01e3
Small fixes based on review by @PieterOlivier
toinehartman Sep 5, 2024
9c8c98f
Move path config function to workspace info field
toinehartman Sep 5, 2024
54d1a41
Split up logic to determine cursor kind.
toinehartman Sep 5, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions rascal-lsp/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,12 @@
<dependency>
<groupId>org.rascalmpl</groupId>
<artifactId>rascal-core</artifactId>
<version>0.12.3</version>
<version>0.12.4</version>
toinehartman marked this conversation as resolved.
Show resolved Hide resolved
</dependency>
<dependency>
<groupId>org.rascalmpl</groupId>
<artifactId>typepal</artifactId>
<version>0.13.4</version>
<version>0.14.0</version>
</dependency>
<!-- Rascal tests require JUnit 4 -->
<dependency>
Expand Down
159 changes: 114 additions & 45 deletions rascal-lsp/src/main/rascal/lang/rascal/lsp/refactor/Rename.rsc
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,10 @@ private set[IllegalRenameReason] rascalCheckCausesDoubleDeclarations(WorkspaceIn
};

rel[loc old, loc new] doubleFieldDeclarations = {<cD, nD>
| Define _: <fieldScope, _, _, fieldId(), nD, _> <- newDefs
, loc cD <- currentDefs
, ws.definitions[cD]?
, Define _: <fieldScope, _, _, fieldId(), cD, _> := ws.definitions[cD]
, fL <- ws.facts, at := ws.facts[fL]
, acons(aadt(_, _, _), _, _) := at
, isStrictlyContainedIn(cD, fL)
, isStrictlyContainedIn(nD, fL)
| Define _: <curFieldScope, _, _, fieldId(), cD, _> <- definitionsRel(ws)[currentDefs]
// The scope of a field def is the surrounding data def
, loc dataDef <- rascalGetOverloadedDefs(ws, {curFieldScope}, rascalMayOverloadSameName)
, loc nD <- (newDefs<idRole, defined>)[fieldId()] & (ws.defines<idRole, scope, defined>)[fieldId(), dataDef]
};

rel[loc old, loc new] doubleTypeParamDeclarations = {<cD, nD>
Expand All @@ -115,9 +111,8 @@ private set[IllegalRenameReason] rascalCheckCausesDoubleDeclarations(WorkspaceIn
, cT: aparameter(_, _) := ws.facts[cD]
, Define fD: <_, _, _, _, _, defType(afunc(_, funcParams:/cT, _))> <- ws.defines
, isContainedIn(cD, fD.defined)
, loc nD <- ws.facts
, <loc nD, nT: aparameter(newName, _)> <- toRel(ws.facts)
, isContainedIn(nD, fD.defined)
, nT: aparameter(newName, _) := ws.facts[nD]
, /nT := funcParams
};

Expand Down Expand Up @@ -225,18 +220,10 @@ private tuple[set[IllegalRenameReason] reasons, list[TextEdit] edits] computeTex
private tuple[set[IllegalRenameReason] reasons, list[TextEdit] edits] computeTextEdits(WorkspaceInfo ws, loc moduleLoc, set[loc] defs, set[loc] uses, str name) =
computeTextEdits(ws, parseModuleWithSpacesCached(moduleLoc), defs, uses, name);

private bool rascalMayOverloadSameName(set[loc] defs, map[loc, Define] definitions) {
set[str] names = {definitions[l].id | l <- defs, definitions[l]?};
if (size(names) > 1) return false;

map[loc, Define] potentialOverloadDefinitions = (l: d | l <- definitions, d := definitions[l], d.id in names);
return rascalMayOverload(defs, potentialOverloadDefinitions);
}

private bool rascalIsFunctionLocalDefs(WorkspaceInfo ws, set[loc] defs) {
for (d <- defs) {
if (Define _: <_, _, _, _, funDef, defType(afunc(_, _, _))> <- ws.defines
, isContainedIn(ws.definitions[d].scope, funDef)) {
if (Define fun: <_, _, _, _, _, defType(afunc(_, _, _))> <- ws.defines
, isContainedIn(ws.definitions[d].scope, fun.defined)) {
continue;
}
return false;
Expand All @@ -249,24 +236,46 @@ private bool rascalIsFunctionLocal(WorkspaceInfo ws, cursor(def(), cursorLoc, _)
private bool rascalIsFunctionLocal(WorkspaceInfo ws, cursor(use(), cursorLoc, _)) =
rascalIsFunctionLocalDefs(ws, rascalGetOverloadedDefs(ws, getDefs(ws, cursorLoc), rascalMayOverloadSameName));
private bool rascalIsFunctionLocal(WorkspaceInfo _, cursor(typeParam(), _, _)) = true;
private bool rascalIsFunctionLocal(WorkspaceInfo _, cursor(collectionField(), _, _)) = false;
private bool rascalIsFunctionLocal(WorkspaceInfo _, cursor(moduleName(), _, _)) = false;
private default bool rascalIsFunctionLocal(_, _) = false;

tuple[Cursor, WorkspaceInfo] rascalGetCursor(WorkspaceInfo ws, Tree cursorT) {
Maybe[AType] rascalAdtCommonKeywordFieldType(WorkspaceInfo ws, str fieldName, Define _:<_, _, _, dataId(), _, DefInfo defInfo>) {
toinehartman marked this conversation as resolved.
Show resolved Hide resolved
if (defInfo.commonKeywordFields?
, kwf:(KeywordFormal) `<Type _> <Name kwName> = <Expression _>` <- defInfo.commonKeywordFields
, "<kwName>" == fieldName) {
if (ft:just(_) := getFact(ws, kwf.src)) return ft;
throw "Unknown field type for <kwf.src>";
}
return nothing();
}

Maybe[AType] rascalConsKeywordFieldType(str fieldName, Define _:<_, _, _, constructorId(), _, defType(acons(_, _, kwFields))>) {
if (kwField(fieldType, fieldName, _) <- kwFields) return just(fieldType);
return nothing();
}

Maybe[AType] rascalConsFieldType(str fieldName, Define _:<_, _, _, constructorId(), _, defType(acons(_, fields, _))>) {
if (field <- fields, field.alabel == fieldName) return just(field);
return nothing();
}

Cursor rascalGetCursor(WorkspaceInfo ws, Tree cursorT) {
toinehartman marked this conversation as resolved.
Show resolved Hide resolved
loc cursorLoc = cursorT.src;
str cursorName = "<cursorT>";

ws = preLoad(ws);

rel[loc field, loc container] fields = {<fieldLoc, containerLoc>
| /Tree t := parseModuleWithSpacesCached(cursorLoc.top)
, just(<containerLoc, fieldLocs>) := rascalGetFieldLocs(cursorName, t)
, just(<containerLoc, fieldLocs, _>) := rascalGetFieldLocs(cursorName, t)
, loc fieldLoc <- fieldLocs
};

rel[loc kw, loc container] keywords = {<kwLoc, containerLoc>
| /Tree t := parseModuleWithSpacesCached(cursorLoc.top)
, just(<containerLoc, kwLocs, _>) := rascalGetKeywordLocs(cursorName, t)
, loc kwLoc <- kwLocs
};

Maybe[loc] smallestFieldContainingCursor = findSmallestContaining(fields.field, cursorLoc);
Maybe[loc] smallestKeywordContainingCursor = findSmallestContaining(keywords.kw, cursorLoc);

rel[loc l, CursorKind kind] locsContainingCursor = {
<l, k>
Expand All @@ -279,6 +288,13 @@ tuple[Cursor, WorkspaceInfo] rascalGetCursor(WorkspaceInfo ws, Tree cursorT) {
, <findSmallestContaining({l | l <- ws.facts, aparameter(cursorName, _) := ws.facts[l]}, cursorLoc), typeParam()>
// Any kind of field; we'll decide which exactly later
, <smallestFieldContainingCursor, collectionField()>
, <smallestFieldContainingCursor, dataField(|unknown:///|, avoid())>
, <smallestFieldContainingCursor, dataKeywordField(|unknown:///|, avoid())>
, <smallestFieldContainingCursor, dataCommonKeywordField(|unknown:///|, avoid())>
// Any kind of keyword param; we'll decide which exactly later
, <smallestKeywordContainingCursor, dataKeywordField(|unknown:///|, avoid())>
, <smallestKeywordContainingCursor, dataCommonKeywordField(|unknown:///|, avoid())>
, <smallestKeywordContainingCursor, keywordParam()>
// Module name declaration, where the cursor location is in the module header
, <flatMap(rascalLocationOfName(parseModuleWithSpacesCached(cursorLoc.top).top.header), Maybe[loc](loc nameLoc) { return isContainedIn(cursorLoc, nameLoc) ? just(nameLoc) : nothing(); }), moduleName()>
}
Expand All @@ -288,48 +304,101 @@ tuple[Cursor, WorkspaceInfo] rascalGetCursor(WorkspaceInfo ws, Tree cursorT) {
throw unsupportedRename("Renaming \'<cursorName>\' at <cursorLoc> is not supported.");
}

Cursor getDataFieldCursor(loc container) {
for (Define dt <- rascalGetADTDefinitions(ws, container)
, adtType := dt.defInfo.atype) {
if (just(fieldType) := rascalAdtCommonKeywordFieldType(ws, cursorName, dt)) {
// Case 4 or 5 (or 0): common keyword field
return cursor(dataCommonKeywordField(dt.defined, fieldType), c, cursorName);
}

for (Define d: <_, _, _, constructorId(), _, defType(acons(adtType, _, _))> <- ws.defines) {
if (just(fieldType) := rascalConsKeywordFieldType(cursorName, d)) {
// Case 3 (or 0): keyword field
return cursor(dataKeywordField(dt.defined, fieldType), c, cursorName);
} else if (just(fieldType) := rascalConsFieldType(cursorName, d)) {
// Case 2 (or 0): positional field
return cursor(dataField(dt.defined, fieldType), c, cursorName);
}
}
}

set[loc] fromDefs = cursorLoc in ws.useDef<1> ? {cursorLoc} : getDefs(ws, cursorLoc);
throw illegalRename("Cannot rename \'<cursorName>\'; it is not defined in this workspace", {definitionsOutsideWorkspace(fromDefs)});
}

loc c = min(locsContainingCursor.l);
Cursor cur = cursor(use(), |unknown:///|, "");
// print("Locs containing cursor: ");
// iprintln(locsContainingCursor);
switch (locsContainingCursor[c]) {
case {moduleName(), *_}: {
cur = cursor(moduleName(), c, cursorName);
return cursor(moduleName(), c, cursorName);
}
case {keywordParam(), dataKeywordField(_, _), *_}: {
if ({loc container} := keywords[c]) {
return getDataFieldCursor(container);
}
}
case {collectionField(), dataField(_, _), dataKeywordField(_, _), dataCommonKeywordField(_, _), *_}: {
/* Possible cases:
0. We are on a field use/access (of either a data or collection field, in an expression/assignment/pattern(?))
1. We are on a collection field
2. We are on a positional field definition (inside a constructor variant, inside a data def)
3. We are on a keyword field definition (inside a constructor variant)
4. We are on a common keyword field definition (inside a data def)
5. We are on a (common) keyword argument (inside a constructor call)
*/

// Let's figure out what kind of field we are exactly
if ({loc container} := fields[c], maybeContainerType := getFact(ws, container)) {
if ((just(containerType) := maybeContainerType && rascalIsCollectionType(containerType))
|| maybeContainerType == nothing()) {
// Case 1 (or 0): collection field
return cursor(collectionField(), c, cursorName);
}
return getDataFieldCursor(container);
}
}
case {def(), *_}: {
// Cursor is at a definition
cur = cursor(def(), c, cursorName);
Define d = ws.definitions[c];
if (d.idRole is fieldId
, Define adt: <_, _, _, dataId(), _, _> <- ws.defines
, isStrictlyContainedIn(c, adt.defined)) {
return getDataFieldCursor(adt.defined);
}
return cursor(def(), c, cursorName);
}
case {use(), *_}: {
set[loc] defs = getDefs(ws, c);
set[Define] defines = {ws.definitions[d] | d <- defs, ws.definitions[d]?};

if (d <- defs, just(amodule(_)) := getFact(ws, d)) {
// Cursor is at an import
cur = cursor(moduleName(), c, cursorName);
return cursor(moduleName(), c, cursorName);
} else if (u <- ws.useDef<0>
, isContainedIn(cursorLoc, u)
, u.end > cursorLoc.end
// If the cursor is on a variable, we expect a module variable (`moduleVariable()`); not a local (`variableId()`)
, {variableId()} !:= (ws.defines<defined, idRole>)[getDefs(ws, u)]
) {
// Cursor is at a qualified name
cur = cursor(moduleName(), c, cursorName);
return cursor(moduleName(), c, cursorName);
} else if (defines != {}) {
// The cursor is at a use with corresponding definitions.
cur = cursor(use(), c, cursorName);
return cursor(use(), c, cursorName);
} else if (just(at) := getFact(ws, c)
, aparameter(cursorName, _) := at) {
// The cursor is at a type parameter
cur = cursor(typeParam(), c, cursorName);
return cursor(typeParam(), c, cursorName);
}
}
case {k}: {
cur = cursor(k, c, cursorName);
return cursor(k, c, cursorName);
}
}

if (cur.l.scheme == "unknown") throw unsupportedRename("Could not retrieve information for \'<cursorName>\' at <cursorLoc>.");

return <cur, ws>;
throw unsupportedRename("Could not retrieve information for \'<cursorName>\' at <cursorLoc>.");
}

private set[Name] rascalNameToEquivalentNames(str name) = {
Expand Down Expand Up @@ -362,11 +431,11 @@ private bool rascalContainsName(loc l, str name) {
- Aliases
- Data types
- Type parameters
- Data constructors
- Data constructor fields (fields, keyword fields, common keyword fields)

The following symbols are currently unsupported.
- Annotations (on functions)
- Data constructors
- Data constructor fields (fields, keyword fields, common keyword fields)

*Name resolution*
A renaming triggers the typechecker on the currently open file to determine the scope of the renaming.
Expand Down Expand Up @@ -400,7 +469,7 @@ list[DocumentEdit] rascalRenameSymbol(Tree cursorT, set[loc] workspaceFolders, s
// Preload
ProjectFiles() {
return { <
min([f | f <- workspaceFolders, isPrefixOf(f, cursorLoc)]),
max([f | f <- workspaceFolders, isPrefixOf(f, cursorLoc)]),
cursorLoc.top
> };
},
Expand Down Expand Up @@ -435,15 +504,15 @@ list[DocumentEdit] rascalRenameSymbol(Tree cursorT, set[loc] workspaceFolders, s
}
);

step("preloading minimal workspace information", 1);
ws = preLoad(ws);

step("analyzing name at cursor", 1);
<cur, ws> = rascalGetCursor(ws, cursorT);
cur = rascalGetCursor(ws, cursorT);

step("loading required type information", 1);
if (!rascalIsFunctionLocal(ws, cur)) {
println("Renaming not module-local; loading more information from workspace.");
ws = loadWorkspace(ws);
} else {
println("Renaming guaranteed to be module-local.");
}

step("collecting uses of \'<cursorName>\'", 1);
Expand All @@ -467,7 +536,7 @@ list[DocumentEdit] rascalRenameSymbol(Tree cursorT, set[loc] workspaceFolders, s
list[DocumentEdit] renames = [renamed(from, to) | <from, to> <- getRenames(newName)];

return changes + renames;
}, totalWork = 5);
}, totalWork = 6);

//// WORKAROUNDS

Expand Down
2 changes: 2 additions & 0 deletions rascal-lsp/src/main/rascal/lang/rascal/lsp/refactor/Util.rsc
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ rel[&K, &V] groupBy(set[&V] s, &K(&V) pred) =
}
bool byLength(loc l1, loc l2) = l1.length < l2.length;
toinehartman marked this conversation as resolved.
Show resolved Hide resolved

bool byLengthTuple(tuple[loc, &T] t1, tuple[loc, &T] t2) = byLength(t1[0], t2[0]);

@synopsis{
Predicate to sort locations by offset.
}
Expand Down
Loading
Loading