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 all 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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ If your project is a multi-package monorepo, you can follow the instructions
| [fp-ts/prefer-chain](docs/rules/prefer-chain.md) | Replace `map` + `flatten` with `chain` | 💡 | |
| [fp-ts/prefer-bimap](docs/rules/prefer-bimap.md) | Replace `map` + `mapLeft` with `bimap` | 💡 | |
| [fp-ts/no-discarded-pure-expression](docs/rules/no-discarded-pure-expression.md) | Disallow expressions returning pure data types (like `Task` or `IO`) in statement position | 💡 | 🦄 |
| [fp-ts/prefer-constructor](docs/rules/prefer-constructor.md) | Replace destructors with constructors | 💡 | 🦄 |

### Fixable legend:

Expand Down
35 changes: 35 additions & 0 deletions docs/rules/prefer-constructor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Replace destructors with constructors (fp-ts/prefer-constructor)

Suggest replacing the combination of a destructor and constructors with a constructor when changing types.

This rule covers:

- `Option.fromEither`

**💡 Fixable**: This rule provides in-editor suggested fixes.

## Rule Details

Examples of **incorrect** code for this rule:

```ts
import { either, option } from "fp-ts"
import { pipe } from "fp-ts/function"

pipe(
either.of(1),
either.fold(() => option.none, option.some)
)
```

Examples of **correct** code for this rule:

```ts
import { either, option } from "fp-ts"
import { pipe } from "fp-ts/function"

pipe(
either.of(1),
option.fromEither
)
```
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const suggestions = {
"no-redundant-flow": require("./rules/no-redundant-flow").default,
"prefer-chain": require("./rules/prefer-chain").default,
"prefer-bimap": require("./rules/prefer-bimap").default,
"prefer-constructor": require("./rules/prefer-constructor").default
};

export const rules = {
Expand Down
61 changes: 61 additions & 0 deletions src/rules/prefer-constructor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { option, readonlyNonEmptyArray } from "fp-ts"
import { flow, pipe } from "fp-ts/function"
import { contextUtils, createRule, ensureArguments } from "../utils"

export default createRule({
name: "prefer-constructor",
meta: {
type: "suggestion",
fixable: "code",
hasSuggestions: true,
schema: [],
docs: {
description: "Replace destructor + constructors with a constructor",
recommended: "warn"
},
messages: {
eitherFoldIsOptionFromEither: "Either.fold can be replaced with Option.fromEither",
replaceEitherFoldWithOptionFromEither: "replace Either.fold with Option.fromEither"
}
},
defaultOptions: [],
create(context) {
const { findNamespace, isCall, isLazyValue } = contextUtils(context)
return {
CallExpression(node) {
pipe(
node,
option.of,
option.filter(isCall("Either", "fold")),
option.chain(ensureArguments([
isLazyValue("Option", "none"),
isCall("Option", "some")
])),
option.bind("namespace", flow(readonlyNonEmptyArray.head, findNamespace)),
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`
)
]
}
}
]
})
})
)
}
}
}
})
189 changes: 173 additions & 16 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, readonlyArray, readonlyNonEmptyArray } from "fp-ts";
import { constant, flow, pipe } from "fp-ts/function";

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

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

type Module = typeof modules[number]

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> {
type Callee =
| TSESTree.CallExpression
| TSESTree.MemberExpression
| TSESTree.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 All @@ -71,12 +77,17 @@ export function calleeIdentifier(
}
}

function isWithinTypes<N extends TSESTree.Node>(
n: TSESTree.Node | undefined,
types: N["type"][]
): n is N {
return !!n && types.includes(n.type);
}
const isWithinTypes = <T extends TSESTree.Node>(types: T["type"][]) => (node: TSESTree.Node): node is T => types.includes(node.type)

const isArrowFunctionExpression = isWithinTypes<TSESTree.ArrowFunctionExpression>([AST_NODE_TYPES.ArrowFunctionExpression])

const isCallExpression = isWithinTypes<TSESTree.CallExpression>([AST_NODE_TYPES.CallExpression])

const isCallee = isWithinTypes<Callee>([AST_NODE_TYPES.CallExpression, AST_NODE_TYPES.MemberExpression, AST_NODE_TYPES.Identifier])

const isIdentifier = isWithinTypes<TSESTree.Identifier>([AST_NODE_TYPES.Identifier])

const isMemberExpression = isWithinTypes<TSESTree.MemberExpression>([AST_NODE_TYPES.MemberExpression])

type CombinatorNode =
| TSESTree.CallExpression
Expand Down Expand Up @@ -106,11 +117,11 @@ export function getAdjacentCombinators<
const firstCombinatorIndex = pipeOrFlowExpression.arguments.findIndex(
(a, index) => {
if (
isWithinTypes(a, combinator1.types) &&
isWithinTypes(combinator1.types)(a) &&
index < pipeOrFlowExpression.arguments.length - 1
) {
const b = pipeOrFlowExpression.arguments[index + 1];
if (isWithinTypes(b, combinator2.types)) {
if (b && isWithinTypes(combinator2.types)(b)) {
return pipe(
apply.sequenceS(option.option)({
idA: calleeIdentifier(a),
Expand Down Expand Up @@ -191,6 +202,91 @@ 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)
)

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

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

const getFirstArgument = flow(
getArguments,
option.map(readonlyNonEmptyArray.head)
)

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

const getFirstParam = flow(
getParams,
option.map(readonlyNonEmptyArray.head)
)

const isIdentifierWithName = (expected: string) => flow(
option.fromPredicate(isIdentifier),
option.exists(({ name }) => name === expected)
)

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

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

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

export const contextUtils = <
TMessageIds extends string,
TOptions extends readonly unknown[]
Expand Down Expand Up @@ -461,6 +557,64 @@ export const contextUtils = <
);
}

const isCall = <T extends TSESTree.Node>(module: Module, name: string) => (node: T) => pipe(
node,
option.fromPredicate(isArrowFunctionExpression),
option.chain(getWrappedCall),
option.altW(constant(option.some(node))),
option.filter(isCallee),
option.exists(isCallTo(module, name))
)

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

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

const isValue = (module: Module, name: string) => flow(
option.fromPredicate((node: TSESTree.MemberExpression) => pipe(node.property, isIdentifierWithName(name))),
option.chain(typeOfNode),
option.exists(isFromModule(module))
)

const isConstantCall = flow(
(node: TSESTree.CallExpression) => pipe(node, calleeIdentifier),
option.filter(({ name }) => name === "constant"),
option.chain(typeOfNode),
option.exists(isFromModule("function"))
)

const findMemberExpressionFromCallExpression = flow(
option.fromPredicate(isConstantCall),
option.chain(getFirstArgument),
option.filter(isMemberExpression)
)

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

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

return {
addNamedImportIfNeeded,
removeImportDeclaration,
Expand All @@ -471,6 +625,9 @@ export const contextUtils = <
typeOfNode,
isFromFpTs,
parserServices,
isCall,
isLazyValue,
findNamespace,
};
};

Expand Down
Loading