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

Turn folding an either into an option into an option.fromEither #64

Open
wants to merge 32 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 25 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
f6bb3fe
Start turning folding an either into an option into an option.fromEither
thewilkybarkid Feb 11, 2021
415aa5b
Only work on option.fold
thewilkybarkid Feb 12, 2021
a864859
Match project style more
thewilkybarkid Feb 12, 2021
dcecac3
Extract some functions
thewilkybarkid Feb 12, 2021
d7c8729
Make use of functions
thewilkybarkid Feb 12, 2021
89ea792
Use a pipe
thewilkybarkid Feb 12, 2021
7ec2f9f
More pipes
thewilkybarkid Feb 12, 2021
a3346ab
Filter out undefined
thewilkybarkid Feb 12, 2021
c696acf
Separate as a filter
thewilkybarkid Feb 12, 2021
f5c0bcf
Refactoring
thewilkybarkid Feb 12, 2021
345146b
Use Do notation
thewilkybarkid Feb 12, 2021
484b51e
Use a simpler pipe
thewilkybarkid Feb 12, 2021
c0175cc
Extract some functions
thewilkybarkid Feb 12, 2021
b388177
Extract a pipe
thewilkybarkid Feb 12, 2021
5a48836
Improve scoping and use short returns
thewilkybarkid Feb 12, 2021
ff96c47
Use types to check Either
thewilkybarkid Feb 13, 2021
3d5a844
Safely determine Option and function modules
thewilkybarkid Feb 15, 2021
2847883
Separate finding the member expression from whether it's option.none
thewilkybarkid Feb 15, 2021
d30b8a4
Set the right namespace
thewilkybarkid Feb 15, 2021
93332ee
Extract isCall and isValue
thewilkybarkid Feb 16, 2021
fa53426
Extract isLazyValue and isConstantCall
thewilkybarkid Feb 16, 2021
8683809
Use isCall everywhere
thewilkybarkid Feb 16, 2021
121bd6f
Rewrite isOptionSomeValue
thewilkybarkid Feb 16, 2021
e81e8e3
Really use isCall everywhere
thewilkybarkid Feb 16, 2021
c22df28
Simplify ensuring arguments
thewilkybarkid Feb 16, 2021
fc4e4ef
Move utilities out of the module
thewilkybarkid Feb 17, 2021
9cf00de
Add to documentation and configuration
thewilkybarkid Feb 17, 2021
ebf3ad7
Move context-aware utilities into contextUtils
thewilkybarkid Feb 17, 2021
a4a384e
Simplify utility changes
thewilkybarkid Feb 17, 2021
3fbaedb
Merge branch 'main' into either-fold-to-option
thewilkybarkid Feb 17, 2021
cb92266
CS tweaks
thewilkybarkid Feb 17, 2021
8b5d086
Merge branch 'main' into either-fold-to-option
thewilkybarkid May 5, 2022
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
204 changes: 204 additions & 0 deletions src/rules/prefer-constructor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
import { AST_NODE_TYPES, TSESTree } from "@typescript-eslint/experimental-utils"
import { option, readonlyArray, readonlyNonEmptyArray } from "fp-ts"
import { constant, flow, pipe } from "fp-ts/function"
import { calleeIdentifier, ContextUtils, contextUtils, createRule, isCallee, isFromModule, Module } from "../utils"

const hasName = (name: string) => (identifier: TSESTree.Identifier) => identifier.name === name

const hasLength = (length: number) => <T>(array: ReadonlyArray<T>) => array.length === length

const isArrowFunctionExpression = (node: TSESTree.Node): node is TSESTree.ArrowFunctionExpression => node.type === AST_NODE_TYPES.ArrowFunctionExpression

const isCallExpression = (node: TSESTree.Node): node is TSESTree.CallExpression => node.type === AST_NODE_TYPES.CallExpression

const isMemberExpression = (node: TSESTree.Node): node is TSESTree.MemberExpression => node.type === AST_NODE_TYPES.MemberExpression

const isIdentifier = (node: TSESTree.Node): node is TSESTree.Identifier => node.type === AST_NODE_TYPES.Identifier

const getArguments = (call: TSESTree.CallExpression) => pipe(
call.arguments,
readonlyNonEmptyArray.fromArray
)

const getFirstArgument = (call: TSESTree.CallExpression) => pipe(
call,
getArguments,
option.map(readonlyNonEmptyArray.head)
)

