Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
26 changes: 20 additions & 6 deletions src/common/printer-helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,33 @@ const { isNextLineEmpty } = util;

export const printComments = (node, path, options, filter = () => true) => {
if (!node.comments) return '';
function isPrintable(comment) {
return (
!comment.trailing &&
!comment.leading &&
!comment.printed &&
filter(comment)
);
}
const document = join(
line,
path
.map((commentPath) => {
.map((commentPath, index, comments) => {
const comment = commentPath.getValue();
if (comment.trailing || comment.leading || comment.printed) {
return null;
}
if (!filter(comment)) {
if (!isPrintable(comment)) {
return null;
}
comment.printed = true;
return options.printer.printComment(commentPath, options);
const isLast =
index === comments.length - 1 ||
comments.slice(index + 1).findIndex(isPrintable) === -1;
return [
options.printer.printComment(commentPath, options),
!isLast &&
util.isNextLineEmpty(options.originalText, options.locEnd(comment))
? hardline
: ''
];
}, 'comments')
.filter(Boolean)
);
Expand Down
8 changes: 6 additions & 2 deletions src/nodes/SourceUnit.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { doc } from 'prettier';
import { printPreservingEmptyLines } from '../common/printer-helpers.js';
import {
printComments,
printPreservingEmptyLines
} from '../common/printer-helpers.js';

const { line } = doc.builders;

export const SourceUnit = {
print: ({ options, path, print }) => [
print: ({ node, options, path, print }) => [
printPreservingEmptyLines(path, 'children', options, print),
printComments(node, path, options),
options.parentParser ? '' : line
]
};
28 changes: 28 additions & 0 deletions src/slang-comments/handlers/handle-source-unit-members-comments.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { NonterminalKind } from '@nomicfoundation/slang/cst';
import addCollectionFirstComment from './add-collection-first-comment.js';
import addCollectionLastComment from './add-collection-last-comment.js';

import type { HandlerParams } from './types.js';

export default function handleSourceUnitMembersComments({
precedingNode,
followingNode,
comment
}: HandlerParams): boolean {
if (
followingNode &&
followingNode.kind === NonterminalKind.SourceUnitMembers
) {
addCollectionFirstComment(followingNode, comment);
return true;
}
if (
precedingNode &&
precedingNode.kind === NonterminalKind.SourceUnitMembers
) {
addCollectionLastComment(precedingNode, comment);
return true;
}

return false;
}
2 changes: 2 additions & 0 deletions src/slang-comments/handlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import handleLibraryDefinitionComments from './handle-library-definition-comment
import handleModifierInvocationComments from './handle-modifier-invocation-comments.js';
import handleParametersDeclarationComments from './handle-parameters-declaration-comments.js';
import handlePositionalArgumentsDeclarationComments from './handle-positional-arguments-declaration-comments.js';
import handleSourceUnitMembersComments from './handle-source-unit-members-comments.js';
import handleStorageLayoutSpecifierComments from './handle-storage-layout-specifier-comments.js';
import handleStructComments from './handle-struct-comments.js';
import handleWhileStatementComments from './handle-while-statement-comments.js';
Expand All @@ -24,6 +25,7 @@ export default [
handleModifierInvocationComments,
handleParametersDeclarationComments,
handlePositionalArgumentsDeclarationComments,
handleSourceUnitMembersComments,
handleStorageLayoutSpecifierComments,
handleStructComments,
handleWhileStatementComments,
Expand Down
3 changes: 1 addition & 2 deletions src/slang-nodes/AddressType.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { NonterminalKind } from '@nomicfoundation/slang/cst';
import { joinExisting } from '../slang-utils/join-existing.js';
import { SlangNode } from './SlangNode.js';

import type * as ast from '@nomicfoundation/slang/ast';
Expand All @@ -17,6 +16,6 @@ export class AddressType extends SlangNode {
}

print(): Doc {
return joinExisting(' ', ['address', this.payableKeyword]);
return ['address', this.payableKeyword ? ' payable' : ''];
}
}
5 changes: 1 addition & 4 deletions src/slang-nodes/ArrayExpression.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { doc } from 'prettier';
import { NonterminalKind } from '@nomicfoundation/slang/cst';
import { SlangNode } from './SlangNode.js';
import { ArrayValues } from './ArrayValues.js';
Expand All @@ -8,8 +7,6 @@ import type { AstPath, Doc, ParserOptions } from 'prettier';
import type { AstNode } from './types.d.ts';
import type { PrintFunction } from '../types.d.ts';

const { group } = doc.builders;

export class ArrayExpression extends SlangNode {
readonly kind = NonterminalKind.ArrayExpression;

Expand All @@ -24,6 +21,6 @@ export class ArrayExpression extends SlangNode {
}

print(path: AstPath<ArrayExpression>, print: PrintFunction): Doc {
return group(['[', path.call(print, 'items'), ']']);
return ['[', path.call(print, 'items'), ']'];
}
}
14 changes: 6 additions & 8 deletions src/slang-nodes/AssignmentExpression.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NonterminalKind, TerminalKind } from '@nomicfoundation/slang/cst';
import { doc } from 'prettier';
import { isBinaryOperation } from '../slang-utils/is-binary-operation.js';
import { printIndentedGroupOrSpacedDocument } from '../slang-printers/print-indented-group-or-spaced-document.js';
import { SlangNode } from './SlangNode.js';
import { Expression } from './Expression.js';

Expand All @@ -9,8 +9,6 @@ import type { AstPath, Doc, ParserOptions } from 'prettier';
import type { AstNode } from './types.d.ts';
import type { PrintFunction } from '../types.d.ts';

const { group, indent, line } = doc.builders;

export class AssignmentExpression extends SlangNode {
readonly kind = NonterminalKind.AssignmentExpression;

Expand All @@ -32,14 +30,14 @@ export class AssignmentExpression extends SlangNode {

print(path: AstPath<AssignmentExpression>, print: PrintFunction): Doc {
const rightOperandVariant = this.rightOperand.variant;
const rightOperand = path.call(print, 'rightOperand');
return [
path.call(print, 'leftOperand'),
` ${this.operator}`,
rightOperandVariant.kind !== TerminalKind.Identifier &&
isBinaryOperation(rightOperandVariant)
? group(indent([line, rightOperand]))
: [' ', rightOperand]
printIndentedGroupOrSpacedDocument(
path.call(print, 'rightOperand'),
rightOperandVariant.kind !== TerminalKind.Identifier &&
isBinaryOperation(rightOperandVariant)
)
];
}
}
15 changes: 5 additions & 10 deletions src/slang-nodes/ContractMembers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { doc } from 'prettier';
import { NonterminalKind } from '@nomicfoundation/slang/cst';
import { printSeparatedItem } from '../slang-printers/print-separated-item.js';
import { printComments } from '../slang-printers/print-comments.js';
import { printPreservingEmptyLines } from '../slang-printers/print-preserving-empty-lines.js';
import { SlangNode } from './SlangNode.js';
import { ContractMember } from './ContractMember.js';
Expand Down Expand Up @@ -31,14 +30,10 @@ export class ContractMembers extends SlangNode {
print: PrintFunction,
options: ParserOptions<AstNode>
): Doc {
return this.items.length === 0 && this.comments.length === 0
? ''
: printSeparatedItem(
[
printPreservingEmptyLines(path, print, options),
printComments(path)
],
{ firstSeparator: hardline, grouped: false }
);
return this.items.length > 0 || this.comments.length > 0
? printSeparatedItem(printPreservingEmptyLines(path, print, options), {
firstSeparator: hardline
})
: '';
}
}
12 changes: 5 additions & 7 deletions src/slang-nodes/ElseBranch.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { doc } from 'prettier';
import { NonterminalKind } from '@nomicfoundation/slang/cst';
import { createKindCheckFunction } from '../slang-utils/create-kind-check-function.js';
import { printIndentedGroupOrSpacedDocument } from '../slang-printers/print-indented-group-or-spaced-document.js';
import { SlangNode } from './SlangNode.js';
import { Statement } from './Statement.js';

Expand All @@ -9,8 +9,6 @@ import type { AstPath, Doc, ParserOptions } from 'prettier';
import type { AstNode } from './types.d.ts';
import type { PrintFunction } from '../types.d.ts';

const { group, indent, line } = doc.builders;

const isIfStatementOrBlock = createKindCheckFunction([
NonterminalKind.Block,
NonterminalKind.IfStatement
Expand All @@ -30,12 +28,12 @@ export class ElseBranch extends SlangNode {
}

print(path: AstPath<ElseBranch>, print: PrintFunction): Doc {
const body = path.call(print, 'body');
return [
'else',
isIfStatementOrBlock(this.body.variant)
? [' ', body]
: group(indent([line, body]))
printIndentedGroupOrSpacedDocument(
path.call(print, 'body'),
!isIfStatementOrBlock(this.body.variant)
)
];
}
}
3 changes: 1 addition & 2 deletions src/slang-nodes/EventDefinition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ export class EventDefinition extends SlangNode {
'event ',
path.call(print, 'name'),
path.call(print, 'parameters'),
this.anonymousKeyword ? ' anonymous' : '',
';'
this.anonymousKeyword ? ' anonymous;' : ';'
];
}
}
11 changes: 6 additions & 5 deletions src/slang-nodes/ForStatement.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { NonterminalKind } from '@nomicfoundation/slang/cst';
import { doc } from 'prettier';
import { printSeparatedList } from '../slang-printers/print-separated-list.js';
import { printIndentedGroupOrSpacedDocument } from '../slang-printers/print-indented-group-or-spaced-document.js';
import { SlangNode } from './SlangNode.js';
import { ForStatementInitialization } from './ForStatementInitialization.js';
import { ForStatementCondition } from './ForStatementCondition.js';
Expand All @@ -12,7 +13,7 @@ import type { AstPath, Doc, ParserOptions } from 'prettier';
import type { AstNode } from './types.d.ts';
import type { PrintFunction } from '../types.d.ts';

const { group, indent, line } = doc.builders;
const { line } = doc.builders;

export class ForStatement extends SlangNode {
readonly kind = NonterminalKind.ForStatement;
Expand Down Expand Up @@ -50,7 +51,6 @@ export class ForStatement extends SlangNode {
const initialization = path.call(print, 'initialization');
const condition = path.call(print, 'condition');
const iterator = path.call(print, 'iterator');
const body = path.call(print, 'body');

return [
'for (',
Expand All @@ -61,9 +61,10 @@ export class ForStatement extends SlangNode {
: ''
}),
')',
this.body.variant.kind === NonterminalKind.Block
? [' ', body]
: group(indent([line, body]))
printIndentedGroupOrSpacedDocument(
path.call(print, 'body'),
this.body.variant.kind !== NonterminalKind.Block
)
];
}
}
12 changes: 6 additions & 6 deletions src/slang-nodes/FunctionCallExpression.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { doc } from 'prettier';
import { NonterminalKind } from '@nomicfoundation/slang/cst';
import { isLabel } from '../slang-utils/is-label.js';
import { printGroupAndIndentIfBreakPair } from '../slang-printers/print-group-and-indent-if-break-pair.js';
import { SlangNode } from './SlangNode.js';
import { Expression } from './Expression.js';
import { ArgumentsDeclaration } from './ArgumentsDeclaration.js';
Expand All @@ -10,7 +11,7 @@ import type { AstPath, Doc, ParserOptions } from 'prettier';
import type { AstNode } from './types.d.ts';
import type { PrintFunction } from '../types.d.ts';

const { group, indentIfBreak, label } = doc.builders;
const { label } = doc.builders;

export class FunctionCallExpression extends SlangNode {
readonly kind = NonterminalKind.FunctionCallExpression;
Expand Down Expand Up @@ -38,13 +39,12 @@ export class FunctionCallExpression extends SlangNode {
// If we are at the end of a MemberAccessChain we should indent the
// arguments accordingly.
if (isLabel(operand) && operand.label === 'MemberAccessChain') {
const groupId = Symbol('Slang.FunctionCallExpression.operand');
// We wrap the expression in a label in case there is an IndexAccess or
// a FunctionCall following this IndexAccess.
return label('MemberAccessChain', [
group(operand.contents, { id: groupId }),
indentIfBreak(argumentsDoc, { groupId })
]);
return label(
'MemberAccessChain',
printGroupAndIndentIfBreakPair(operand.contents, argumentsDoc)
);
}

return [operand, argumentsDoc].flat();
Expand Down
15 changes: 8 additions & 7 deletions src/slang-nodes/IfStatement.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { doc } from 'prettier';
import { NonterminalKind } from '@nomicfoundation/slang/cst';
import { printSeparatedItem } from '../slang-printers/print-separated-item.js';
import { printIndentedGroupOrSpacedDocument } from '../slang-printers/print-indented-group-or-spaced-document.js';
import { isBlockComment } from '../slang-utils/is-comment.js';
import { SlangNode } from './SlangNode.js';
import { Expression } from './Expression.js';
Expand All @@ -12,7 +13,7 @@ import type { AstPath, Doc, ParserOptions } from 'prettier';
import type { AstNode } from './types.d.ts';
import type { PrintFunction } from '../types.d.ts';

const { group, hardline, indent, line } = doc.builders;
const { hardline } = doc.builders;

export class IfStatement extends SlangNode {
readonly kind = NonterminalKind.IfStatement;
Expand All @@ -37,16 +38,16 @@ export class IfStatement extends SlangNode {

print(path: AstPath<IfStatement>, print: PrintFunction): Doc {
const { kind: bodyKind, comments: bodyComments } = this.body.variant;
const body = path.call(print, 'body');
return [
'if (',
printSeparatedItem(path.call(print, 'condition')),
')',
bodyKind === NonterminalKind.Block
? [' ', body]
: group(indent([line, body]), {
shouldBreak: bodyKind === NonterminalKind.IfStatement // `if` within `if`
}),
printIndentedGroupOrSpacedDocument(
path.call(print, 'body'),
bodyKind !== NonterminalKind.Block,
// `if` within `if`
{ shouldBreak: bodyKind === NonterminalKind.IfStatement }
),
this.elseBranch
? [
bodyKind !== NonterminalKind.Block || // else on a new line if body is not a block
Expand Down
3 changes: 1 addition & 2 deletions src/slang-nodes/ImportDeconstructionSymbols.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ export class ImportDeconstructionSymbols extends SlangNode {
? {
// if the compiler exists and is greater than or equal to 0.7.4 we will
// split the ImportDirective.
firstSeparator: bracketSpacing ? line : softline,
separator: [',', line]
firstSeparator: bracketSpacing ? line : softline
}
: {
// if the compiler is not given or is lower than 0.7.4 we will not
Expand Down
Loading
Loading