Skip to content

Commit

Permalink
before breaking
Browse files Browse the repository at this point in the history
  • Loading branch information
cancerberoSgx committed Jun 18, 2018
1 parent 1f3772e commit c1016fd
Show file tree
Hide file tree
Showing 11 changed files with 159 additions and 92 deletions.
6 changes: 6 additions & 0 deletions typescript-ast-util/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ export function findChildContainingRangeLight(sourceFile: ts.SourceFile, r: ts.T
}
return find(sourceFile)
}
export function findChildContainingRangeGetChildren(parent: ts.Node, r: ts.TextRange): ts.Node | undefined {
// let found:ts.Node = parent
let found:ts.Node = parent.getChildren().find(node => r.pos >= node.getFullStart() && r.end <= node.getEnd())
return found && findChildContainingRangeGetChildren(found, r) || parent
}

//TODO. rename to findFirstChildContainedRange
export function findChildContainedRange(sourceFile: ts.SourceFile, r: ts.TextRange): ts.Node | undefined {
function find(node: ts.Node): ts.Node | undefined {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,36 @@
function fofofofo1(n: number, date1: Date[][]): Promise<Boolean>{

function fofofofo1(date1: Date[][], n: number): Promise<Boolean>{
return Promise.resolve(true)
}


// &%&% reorderParams("fofofofo", [1, 0])
// &%&%
// &%&% /* Help: The second argument is the new order of parameters. Number N in index M means move the M-th
// &%&% argument to index N. Examples:
// &%&% * [1] means switch between first and second
// &%&% * [3, 2] means move the first parameter to fourth position and move the second parameter to the third.
// &%&% * (the rest of the parameters, (third and fourth) will move left to accommodate this requirements) */
function fofofofo(date1: Date[][], n: number): Promise<Boolean>{
function fofofofo(n: number, date1: Date[][] /* [1] */): Promise<Boolean>{
return Promise.resolve(true)
}

class C123 {
method1(d: Date, b: boolean[][], a: number): number[] {
return []
}

}

import { TypeGuards, QuoteKind } from 'ts-simple-ast';
import { EvalContext } from 'typescript-plugin-ast-inspector';
import { findChildContainingRangeLight, positionOrRangeToRange, findChildContainedRange, findChildContainingRangeGetChildren, getKindName } from 'typescript-ast-util';
import * as ts from 'typescript'
declare const c: EvalContext;

function eval1(){
const position = 151
const sourceFile = c.info.languageService.getProgram().getSourceFile(c.fileName)
// const target = findChildContainingRangeLight(sourceFile, positionOrRangeToRange(position))
const target = findChildContainingRangeGetChildren(sourceFile, positionOrRangeToRange(position))
c.print(getKindName(target)+ target.getFullText() + target.getLeadingTriviaWidth() + ' - ' + getLeadingTrivia(target)+' - '+
ts.getSyntheticLeadingComments(target).map(c=>c.text).join(', '))

function getLeadingTrivia(target){
return target.getFullText().substring(0, target.getLeadingTriviaWidth())
}
// const thisSourceFile = c.project.getSourceFile(c.fileName)
// consts node = thisSourceFile.getDescendantAtPos(position)
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
"name": "reOrderParamsLiteralObjectSpec",
"preLaunchTask": "build",
"args": [
"--config=spec/support/jasmine-js.json",
"**/reOrderParamsLiteralObjectSpec.js"
// "--config=spec/support/jasmine-js.json",
"/home/sg/git/typescript-plugins-of-mine/typescript-plugin-function-signature-refactors/dist/spec/reOrderParamsLiteralObjectSpec.js"
],
"runtimeArgs": [
"--inspect",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Node, ReferenceFindableNode } from 'ts-simple-ast';
import { createProjectFiles, modifyAndAssert } from "typescript-plugin-util";
import { reorderParameters } from '../src/refactors/reorderParams/reorderParams';

export function operation(reorder: number[]) {
export function reorderParamOperation(reorder: number[]) {
return function (node: ReferenceFindableNode & Node) {
reorderParameters(node, reorder, console.log)
}
Expand Down Expand Up @@ -41,7 +41,7 @@ describe('try to change signature param type', () => {
}
],
node: test.files.helper.getFunction('helper'),
modification: operation([1, 0])
modification: reorderParamOperation([1, 0])
})

modifyAndAssert({
Expand All @@ -58,7 +58,7 @@ describe('try to change signature param type', () => {
}
],
node: test.files.helper.getFunction('helper'),
modification: operation([2, 0, 1])
modification: reorderParamOperation([2, 0, 1])
})

modifyAndAssert({
Expand All @@ -75,7 +75,7 @@ describe('try to change signature param type', () => {
}
],
node: test.files.helper.getFunction('helper'),
modification: operation([2])
modification: reorderParamOperation([2])
})

})
Expand Down Expand Up @@ -126,7 +126,7 @@ describe('try to change signature param type', () => {
let test = createProjectFiles(dataWithClassesAndInterfaces)
modifyAndAssert({
node: test.files.Animal.getClass('Animal').getMethod('born'),
modification: operation([1, 0]),
modification: reorderParamOperation([1, 0]),
asserts: [
{
file: test.files.types,
Expand All @@ -145,6 +145,7 @@ describe('try to change signature param type', () => {
}
],
})

modifyAndAssert({
asserts: [
{
Expand All @@ -154,8 +155,9 @@ describe('try to change signature param type', () => {
}
],
node: test.files.Animal.getClass('Animal').getMethod('born'),
modification: operation([1, 3, 0])
modification: reorderParamOperation([1, 3, 0])
})

})


Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createProjectFiles, modifyAndAssert } from "typescript-plugin-util";
import { operation } from './reOrderParamsBasicSpec';
import { reorderParamOperation } from './reOrderParamsBasicSpec';
import { ObjectLiteralElementLike, TypeGuards } from 'ts-simple-ast';
import * as ts from 'typescript'

Expand Down Expand Up @@ -40,7 +40,7 @@ describe('reorder params literal objects', () => {
export interface Interface1{
method1(a: number,b: boolean,c: Date[][]): undefined
method2: (d: Date, isIt: boolean, names: string[]): number
method3: function(f: Date[][], isIt: boolean[], lastName: string): number
method3: (f: Date[][], isIt: boolean[], lastName: string): number
}
`
},
Expand Down Expand Up @@ -71,7 +71,7 @@ describe('reorder params literal objects', () => {
}
],
node: test.files.test1.getVariableDeclaration('obj').getFirstChildByKind(ts.SyntaxKind.ObjectLiteralExpression).getProperty('method1'),
modification: operation([1, 2])
modification: reorderParamOperation([1, 2])
})


Expand All @@ -97,7 +97,19 @@ describe('reorder params literal objects', () => {
}
],
node: test.files.test1.getVariableDeclaration('obj').getFirstChildByKind(ts.SyntaxKind.ObjectLiteralExpression).getProperty('method2'),
modification: operation([2])
modification: reorderParamOperation([2])
})

modifyAndAssert({
asserts: [
{
file: test.files.test2,
before: `obj.method2(false, ['sebastian'], date2)`,
after: `obj.method2(['sebastian'], date2, false)`,
},
],
node: test.files.test2.getStatements()[2].getFirstDescendantByKind(ts.SyntaxKind.PropertyAccessExpression).getNameNode(),
modification: reorderParamOperation([2])
})


Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createProjectFiles, modifyAndAssert } from "typescript-plugin-util";
import { operation } from './reOrderParamsBasicSpec';
import { reorderParamOperation } from './reOrderParamsBasicSpec';


describe('reorder params on other members than methods', () => {
Expand All @@ -22,24 +22,24 @@ describe('reorder params on other members than methods', () => {
]
})

modifyAndAssert({
asserts: [
// {
// file: test.files.index,
// before: `console.log(helper('param', 3.14, true))`,
// after: `constructor(private description: string, private name: string, private storeCreateDate: boolean)`,
// }, {
// file: test.files.helper,
// before: `export function helper(param1: string, param2: number, param3: boolean): string`,
// after: `export function helper(param2: number, param1: string, param3: boolean): string`,
// }
],
node: test.files.Thing.getClass('ThingImpl').getConstructors()[0],
modification: operation([1, 0])
})
console.log(test.files.Thing.getText());

test.project.getLanguageService().getDefinitionsAtPosition
// modifyAndAssert({
// asserts: [
// // {
// // file: test.files.index,
// // before: `console.log(helper('param', 3.14, true))`,
// // after: `constructor(private description: string, private name: string, private storeCreateDate: boolean)`,
// // }, {
// // file: test.files.helper,
// // before: `export function helper(param1: string, param2: number, param3: boolean): string`,
// // after: `export function helper(param2: number, param1: string, param3: boolean): string`,
// // }
// ],
// node: test.files.Thing.getClass('ThingImpl').getConstructors()[0],
// modification: reorderParamOperation([1, 0])
// })
// console.log(test.files.Thing.getText());

// test.project.getLanguageService().getDefinitionsAtPosition

})

Expand Down
3 changes: 1 addition & 2 deletions typescript-plugin-function-signature-refactors/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ function getCompletionsAtPosition(fileName: string, position: number, options: t
return prior
}

let selectedAction: Action
let opts: CodeFixOptions


Expand Down Expand Up @@ -76,7 +75,7 @@ function getEditsForRefactor(fileName: string, formatOptions: ts.FormatCodeSetti
catch (error) {
log(`getEditsForRefactor error ${error + ' - ' + error.stack}`)
}
log(`getEditsForRefactor ${selectedAction.name} took ${timeFrom(t0)}`)
log(`getEditsForRefactor ${actionName} took ${timeFrom(t0)}`)
}
return
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CallExpression, NamedNode, Node, ReferenceFindableNode, SignaturedDeclaration, SourceFile, TypeGuards } from "ts-simple-ast";
import * as ts from 'typescript';
import { findAscendant, findChildContainingRangeLight, getNextSibling, getPreviousSibling, positionOrRangeToRange } from 'typescript-ast-util';
import { findAscendant, findChildContainingRangeLight, getNextSibling, getPreviousSibling, positionOrRangeToRange, findChild, getKindName } from 'typescript-ast-util';
import { getChildrenForEachChild, getName } from "typescript-plugin-util";

/**
Expand All @@ -12,9 +12,9 @@ function getAllCallsExpressions(targetDeclaration: Node & ReferenceFindableNode,
for (const reference of referencedSymbol.getReferences()) {
const parent = reference.getNode().getParent()
const extras = [parent, parent.getParent && parent.getParent(), targetDeclaration]
const found = (extras
.concat(getChildrenForEachChild(parent)))
const collection = (extras.concat(getChildrenForEachChild(parent)))
.filter((value, pos, arr) => arr.indexOf(value) === pos)
const found = collection
.find(p =>
(!getName(p) || getName(targetDeclaration) === getName(p)) &&
(TypeGuards.isCallExpression(p) || TypeGuards.isSignaturedDeclaration(p))
Expand All @@ -25,7 +25,7 @@ function getAllCallsExpressions(targetDeclaration: Node & ReferenceFindableNode,
else {
log('getAllCallsExpressions ignoring reference parent: ' + parent.getKindName() +
' ref: ' + reference.getNode().getKindName() +
'chh ' + parent.getChildren().map(c => c.getKindName()).join(', ') +
', chh ' + parent.getChildren().map(c => c.getKindName()).join(', ') +
' ancestors: ' + parent.getAncestors().map(c => c.getKindName()).join(', ')
)
}
Expand All @@ -44,8 +44,6 @@ function getAllCallsExpressions(targetDeclaration: Node & ReferenceFindableNode,
* @param reorder [1,0] means switching the positions between first and second params
*/
export function reorderParameters(node: Node, reorder: number[], log: (msg: string) => void) {

// let targetDeclaration: Node & ReferenceFindableNode
if(TypeGuards.isReferenceFindableNode(node)){
getAllCallsExpressions(node, log).forEach(call => {
if (TypeGuards.isCallExpression(call)) {
Expand All @@ -57,28 +55,11 @@ export function reorderParameters(node: Node, reorder: number[], log: (msg: stri
})
}
else {// if(TypeGuards.isConstructorDeclaration(node)) {
console.log('!TypeGuards.isReferenceFindableNode(node)');
console.log('!TypeGuards.isReferenceFindableNode(node) '+node.getText());

//TODO: find interface constructor implememted by this one and rename that one and then run this function calling it with node.getAncestors().find(TypeGuards.isReferenceFindableNode) to rename new A calls
return []//TODO:
// node.getFirstAncestorByKind(ts.SyntaxKind.ClassDeclaration)
// targetDeclaration = node.getAncestors().find(TypeGuards.isReferenceFindableNode)
// targetDeclaration = node
return []
}
// if(!targetDeclaration){
// log('getAllCallsExpressions aborted since cannot find a isReferenceFindableNode ')
// return []
// }


// getAllCallsExpressions(targetDeclaration, log).forEach(call => {
// if (TypeGuards.isCallExpression(call)) {
// changeCallArgs(reorder, call.getArguments(), log)
// }
// else {
// changeCallArgs(reorder, call.getParameters(), log)
// }
// })
}

function changeCallArgs(reorder: ReadonlyArray<number>, args: ReadonlyArray<Node>, log: (msg: string) => void) {
Expand Down Expand Up @@ -138,27 +119,41 @@ function changeCallArgs(reorder: ReadonlyArray<number>, args: ReadonlyArray<Node
}

/** same as getFunction but in ts-simple-ast project */
export function getFunctionSimple(file: SourceFile, position: number, name: string): SignaturedDeclaration & NamedNode & Node | undefined {
export function getFunctionSimple(file: SourceFile, position: number, name: string, log: (msg: string) => void): SignaturedDeclaration & NamedNode & Node | undefined {
let expr = file.getDescendantAtPos(position)
if (!expr) {
return
}
const e = [expr].concat(expr.getAncestors()).find(e => TypeGuards.isSignaturedDeclaration(e) && TypeGuards.isNamedNode(e) && e.getName() === name)
if (TypeGuards.isSignaturedDeclaration(e) && TypeGuards.isNamedNode(e)) {
return e
// log('getfuncionsimple: '+expr.getKindName() + ' - ' + expr.getText() + ' - ' + expr.getAncestors().map(e=>e.getKindName() + ' - TypeGuards.isSignaturedDeclaration(e)||TypeGuards.isFunctionLikeDeclaration(e)' +( TypeGuards.isSignaturedDeclaration(e)||TypeGuards.isFunctionLikeDeclaration(e)) + ' - (TypeGuards.isNamedNode(e)||TypeGuards.isNameableNode(e)||TypeGuards.isPropertyNamedNode(e) '+((TypeGuards.isNamedNode(e)||TypeGuards.isNameableNode(e)||TypeGuards.isPropertyNamedNode(e)))))
const e = [expr].concat(expr.getAncestors()).find(e => (TypeGuards.isSignaturedDeclaration(e)||TypeGuards.isFunctionLikeDeclaration(e)) && (((TypeGuards.isNamedNode(e)||TypeGuards.isNameableNode(e)||TypeGuards.isPropertyNamedNode(e)) && e.getName() === name)))

if(!e){
return
}
// if (TypeGuards.isSignaturedDeclaration(e) && TypeGuards.isNamedNode(e)) {
return e as any
// }
}

export function getFunction(fileName: string, position: number, program: ts.Program) {
export function getFunction(fileName: string, position: number, program: ts.Program, log: (msg: string) => void) : ts.SignatureDeclaration|ts.CallExpression | ts.NewExpression{
const sourceFile = program.getSourceFile(fileName)
const node = findChildContainingRangeLight(sourceFile, positionOrRangeToRange(position))
if (!node) {
log('getFunction !node ')
return
}
const expr = findAscendant<ts.ExpressionStatement>(node, ts.isExpressionStatement, true)
let expr = findAscendant<ts.ExpressionStatement>(node, ts.isExpressionStatement, true)
if(!expr){
expr = findAscendant<ts.ExpressionStatement>(node, n=>getKindName(n).endsWith('Declaration'), true)
}
if (!expr) {
log('getFunction !expr ')
return
}
return [getNextSibling(expr), getPreviousSibling(expr)].find(ts.isFunctionLike)
let result: ts.SignatureDeclaration|ts.CallLikeExpression = [getNextSibling(expr)/* , getPreviousSibling(expr) */].find(ts.isFunctionLike)
if(!result){
findChild(getNextSibling(expr)/* || getPreviousSibling(expr) */, n => ts.isIdentifier(n) && !!(result = findAscendant(n, p=>/* log('getKindName '+getKindName(p)) || */ts.isCallSignatureDeclaration(p)||ts.isFunctionLike(p)||ts.isCallOrNewExpression(p))), true)
}
result && log('getFunction result '+getKindName(result) + ' - ' + result.getText())
return result
}

Loading

0 comments on commit c1016fd

Please sign in to comment.