const getParams = (call: TSESTree.FunctionLike) => pipe(
call.params,
readonlyNonEmptyArray.fromArray
)

const getFirstParam = (call: TSESTree.FunctionLike) => pipe(
call,
getParams,
option.map(readonlyNonEmptyArray.head)
)

const isIdentifierWithName = (name: string) => (node: TSESTree.Node) => pipe(
node,
option.of,
option.filter(isIdentifier),
option.exists(hasName(name))
)

const hasPropertyIdentifierWithName = (name: string) => (node: TSESTree.MemberExpression) => pipe(
node.property,
isIdentifierWithName(name)
)

const getWrappedCall = (node: TSESTree.ArrowFunctionExpression) => pipe(
node.body,
option.of,
option.filter(isCallExpression),
option.filter(flow(
option.of,
option.bindTo("call"),
option.bind("param", () => pipe(node, getFirstParam, option.filter(isIdentifier))),
option.exists(({ call, param }) => pipe(call, hasArguments([isIdentifierWithName(param.name)])))
))
)

const isCall = <T extends TSESTree.Node>(utils: ContextUtils, module: Module, name: string) => (node: T) => pipe(
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There’s a generic here due to type inference problems.

node,
option.fromPredicate(isArrowFunctionExpression),
option.chain(getWrappedCall),
option.altW(constant(option.some(node))),
option.filter(isCallee),
option.exists(isCallTo(utils, module, name))
)

const isCallTo = ({ typeOfNode }: ContextUtils, module: Module, name: string) => flow(
calleeIdentifier,
option.filter(hasName(name)),
option.chain(typeOfNode),
option.exists(isFromModule(module))
)

const isLazyValue = (utils: ContextUtils, module: Module, name: string) => flow(
findMemberExpression(utils),
option.exists(isValue(utils, module, name))
)

const isValue = ({ typeOfNode }: ContextUtils, module: Module, name: string) => (node: TSESTree.MemberExpression) => pipe(
node,
option.of,
option.filter(hasPropertyIdentifierWithName(name)),
option.chain(typeOfNode),
option.exists(isFromModule(module))
)

const findMemberExpressionFromArrowFunctionExpression = (node: TSESTree.ArrowFunctionExpression) => pipe(
node.body,
option.of,
option.filter(isMemberExpression)
)

const isConstantCall = ({ typeOfNode }: ContextUtils) => (node: TSESTree.CallExpression) => pipe(
node,
calleeIdentifier,
option.filter(hasName("constant")),
option.chain(typeOfNode),
option.exists(isFromModule("function"))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could probably just check it’s from fp-ts rather than the type check.

)

const findMemberExpressionFromCallExpression = (utils: ContextUtils) => (node: TSESTree.CallExpression) => pipe(
node,
option.of,
option.filter(isConstantCall(utils)),
option.chain(getFirstArgument),
option.filter(isMemberExpression)
)

const findMemberExpression = (utils: ContextUtils) => (node: TSESTree.Expression) => {
switch (node.type) {
case AST_NODE_TYPES.ArrowFunctionExpression:
return findMemberExpressionFromArrowFunctionExpression(node)
case AST_NODE_TYPES.CallExpression:
return findMemberExpressionFromCallExpression(utils)(node)
default:
return option.none
}
}

const findNamespace = (utils: ContextUtils) => flow(
findMemberExpression(utils),
option.map((node) => node.object),
option.filter(isIdentifier),
option.map((identifier) => identifier.name)
)

const hasArguments = (args: ReadonlyArray<(node: TSESTree.Expression) => boolean>) => flow(
ensureArguments(args),
option.isSome
)

const ensureArguments = (args: ReadonlyArray<(node: TSESTree.Expression) => boolean>) => flow(
getArguments,
option.filter(pipe(args.length, hasLength)),
option.chain(
readonlyNonEmptyArray.traverseWithIndex(option.option)(
(i, value) => pipe(args, readonlyArray.lookup(i), option.filter(test => test(value)), option.map(constant(value)))
)
)
)

