Skip to content

Commit

Permalink
Account for multiple possible definition blocks on a given variable
Browse files Browse the repository at this point in the history
  • Loading branch information
thsparks committed May 1, 2024
1 parent 8422afb commit fa33f81
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions pxteditor/code-validation/validateVariableUsage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ export function validateVariableUsage({
name?: String;
}): {
passingVarDefinitions: Blockly.Block[];
passingVarCount: number;
passed: boolean;
} {
const varDefinitionBlocks: Map<string, Blockly.Block> = new Map();
const varDefinitionBlocks: Map<string, Blockly.Block[]> = new Map();
const usedVars: Set<string> = new Set(); // Use set so we don't double count vars

for (const block of usedBlocks) {
Expand All @@ -30,7 +31,10 @@ export function validateVariableUsage({
if (!name || varName === name) {
if (block.type === "variables_set" || block.type === "variables_change") {
// Variable created
varDefinitionBlocks.set(varName, block);
if (!varDefinitionBlocks.has(varName)) {
varDefinitionBlocks.set(varName, []);
}
varDefinitionBlocks.get(varName).push(block);
} else {
// Variable used
usedVars.add(varName);
Expand All @@ -41,13 +45,18 @@ export function validateVariableUsage({

// Var passes check if it is both used and defined.
// We return the definition blocks to allow for recursively checking how the var was set.
// Track passingVarCount separately, since a var could have more than one set block.
const passingVarDefinitions: Blockly.Block[] = [];
let passingVarCount = 0;
for (const varName of usedVars) {
const varBlock = varDefinitionBlocks.get(varName);
if (varBlock) {
passingVarDefinitions.push(varBlock);
const varBlocks = varDefinitionBlocks.get(varName) ?? [];
if (varBlocks.length > 0) {
passingVarCount++;
for (const varBlock of varBlocks) {
passingVarDefinitions.push(varBlock);
}
}
}

return { passingVarDefinitions, passed: passingVarDefinitions.length >= count };
return { passingVarDefinitions, passingVarCount, passed: passingVarCount >= count };
}

0 comments on commit fa33f81

Please sign in to comment.