prettier-plugin-solidity 1.1.4-dev → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prettier-plugin-solidity",
3
- "version": "1.1.4-dev",
3
+ "version": "1.3.0",
4
4
  "description": "A Prettier Plugin for automatically formatting your Solidity code.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -98,21 +98,21 @@
98
98
  "esmock": "^2.3.8",
99
99
  "exports-loader": "^4.0.0",
100
100
  "jest": "^29.6.3",
101
- "jest-light-runner": "^0.5.0",
101
+ "jest-light-runner": "^0.6.0",
102
102
  "jest-snapshot-serializer-ansi": "^2.1.0",
103
103
  "jest-snapshot-serializer-raw": "^2.0.0",
104
104
  "jest-watch-typeahead": "^2.2.2",
105
105
  "lines-and-columns": "^2.0.3",
106
- "prettier": "^3.0.2",
106
+ "prettier": "^3.1.0",
107
107
  "proxyquire": "^2.1.3",
108
- "solc": "^0.8.21",
108
+ "solc": "^0.8.23-fixed",
109
109
  "webpack": "^5.88.2",
110
110
  "webpack-cli": "^5.1.4"
111
111
  },
112
112
  "dependencies": {
113
- "@solidity-parser/parser": "^0.16.1",
113
+ "@solidity-parser/parser": "^0.17.0",
114
114
  "semver": "^7.5.4",
115
- "solidity-comments-extractor": "^0.0.7"
115
+ "solidity-comments-extractor": "^0.0.8"
116
116
  },
