UNPKG

p5

Version:

[![npm version](https://badge.fury.io/js/p5.svg)](https://www.npmjs.com/package/p5)

1,505 lines (1,504 loc) • 46.6 kB
import { UnarySymbolToName } from "./ir_types.js"; import { internalError, userError } from "./strands_FES.js"; import { createStrandsShaderNameMap, createStrandsShaderNameState, getOrCreateInternalShaderName } from "./strands_names.js"; import { parse } from "acorn"; import { ancestor, recursive } from "acorn-walk"; import escodegen from "escodegen"; //#region src/strands/strands_transpiler.js function getArgTypes(fnName, p5) { return p5?.prototype?.[fnName]?.argTypes; } let blockVarCounter = 0; let loopVarCounter = 0; function replaceBinaryOperator(codeSource) { switch (codeSource) { case "+": return "add"; case "-": return "sub"; case "*": return "mult"; case "/": return "div"; case "%": return "mod"; case "==": case "===": return "equalTo"; case "!=": case "!==": return "notEqual"; case ">": return "greaterThan"; case ">=": return "greaterEqual"; case "<": return "lessThan"; case "<=": return "lessEqual"; case "&&": return "and"; case "||": return "or"; } } function nodeIsUniform(ancestor) { return ancestor && ancestor.type === "CallExpression" && (ancestor.callee?.type === "Identifier" && ancestor.callee?.name.startsWith("uniform") || ancestor.callee?.type === "MemberExpression" && ancestor.callee?.property.name.startsWith("uniform")); } function nodeIsUniformCallbackFn(node, names) { if (!names?.size) return false; if (node.type === "FunctionDeclaration" && names.has(node.id?.name)) return true; if (node.type === "VariableDeclarator" && names.has(node.id?.name) && (node.init?.type === "FunctionExpression" || node.init?.type === "ArrowFunctionExpression")) return true; return false; } function collectUniformCallbackNames(ast) { const namedFunctions = /* @__PURE__ */ new Set(); ancestor(ast, { FunctionDeclaration(node) { if (node.id) namedFunctions.add(node.id.name); }, VariableDeclarator(node) { if (node.id?.type === "Identifier" && (node.init?.type === "FunctionExpression" || node.init?.type === "ArrowFunctionExpression")) namedFunctions.add(node.id.name); } }); const names = /* @__PURE__ */ new Set(); ancestor(ast, { CallExpression(node) { if (nodeIsUniform(node)) { for (const arg of node.arguments) if (arg.type === "Identifier" && namedFunctions.has(arg.name)) names.add(arg.name); } } }); return names; } function nodeIsVarying(node) { return node && node.type === "CallExpression" && (node.callee?.type === "Identifier" && (node.callee?.name.startsWith("varying") || node.callee?.name.startsWith("shared")) || node.callee?.type === "MemberExpression" && (node.callee?.property.name.startsWith("varying") || node.callee?.property.name.startsWith("shared"))); } function getMemberExpressionPath(node) { if (node?.type === "Identifier") return node.name; if (node?.type !== "MemberExpression" || node.computed) return null; const objectPath = getMemberExpressionPath(node.object); const propertyName = node.property?.name; return objectPath && propertyName ? `${objectPath}.${propertyName}` : null; } function isLoopProtectionCall(node) { if (node?.type !== "CallExpression") return false; const path = getMemberExpressionPath(node.callee); if (!path) return false; return path === "loopProtect.protect" || path.endsWith(".loopProtect") || path.endsWith(".loopProtect.protect"); } function throwIfLoopProtectionInserted(ast) { let found = false; ancestor(ast, { CallExpression(node) { if (isLoopProtectionCall(node)) found = true; }, LogicalExpression(node) { if (node.right?.type === "CallExpression" && isLoopProtectionCall(node.right)) found = true; } }); if (found) internalError("loop protection error Loop protection code detected. Add `// noprotect` at the top of your sketch and run again."); } function isUnusedResultControlFlow(expr) { return expr.type === "ConditionalExpression" || expr.type === "LogicalExpression" && (expr.operator === "&&" || expr.operator === "||"); } function toBlock(statements) { return { type: "BlockStatement", body: statements }; } function restoreConditionalStatement(stmt) { if (stmt.type !== "ExpressionStatement") return [stmt]; const expr = stmt.expression; const asStatement = (expression) => ({ type: "ExpressionStatement", expression }); if (expr.type === "SequenceExpression") { if (!expr.expressions.some(isUnusedResultControlFlow)) return [stmt]; return expr.expressions.flatMap((e) => restoreConditionalStatement(asStatement(e))); } if (expr.type === "LogicalExpression" && isUnusedResultControlFlow(expr)) return [{ type: "IfStatement", test: expr.operator === "&&" ? expr.left : { type: "UnaryExpression", operator: "!", prefix: true, argument: expr.left }, consequent: toBlock(restoreConditionalStatement(asStatement(expr.right))), alternate: null }]; if (expr.type === "ConditionalExpression") return [{ type: "IfStatement", test: expr.test, consequent: toBlock(restoreConditionalStatement(asStatement(expr.consequent))), alternate: toBlock(restoreConditionalStatement(asStatement(expr.alternate))) }]; return [stmt]; } function restoreMinifiedConditionals(ast, uniformCallbackNames) { const inUniform = (ancestors) => ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, uniformCallbackNames)); const restoreBlockBody = (node, state, ancestors) => { if (inUniform(ancestors)) return; node.body = node.body.flatMap(restoreConditionalStatement); }; const restoreUnbracedBodies = (node, state, ancestors) => { if (inUniform(ancestors)) return; for (const key of [ "consequent", "alternate", "body" ]) { const child = node[key]; if (child?.type === "ExpressionStatement") node[key] = toBlock(restoreConditionalStatement(child)); } }; ancestor(ast, { Program: restoreBlockBody, BlockStatement: restoreBlockBody, IfStatement: restoreUnbracedBodies, ForStatement: restoreUnbracedBodies, WhileStatement: restoreUnbracedBodies }); } function statementContainsStrandsControlFlow(stmt) { if (stmt.type === "VariableDeclaration") return stmt.declarations.some((decl) => decl.init?.type === "CallExpression" && (decl.init?.callee?.type === "MemberExpression" && decl.init?.callee?.object?.type === "Identifier" && decl.init?.callee?.object?.name === "__p5" && (decl.init?.callee?.property?.name === "strandsFor" || decl.init?.callee?.property?.name === "strandsIf") || decl.init?.callee?.type === "Identifier" && (decl.init?.callee?.name === "__p5.strandsFor" || decl.init?.callee?.name === "__p5.strandsIf"))); return false; } function isSwizzle(propertyName) { if (!propertyName || typeof propertyName !== "string") return false; return [ [ "x", "y", "z", "w" ], [ "r", "g", "b", "a" ], [ "s", "t", "p", "q" ] ].some((set) => [...propertyName].every((char) => set.includes(char))); } function buildPropertyPath(memberExpr) { const parts = []; let current = memberExpr; while (current.type === "MemberExpression") { if (current.computed) return null; const propName = current.property.name || current.property.value; if (isSwizzle(propName)) { current = current.object; continue; } parts.unshift(propName); current = current.object; } if (current.type === "Identifier") parts.unshift(current.name); else return null; return parts.join("."); } function replaceReferences(node, tempVarMap) { const internalReplaceReferences = (node) => { if (!node || typeof node !== "object") return; if (node.type === "MemberExpression") { if (isSwizzle(node.property.name || node.property.value)) { internalReplaceReferences(node.object); return; } const propertyPath = buildPropertyPath(node); if (propertyPath && tempVarMap.has(propertyPath)) { Object.assign(node, { type: "Identifier", name: tempVarMap.get(propertyPath) }); return; } } if (node.type === "Identifier" && tempVarMap.has(node.name)) node.name = tempVarMap.get(node.name); if (node.type === "AssignmentExpression") { let leftPath = null; if (node.left.type === "Identifier") leftPath = node.left.name; else if (node.left.type === "MemberExpression") leftPath = buildPropertyPath(node.left); if (leftPath && tempVarMap.has(leftPath) && (node.right.type === "Literal" || node.right.type === "ArrayExpression")) node.right = { type: "CallExpression", callee: { type: "Identifier", name: "__p5.strandsNode" }, arguments: [node.right] }; } for (const key in node) if (node.hasOwnProperty(key) && key !== "parent") { if (node.type === "MemberExpression" && key === "property" && !node.computed) continue; if (Array.isArray(node[key])) node[key].forEach(internalReplaceReferences); else if (typeof node[key] === "object") internalReplaceReferences(node[key]); } }; internalReplaceReferences(node); } function replaceIdentifierReferences(node, oldName, newName) { if (!node || typeof node !== "object") return node; const replaceInNode = (n) => { if (!n || typeof n !== "object") return n; if (n.type === "Identifier" && n.name === oldName) return { ...n, name: newName }; const newNode = { ...n }; for (const key in n) if (n.hasOwnProperty(key) && key !== "parent") { if (Array.isArray(n[key])) newNode[key] = n[key].map(replaceInNode); else if (typeof n[key] === "object") newNode[key] = replaceInNode(n[key]); } return newNode; }; return replaceInNode(node); } function wrapExpressionOperand(operator, expression) { return { type: "CallExpression", callee: { type: "Identifier", name: "__p5.strandsOperand" }, arguments: [{ type: "Literal", value: operator }, { type: "ArrowFunctionExpression", id: null, params: [], body: expression, expression: true, generator: false, async: false }] }; } function transformBinaryOrLogical(node, state, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, state.uniformCallbackNames))) return; if (node.type === "LogicalExpression" && (node.operator === "&&" || node.operator === "||")) { node.left = wrapExpressionOperand(node.operator, node.left); node.right = wrapExpressionOperand(node.operator, node.right); } node.left = { type: "CallExpression", callee: { type: "Identifier", name: "__p5.strandsNode" }, arguments: [node.left] }; node.type = "CallExpression"; node.callee = { type: "MemberExpression", object: node.left, property: { type: "Identifier", name: replaceBinaryOperator(node.operator) } }; node.arguments = [node.right]; } function addCopyingAndReturn(functionBody, varsToReturn, sourcePrefix = null) { if (functionBody.type !== "BlockStatement") return; const tempVarMap = /* @__PURE__ */ new Map(); const copyStatements = []; for (const varPath of varsToReturn) { const parts = varPath.split("."); const tempName = `__copy_${parts.join("_")}_${blockVarCounter++}`; tempVarMap.set(varPath, tempName); let sourceExpr = sourcePrefix ? { type: "MemberExpression", object: { type: "Identifier", name: sourcePrefix }, property: { type: "Literal", value: varPath }, computed: true } : { type: "Identifier", name: parts[0] }; const pathParts = sourcePrefix ? [] : parts.slice(1); for (const part of pathParts) sourceExpr = { type: "MemberExpression", object: sourceExpr, property: { type: "Identifier", name: part }, computed: false }; copyStatements.push({ type: "VariableDeclaration", declarations: [{ type: "VariableDeclarator", id: { type: "Identifier", name: tempName }, init: { type: "CallExpression", callee: { type: "MemberExpression", object: sourceExpr, property: { type: "Identifier", name: "copy" }, computed: false }, arguments: [] } }], kind: "let" }); } functionBody.body.forEach((node) => replaceReferences(node, tempVarMap)); functionBody.body.unshift(...copyStatements); const returnObj = { type: "ObjectExpression", properties: Array.from(varsToReturn).map((varPath) => ({ type: "Property", key: { type: "Literal", value: varPath }, value: { type: "Identifier", name: tempVarMap.get(varPath) }, kind: "init", computed: false, shorthand: false })) }; functionBody.body.push({ type: "ReturnStatement", argument: returnObj }); } function replaceWithMethodCall(node, object, methodName, args) { delete node.operator; delete node.left; delete node.right; node.type = "CallExpression"; node.callee = { type: "MemberExpression", computed: false, object, property: { type: "Identifier", name: methodName } }; node.arguments = args; } const ASTCallbacks = { UnaryExpression(node, state, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, state.uniformCallbackNames))) return; const unaryFnName = UnarySymbolToName[node.operator]; const standardReplacement = (node) => { node.type = "CallExpression"; node.callee = { type: "Identifier", name: `__p5.${unaryFnName}` }; node.arguments = [node.argument]; }; if (node.type === "MemberExpression") { const property = node.argument.property.name; if ([ [ "x", "y", "z", "w" ], [ "r", "g", "b", "a" ], [ "s", "t", "p", "q" ] ].some((set) => [...property].every((char) => set.includes(char))) && node.argument.type === "MemberExpression" && !node.argument.computed) { node.type = "MemberExpression"; node.object = { type: "CallExpression", callee: { type: "Identifier", name: `__p5.${unaryFnName}` }, arguments: [node.argument.object] }; node.property = { type: "Identifier", name: property }; } else standardReplacement(node); } else standardReplacement(node); delete node.argument; delete node.operator; }, BreakStatement(node, state, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, state.uniformCallbackNames))) return; node.callee = { type: "Identifier", name: "__p5.break" }; node.arguments = []; node.type = "CallExpression"; }, MemberExpression(node, state, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, state.uniformCallbackNames))) return; if (ancestors.at(-2)?.type === "AssignmentExpression" && ancestors.at(-2).left === node) return; if (node.computed) { const callee = node.object; const member = node.property; node.computed = void 0; node.object = void 0; node.callee = { type: "MemberExpression", object: callee, property: { type: "Identifier", name: "get" } }; node.arguments = [member]; node.type = "CallExpression"; } }, VariableDeclarator(node, state, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, state.uniformCallbackNames))) return; if (nodeIsUniform(node.init)) { if (node.init.arguments.length === 0 || !(node.init.arguments[0].type === "Literal" && typeof node.init.arguments[0].value === "string" || node.init.arguments[0].type === "TemplateLiteral")) { const uniformNameLiteral = { type: "Literal", value: getOrCreateInternalShaderName(state.shaderNameMap, state.shaderNameState, node.id.name) }; node.init.arguments.unshift(uniformNameLiteral); } } if (nodeIsVarying(node.init)) { if (node.init.arguments.length === 0 || node.init.arguments[0].type !== "Literal" || typeof node.init.arguments[0].value !== "string") { const varyingNameLiteral = { type: "Literal", value: getOrCreateInternalShaderName(state.shaderNameMap, state.shaderNameState, node.id.name) }; node.init.arguments.unshift(varyingNameLiteral); state.varyings[node.id.name] = varyingNameLiteral; } else state.varyings[node.id.name] = node.init.arguments[0]; } }, Identifier(node, state, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, state.uniformCallbackNames))) return; if (state.varyings[node.name] && !ancestors.some((a) => a.type === "AssignmentExpression" && a.left === node)) { node.type = "CallExpression"; node.callee = { type: "MemberExpression", object: { type: "Identifier", name: node.name }, property: { type: "Identifier", name: "getValue" } }; node.arguments = []; } }, ArrayExpression(node, state, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, state.uniformCallbackNames))) return; for (let i = ancestors.length - 1; i >= 0; i--) { const a = ancestors[i]; if (a.type === "CallExpression") { const fnName = a.callee?.type === "Identifier" ? a.callee.name : a.callee?.type === "MemberExpression" && a.callee.property?.type === "Identifier" ? a.callee.property.name : void 0; const argTypes = fnName && getArgTypes(fnName, state.p5); if (argTypes) { const path = ancestors.slice(i + 1); const argIndex = a.arguments.indexOf(path[0]); let argType = argIndex !== -1 ? argTypes[argIndex] : void 0; for (let depth = 1; depth < path.length && argType; depth++) argType = argType.subtype; if (argType?.type === "Array") return; } break; } } if (node.elements.length < 2 || node.elements.length > 4) userError("type error", `Array literals in shader functions are transpiled to vectors and must have 2-4 elements (got ${node.elements.length}).`); const original = JSON.parse(JSON.stringify(node)); node.type = "CallExpression"; node.callee = { type: "Identifier", name: "__p5.strandsNode" }; node.arguments = [original]; }, AssignmentExpression(node, state, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, state.uniformCallbackNames))) return; const unsafeTypes = [ "Literal", "ArrayExpression", "Identifier" ]; if (node.operator !== "=") { const methodName = replaceBinaryOperator(node.operator.replace("=", "")); const right = node.operator === "&&=" || node.operator === "||=" ? wrapExpressionOperand(node.operator, node.right) : node.right; const rightReplacementNode = { type: "CallExpression", callee: { type: "MemberExpression", object: unsafeTypes.includes(node.left.type) ? { type: "CallExpression", callee: { type: "Identifier", name: "__p5.strandsNode" }, arguments: [node.left] } : node.left, property: { type: "Identifier", name: methodName } }, arguments: [right] }; node.operator = "="; node.right = rightReplacementNode; } if (state.varyings[node.left.name]) replaceWithMethodCall(node, { type: "Identifier", name: node.left.name }, "bridge", [node.right]); else if (node.left.type === "MemberExpression") { if (node.left.computed) { const source = node.left; const value = node.right; const callee = source.object; const member = source.property; replaceWithMethodCall(node, callee, "set", [member, value]); return; } let varyingName = null; if (node.left.object.type === "Identifier" && state.varyings[node.left.object.name]) varyingName = node.left.object.name; else if (node.left.object.type === "CallExpression" && node.left.object.callee?.type === "MemberExpression" && node.left.object.callee.property?.name === "getValue" && node.left.object.callee.object?.type === "Identifier" && state.varyings[node.left.object.callee.object.name]) varyingName = node.left.object.callee.object.name; if (varyingName) { const swizzlePattern = node.left.property.name; replaceWithMethodCall(node, { type: "Identifier", name: varyingName }, "bridgeSwizzle", [{ type: "Literal", value: swizzlePattern }, node.right]); } } }, BinaryExpression: transformBinaryOrLogical, LogicalExpression: transformBinaryOrLogical, ConditionalExpression(node, state, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, state.uniformCallbackNames))) return; const test = node.test; const consequent = wrapExpressionOperand("?:", node.consequent); const alternate = wrapExpressionOperand("?:", node.alternate); node.type = "CallExpression"; node.callee = { type: "Identifier", name: "__p5.strandsTernary" }; node.arguments = [ test, consequent, alternate ]; delete node.test; delete node.consequent; delete node.alternate; }, IfStatement(node, state, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, state.uniformCallbackNames))) return; const condition = node.test; const thenFunction = { type: "ArrowFunctionExpression", params: [], body: node.consequent.type === "BlockStatement" ? node.consequent : { type: "BlockStatement", body: [node.consequent] } }; let callExpression = { type: "CallExpression", callee: { type: "Identifier", name: "__p5.strandsIf" }, arguments: [condition, thenFunction] }; let elseFunction; if (node.alternate) elseFunction = { type: "ArrowFunctionExpression", params: [], body: node.alternate.type === "BlockStatement" ? node.alternate : { type: "BlockStatement", body: [node.alternate] } }; else elseFunction = { type: "ArrowFunctionExpression", params: [], body: { type: "BlockStatement", body: [] } }; callExpression = { type: "CallExpression", callee: { type: "MemberExpression", object: callExpression, property: { type: "Identifier", name: "Else" } }, arguments: [elseFunction] }; const assignedVars = /* @__PURE__ */ new Set(); const analyzeBranch = (functionBody) => { const localVars = /* @__PURE__ */ new Set(); ancestor(functionBody, { VariableDeclarator(node, ancestors) { if (ancestors.some(statementContainsStrandsControlFlow)) return; if (node.id.type === "Identifier") localVars.add(node.id.name); } }); ancestor(functionBody, { AssignmentExpression(node, ancestors) { if (ancestors.some(statementContainsStrandsControlFlow)) return; const left = node.left; if (left.type === "Identifier") { if (!localVars.has(left.name)) assignedVars.add(left.name); } else if (left.type === "MemberExpression") { const propertyPath = buildPropertyPath(left); if (propertyPath) { const baseName = propertyPath.split(".")[0]; if (!localVars.has(baseName)) assignedVars.add(propertyPath); } } } }); }; analyzeBranch(thenFunction.body); analyzeBranch(elseFunction.body); if (assignedVars.size > 0) { addCopyingAndReturn(thenFunction.body, assignedVars); addCopyingAndReturn(elseFunction.body, assignedVars); const blockVar = `__block_${blockVarCounter++}`; const statements = []; for (const varPath of assignedVars) { const parts = varPath.split("."); let leftExpr = { type: "Identifier", name: parts[0] }; for (let i = 1; i < parts.length; i++) leftExpr = { type: "MemberExpression", object: leftExpr, property: { type: "Identifier", name: parts[i] }, computed: false }; let rightArgExpr = { type: "Identifier", name: parts[0] }; for (let i = 1; i < parts.length; i++) rightArgExpr = { type: "MemberExpression", object: rightArgExpr, property: { type: "Identifier", name: parts[i] }, computed: false }; statements.push({ type: "ExpressionStatement", expression: { type: "AssignmentExpression", operator: "=", left: leftExpr, right: { type: "CallExpression", callee: { type: "Identifier", name: "__p5.strandsNode" }, arguments: [rightArgExpr] } } }); } statements.push({ type: "VariableDeclaration", declarations: [{ type: "VariableDeclarator", id: { type: "Identifier", name: blockVar }, init: callExpression }], kind: "const" }); for (const varPath of assignedVars) { const parts = varPath.split("."); let leftExpr = { type: "Identifier", name: parts[0] }; for (let i = 1; i < parts.length; i++) leftExpr = { type: "MemberExpression", object: leftExpr, property: { type: "Identifier", name: parts[i] }, computed: false }; const rightExpr = { type: "MemberExpression", object: { type: "Identifier", name: blockVar }, property: { type: "Literal", value: varPath }, computed: true }; statements.push({ type: "ExpressionStatement", expression: { type: "AssignmentExpression", operator: "=", left: leftExpr, right: rightExpr } }); } node.type = "BlockStatement"; node.body = statements; } else { node.type = "ExpressionStatement"; node.expression = callExpression; } delete node.test; delete node.consequent; delete node.alternate; }, UpdateExpression(node, state, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, state.uniformCallbackNames))) return; let operator; if (node.operator === "++") operator = "+"; else if (node.operator === "--") operator = "-"; else return; const assignmentExpr = { type: "AssignmentExpression", operator: "=", left: node.argument, right: { type: "BinaryExpression", operator, left: node.argument, right: { type: "Literal", value: 1 } } }; Object.assign(node, assignmentExpr); delete node.prefix; ASTCallbacks.BinaryExpression(node.right, state, [...ancestors, node]); ASTCallbacks.AssignmentExpression(node, state, ancestors); }, ForStatement(node, state, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, state.uniformCallbackNames))) return; const uniqueLoopVar = `loopVar${loopVarCounter++}`; let initialFunction; if (node.init && node.init.type === "VariableDeclaration") { let initValue = node.init.declarations[0].init; initValue = { type: "Program", body: [{ type: "ExpressionStatement", expression: initValue }] }.body[0].expression; initialFunction = { type: "ArrowFunctionExpression", params: [], body: { type: "BlockStatement", body: [{ type: "ReturnStatement", argument: initValue }] } }; } else initialFunction = { type: "ArrowFunctionExpression", params: [], body: { type: "BlockStatement", body: [{ type: "ReturnStatement", argument: { type: "Literal", value: 0 } }] } }; let conditionBody = node.test || { type: "Literal", value: true }; if (node.init?.type === "VariableDeclaration") { const loopVarName = node.init.declarations[0].id.name; conditionBody = replaceIdentifierReferences(conditionBody, loopVarName, uniqueLoopVar); } conditionBody = { type: "Program", body: [{ type: "ExpressionStatement", expression: conditionBody }] }.body[0].expression; const conditionFunction = { type: "ArrowFunctionExpression", params: [{ type: "Identifier", name: uniqueLoopVar }], body: conditionBody }; let updateFunction; if (node.update) { let updateExpr = node.update; if (node.init?.type === "VariableDeclaration") { const loopVarName = node.init.declarations[0].id.name; updateExpr = replaceIdentifierReferences(updateExpr, loopVarName, uniqueLoopVar); } updateExpr = { type: "Program", body: [{ type: "ExpressionStatement", expression: updateExpr }] }.body[0].expression; updateFunction = { type: "ArrowFunctionExpression", params: [{ type: "Identifier", name: uniqueLoopVar }], body: { type: "BlockStatement", body: [{ type: "ReturnStatement", argument: updateExpr }] } }; } else updateFunction = { type: "ArrowFunctionExpression", params: [{ type: "Identifier", name: uniqueLoopVar }], body: { type: "BlockStatement", body: [{ type: "ReturnStatement", argument: { type: "Identifier", name: uniqueLoopVar } }] } }; let bodyBlock = node.body.type === "BlockStatement" ? node.body : { type: "BlockStatement", body: [node.body] }; if (node.init?.type === "VariableDeclaration") { const loopVarName = node.init.declarations[0].id.name; bodyBlock = replaceIdentifierReferences(bodyBlock, loopVarName, uniqueLoopVar); } const bodyFunction = { type: "ArrowFunctionExpression", params: [{ type: "Identifier", name: uniqueLoopVar }, { type: "Identifier", name: "vars" }], body: bodyBlock }; const assignedVars = findLoopCarriedVars(bodyFunction.body); if (assignedVars.size > 0) { addCopyingAndReturn(bodyFunction.body, assignedVars, "vars"); const blockVar = `__block_${blockVarCounter++}`; const statements = []; const initialVarsObject = { type: "ObjectExpression", properties: Array.from(assignedVars).map((varPath) => { const parts = varPath.split("."); let expr = { type: "Identifier", name: parts[0] }; for (let i = 1; i < parts.length; i++) expr = { type: "MemberExpression", object: expr, property: { type: "Identifier", name: parts[i] }, computed: false }; return { type: "Property", key: { type: "Literal", value: varPath }, value: { type: "CallExpression", callee: { type: "Identifier", name: "__p5.strandsNode" }, arguments: [expr] }, kind: "init", computed: false, shorthand: false }; }) }; const callExpression = { type: "CallExpression", callee: { type: "Identifier", name: "__p5.strandsFor" }, arguments: [ initialFunction, conditionFunction, updateFunction, bodyFunction, initialVarsObject ] }; statements.push({ type: "VariableDeclaration", declarations: [{ type: "VariableDeclarator", id: { type: "Identifier", name: blockVar }, init: callExpression }], kind: "const" }); for (const varPath of assignedVars) { const parts = varPath.split("."); let leftExpr = { type: "Identifier", name: parts[0] }; for (let i = 1; i < parts.length; i++) leftExpr = { type: "MemberExpression", object: leftExpr, property: { type: "Identifier", name: parts[i] }, computed: false }; const rightExpr = { type: "MemberExpression", object: { type: "Identifier", name: blockVar }, property: { type: "Literal", value: varPath }, computed: true }; statements.push({ type: "ExpressionStatement", expression: { type: "AssignmentExpression", operator: "=", left: leftExpr, right: rightExpr } }); } node.type = "BlockStatement"; node.body = statements; } else { node.type = "ExpressionStatement"; node.expression = { type: "CallExpression", callee: { type: "Identifier", name: "__p5.strandsFor" }, arguments: [ initialFunction, conditionFunction, updateFunction, bodyFunction, { type: "ObjectExpression", properties: [] } ] }; } delete node.init; delete node.test; delete node.update; } }; function findLoopCarriedVars(loopBody) { const assignedVars = /* @__PURE__ */ new Set(); const localVars = /* @__PURE__ */ new Set(); ancestor(loopBody, { VariableDeclarator(node, ancestors) { if (ancestors.some(statementContainsStrandsControlFlow)) return; if (node.id.type === "Identifier") localVars.add(node.id.name); } }); ancestor(loopBody, { AssignmentExpression(node, ancestors) { if (ancestors.some(statementContainsStrandsControlFlow)) return; const left = node.left; if (left.type === "Identifier") { if (!localVars.has(left.name)) assignedVars.add(left.name); } else if (left.type === "MemberExpression") { const propertyPath = buildPropertyPath(left); if (propertyPath) { const baseName = propertyPath.split(".")[0]; if (!localVars.has(baseName)) assignedVars.add(propertyPath); } } } }); return assignedVars; } function addCarriedValuesToBreaks(loopBody) { const carriedVars = findLoopCarriedVars(loopBody); ancestor(loopBody, { CallExpression(node, ancestors) { if (node.callee.name !== "__p5.break") return; if (ancestors.some((a) => a.type === "ForStatement")) return; node.arguments = [{ type: "ObjectExpression", properties: Array.from(carriedVars).map((varPath) => { const parts = varPath.split("."); let expr = { type: "Identifier", name: parts[0] }; for (let i = 1; i < parts.length; i++) expr = { type: "MemberExpression", object: expr, property: { type: "Identifier", name: parts[i] }, computed: false }; return { type: "Property", key: { type: "Literal", value: varPath }, value: expr, kind: "init", computed: false, shorthand: false }; }) }]; } }); } function functionHasEarlyReturns(functionNode) { let hasEarlyReturn = false; let inControlFlow = 0; const checkForEarlyReturns = { IfStatement(node, state, c) { inControlFlow++; if (node.test) c(node.test, state); if (node.consequent) c(node.consequent, state); if (node.alternate) c(node.alternate, state); inControlFlow--; }, ForStatement(node, state, c) { inControlFlow++; if (node.init) c(node.init, state); if (node.test) c(node.test, state); if (node.update) c(node.update, state); if (node.body) c(node.body, state); inControlFlow--; }, ReturnStatement(node) { if (inControlFlow > 0) hasEarlyReturn = true; } }; if (functionNode.body && functionNode.body.type === "BlockStatement") recursive(functionNode.body, {}, checkForEarlyReturns); return hasEarlyReturn; } function blockContainsReturn(block) { let hasReturn = false; const findReturn = { ReturnStatement() { hasReturn = true; } }; if (block) recursive(block, {}, findReturn); return hasReturn; } function transformHelperFunction(functionNode) { const returnValueDecl = { type: "VariableDeclaration", declarations: [{ type: "VariableDeclarator", id: { type: "Identifier", name: "__returnValue" }, init: null }], kind: "let" }; if (!functionNode.body || functionNode.body.type !== "BlockStatement") return; functionNode.body.body.unshift(returnValueDecl); function restructureIfStatements(statements) { for (let i = 0; i < statements.length; i++) { const stmt = statements[i]; if (stmt.type === "IfStatement" && blockContainsReturn(stmt.consequent) && !stmt.alternate) { const subsequentStatements = statements.slice(i + 1); if (subsequentStatements.length > 0) { stmt.alternate = { type: "BlockStatement", body: subsequentStatements }; statements.splice(i + 1); restructureIfStatements(stmt.alternate.body); } } if (stmt.type === "IfStatement") { if (stmt.consequent && stmt.consequent.type === "BlockStatement") restructureIfStatements(stmt.consequent.body); if (stmt.alternate && stmt.alternate.type === "BlockStatement") restructureIfStatements(stmt.alternate.body); } else if (stmt.type === "ForStatement" && stmt.body && stmt.body.type === "BlockStatement") restructureIfStatements(stmt.body.body); else if (stmt.type === "BlockStatement") restructureIfStatements(stmt.body); } } restructureIfStatements(functionNode.body.body); recursive(functionNode.body, {}, { ReturnStatement(node) { node.type = "ExpressionStatement"; node.expression = { type: "AssignmentExpression", operator: "=", left: { type: "Identifier", name: "__returnValue" }, right: node.argument || { type: "Identifier", name: "undefined" } }; delete node.argument; } }); functionNode.body.body.push({ type: "ReturnStatement", argument: { type: "Identifier", name: "__returnValue" } }); } function functionHasSetInControlFlow(functionNode) { let hasSetInControlFlow = false; let inControlFlow = 0; const checkForSetCalls = { IfStatement(node, state, c) { inControlFlow++; if (node.test) c(node.test, state); if (node.consequent) c(node.consequent, state); if (node.alternate) c(node.alternate, state); inControlFlow--; }, ForStatement(node, state, c) { inControlFlow++; if (node.init) c(node.init, state); if (node.test) c(node.test, state); if (node.update) c(node.update, state); if (node.body) c(node.body, state); inControlFlow--; }, CallExpression(node) { if (inControlFlow > 0 && node.callee?.type === "MemberExpression" && node.callee?.property?.name === "set") hasSetInControlFlow = true; } }; if (functionNode.body && functionNode.body.type === "BlockStatement") recursive(functionNode.body, {}, checkForSetCalls); return hasSetInControlFlow; } function statementCallsHookMethod(stmt, methodName, exprString) { if (stmt.type !== "ExpressionStatement") return false; return (stmt.expression?.type === "SequenceExpression" ? stmt.expression.expressions : [stmt.expression]).some((expr) => expr?.type === "CallExpression" && expr.callee?.type === "MemberExpression" && expr.callee?.property?.name === methodName && escodegen.generate(expr.callee.object) === exprString); } function transformFunctionSetCalls(functionNode) { if (!functionNode.body || functionNode.body.type !== "BlockStatement") return; const hooksWithSetCalls = /* @__PURE__ */ new Map(); recursive(functionNode.body, {}, { CallExpression(node) { if (node.callee?.type === "MemberExpression" && node.callee?.property?.name === "set" && node.callee?.object) { const hookObjectNode = node.callee.object; const exprString = escodegen.generate(hookObjectNode); if (!hooksWithSetCalls.has(exprString)) hooksWithSetCalls.set(exprString, hookObjectNode); } } }); if (hooksWithSetCalls.size === 0) return; for (const [exprString, hookObjectNode] of hooksWithSetCalls) { const intermediateVarName = `__${exprString.replace(/[^a-zA-Z0-9_]/g, "_")}_value`; const intermediateVarDecl = { type: "VariableDeclaration", declarations: [{ type: "VariableDeclarator", id: { type: "Identifier", name: intermediateVarName }, init: null }], kind: "let" }; let beginCallIndex = -1; for (let i = 0; i < functionNode.body.body.length; i++) if (statementCallsHookMethod(functionNode.body.body[i], "begin", exprString)) { beginCallIndex = i; break; } if (beginCallIndex !== -1) functionNode.body.body.splice(beginCallIndex, 0, intermediateVarDecl); else functionNode.body.body.unshift(intermediateVarDecl); ancestor(functionNode.body, { CallExpression(node, state, ancestors) { if (node.callee?.type === "MemberExpression" && node.callee?.property?.name === "set" && node.callee?.object) { if (escodegen.generate(node.callee.object) === exprString && node.arguments.length > 0) { const value = node.arguments[0]; delete node.callee; delete node.arguments; node.type = "AssignmentExpression"; node.operator = "="; node.left = { type: "Identifier", name: intermediateVarName }; node.right = value; } } } }); const finalSetCall = { type: "ExpressionStatement", expression: { type: "CallExpression", callee: { type: "MemberExpression", object: JSON.parse(JSON.stringify(hookObjectNode)), property: { type: "Identifier", name: "set" }, computed: false }, arguments: [{ type: "Identifier", name: intermediateVarName }] } }; let endCallIndex = -1; for (let i = 0; i < functionNode.body.body.length; i++) if (statementCallsHookMethod(functionNode.body.body[i], "end", exprString)) { endCallIndex = i; break; } if (endCallIndex !== -1) functionNode.body.body.splice(endCallIndex, 0, finalSetCall); else { const lastStatement = functionNode.body.body[functionNode.body.body.length - 1]; if (lastStatement && lastStatement.type === "ReturnStatement") functionNode.body.body.splice(functionNode.body.body.length - 1, 0, finalSetCall); else functionNode.body.body.push(finalSetCall); } } } function transformSetCallsInControlFlow(ast, names) { const functionsToTransform = []; ancestor(ast, { ArrowFunctionExpression(node, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, names))) return; if (functionHasSetInControlFlow(node)) functionsToTransform.push(node); }, FunctionExpression(node, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, names))) return; if (functionHasSetInControlFlow(node)) functionsToTransform.push(node); }, FunctionDeclaration(node, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, names))) return; if (functionHasSetInControlFlow(node)) functionsToTransform.push(node); } }); for (const funcNode of functionsToTransform) transformFunctionSetCalls(funcNode); } function transformHelperFunctionEarlyReturns(ast, names) { const helperFunctionsToTransform = []; ancestor(ast, { VariableDeclarator(node, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, names))) return; const init = node.init; if (init && (init.type === "ArrowFunctionExpression" || init.type === "FunctionExpression")) { if (functionHasEarlyReturns(init)) helperFunctionsToTransform.push(init); } }, FunctionDeclaration(node, ancestors) { if (ancestors.some((a) => nodeIsUniform(a) || nodeIsUniformCallbackFn(a, names))) return; if (functionHasEarlyReturns(node)) helperFunctionsToTransform.push(node); }, CallExpression(node, ancestors) {} }); for (const funcNode of helperFunctionsToTransform) transformHelperFunction(funcNode); } function runNonControlFlowPass(ast, uniformCallbackNames, initialShaderNameState, p5) { const nonControlFlowCallbacks = { ...ASTCallbacks }; delete nonControlFlowCallbacks.IfStatement; delete nonControlFlowCallbacks.ForStatement; const state = { varyings: {}, uniformCallbackNames, shaderNameMap: createStrandsShaderNameMap(), shaderNameState: createStrandsShaderNameState(initialShaderNameState?.nextSuffix || 0), p5 }; ancestor(ast, nonControlFlowCallbacks, void 0, state); return { shaderNameMap: state.shaderNameMap, shaderNameState: state.shaderNameState }; } function runControlFlowPass(ast, uniformCallbackNames) { recursive(ast, { varyings: {}, inControlFlow: 0, uniformCallbackNames }, { CallExpression(node, state, c) { if (nodeIsUniform(node)) return; if (node.callee) c(node.callee, state); for (const arg of node.arguments) c(arg, state); }, FunctionDeclaration(node, state, c) { if (state.uniformCallbackNames?.has(node.id?.name)) return; if (node.body) c(node.body, state); }, VariableDeclarator(node, state, c) { if (state.uniformCallbackNames?.has(node.id?.name) && (node.init?.type === "FunctionExpression" || node.init?.type === "ArrowFunctionExpression")) return; if (node.init) c(node.init, state); }, IfStatement(node, state, c) { state.inControlFlow++; if (node.test) c(node.test, state); if (node.consequent) c(node.consequent, state); if (node.alternate) c(node.alternate, state); ASTCallbacks.IfStatement(node, state, []); state.inControlFlow--; }, ForStatement(node, state, c) { state.inControlFlow++; if (node.init) c(node.init, state); if (node.test) c(node.test, state); if (node.update) c(node.update, state); if (node.body) { addCarriedValuesToBreaks(node.body); c(node.body, state); } ASTCallbacks.ForStatement(node, state, []); state.inControlFlow--; }, ReturnStatement(node, state, c) { if (!state.inControlFlow) return; node.type = "ExpressionStatement"; node.expression = { type: "CallExpression", callee: { type: "Identifier", name: "__p5.strandsEarlyReturn" }, arguments: node.argument ? [node.argument] : [] }; delete node.argument; } }); } function buildStrandsCallback(p5, ast, scope) { const scopeKeys = Object.keys(scope); const fn = ast.body.length === 1 && ast.body[0].expression; if (!fn || fn.type !== "FunctionExpression" && fn.type !== "ArrowFunctionExpression") { console.log(escodegen.generate(ast)); throw new Error("Could not parse p5.strands function!"); } const params = fn.params.map((param) => escodegen.generate(param)); let paramVals, paramNames; if (params.length > 0) { paramNames = params; paramVals = [scope]; } else { paramNames = scopeKeys; paramVals = scopeKeys.map((key) => scope[key]); } const body = fn.body.type === "BlockStatement" ? fn.body.body.map((statement) => escodegen.generate(statement)).join("\n") : `return ${escodegen.generate(fn.body)};`; try { const internalStrandsCallback = new Function("__p5", ...paramNames, body); return () => internalStrandsCallback(p5, ...paramVals); } catch (e) { console.error(e); console.log(paramNames); console.log(body); throw new Error("Error transpiling p5.strands callback!"); } } function transpileStrandsToJS(p5, sourceString, srcLocations, scope, initialShaderNameState) { blockVarCounter = 0; loopVarCounter = 0; const ast = parse(sourceString, { ecmaVersion: 2021, locations: srcLocations }); throwIfLoopProtectionInserted(ast); const uniformCallbackNames = collectUniformCallbackNames(ast); restoreMinifiedConditionals(ast, uniformCallbackNames); transformSetCallsInControlFlow(ast, uniformCallbackNames); const { shaderNameMap, shaderNameState } = runNonControlFlowPass(ast, uniformCallbackNames, initialShaderNameState, p5); transformHelperFunctionEarlyReturns(ast, uniformCallbackNames); runControlFlowPass(ast, uniformCallbackNames); return { callback: buildStrandsCallback(p5, ast, scope), shaderNameMap, shaderNameState }; } //#endregion export { transpileStrandsToJS };