Skip to content

Commit

Permalink
Fix trailing semicolon corner case (#91)
Browse files Browse the repository at this point in the history
* Add unit test

* Merge

* Allow 'trailingComma: false' as alternative to 'none'

* Implement fix

* 0.3.6

* Bump mo-fmt

* Update CI

* Create diff directory if not found
  • Loading branch information
rvanasa authored Mar 13, 2023
1 parent 1d2c9d8 commit 7b185b1
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 48 deletions.
1 change: 1 addition & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jobs:
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: git clone https://github.com/dfinity/motoko.git ../motoko --depth 1
- run: npm ci
- run: npm i prettier
- run: npm run build --if-present
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "prettier-plugin-motoko",
"version": "0.3.5",
"version": "0.3.6",
"description": "A code formatter for the Motoko smart contract language.",
"main": "lib/environments/node.js",
"browser": "lib/environments/web.js",
Expand Down
18 changes: 9 additions & 9 deletions packages/mo-fmt/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/mo-fmt/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mo-fmt",
"version": "0.3.5",
"version": "0.3.6",
"description": "An easy-to-use Motoko formatter command.",
"main": "src/cli.js",
"bin": {
Expand All @@ -21,7 +21,7 @@
"commander": "^9.4.0",
"fast-glob": "^3.2.11",
"prettier": "^2.7",
"prettier-plugin-motoko": "^0.3.5"
"prettier-plugin-motoko": "^0.3.6"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^22.0.2",
Expand Down
20 changes: 15 additions & 5 deletions src/printers/motoko-tt-ast/print.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ function printTokenTree(
const results: Doc[] = [];
let resultGroup: Doc[] = [];
let ignoringNextStatement = false;
let allowTrailingSeparator = false;
const endGroup = () => {
if (resultGroup.length) {
results.push(fill(resultGroup));
Expand Down Expand Up @@ -292,15 +293,20 @@ function printTokenTree(
}
}

// allow trailing delimiter for everything except comments
if (comment === undefined) {
// allow trailing comma/semicolon if something exists in the group other than a comment
allowTrailingSeparator = true;
}
// check for prettier-ignore comments
if (comment) {
if (comment === 'prettier-ignore') {
ignoringNextStatement = true;
}
else if (comment === 'prettier-ignore') {
ignoringNextStatement = true;
}

if (isSeparator) {
endGroup();
// reset to default
allowTrailingSeparator = false;
}

if (ignoringNextStatement) {
Expand Down Expand Up @@ -336,13 +342,17 @@ function printTokenTree(

// trailing delimiter
if (
(allowTrailingSeparator ||
!results.length ||
isDelim) &&
(!isSeparator || isDelim) &&
!hasNestedGroup &&
!shouldKeepSameLine() &&
(groupType !== 'Paren' || results.length > 1) &&
(groupType === 'Unenclosed' || groupType === 'Curly'
? options.semi
: options.trailingComma !== 'none') &&
: options.trailingComma &&
options.trailingComma !== 'none') &&
!isPossiblyRecordExtension() &&
!(
groupType === 'Square' &&
Expand Down
49 changes: 49 additions & 0 deletions tests/compiler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import prettier from 'prettier';
import * as motokoPlugin from '../src/environments/node';
import glob from 'fast-glob';
import { join, basename } from 'path';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';

const prettierOptions: prettier.Options = {
plugins: [motokoPlugin],
filepath: 'Main.mo',
};

const format = (input: string, options?: prettier.Options): string => {
return prettier.format(input, { ...prettierOptions, ...options });
};

describe('Motoko compiler suite', () => {
test('generate diff files from compiler tests', () => {
for (const extension of ['mo', 'did']) {
let preOutput = '';
let postOutput = '';
for (const file of glob.sync(
join(__dirname, `../../motoko/test/**/*.${extension}`),
)) {
const code = readFileSync(file, 'utf-8');
const formatted = prettier.format(code, {
filepath: file,
plugins: [motokoPlugin],
// semi: false,///
});
preOutput += `// >>> ${basename(file)} <<<\n\n${code}\n\n`;
postOutput += `// >>> ${basename(
file,
)} <<<\n\n${formatted}\n\n`;
}
const generatedDir = join(__dirname, 'generated');
if (!existsSync(generatedDir)) {
mkdirSync(generatedDir);
}
writeFileSync(
join(generatedDir, `_CompilerTests_Before.${extension}_`),
preOutput,
);
writeFileSync(
join(generatedDir, `_CompilerTests_Formatted.${extension}_`),
postOutput,
);
}
});
});
35 changes: 6 additions & 29 deletions tests/formatter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ describe('Motoko formatter', () => {
expect(format('let/*{{*/x = 0;//x\n (x)')).toStrictEqual(
'let /*{{*/ x = 0; //x\n(x);\n',
);
expect(format('\n/**/\n\n\n/**/')).toStrictEqual('/**/\n\n/**/;\n');
expect(format('/**//**/')).toStrictEqual('/**/ /**/\n');
expect(format('\n/**/\n\n\n/**/')).toStrictEqual('/**/\n\n/**/\n');
expectFormatted('/*=*/\n');
expectFormatted('/**=*/\n');
expectFormatted('/**=**/\n');
Expand Down Expand Up @@ -352,32 +353,8 @@ describe('Motoko formatter', () => {
expect(format('if(\nx) { y }')).toStrictEqual('if (\n x\n) { y };\n');
});

// test('generate diff files from compiler tests', () => {
// for (const extension of ['mo', 'did']) {
// let preOutput = '';
// let postOutput = '';
// for (const file of glob.sync(
// join(__dirname, `../../motoko/test/**/*.${extension}`),
// )) {
// const code = readFileSync(file, 'utf-8');
// const formatted = prettier.format(code, {
// filepath: file,
// plugins: [motokoPlugin],
// // semi: false,///
// });
// preOutput += `// >>> ${basename(file)} <<<\n\n${code}\n\n`;
// postOutput += `// >>> ${basename(
// file,
// )} <<<\n\n${formatted}\n\n`;
// }
// writeFileSync(
// join(__dirname, `generated/_CompilerTests_Before.${extension}_`),
// preOutput,
// );
// writeFileSync(
// join(__dirname, `generated/_CompilerTests_Formatted.${extension}_`),
// postOutput,
// );
// }
// });
test('trailing semicolon after block comment', () => {
expect(format("x;\n/**/")).toStrictEqual("x;\n/**/\n");
expect(format("x;\n/*\n*/")).toStrictEqual("x;\n/*\n*/\n");
});
});

0 comments on commit 7b185b1

Please sign in to comment.