117
117
  "peerDependencies": {
118
118
  "prettier": ">=2.3.0"
@@ -5,13 +5,19 @@ const { group, line, indent } = doc.builders;
5
5
  const groupIfNecessaryBuilder = (path) => (document) =>
6
6
  path.getParentNode().type === 'BinaryOperation' ? document : group(document);
7
7
 
8
- const indentIfNecessaryBuilder = (path) => (document) => {
8
+ const indentIfNecessaryBuilder = (path, options) => (document) => {
9
9
  let node = path.getNode();
10
10
  for (let i = 0; ; i += 1) {
11
11
  const parentNode = path.getParentNode(i);
12
12
  if (parentNode.type === 'ReturnStatement') return document;
13
13
  if (parentNode.type === 'IfStatement') return document;
14
14
  if (parentNode.type === 'WhileStatement') return document;
15
+ if (
16
+ options.experimentalTernaries &&
17
+ parentNode.type === 'Conditional' &&
18
+ parentNode.condition === node
19
+ )
20
+ return document;
15
21
  if (parentNode.type !== 'BinaryOperation') return indent(document);
16
22
  if (node === parentNode.right) return document;
17
23
  node = parentNode;
@@ -20,9 +26,9 @@ const indentIfNecessaryBuilder = (path) => (document) => {
20
26
 
21
27
  export const logical = {
22
28
  match: (op) => ['&&', '||'].includes(op),
23
- print: (node, path, print) => {
29
+ print: (node, path, print, options) => {
24
30
  const groupIfNecessary = groupIfNecessaryBuilder(path);
25
- const indentIfNecessary = indentIfNecessaryBuilder(path);
31
+ const indentIfNecessary = indentIfNecessaryBuilder(path, options);
26
32
 
27
33
  const right = [node.operator, line, path.call(print, 'right')];
28
34
  // If it's a single binary operation, avoid having a small right
@@ -1,5 +1,5 @@
1
1
  import { util } from 'prettier';
2
- import { getNextNonSpaceNonCommentCharacter } from '../../common/util.js';
2
+ import { getNextNonSpaceNonCommentCharacter } from '../../common/backward-compatibility.js';
3
3
 
4
4
  const { addLeadingComment, addTrailingComment, addDanglingComment } = util;
5
5
 
@@ -27,13 +27,10 @@ function handleContractDefinitionComments({
27
27
  );
28
28
 
29
29
  // The comment is behind the start of the Block `{}` or behind a base contract
30
- if (
31
- (followingNode && followingNode.type === 'InheritanceSpecifier') ||
32
- nextCharacter === '{'
33
- ) {
30
+ if (followingNode?.type === 'InheritanceSpecifier' || nextCharacter === '{') {
34
31
  // In this scenario the comment belongs to a base contract.
35
32
  // contract A is B, /* comment for B */ C /* comment for C */ {}
36
- if (precedingNode && precedingNode.type === 'InheritanceSpecifier') {
33
+ if (precedingNode?.type === 'InheritanceSpecifier') {
37
34
  addTrailingComment(precedingNode, comment);
38
35
  return true;
39
36
  }
@@ -1,5 +1,5 @@
1
1
  import { util } from 'prettier';
2
- import { getNextNonSpaceNonCommentCharacter } from '../../common/util.js';
2
+ import { getNextNonSpaceNonCommentCharacter } from '../../common/backward-compatibility.js';
3
3
 
4
4
  const { addLeadingComment, addTrailingComment, addDanglingComment } = util;
5
5
 
@@ -0,0 +1,34 @@
1
+ import { util } from 'prettier';
2
+ import { prettierVersionSatisfies } from './util.js';
3
+
4
+ export const isPrettier2 = prettierVersionSatisfies('^2.3.0');
5
+
6
+ // The functions in this file will never be 100% covered in a single run
7
+ // since it depends on the version of Prettier being used.
8
+ // Mocking the behaviour will introduce a lot of maintenance in the tests.
9
+
10
+ export function isNextLineEmpty(text, startIndex) {
11
+ return isPrettier2
12
+ ? util.isNextLineEmptyAfterIndex(text, startIndex)
13
+ : util.isNextLineEmpty(text, startIndex); // V3 deprecated `isNextLineEmptyAfterIndex`
14
+ }
15
+
16
+ export function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
17
+ return isPrettier2
18
+ ? util.getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd)
19
+ : util.getNextNonSpaceNonCommentCharacterIndex(text, locEnd(node)); // V3 signature changed
20
+ }
21
+
22
+ export function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
23
+ return isPrettier2
24
+ ? text.charAt(
25
+ util.getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd)
26
+ )
27
+ : util.getNextNonSpaceNonCommentCharacter(text, locEnd(node)); // V3 exposes this function directly
28
+ }
29
+
30
+ export function isLast(path, key, index) {
31
+ return isPrettier2
32
+ ? index === path.getParentNode()[key].length - 1
33
+ : path.isLast;
34
+ }
@@ -1,5 +1,9 @@
1
1
  import { doc } from 'prettier';
2
- import { isNextLineEmpty, isPrettier2 } from './util.js';
2
+ import {
3
+ isLast,
4
+ isNextLineEmpty,
5
+ isPrettier2
6
+ } from './backward-compatibility.js';
3
7
 
4
8
  const { group, indent, join, line, softline, hardline } = doc.builders;
5
9
 
@@ -17,7 +21,7 @@ export const printComments = (node, path, options, filter = () => true) => {
17
21
  return null;
18
22
  }
19
23
  comment.printed = true;
20
- return options.printer.printComment(commentPath);
24
+ return options.printer.printComment(commentPath, options);
21
25
  }, 'comments')
22
26
  .filter(Boolean)
23
27
  );
@@ -26,7 +30,7 @@ export const printComments = (node, path, options, filter = () => true) => {
26
30
  // since it depends on the version of Prettier being used.
27
31
  // Mocking the behaviour will introduce a lot of maintenance in the tests.
28
32
  /* c8 ignore start */
29
- return isPrettier2()
33
+ return isPrettier2
30
34
  ? document.parts // Prettier V2
31
35
  : document; // Prettier V3
32
36
  /* c8 ignore stop */
@@ -48,29 +52,19 @@ export function printPreservingEmptyLines(path, key, options, print) {
48
52
  parts.push(hardline);
49
53
  }
50
54
 
51
- if (index > 0) {
52
- if (
53
- ['ContractDefinition', 'FunctionDefinition'].includes(nodeType) &&
54
- parts[parts.length - 2] !== hardline
55
- ) {
56
- parts.push(hardline);
57
- }
58
- }
59
-
60
55
  parts.push(print(childPath));
61
56
 
57
+ // Only attempt to append an empty line if `node` is not the last item
62
58
  if (
63
- isNextLineEmpty(options.originalText, options.locEnd(node) + 1) ||
64
- nodeType === 'FunctionDefinition'
59
+ !isLast(childPath, key, index) &&
60
+ isNextLineEmpty(options.originalText, options.locEnd(node) + 1)
65
61
  ) {
62
+ // Append an empty line if the original text already had an one after
63
+ // the current `node`
66
64
  parts.push(hardline);
67
65
  }
68
66
  }, key);
69
67
 
70
- if (parts.length > 1 && parts[parts.length - 1] === hardline) {
71
- parts.pop();
72
- }
73
-
74
68
  return parts;
75
69
  }
76
70
 
@@ -2,32 +2,6 @@ import { util, version } from 'prettier';
2
2
  import satisfies from 'semver/functions/satisfies.js';
3
3
 
4
4
  export const prettierVersionSatisfies = (range) => satisfies(version, range);
5
- export const isPrettier2 = () => prettierVersionSatisfies('^2.3.0');
6
-
7
- // The following functions will never be 100% covered in a single run
8
- // since it depends on the version of Prettier being used.
9
- // Mocking the behaviour will introduce a lot of maintenance in the tests.
10
- /* c8 ignore start */
11
- export function isNextLineEmpty(text, startIndex) {
12
- return isPrettier2()
13
- ? util.isNextLineEmptyAfterIndex(text, startIndex)
14
- : util.isNextLineEmpty(text, startIndex); // V3 deprecated `isNextLineEmptyAfterIndex`
15
- }
16
-
17
- export function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
18
- return isPrettier2()
19
- ? util.getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd)
20
- : util.getNextNonSpaceNonCommentCharacterIndex(text, locEnd(node)); // V3 signature changed
21
- }
22
-
23
- export function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
24
- return isPrettier2()
25
- ? text.charAt(
26
- util.getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd)
27
- )
28
- : util.getNextNonSpaceNonCommentCharacter(text, locEnd(node)); // V3 exposes this function directly
29
- }
30
- /* c8 ignore stop */
31
5
 
