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

add rule for creating node child within a loop #123

Open
wants to merge 1 commit into
base: v1
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,8 @@ Default rules:

- `no-array-component-field-type`: Using 'array' type in component markup can result in inefficient copying of data during transfer to the render thread. Use 'node' type if possible for more efficient transfer of data from the task thread to the render thread (`error | warn | info | off`)

- `no-createchild-in-loop`: CreateChild should be used when you want to append a single instance of a type of node to a parent, but avoid modifiing that child after it's created. Do not use in a loop to append multiple children. Use CreateChildren() instead (`error | warn | info | off`)

### Strictness rules

- `type-annotations`: validation of presence of `as` type annotations, for function
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export type BsLintConfig = Pick<BsConfig, 'project' | 'rootDir' | 'files' | 'cwd
'color-cert'?: RuleColorCertCompliant;
'no-assocarray-component-field-type'?: RuleSeverity;
'no-array-component-field-type'?: RuleSeverity;
'no-createchild-in-loop'?: RuleSeverity;
};
globals?: string[];
ignores?: string[];
Expand Down Expand Up @@ -86,6 +87,7 @@ export interface BsLintRules {
colorCertCompliant: RuleColorCertCompliant;
noAssocarrayComponentFieldType: BsLintSeverity;
noArrayComponentFieldType: BsLintSeverity;
noCreateObjectInLoop: BsLintSeverity;
}

export { Linter };
Expand Down
10 changes: 9 additions & 1 deletion src/plugins/codeStyle/diagnosticMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export enum CodeStyleError {
ColorAlphaDefaults = 'LINT3022',
ColorCertCompliant = 'LINT3023',
NoAssocarrayFieldType = 'LINT3024',
NoArrayFieldType = 'LINT3025'
NoArrayFieldType = 'LINT3025',
NoCreateChildInLoop = 'LINT3027'
}

const CS = 'Code style:';
Expand Down Expand Up @@ -215,5 +216,12 @@ export const messages = {
severity: severity,
source: 'bslint',
range
}),
NoCreateChildInLoop: (range: Range, severity: DiagnosticSeverity) => ({
severity,
code: CodeStyleError.NoCreateChildInLoop,
source: 'bslint',
message: 'Avoid setting a value to node field after its creation within the same loop',
range
})
};
91 changes: 89 additions & 2 deletions src/plugins/codeStyle/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ import {
FunctionExpression,
isBrsFile,
isXmlFile,
isFunctionExpression,
isForEachStatement,
isForStatement,
isWhileStatement,
isDottedGetExpression,
isComponentType,
isGroupingExpression,
TokenKind,
WalkMode,
Expand All @@ -18,7 +24,12 @@ import {
isVoidType,
Statement,
SymbolTypeFlag,
XmlFile
XmlFile,
isAssignmentStatement,
isDottedSetStatement,
isVariableExpression,
CallExpression,
AstNode
} from 'brighterscript';
import { RuleAAComma } from '../..';
import { addFixesToEvent } from '../../textEdit';
Expand Down Expand Up @@ -76,7 +87,7 @@ export default class CodeStyle implements CompilerPlugin {
validateBrsFile(file: BrsFile) {
const diagnostics: (Omit<BsDiagnostic, 'file'>)[] = [];
const { severity } = this.lintContext;
const { inlineIfStyle, blockIfStyle, conditionStyle, noPrint, noTodo, noStop, aaCommaStyle, eolLast, colorFormat } = severity;
const { inlineIfStyle, blockIfStyle, conditionStyle, noPrint, noTodo, noStop, aaCommaStyle, eolLast, colorFormat, noCreateObjectInLoop } = severity;
const validatePrint = noPrint !== DiagnosticSeverity.Hint;
const validateTodo = noTodo !== DiagnosticSeverity.Hint;
const validateNoStop = noStop !== DiagnosticSeverity.Hint;
Expand All @@ -92,6 +103,7 @@ export default class CodeStyle implements CompilerPlugin {
const validateEolLast = eolLast !== 'off';
const disallowEolLast = eolLast === 'never';
const validateColorStyle = validateColorFormat ? createColorValidator(severity) : undefined;
const validateNoCreateChildInLoop = noCreateObjectInLoop !== DiagnosticSeverity.Hint;

// Check if the file is empty by going backwards from the last token,
// meaning there are tokens other than `Eof` and `Newline`.
Expand Down Expand Up @@ -133,6 +145,8 @@ export default class CodeStyle implements CompilerPlugin {
}
}

const createChildinLoop = new Map<AstNode, string[]>();

file.ast.walk(createVisitor({
// validate function style (`function` or `sub`)
FunctionExpression: (func) => {
Expand Down Expand Up @@ -212,12 +226,85 @@ export default class CodeStyle implements CompilerPlugin {
}
}
}
},
CallExpression: (node) => {
if (validateNoCreateChildInLoop) {
this.findCreateChildinLoop(node, createChildinLoop);
}
}
}), { walkMode: WalkMode.visitAllRecursive });

for (const [loop, candidates] of createChildinLoop) {
loop.walk(createVisitor({
DottedSetStatement: (s) => {
const leftExpression = s.obj;
let varStr = '';
if (isVariableExpression(leftExpression)) {
varStr = leftExpression.tokens.name.text;
} else if (isDottedGetExpression(leftExpression)) {
varStr = this.getDottedStr(leftExpression.obj);
}

if (candidates.includes(varStr)) {
diagnostics.push(messages.NoCreateChildInLoop(s.tokens.name.location.range, noCreateObjectInLoop));
}
}
}), { walkMode: WalkMode.visitAllRecursive });
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't use visitAllRecursive here. That would step into nested function bodies, which we don't want. I think you can use visitStatements since you're only looking at DottedSetStatements

}

return diagnostics;
}

