diff --git a/tests/browser/graph-clone-identity.test.js b/tests/browser/graph-clone-identity.test.js index 8b44bff81..1e0d78297 100644 --- a/tests/browser/graph-clone-identity.test.js +++ b/tests/browser/graph-clone-identity.test.js @@ -49,17 +49,23 @@ function candidate( duplicate, invalidId, invalidRoot, + mixed, nullNeighbor, originalNeighbors, root = "a", } = {}, ) { const id = duplicate || 1; + // "nonRoot" nulls a neighbor of b, reached from the root, so a check that + // looked only at the root's own list would not pass it. + const holder = nullNeighbor === "nonRoot" ? "b" : "a"; if (language === "javascript") return `function replicateTopology(node) { const a = new Node(1), b = new Node(2), c = new Node(3); a.neighbors = [c, b]; b.neighbors = [c, a]; c.neighbors = [b, a]; ${duplicate ? `const d = new Node(${id}, ${id === 1 ? "a" : "b"}.neighbors.slice()); ${id === 1 ? "b.neighbors = [c, d]" : "c.neighbors = [d, a]"};` : ""} + ${nullNeighbor ? `${holder}.neighbors[0] = ${nullNeighbor === "undefined" ? "undefined" : "null"};` : ""} + ${mixed ? "a.neighbors = [node, null];" : ""} return ${root}; }`; if (language === "python") @@ -67,6 +73,8 @@ function candidate( a, b, c = Node(1), Node(2), Node(3) a.neighbors, b.neighbors, c.neighbors = [c, b], [c, a], [b, a] ${duplicate ? `d = Node(${id})\n d.neighbors = list(${id === 1 ? "a" : "b"}.neighbors)\n ${id === 1 ? "b.neighbors = [c, d]" : "c.neighbors = [d, a]"}` : ""} + ${nullNeighbor ? `${holder}.neighbors[0] = None` : ""} + ${mixed ? "a.neighbors = [node, None]" : ""} return ${root} `; if (language === "cpp") @@ -74,6 +82,8 @@ function candidate( auto* a = new Node(1); auto* b = new Node(2); auto* c = new Node(3); a->neighbors = {c, b}; b->neighbors = {c, a}; c->neighbors = {b, a}; ${duplicate ? `auto* d = new Node(${id}); d->neighbors = ${id === 1 ? "a" : "b"}->neighbors; ${id === 1 ? "b->neighbors = {c, d}" : "c->neighbors = {d, a}"};` : ""} + ${nullNeighbor ? `${holder}->neighbors[0] = nullptr;` : ""} + ${mixed ? "a->neighbors = {node, nullptr};" : ""} return ${root}; }};`; if (language === "java") @@ -81,6 +91,8 @@ function candidate( Node a = new Node(1), b = new Node(2), c = new Node(3); a.neighbors.addAll(Arrays.asList(c, b)); b.neighbors.addAll(Arrays.asList(c, a)); c.neighbors.addAll(Arrays.asList(b, a)); ${duplicate ? `Node d = new Node(${id}); d.neighbors.addAll(${id === 1 ? "a" : "b"}.neighbors); ${id === 1 ? "b.neighbors.set(1, d)" : "c.neighbors.set(0, d)"};` : ""} + ${nullNeighbor ? `${holder}.neighbors.set(0, null);` : ""} + ${mixed ? "a.neighbors.set(0, node); a.neighbors.set(1, null);" : ""} return ${root}; }}`; return `struct Node* replicateTopology(struct Node* node) { @@ -96,12 +108,48 @@ function candidate( : `struct Node* extra = calloc(1, sizeof(*extra)); extra->val = ${invalidId}; ${invalidRoot ? `struct Node* root = calloc(1, sizeof(*root)); root->val = ${invalidId}; root->numNeighbors = 2; root->neighbors = calloc(2, sizeof(*root->neighbors)); root->neighbors[0] = a; root->neighbors[1] = extra; return root;` : "a->neighbors = realloc(a->neighbors, 3 * sizeof(*a->neighbors)); a->neighbors[2] = extra; a->numNeighbors = 3;"}` } - ${nullNeighbor ? "a->neighbors[0] = NULL;" : ""} + ${nullNeighbor ? `${holder}->neighbors[0] = NULL;` : ""} + ${mixed ? "a->neighbors[0] = node; a->neighbors[1] = NULL;" : ""} ${originalNeighbors ? "b->neighbors = node->neighbors[0]->neighbors;" : ""} return ${root}; }`; } +const nullNeighborName = (kind, word) => + kind === "undefined" + ? "an undefined neighbor" + : `a ${word} neighbor${kind === "nonRoot" ? " of a non-root node" : ""}`; + +// A scenario sets one kind at most, and is named for it in the order the +// toolchain suite checks its refusals: entry node, input nodes, null +// neighbor, mixed violation, out-of-range ID, duplicate ID. +function title(language, scenario) { + const { + duplicate, + invalidId, + invalidRoot, + mixed, + nullNeighbor, + originalNeighbors, + root = "a", + } = scenario; + const browserRun = language === "javascript" || language === "python"; + const nullWord = browserRun ? "null" : "NULL"; + let what; + if (root !== "a") what = `rejects entry node ${root}`; + else if (originalNeighbors) what = "reports input nodes before duplicate IDs"; + else if (nullNeighbor) + what = `rejects ${nullNeighborName(nullNeighbor, nullWord)}`; + else if (mixed) + what = `names the ${language === "c" ? "input node" : `${nullWord} neighbor`} in a mixed violation`; + else if (invalidId !== undefined) + what = `rejects out-of-range ${invalidRoot ? "root" : "neighbor"} ID ${invalidId}`; + else if (duplicate) what = `rejects duplicate ID ${duplicate}`; + else if (language === "c") what = "accepts shared nodes"; + else what = "accepts shared nodes and reordered neighbors"; + return `${language} graph clone ${what}`; +} + let browser, server, base; before(async () => { browser = await launchChromium(); @@ -121,14 +169,19 @@ after(async () => { }); for (const language of ["javascript", "python"]) { - for (const [duplicate, root] of [ - [0, "a"], - [1, "a"], - [2, "a"], - [0, "b"], - [0, "c"], + for (const scenario of [ + {}, + { duplicate: 1 }, + { duplicate: 2 }, + { root: "b" }, + { root: "c" }, + { nullNeighbor: true }, + { nullNeighbor: "nonRoot" }, + ...(language === "javascript" ? [{ nullNeighbor: "undefined" }] : []), + { mixed: true }, ]) { - test(`${language} graph clone ${root !== "a" ? `rejects entry node ${root}` : duplicate ? `rejects duplicate ID ${duplicate}` : "accepts shared nodes and reordered neighbors"}`, async (t) => { + const { duplicate, root = "a", nullNeighbor, mixed } = scenario; + test(title(language, scenario), async (t) => { if (!browser) return t.skip("playwright chromium unavailable"); const page = await browser.newPage(); try { @@ -140,13 +193,16 @@ for (const language of ["javascript", "python"]) { }, { language, - code: candidate(language, { duplicate, root }), + code: candidate(language, scenario), }, ); assert.equal(summary.setupError, undefined); assert.equal(summary.total, 1); assert.equal(summary.cases.length, 1); - assert.equal(summary.passed, duplicate || root !== "a" ? 0 : 1); + assert.equal( + summary.passed, + duplicate || root !== "a" || nullNeighbor || mixed ? 0 : 1, + ); if (root !== "a") assert.match(summary.cases[0].error, /must start at node 1/); if (duplicate) @@ -154,6 +210,11 @@ for (const language of ["javascript", "python"]) { summary.cases[0].error, /distinct nodes with the same ID/, ); + if (nullNeighbor || mixed) + assert.match( + summary.cases[0].error, + /Returned graph has a NULL neighbor\./, + ); } finally { await page.close(); } @@ -178,26 +239,36 @@ describe("graph clone toolchain harnesses", { concurrency: 4 }, () => { } catch { available = false; } - const scenarios = [0, 1, 2].map((duplicate) => ({ duplicate })); - scenarios.push({ duplicate: 0, root: "b" }, { duplicate: 0, root: "c" }); + const scenarios = [{}, { duplicate: 1 }, { duplicate: 2 }]; + scenarios.push({ root: "b" }, { root: "c" }); if (language === "c") for (const invalidId of [0, 1024]) for (const invalidRoot of [true, false]) - scenarios.push({ duplicate: 0, invalidId, invalidRoot }); - if (language === "c") scenarios.push({ duplicate: 0, nullNeighbor: true }); - if (language === "c") - scenarios.push({ duplicate: 0, originalNeighbors: true }); + scenarios.push({ invalidId, invalidRoot }); + // A copied node whose neighbors are [an input node, null] breaks two + // rules at once, and which one is named depends on the walk: C checks + // each edge in order and meets the input node first, while C++, Java, + // JavaScript and Python refuse a null while queueing every neighbor of + // the node before any of them is visited. Only a single violation reads + // the same in all five; these scenarios pin C, C++ and Java, and the + // browser suite above pins JavaScript and Python. + scenarios.push( + { nullNeighbor: true }, + { nullNeighbor: "nonRoot" }, + { mixed: true }, + ); + if (language === "c") scenarios.push({ originalNeighbors: true }); for (const scenario of scenarios) { const { duplicate, invalidId, - invalidRoot, + mixed, nullNeighbor, originalNeighbors, root = "a", } = scenario; test( - `${language} graph clone ${root !== "a" ? `rejects entry node ${root}` : originalNeighbors ? "reports input nodes before duplicate IDs" : nullNeighbor ? "rejects a NULL neighbor" : invalidId !== undefined ? `rejects out-of-range ${invalidRoot ? "root" : "neighbor"} ID ${invalidId}` : duplicate ? `rejects duplicate ID ${duplicate}` : language === "c" ? "accepts shared nodes" : "accepts shared nodes and reordered neighbors"}`, + title(language, scenario), { skip: available ? false @@ -229,15 +300,17 @@ describe("graph clone toolchain harnesses", { concurrency: 4 }, () => { assert.equal(results.length, 1); if (root !== "a") assert.match(results[0].error, /must start at node 1/); - else if (originalNeighbors) + else if (originalNeighbors || (mixed && language === "c")) assert.equal( results[0].error, "Returned graph must be a deep copy.", ); - else if (nullNeighbor) - assert.equal( + else if (nullNeighbor || mixed) + assert.ok( + results[0].error.endsWith( + "Returned graph has a NULL neighbor.", + ), results[0].error, - "Returned graph has a NULL neighbor.", ); else if (invalidId !== undefined) assert.equal( diff --git a/web/compiler-explorer.js b/web/compiler-explorer.js index d618ddaff..b49845a70 100644 --- a/web/compiler-explorer.js +++ b/web/compiler-explorer.js @@ -610,7 +610,7 @@ TreeNode* findTreeNode(TreeNode* root, int value) { queue q; if (root Node* randomList(vector>> items) { vector nodes; for (auto item : items) nodes.push_back(new Node(item.first)); originalRandomNodes = set(nodes.begin(), nodes.end()); for (size_t i = 0; i < nodes.size(); ++i) { nodes[i]->next = i + 1 < nodes.size() ? nodes[i + 1] : nullptr; if (items[i].second) nodes[i]->random = nodes[*items[i].second]; } return nodes.empty() ? nullptr : nodes[0]; } string randomListToJson(Node* node) { vector nodes; map index; set seen; for (auto* cur = node; cur; cur = cur->next) { if (!seen.insert(cur).second) throw runtime_error("Returned list must not reach a node twice."); if (originalRandomNodes.count(cur)) throw runtime_error("Returned list must be a deep copy."); index[cur] = nodes.size(); nodes.push_back(cur); } string out = "["; for (size_t i = 0; i < nodes.size(); ++i) { if (i) out += ","; if (nodes[i]->random && !index.count(nodes[i]->random)) throw runtime_error("Returned random pointer must stay inside the copied list."); out += "[" + to_string(nodes[i]->val) + "," + (nodes[i]->random ? to_string(index[nodes[i]->random]) : string("null")) + "]"; } return out + "]"; } Node* graphNode(vector> adjacency) { if (adjacency.empty()) { originalGraphNodes.clear(); return nullptr; } vector nodes; for (size_t i = 0; i < adjacency.size(); ++i) nodes.push_back(new Node(i + 1)); originalGraphNodes = set(nodes.begin(), nodes.end()); for (size_t i = 0; i < adjacency.size(); ++i) for (int value : adjacency[i]) nodes[i]->neighbors.push_back(nodes[value - 1]); return nodes[0]; } -string graphToJson(Node* node) { if (!node) return "[]"; map byValue; queue q; q.push(node); while (!q.empty()) { auto* cur = q.front(); q.pop(); if (!cur) continue; if (originalGraphNodes.count(cur)) throw runtime_error("Returned graph must be a deep copy."); if (byValue.count(cur->val)) { if (byValue.at(cur->val) != cur) throw runtime_error("Returned graph must not contain distinct nodes with the same ID."); continue; } byValue[cur->val] = cur; for (auto* next : cur->neighbors) { if (!next) throw runtime_error("Returned graph has a NULL neighbor."); q.push(next); } } if (node->val != 1) throw runtime_error("Returned graph must start at node 1."); string out = "["; bool first = true; for (auto& [value, cur] : byValue) { if (!first) out += ","; first = false; vector neighbors; for (auto* next : cur->neighbors) neighbors.push_back(next->val); sort(neighbors.begin(), neighbors.end()); out += toJson(neighbors); } return out + "]"; } +string graphToJson(Node* node) { if (!node) return "[]"; map byValue; queue q; q.push(node); while (!q.empty()) { auto* cur = q.front(); q.pop(); if (originalGraphNodes.count(cur)) throw runtime_error("Returned graph must be a deep copy."); if (byValue.count(cur->val)) { if (byValue.at(cur->val) != cur) throw runtime_error("Returned graph must not contain distinct nodes with the same ID."); continue; } byValue[cur->val] = cur; for (auto* next : cur->neighbors) { if (!next) throw runtime_error("Returned graph has a NULL neighbor."); q.push(next); } } if (node->val != 1) throw runtime_error("Returned graph must start at node 1."); string out = "["; bool first = true; for (auto& [value, cur] : byValue) { if (!first) out += ","; first = false; vector neighbors; for (auto* next : cur->neighbors) neighbors.push_back(next->val); sort(neighbors.begin(), neighbors.end()); out += toJson(neighbors); } return out + "]"; } Node* nextTree(vector> values) { if (values.empty() || !values[0]) return nullptr; auto* root = new Node(*values[0]); queue q; q.push(root); size_t i = 1; while (!q.empty() && i < values.size()) { auto* node = q.front(); q.pop(); if (i < values.size() && values[i]) { node->left = new Node(*values[i]); q.push(node->left); } ++i; if (i < values.size() && values[i]) { node->right = new Node(*values[i]); q.push(node->right); } ++i; } return root; } string nextTreeToJson(Node* root) { vector levels; queue q; unordered_set seen; if (root) q.push(root); while (!q.empty()) { size_t count = q.size(); vector level; for (size_t i = 0; i < count; ++i) { auto* node = q.front(); q.pop(); if (!seen.insert(node).second) throw runtime_error("Returned tree must not reach a node twice."); level.push_back(node); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } vector row; for (size_t i = 0; i < level.size(); ++i) { if (level[i]->next != (i + 1 < level.size() ? level[i + 1] : nullptr)) throw runtime_error("next pointers do not match the tree level order."); row.push_back(level[i]->val); } levels.push_back(toJson(row)); } string out = "["; for (size_t i = 0; i < levels.size(); ++i) { if (i) out += ","; out += levels[i]; } return out + "]"; } string quadTreeToJson(Node* root) { vector rows; unordered_set ancestors; function visit = [&](Node* node) { if (!node) return; if (!ancestors.insert(node).second) throw runtime_error("Returned tree must not contain a cycle."); if (rows.size() >= ${MAX_QUAD_TREE_NODES}) throw runtime_error("Returned quad tree must not expand to more than ${MAX_QUAD_TREE_NODES} nodes."); rows.push_back("[" + to_string(node->isLeaf ? 1 : 0) + "," + to_string(node->isLeaf ? (node->val ? 1 : 0) : 1) + "]"); if (!node->isLeaf) { visit(node->topLeft); visit(node->topRight); visit(node->bottomLeft); visit(node->bottomRight); } ancestors.erase(node); }; visit(root); string out = "["; for (size_t i = 0; i < rows.size(); ++i) { if (i) out += ","; out += rows[i]; } return out + "]"; }`; @@ -779,7 +779,7 @@ class Main { static Node randomList(int[][] items) { ArrayList nodes = new ArrayList<>(); for (int[] item : items) nodes.add(new Node(item[0])); originalRandomNodes = new HashSet<>(nodes); for (int i = 0; i < nodes.size(); i++) { nodes.get(i).next = i + 1 < nodes.size() ? nodes.get(i + 1) : null; if (items[i][1] >= 0) nodes.get(i).random = nodes.get(items[i][1]); } return nodes.isEmpty() ? null : nodes.get(0); } static String randomListJson(Node node) { ArrayList nodes = new ArrayList<>(); HashMap index = new HashMap<>(); HashSet seen = new HashSet<>(); for (Node cur = node; cur != null; cur = cur.next) { if (!seen.add(cur)) throw new IllegalArgumentException("Returned list must not reach a node twice."); if (originalRandomNodes.contains(cur)) throw new IllegalArgumentException("Returned list must be a deep copy."); index.put(cur, nodes.size()); nodes.add(cur); } StringJoiner out = new StringJoiner(",", "[", "]"); for (Node cur : nodes) { if (cur.random != null && !index.containsKey(cur.random)) throw new IllegalArgumentException("Returned random pointer must stay inside the copied list."); out.add("[" + cur.val + "," + (cur.random == null ? "null" : index.get(cur.random)) + "]"); } return out.toString(); } static Node graphNode(int[][] adjacency) { if (adjacency.length == 0) { originalGraphNodes = new HashSet<>(); return null; } ArrayList nodes = new ArrayList<>(); for (int i = 0; i < adjacency.length; i++) nodes.add(new Node(i + 1)); originalGraphNodes = new HashSet<>(nodes); for (int i = 0; i < adjacency.length; i++) for (int value : adjacency[i]) nodes.get(i).neighbors.add(nodes.get(value - 1)); return nodes.get(0); } - static String graphJson(Node node) { if (node == null) return "[]"; TreeMap byValue = new TreeMap<>(); ArrayDeque q = new ArrayDeque<>(); q.add(node); while (!q.isEmpty()) { Node cur = q.remove(); if (cur == null) continue; if (originalGraphNodes.contains(cur)) throw new IllegalArgumentException("Returned graph must be a deep copy."); if (byValue.containsKey(cur.val)) { if (byValue.get(cur.val) != cur) throw new IllegalArgumentException("Returned graph must not contain distinct nodes with the same ID."); continue; } byValue.put(cur.val, cur); for (Node next : cur.neighbors) q.add(next); } if (node.val != 1) throw new IllegalArgumentException("Returned graph must start at node 1."); StringJoiner out = new StringJoiner(",", "[", "]"); for (Node cur : byValue.values()) { ArrayList row = new ArrayList<>(); for (Node next : cur.neighbors) row.add(next.val); Collections.sort(row); out.add(json(row)); } return out.toString(); } + static String graphJson(Node node) { if (node == null) return "[]"; TreeMap byValue = new TreeMap<>(); ArrayDeque q = new ArrayDeque<>(); q.add(node); while (!q.isEmpty()) { Node cur = q.remove(); if (originalGraphNodes.contains(cur)) throw new IllegalArgumentException("Returned graph must be a deep copy."); if (byValue.containsKey(cur.val)) { if (byValue.get(cur.val) != cur) throw new IllegalArgumentException("Returned graph must not contain distinct nodes with the same ID."); continue; } byValue.put(cur.val, cur); for (Node next : cur.neighbors) { if (next == null) throw new IllegalArgumentException("Returned graph has a NULL neighbor."); q.add(next); } } if (node.val != 1) throw new IllegalArgumentException("Returned graph must start at node 1."); StringJoiner out = new StringJoiner(",", "[", "]"); for (Node cur : byValue.values()) { ArrayList row = new ArrayList<>(); for (Node next : cur.neighbors) row.add(next.val); Collections.sort(row); out.add(json(row)); } return out.toString(); } static Node nextTree(Integer[] values) { if (values.length == 0 || values[0] == null) return null; Node root = new Node(values[0]); ArrayDeque q = new ArrayDeque<>(); q.add(root); int i = 1; while (!q.isEmpty() && i < values.length) { Node node = q.remove(); if (i < values.length && values[i] != null) { node.left = new Node(values[i]); q.add(node.left); } i++; if (i < values.length && values[i] != null) { node.right = new Node(values[i]); q.add(node.right); } i++; } return root; } static String nextTreeJson(Node root) { ArrayList levels = new ArrayList<>(); ArrayDeque q = new ArrayDeque<>(); Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); if (root != null) q.add(root); while (!q.isEmpty()) { int count = q.size(); ArrayList level = new ArrayList<>(); for (int i = 0; i < count; i++) { Node node = q.remove(); if (!seen.add(node)) throw new IllegalArgumentException("Returned tree must not reach a node twice."); level.add(node); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); } ArrayList row = new ArrayList<>(); for (int i = 0; i < level.size(); i++) { if (level.get(i).next != (i + 1 < level.size() ? level.get(i + 1) : null)) throw new IllegalArgumentException("next pointers do not match the tree level order."); row.add(level.get(i).val); } levels.add(json(row)); } return "[" + String.join(",", levels) + "]"; } static String quadTreeJson(Node root) { ArrayList rows = new ArrayList<>(); quadTreeVisit(root, rows, Collections.newSetFromMap(new IdentityHashMap<>())); return "[" + String.join(",", rows) + "]"; } diff --git a/web/runners.js b/web/runners.js index 8cfeb36e1..f5e1be67c 100644 --- a/web/runners.js +++ b/web/runners.js @@ -781,14 +781,16 @@ const JS_RUNNER_SOURCE = ` if (!node) return []; const byValue = new Map(), queue = [node]; for (const current of queue) { - if (!current) continue; if (originalGraphNodes.has(current)) throw new TypeError("Returned graph must be a deep copy."); if (byValue.has(current.val)) { if (byValue.get(current.val) !== current) throw new TypeError("Returned graph must not contain distinct nodes with the same ID."); continue; } byValue.set(current.val, current); - for (const neighbor of current.neighbors || []) queue.push(neighbor); + for (const neighbor of current.neighbors || []) { + if (neighbor == null) throw new TypeError("Returned graph has a NULL neighbor."); + queue.push(neighbor); + } } // graphFromAdjacency always supplies node 1; sorting below loses the entry node. if (node.val !== 1) throw new TypeError("Returned graph must start at node 1."); @@ -1137,8 +1139,6 @@ def _graph_to_adjacency(node): by_value = {} queue = [node] for current in queue: - if current is None: - continue if id(current) in _original_graph_nodes: raise TypeError("Returned graph must be a deep copy.") if current.val in by_value: @@ -1146,7 +1146,10 @@ def _graph_to_adjacency(node): raise TypeError("Returned graph must not contain distinct nodes with the same ID.") continue by_value[current.val] = current - queue.extend(getattr(current, "neighbors", []) or []) + for neighbor in getattr(current, "neighbors", []) or []: + if neighbor is None: + raise TypeError("Returned graph has a NULL neighbor.") + queue.append(neighbor) if node.val != 1: raise TypeError("Returned graph must start at node 1.") return [sorted(neighbor.val for neighbor in by_value[value].neighbors) for value in sorted(by_value)]