32
6
  export function printString(rawContent, options) {
33
7
  const double = { quote: '"', regex: /"/g };
@@ -66,9 +40,7 @@ export function printString(rawContent, options) {
66
40
 
67
41
  export function hasNodeIgnoreComment(node) {
68
42
  return (
69
- node &&
70
- node.comments &&
71
- node.comments.length > 0 &&
43
+ node?.comments?.length > 0 &&
72
44
  node.comments.some((comment) => comment.value.trim() === 'prettier-ignore')
73
45
  );
74
46
  }
package/src/loc.js CHANGED
@@ -4,7 +4,7 @@ function getRange(index, node) {
4
4
  if (node.range) {
5
5
  return node.range[index];
6
6
  }
7
- if (node.expression && node.expression.range) {
7
+ if (node.expression?.range) {
8
8
  return node.expression.range[index];
9
9
  }
10
10
  return null;
@@ -1,18 +1,88 @@
1
1
  import { doc } from 'prettier';
2
+ import { printSeparatedItem } from '../common/printer-helpers.js';
2
3
 
3
- const { group, indent, line } = doc.builders;
4
+ const { group, hardline, ifBreak, indent, line, softline } = doc.builders;
4
5
 
5
- export const Conditional = {
6
- print: ({ path, print }) =>
7
- group([
8
- path.call(print, 'condition'),
9
- indent([
10
- line,
11
- '? ',
12
- path.call(print, 'trueExpression'),
13
- line,
14
- ': ',
15
- path.call(print, 'falseExpression')
16
- ])
6
+ let groupIndex = 0;
7
+ const experimentalTernaries = (node, path, print, options) => {
8
+ const parent = path.getParentNode();
9
+ const isNested = parent.type === 'Conditional';
10
+ const isNestedAsTrueExpression = isNested && parent.trueExpression === node;
11
+ const falseExpressionIsNested = node.falseExpression.type === 'Conditional';
12
+
13
+ // If the `condition` breaks into multiple lines, we add parentheses,
14
+ // unless it already is a `TupleExpression`.
15
+ const condition = path.call(print, 'condition');
16
+ const conditionDoc = group([
17
+ node.condition.type === 'TupleExpression'
18
+ ? condition
19
+ : ifBreak(['(', printSeparatedItem(condition), ')'], condition),
20
+ ' ?'
21
+ ]);
22
+
23
+ // To switch between "case-style" and "curious" ternaries we force a new line
24
+ // before a nested `trueExpression` if the current `Conditional` is also a
25
+ // `trueExpression`.
26
+ const trueExpressionDoc = indent([
27
+ isNestedAsTrueExpression ? hardline : line,
28
+ path.call(print, 'trueExpression')
29
+ ]);
30
+
31
+ const conditionAndTrueExpressionGroup = group(
32
+ [conditionDoc, trueExpressionDoc],
33
+ { id: `Conditional.trueExpressionDoc-${groupIndex}` }
34
+ );
35
+
36
+ groupIndex += 1;
37
+
38
+ // For the odd case of `tabWidth` of 1 or 0 we initiate `fillTab` as a single
39
+ // space.
40
+ let fillTab = ' ';
41
+ if (
42
+ !falseExpressionIsNested && // avoid processing if it's not needed
43
+ (options.tabWidth > 2 || options.useTabs)
44
+ ) {
45
+ fillTab = options.useTabs ? '\t' : ' '.repeat(options.tabWidth - 1);
46
+ }
47
+
48
+ // A nested `falseExpression` is always printed in a new line.
49
+ const falseExpression = path.call(print, 'falseExpression');
50
+ const falseExpressionDoc = [
51
+ isNested ? hardline : line,
52
+ ':',
53
+ falseExpressionIsNested
54
+ ? [' ', falseExpression]
55
+ : ifBreak([fillTab, indent(falseExpression)], [' ', falseExpression], {
56
+ // We only add `fillTab` if we are sure the trueExpression is indented
57
+ groupId: conditionAndTrueExpressionGroup.id
58
+ })
59
+ ];
60
+
61
+ const document = group([conditionAndTrueExpressionGroup, falseExpressionDoc]);
62
+
63
+ return parent.type === 'VariableDeclarationStatement'
64
+ ? indent([softline, document])
65
+ : document;
66
+ };
67
+
68
+ const traditionalTernaries = (path, print) =>
69
+ group([
70
+ path.call(print, 'condition'),
71
+ indent([
72
+ // Nested trueExpression and falseExpression are always printed in a new
73
+ // line
74
+ path.getParentNode().type === 'Conditional' ? hardline : line,
75
+ '? ',
76
+ path.call(print, 'trueExpression'),
77
+ line,
78
+ ': ',
79
+ path.call(print, 'falseExpression')
17
80
  ])
81
+ ]);
82
+
83
+ export const Conditional = {
84
+ print: ({ node, path, print, options }) =>
85
+ options.experimentalTernaries
86
+ ? experimentalTernaries(node, path, print, options)
87
+ : traditionalTernaries(path, print)
18
88
  };
@@ -20,7 +20,7 @@ const inheritance = (node, path, print) =>
20
20
 
21
21
  const body = (node, path, options, print) => {
22
22
  const comments = printComments(node, path, options);
23
- return node.subNodes.length > 0 || (comments && comments.length)
23
+ return node.subNodes.length > 0 || comments?.length
24
24
  ? printSeparatedItem(
25
25
  [printPreservingEmptyLines(path, 'subNodes', options, print), comments],
26
26
  { firstSeparator: hardline, grouped: false }
@@ -1,7 +1,7 @@
1
1
  import { printSeparatedList } from '../common/printer-helpers.js';
2
2
 
3
3
  const parameters = (node, path, print) =>
4
- node.parameters && node.parameters.length > 0
4
+ node.parameters?.length > 0
5
5
  ? printSeparatedList(path.map(print, 'parameters'))
6
6
  : '';
7
7
 
@@ -1,7 +1,5 @@
1
1
  const stateMutability = (node) =>
2
- node.stateMutability && node.stateMutability.length > 0
3
- ? [' ', node.stateMutability]
4
- : '';
2
+ node.stateMutability?.length > 0 ? [' ', node.stateMutability] : '';
5
3
 
6
4
  export const ElementaryTypeName = {
7
5
  print: ({ node }) => [node.name, stateMutability(node)]
@@ -1,7 +1,7 @@
1
1
  import { printSeparatedList } from '../common/printer-helpers.js';
2
2
 
3
3
  const parameters = (node, path, print) =>
4
- node.parameters && node.parameters.length > 0
4
+ node.parameters?.length > 0
5
5
  ? printSeparatedList(path.map(print, 'parameters'))
6
6
  : '';
7
7
 
@@ -10,9 +10,9 @@ export const ExpressionStatement = {
10
10
  const parent = path.getParentNode();
11
11
 
12
12
  if (parent.type === 'IfStatement') {
13
- if (node.comments && node.comments.length) {
13
+ if (node.comments?.length) {
14
14
  const comments = printComments(node, path, options);
15
- if (comments && comments.length) {
15
+ if (comments?.length) {
16
16
  parts.push(comments);
17
17
  parts.push(hardline);
18
18
  }
@@ -30,8 +30,8 @@ export const FunctionCall = {
30
30
  let expressionDoc = path.call(print, 'expression');
31
31
  let argumentsDoc = ')';
32
32
 
33
- if (node.arguments && node.arguments.length > 0) {
34
- if (node.identifiers && node.identifiers.length > 0) {
33
+ if (node.arguments?.length > 0) {
34
+ if (node.identifiers?.length > 0) {
35
35
  argumentsDoc = printObject(path, print, options);
36
36
  } else {
37
37
  argumentsDoc = printArguments(path, print);
@@ -1,5 +1,5 @@
1
1
  import { doc } from 'prettier';
2
- import { getNextNonSpaceNonCommentCharacter } from '../common/util.js';
2
+ import { getNextNonSpaceNonCommentCharacter } from '../common/backward-compatibility.js';
3
3
  import {
4
4
  printComments,
5
5
  printSeparatedItem,
@@ -26,12 +26,12 @@ const functionName = (node, options) => {
26
26
  };
27
27
 
28
28
  const parameters = (parametersType, node, path, print, options) => {
29
- if (node[parametersType] && node[parametersType].length > 0) {
29
+ if (node[parametersType]?.length > 0) {
30
30
  return printSeparatedList(path.map(print, parametersType), {
31
31
  grouped: false
32
32
  });
33
33
  }
34
- if (node.comments && node.comments.length > 0) {
34
+ if (node.comments?.length > 0) {
35
35
  // we add a check to see if the comment is inside the parentheses
36
36
  const parameterComments = printComments(
37
37
  node,
@@ -1,7 +1,7 @@
1
1
  import { printSeparatedList } from '../common/printer-helpers.js';
2
2
 
3
3
  const printArguments = (node, path, print) =>
4
- node.arguments && node.arguments.length
4
+ node.arguments?.length
5
5
  ? ['(', printSeparatedList(path.map(print, 'arguments')), ')']
6
6
  : '';
7
7
 
@@ -6,7 +6,7 @@ export const InlineAssemblyStatement = {
6
6
  print: ({ node, path, print, options }) => [
7
7
  'assembly ',
8
8
  node.language ? `${printString(node.language, options)} ` : '',
9
- node.flags && node.flags.length > 0
9
+ node.flags?.length > 0
10
10
  ? [
11
11
  '(',
12
12
  printSeparatedList(
@@ -4,7 +4,7 @@ import { printSeparatedList } from '../common/printer-helpers.js';
4
4
  const { group, hardline, indent, line } = doc.builders;
5
5
 
6
6
  const modifierParameters = (node, path, print) => {
7
- if (node.parameters && node.parameters.length > 0) {
7
+ if (node.parameters?.length > 0) {
8
8
  return [
9
9
  '(',
10
10
  printSeparatedList(path.map(print, 'parameters'), {
@@ -13,8 +13,7 @@ const modifierArguments = (node, path, print, options) => {
13
13
  }
14
14
 
15
15
  if (
16
- node.comments &&
17
- node.comments.some(
16
+ node.comments?.some(
18
17
  (comment) => !comment.leading && !comment.trailing && !comment.printed
19
18
  )
20
19
  ) {
@@ -2,9 +2,10 @@ import { doc } from 'prettier';
2
2
 
3
3
  const { group, indent, line } = doc.builders;
4
4
 
5
- const expression = (node, path, print) => {
5
+ const expression = (node, path, print, options) => {
6
6
  if (node.expression) {
7
- return node.expression.type === 'TupleExpression'
7
+ return node.expression.type === 'TupleExpression' ||
8
+ (options.experimentalTernaries && node.expression.type === 'Conditional')
8
9
  ? [' ', path.call(print, 'expression')]
9
10
  : group(indent([line, path.call(print, 'expression')]));
10
11
  }
@@ -12,9 +13,9 @@ const expression = (node, path, print) => {
12
13
  };
13
14
 
14
15
  export const ReturnStatement = {
15
- print: ({ node, path, print }) => [
16
+ print: ({ node, path, print, options }) => [
16
17
  'return',
17
- expression(node, path, print),
18
+ expression(node, path, print, options),
18
19
  ';'
19
20
  ]
20
21
  };
@@ -4,17 +4,15 @@ import { printSeparatedList } from '../common/printer-helpers.js';
4
4
  const { group } = doc.builders;
5
5
 
6
6
  const contents = (node, path, print) =>
7
- node.components &&
8
- node.components.length === 1 &&
9
- node.components[0].type === 'BinaryOperation'
7
+ node.components?.length === 1 && node.components[0].type === 'BinaryOperation'
10
8
  ? path.map(print, 'components')
11
- : [printSeparatedList(path.map(print, 'components'))];
9
+ : printSeparatedList(path.map(print, 'components'));
12
10
 
13
11
  export const TupleExpression = {
14
12
  print: ({ node, path, print }) =>
15
13
  group([
16
14
  node.isArray ? '[' : '(',
17
- ...contents(node, path, print),
15
+ contents(node, path, print),
18
16
  node.isArray ? ']' : ')'
19
17
  ])
20
18
  };
@@ -6,7 +6,7 @@ const { line, softline } = doc.builders;
6
6
  export const UsingForDeclaration = {
7
7
  print: ({ node, path, print, options }) => [
8
8
  'using ',
9
- node.functions && node.functions.length
9
+ node.functions?.length
10
10
  ? [
11
11
  '{',
12
12
  printSeparatedList(
@@ -13,7 +13,7 @@ let groupIndex = 0;
13
13
  export const VariableDeclarationStatement = {
14
14
  print: ({ node, path, print }) => {
15
15
  const startsWithVar =
16
- node.variables.filter((x) => x && x.typeName).length === 0;
16
+ node.variables.filter((x) => x?.typeName).length === 0;
17
17
 
18
18
  const declarationDoc = group(
19
19
  [
package/src/options.js CHANGED
@@ -1,5 +1,6 @@
1
1
  const CATEGORY_GLOBAL = 'Global';
2
2
  const CATEGORY_COMMON = 'Common';
3
+ const CATEGORY_JAVASCRIPT = 'JavaScript';
3
4
  const CATEGORY_SOLIDITY = 'Solidity';
4
5
 
5
6
  const options = {
@@ -40,6 +41,15 @@ const options = {
40
41
  default: false,
41
42
  description: 'Use single quotes instead of double quotes.'
42
43
  },
44
+ experimentalTernaries: {
45
+ category: CATEGORY_JAVASCRIPT,
46
+ type: 'boolean',
47
+ default: false,
48
+ description:
49
+ 'Use curious ternaries, with the question mark after the condition.',
50
+ oppositeDescription:
51
+ 'Default behavior of ternaries; keep question marks on the same line as the consequent.'
52
+ },
43
53
  compiler: {
44
54
  category: CATEGORY_SOLIDITY,
45
55
  type: 'string',