export default createRule({
name: "prefer-constructor",
meta: {
type: "suggestion",
fixable: "code",
schema: [],
docs: {
category: "Best Practices",
description: "afsafaf",
recommended: "warn"
},
messages: {
eitherFoldIsOptionFromEither: "cacsaffg",
replaceEitherFoldWithOptionFromEither: "dsagdgdsg"
}
},
defaultOptions: [],
create(context) {
const utils = contextUtils(context)
return {
CallExpression(node) {
pipe(
node,
option.of,
option.filter(isCall(utils, "Either", "fold")),
option.chain(ensureArguments([
isLazyValue(utils, "Option", "none"),
isCall(utils, "Option", "some")
])),
option.bind("namespace", flow(readonlyNonEmptyArray.head, findNamespace(utils))),
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't ideal, would rather use the imports than reading the code.

option.map(({ namespace }) => {
context.report({
loc: {
start: node.loc.start,
end: node.loc.end
},
messageId: "eitherFoldIsOptionFromEither",
suggest: [
{
messageId: "replaceEitherFoldWithOptionFromEither",
fix(fixer) {
return [
fixer.replaceTextRange(
node.range,
`${namespace}.fromEither`
)
]
}
}
]
})
})
)
}
}
}
})
62 changes: 54 additions & 8 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import {
} from "@typescript-eslint/experimental-utils";
import * as recast from "recast";
import { visitorKeys as tsVisitorKeys } from "@typescript-eslint/typescript-estree";
import { array, option, apply } from "fp-ts";
import { pipe } from "fp-ts/function";
import { array, option, apply, readonlyNonEmptyArray } from "fp-ts"
import { flow, pipe } from "fp-ts/function"

import estraverse from "estraverse";
import {
Expand All @@ -32,19 +32,29 @@ declare module "typescript" {
function toFileNameLowerCase(x: string): string;
}

const modules = ["Either", "Option", "function"] as const

export type Module = typeof modules[number]

const is = <T>(original: T) => (value: unknown): value is T => original === value

const isModule = (name: string): name is Module => modules.includes(name as Module)

const version = require("../package.json").version;

export const createRule = ESLintUtils.RuleCreator(
(name) =>
`https://github.com/buildo/eslint-plugin-fp-ts/blob/v${version}/docs/rules/${name}.md`
);

export function calleeIdentifier(
node:
| TSESTree.CallExpression
| TSESTree.MemberExpression
| TSESTree.Identifier
): option.Option<TSESTree.Identifier> {
export type Callee =
| TSESTree.CallExpression
| TSESTree.MemberExpression
| TSESTree.Identifier

export const isCallee = (node: TSESTree.Node): node is Callee => isWithinTypes(node, [AST_NODE_TYPES.CallExpression, AST_NODE_TYPES.MemberExpression, AST_NODE_TYPES.Identifier])

export function calleeIdentifier(node: Callee): option.Option<TSESTree.Identifier> {
switch (node.type) {
case AST_NODE_TYPES.MemberExpression:
if (node.property.type === AST_NODE_TYPES.Identifier) {
Expand Down Expand Up @@ -189,6 +199,41 @@ export function inferQuote(node: TSESTree.Literal): Quote {
return node.raw[0] === "'" ? "'" : '"';
}

const getDeclarationFileName = (declaration: ts.Declaration) => declaration.getSourceFile().fileName

const getDeclarations = flow(
(symbol: ts.Symbol) => symbol.getDeclarations(),
option.fromNullable,
option.chain(readonlyNonEmptyArray.fromArray)
)

const getFileName = flow(
(type: ts.Type) => type.aliasSymbol ?? type.symbol,
option.fromNullable,
option.chain(getDeclarations),
option.map(readonlyNonEmptyArray.head),
option.map(getDeclarationFileName)
)

const getFpTsModule = flow(
(fileName: string) => /\/fp-ts\/lib\/(.+?)\.d\.ts$/.exec(fileName),
option.fromNullable,
option.chain(array.lookup(1)),
option.filter(isModule)
)

const getModule = flow(
getFileName,
option.chain(getFpTsModule)
)

export const isFromModule = (module: Module) => flow(
getModule,
option.exists(is(module))
)

export type ContextUtils = ReturnType<typeof contextUtils>

export const contextUtils = <
TMessageIds extends string,
TOptions extends readonly unknown[]
Expand Down Expand Up @@ -460,6 +505,7 @@ export const contextUtils = <
}

return {
findModuleImport,
addNamedImportIfNeeded,
removeImportDeclaration,
isFlowExpression,
Expand Down
Loading