Skip to content

Commit

Permalink
Refine code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
lukastaegert committed Sep 18, 2021
1 parent a21a0bc commit 028d45e
Show file tree
Hide file tree
Showing 22 changed files with 142 additions and 107 deletions.
4 changes: 2 additions & 2 deletions docs/999-big-list-of-options.md
Expand Up @@ -473,7 +473,7 @@ Whether to use arrow functions for auto-generated code snippets. Note that in ce

**output.generatedCode.constBindings**<br> Type: `boolean`<br> CLI: `--generatedCode.constBindings`/`--no-generatedCode.constBindings`<br> Default: `false`

This will use `const` instead of `var` in certain places and helper functions. Depending on the engine, this can provide [marginally better performance](https://benediktmeurer.de/2017/06/29/javascript-optimization-patterns-part2) in optimized machine code. It will also allow Rollup to generate more efficient helpers due to block scoping.
This will use `const` instead of `var` in certain places and helper functions. This will allow Rollup to generate more efficient helpers due to block scoping.

```js
// input
Expand Down Expand Up @@ -555,7 +555,7 @@ export default {

**output.generatedCode.reservedNamesAsProps**<br> Type: `boolean`<br> CLI: `--generatedCode.reservedNamesAsProps`/`--no-generatedCode.reservedNamesAsProps`<br> Default: `false`

Determine whether reserved words like "default" can be used as prop names without using quotes.
Determine whether reserved words like "default" can be used as prop names without using quotes. This will make the syntax of the generated code ES3 compliant. Note however that for full ES3 compliance, you may also need to polyfill some builtin functions like `Object.keys` or `Array.prototype.forEach`.

```javascript
// input
Expand Down
42 changes: 17 additions & 25 deletions src/ast/nodes/ImportExpression.ts
Expand Up @@ -50,11 +50,10 @@ export default class ImportExpression extends NodeBase {
const {
snippets: { getDirectReturnFunction, getPropertyAccess }
} = options;
const { left, right } = getDirectReturnFunction([], {
const [left, right] = getDirectReturnFunction([], {
functionReturn: true,
lineBreakIndent: false,
name: null,
t: ''
lineBreakIndent: null,
name: null
});
code.overwrite(
this.start,
Expand Down Expand Up @@ -85,11 +84,10 @@ export default class ImportExpression extends NodeBase {
): void {
code.overwrite(this.source.start, this.source.end, resolution);
if (namespaceExportName) {
const { left, right } = getDirectReturnFunction(['n'], {
const [left, right] = getDirectReturnFunction(['n'], {
functionReturn: true,
lineBreakIndent: false,
name: null,
t: ''
lineBreakIndent: null,
name: null
});
code.prependLeft(this.end, `.then(${left}n.${namespaceExportName}${right})`);
}
Expand Down Expand Up @@ -161,11 +159,10 @@ export default class ImportExpression extends NodeBase {
left = `/*#__PURE__*/${helper}(${left}`;
right += ')';
}
const { left: functionLeft, right: functionRight } = getDirectReturnFunction([], {
const [functionLeft, functionRight] = getDirectReturnFunction([], {
functionReturn: true,
lineBreakIndent: false,
name: null,
t: ''
lineBreakIndent: null,
name: null
});
left = `Promise.resolve().then(${functionLeft}${left}`;
right += `${functionRight})`;
Expand All @@ -185,24 +182,19 @@ export default class ImportExpression extends NodeBase {
const resolve = compact ? 'c' : 'resolve';
const reject = compact ? 'e' : 'reject';
const helper = getInteropHelper(resolution, exportMode, interop);
const { left: resolveLeft, right: resolveRight } = getDirectReturnFunction(['m'], {
const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
functionReturn: false,
lineBreakIndent: false,
name: null,
t: ''
lineBreakIndent: null,
name: null
});
const resolveNamespace = helper
? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
: resolve;
const { left: handlerLeft, right: handlerRight } = getDirectReturnFunction(
[resolve, reject],
{
functionReturn: false,
lineBreakIndent: false,
name: null,
t: ''
}
);
const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
functionReturn: false,
lineBreakIndent: null,
name: null
});
let left = `new Promise(${handlerLeft}require([`;
let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
if (!arrowFunctions && hasDynamicTarget) {
Expand Down
2 changes: 1 addition & 1 deletion src/ast/variables/NamespaceVariable.ts
Expand Up @@ -83,7 +83,7 @@ export default class NamespaceVariable extends Variable {

members.unshift([null, `__proto__:${_}null`]);

let output = getObject(members, { lineBreakIndent: t });
let output = getObject(members, { lineBreakIndent: { base: '', t } });
if (this.mergedNamespaces.length > 0) {
const assignmentArgs = this.mergedNamespaces.map(variable =>
variable.getName(getPropertyAccess)
Expand Down
14 changes: 6 additions & 8 deletions src/finalisers/shared/getExportBlock.ts
Expand Up @@ -56,11 +56,10 @@ export function getExportBlock(
);
if (exportBlock) exportBlock += n;
if (specifier.imported !== '*' && specifier.needsLiveBinding) {
const { left, right } = getDirectReturnFunction([], {
const [left, right] = getDirectReturnFunction([], {
functionReturn: true,
lineBreakIndent: false,
name: null,
t: ''
lineBreakIndent: null,
name: null
});
exportBlock +=
`Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
Expand Down Expand Up @@ -227,11 +226,10 @@ const getDefineProperty = (
{ _, getDirectReturnFunction, n }: GenerateCodeSnippets
) => {
if (needsLiveBinding) {
const { left, right } = getDirectReturnFunction([], {
const [left, right] = getDirectReturnFunction([], {
functionReturn: true,
lineBreakIndent: false,
name: null,
t: ''
lineBreakIndent: null,
name: null
});
return (
`Object.defineProperty(exports,${_}k,${_}{${n}` +
Expand Down
4 changes: 2 additions & 2 deletions src/finalisers/system.ts
Expand Up @@ -132,7 +132,7 @@ function analyzeDependencies(
}
}
if (reexportedNames.length > 1 || hasStarReexport) {
const exportMapping = getObject(reexportedNames, { lineBreakIndent: false });
const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
if (hasStarReexport) {
if (!starExcludes) {
starExcludes = getStarExcludes({ dependencies, exports });
Expand Down Expand Up @@ -178,7 +178,7 @@ const getStarExcludesBlock = (
starExcludes
? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject(
[...starExcludes].map(prop => [prop, '1']),
{ lineBreakIndent: false }
{ lineBreakIndent: { base: t, t } }
)};`
: '';

Expand Down
41 changes: 21 additions & 20 deletions src/utils/generateCodeSnippets.ts
Expand Up @@ -10,11 +10,10 @@ export interface GenerateCodeSnippets {
params: string[],
options: {
functionReturn: boolean;
lineBreakIndent: string | false;
lineBreakIndent: { base: string; t: string } | null;
name: string | null;
t: string;
}
): { left: string; right: string };
): [left: string, right: string];
getDirectReturnIifeLeft(
params: string[],
returned: string,
Expand All @@ -28,10 +27,9 @@ export interface GenerateCodeSnippets {
params: string[],
options: { isAsync: boolean; name: string | null }
): string;
// TODO Lukas adjust line-break handling with functions, change in System wrapper
getObject(
fields: [key: string | null, value: string][],
options: { lineBreakIndent: string | false }
options: { lineBreakIndent: { base: string; t: string } | null }
): string;
getPropertyAccess(name: string): string;
}
Expand Down Expand Up @@ -60,22 +58,24 @@ export function getGenerateCodeSnippets({

const getDirectReturnFunction: GenerateCodeSnippets['getDirectReturnFunction'] = (
params,
{ functionReturn, t, lineBreakIndent, name }
) => ({
left: `${getFunctionIntro(params, {
{ functionReturn, lineBreakIndent, name }
) => [
`${getFunctionIntro(params, {
isAsync: false,
name
})}${
arrowFunctions
? lineBreakIndent
? `${n}${lineBreakIndent}${t}`
? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
: ''
: `{${lineBreakIndent ? `${n}${lineBreakIndent}${t}` : _}${functionReturn ? 'return ' : ''}`
: `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${
functionReturn ? 'return ' : ''
}`
}`,
right: arrowFunctions
? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent}` : ''}`
: `${s}${lineBreakIndent ? `${n}${lineBreakIndent}` : _}}`
});
arrowFunctions
? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
: `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
];

const isValidPropName = reservedNamesAsProps
? (name: string): boolean => validPropName.test(name)
Expand All @@ -90,11 +90,10 @@ export function getGenerateCodeSnippets({
returned,
{ needsArrowReturnParens, needsWrappedFunction }
) => {
const { left, right } = getDirectReturnFunction(params, {
const [left, right] = getDirectReturnFunction(params, {
functionReturn: true,
lineBreakIndent: false,
name: null,
t: ''
lineBreakIndent: null,
name: null
});
return `${wrapIfNeeded(
`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`,
Expand All @@ -104,7 +103,7 @@ export function getGenerateCodeSnippets({
getFunctionIntro,
getNonArrowFunctionIntro,
getObject(fields, { lineBreakIndent }) {
const prefix = lineBreakIndent === false ? _ : `${n}${lineBreakIndent}`;
const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
return `{${fields
.map(([key, value]) => {
if (key === null) return `${prefix}${value}`;
Expand All @@ -113,7 +112,9 @@ export function getGenerateCodeSnippets({
? prefix + key
: `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
})
.join(`,`)}${fields.length === 0 ? '' : lineBreakIndent === false ? _ : n}}`;
.join(`,`)}${
fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _
}}`;
},
getPropertyAccess: (name: string): string =>
isValidPropName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
Expand Down
57 changes: 23 additions & 34 deletions src/utils/interopHelpers.ts
Expand Up @@ -77,11 +77,10 @@ const HELPER_GENERATORS: {
} = {
[INTEROP_DEFAULT_LEGACY_VARIABLE](_t, snippets, liveBindings) {
const { _, getDirectReturnFunction, n } = snippets;
const { left, right } = getDirectReturnFunction(['e'], {
const [left, right] = getDirectReturnFunction(['e'], {
functionReturn: true,
lineBreakIndent: false,
name: INTEROP_DEFAULT_LEGACY_VARIABLE,
t: ''
lineBreakIndent: null,
name: INTEROP_DEFAULT_LEGACY_VARIABLE
});
return (
`${left}e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
Expand All @@ -92,11 +91,10 @@ const HELPER_GENERATORS: {
},
[INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
const { _, getDirectReturnFunction, n } = snippets;
const { left, right } = getDirectReturnFunction(['e'], {
const [left, right] = getDirectReturnFunction(['e'], {
functionReturn: true,
lineBreakIndent: false,
name: INTEROP_DEFAULT_VARIABLE,
t: ''
lineBreakIndent: null,
name: INTEROP_DEFAULT_VARIABLE
});
return (
`${left}e${_}&&${_}e.__esModule${_}?${_}` +
Expand All @@ -112,11 +110,10 @@ const HELPER_GENERATORS: {
freeze: boolean,
namespaceToStringTag: boolean
) {
const { left, right } = getDirectReturnFunction(['e'], {
const [left, right] = getDirectReturnFunction(['e'], {
functionReturn: true,
lineBreakIndent: false,
name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
t: ''
lineBreakIndent: null,
name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
});
return `${left}${getFrozen(
getObject(
Expand All @@ -127,7 +124,7 @@ const HELPER_GENERATORS: {
: []),
['default', 'e']
],
{ lineBreakIndent: false }
{ lineBreakIndent: null }
),
freeze
)}${right}${n}${n}`;
Expand All @@ -150,11 +147,10 @@ const HELPER_GENERATORS: {
) {
const { _, getDirectReturnFunction, n } = snippets;
if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
const { left, right } = getDirectReturnFunction(['e'], {
const [left, right] = getDirectReturnFunction(['e'], {
functionReturn: true,
lineBreakIndent: false,
name: INTEROP_NAMESPACE_VARIABLE,
t: ''
lineBreakIndent: null,
name: INTEROP_NAMESPACE_VARIABLE
});
return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
}
Expand All @@ -167,7 +163,6 @@ const HELPER_GENERATORS: {
},
[MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze) {
const { _, n } = snippets;
// TODO Lukas mention improved helpers and used builtins in generatedCode docs
return (
`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
`${t}${loopOverNamespaces(
Expand All @@ -191,7 +186,7 @@ const HELPER_GENERATORS: {
};

const getDefaultLiveBinding = ({ _, getObject }: GenerateCodeSnippets) =>
`e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: false })}`;
`e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;

const getDefaultStatic = ({ _, getPropertyAccess }: GenerateCodeSnippets) =>
`e${getPropertyAccess('default')}${_}:${_}e`;
Expand Down Expand Up @@ -220,7 +215,7 @@ const createNamespaceObject = (
: 'Object.create(null)'
};${n}` +
`${i}if${_}(e)${_}{${n}` +
`${i}${t}${loopOverKeys(copyProperty, !liveBindings, true, snippets)}${n}` +
`${i}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
`${i}}${n}` +
`${i}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
`${i}return ${getFrozen('n', freeze)}${s}${n}`
Expand All @@ -230,15 +225,14 @@ const createNamespaceObject = (
const loopOverKeys = (
body: string,
allowVarLoopVariable: boolean,
isStatement: boolean,
{ _, cnst, getFunctionIntro, s }: GenerateCodeSnippets
) =>
cnst !== 'var' || allowVarLoopVariable
? wrapBracesIfNeeded(`for${_}(${cnst} k in e)${_}${body}`, !isStatement, _)
? `for${_}(${cnst} k in e)${_}${body}`
: `Object.keys(e).forEach(${getFunctionIntro(['k'], {
isAsync: false,
name: null
})}${body})${isStatement ? s : ''}`;
})}${body})${s}`;

const loopOverNamespaces = (
body: string,
Expand All @@ -253,11 +247,10 @@ const loopOverNamespaces = (
`${t}${t}for${_}(${cnst} k in e)${_}${body}${n}${t}}`
);
}
const { left, right } = getDirectReturnFunction(['e'], {
const [left, right] = getDirectReturnFunction(['e'], {
functionReturn: false,
lineBreakIndent: t,
name: null,
t
lineBreakIndent: { base: t, t },
name: null
});
return (
`m.forEach(${left}` +
Expand Down Expand Up @@ -286,11 +279,10 @@ const copyPropertyLiveBinding = (
i: string,
{ _, cnst, getDirectReturnFunction, n }: GenerateCodeSnippets
) => {
const { left, right } = getDirectReturnFunction([], {
const [left, right] = getDirectReturnFunction([], {
functionReturn: true,
lineBreakIndent: false,
name: null,
t: ''
lineBreakIndent: null,
name: null
});
return (
`${i}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
Expand All @@ -308,6 +300,3 @@ const getFrozen = (fragment: string, freeze: boolean) =>
freeze ? `Object.freeze(${fragment})` : fragment;

export const HELPER_NAMES = Object.keys(HELPER_GENERATORS);

const wrapBracesIfNeeded = (code: string, needsBraces: boolean | undefined, _: string): string =>
needsBraces ? `{${_}${code}${_}` : code;

0 comments on commit 028d45e

Please sign in to comment.