isLoop(statement: AstNode) {
return isForStatement(statement) || isForEachStatement(statement) || isWhileStatement(statement);
}

findCreateChildinLoop(node: CallExpression, createChildinLoop: Map<AstNode, string[]>) {
if (!isDottedGetExpression(node.callee) || node.callee?.tokens?.name.text.toLowerCase() !== 'createchild') {
return;
}
const objType = node.callee.obj.getType({ flags: SymbolTypeFlag.runtime });
if (isComponentType(objType)) {
const parentLoop = node.findAncestor((node, cancel) => {
if (isFunctionExpression(node)) {
cancel.cancel();
} else if (this.isLoop(node)) {
return true;
}
});
if (this.isLoop(parentLoop)) {
let candidatesArray = createChildinLoop.get(parentLoop);

if (!candidatesArray) {
candidatesArray = [];
createChildinLoop.set(parentLoop, []);
}

let varStr = '';
if (isAssignmentStatement(node.parent)) {
varStr = node.parent.tokens.name.text;
} else if (isDottedSetStatement(node.parent)) {
varStr = this.getDottedStr(node.parent.obj);
}
createChildinLoop.get(parentLoop).push(varStr);
}
}
}

getDottedStr(expression: Expression) {
let currentExpression = expression;
let varStr = '';
while (isDottedGetExpression(currentExpression)) {
varStr = `.${currentExpression.tokens.name.text}${varStr}`;
currentExpression = currentExpression.obj;
}
if (isVariableExpression(currentExpression)) {
varStr = currentExpression.tokens.name.text + varStr;
}

return varStr;
}

afterFileValidate(event: AfterFileValidateEvent) {
const { file } = event;
if (this.lintContext.ignores(file)) {
Expand Down
6 changes: 4 additions & 2 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ export function getDefaultRules(): BsLintConfig['rules'] {
'type-annotations': 'off',
'no-print': 'off',
'no-assocarray-component-field-type': 'off',
'no-array-component-field-type': 'off'
'no-array-component-field-type': 'off',
'no-createchild-in-loop': 'off'
};
}

Expand Down Expand Up @@ -166,7 +167,8 @@ function rulesToSeverity(rules: BsLintConfig['rules']) {
colorAlphaDefaults: rules['color-alpha-defaults'],
colorCertCompliant: rules['color-cert'],
noAssocarrayComponentFieldType: ruleToSeverity(rules['no-assocarray-component-field-type']),
noArrayComponentFieldType: ruleToSeverity(rules['no-array-component-field-type'])
noArrayComponentFieldType: ruleToSeverity(rules['no-array-component-field-type']),
noCreateObjectInLoop: ruleToSeverity(rules['no-createchild-in-loop'])
};
}

Expand Down