diff --git a/tests/browser/graph-clone-identity.test.js b/tests/browser/graph-clone-identity.test.js index 1e0d78297..c3ee2fc61 100644 --- a/tests/browser/graph-clone-identity.test.js +++ b/tests/browser/graph-clone-identity.test.js @@ -50,6 +50,7 @@ function candidate( invalidId, invalidRoot, mixed, + nullList, nullNeighbor, originalNeighbors, root = "a", @@ -66,6 +67,7 @@ function candidate( ${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];" : ""} + ${nullList ? "b.neighbors = null;" : ""} return ${root}; }`; if (language === "python") @@ -75,6 +77,7 @@ function candidate( ${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]" : ""} + ${nullList ? "b.neighbors = None" : ""} return ${root} `; if (language === "cpp") @@ -93,6 +96,7 @@ function candidate( ${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);" : ""} + ${nullList ? "b.neighbors = null;" : ""} return ${root}; }}`; return `struct Node* replicateTopology(struct Node* node) { @@ -111,6 +115,7 @@ function candidate( ${nullNeighbor ? `${holder}->neighbors[0] = NULL;` : ""} ${mixed ? "a->neighbors[0] = node; a->neighbors[1] = NULL;" : ""} ${originalNeighbors ? "b->neighbors = node->neighbors[0]->neighbors;" : ""} + ${nullList ? "b->neighbors = NULL;" : ""} return ${root}; }`; } @@ -122,13 +127,14 @@ const nullNeighborName = (kind, word) => // 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. +// neighbor, null list, mixed violation, out-of-range ID, duplicate ID. function title(language, scenario) { const { duplicate, invalidId, invalidRoot, mixed, + nullList, nullNeighbor, originalNeighbors, root = "a", @@ -140,6 +146,7 @@ function title(language, scenario) { else if (originalNeighbors) what = "reports input nodes before duplicate IDs"; else if (nullNeighbor) what = `rejects ${nullNeighborName(nullNeighbor, nullWord)}`; + else if (nullList) what = "reads a null neighbors list as empty"; else if (mixed) what = `names the ${language === "c" ? "input node" : `${nullWord} neighbor`} in a mixed violation`; else if (invalidId !== undefined) @@ -179,8 +186,9 @@ for (const language of ["javascript", "python"]) { { nullNeighbor: "nonRoot" }, ...(language === "javascript" ? [{ nullNeighbor: "undefined" }] : []), { mixed: true }, + { nullList: true }, ]) { - const { duplicate, root = "a", nullNeighbor, mixed } = scenario; + const { duplicate, root = "a", nullNeighbor, mixed, nullList } = scenario; test(title(language, scenario), async (t) => { if (!browser) return t.skip("playwright chromium unavailable"); const page = await browser.newPage(); @@ -201,7 +209,9 @@ for (const language of ["javascript", "python"]) { assert.equal(summary.cases.length, 1); assert.equal( summary.passed, - duplicate || root !== "a" || nullNeighbor || mixed ? 0 : 1, + duplicate || root !== "a" || nullNeighbor || mixed || nullList + ? 0 + : 1, ); if (root !== "a") assert.match(summary.cases[0].error, /must start at node 1/); @@ -215,6 +225,10 @@ for (const language of ["javascript", "python"]) { summary.cases[0].error, /Returned graph has a NULL neighbor\./, ); + if (nullList) { + assert.equal(summary.cases[0].error, undefined); + assert.equal(summary.cases[0].got, "[[2,3],[],[1,2]]"); + } } finally { await page.close(); } @@ -258,11 +272,16 @@ describe("graph clone toolchain harnesses", { concurrency: 4 }, () => { { mixed: true }, ); if (language === "c") scenarios.push({ originalNeighbors: true }); + // C++ holds neighbors in a vector, which cannot be null. In C the null + // list keeps its numNeighbors of two, so the harness must not trust it. + if (language === "c" || language === "java") + scenarios.push({ nullList: true }); for (const scenario of scenarios) { const { duplicate, invalidId, mixed, + nullList, nullNeighbor, originalNeighbors, root = "a", @@ -318,7 +337,10 @@ describe("graph clone toolchain harnesses", { concurrency: 4 }, () => { "Returned graph node IDs must be between 1 and 1023.", ); else if (duplicate) assert.ok(results[0].error.endsWith(message)); - else assert.deepEqual(results[0].actual, spec.cases[0].expected); + else if (nullList) { + assert.equal(results[0].error, undefined); + assert.deepEqual(results[0].actual, [[2, 3], [], [1, 2]]); + } else assert.deepEqual(results[0].actual, spec.cases[0].expected); } finally { rmSync(dir, { recursive: true, force: true }); } diff --git a/web/compiler-explorer.js b/web/compiler-explorer.js index ae0246086..571cc6679 100644 --- a/web/compiler-explorer.js +++ b/web/compiler-explorer.js @@ -448,7 +448,7 @@ static size_t tree_slot(struct TreeNode** seen, int bits, struct TreeNode* node) static void json_tree(FILE* out, struct TreeNode* root) { if (!root) { fputs("[]", out); return; } int bits = 6, capacity = 1 << bits, head = 0, tail = 0, nodes = 0; struct TreeNode** queue = malloc((size_t)capacity * sizeof(*queue)); struct TreeNode** seen = calloc((size_t)capacity, sizeof(*seen)); if (!queue || !seen) exit(EXIT_FAILURE); const char* error = NULL; queue[tail++] = root; while (head < tail && !error) { struct TreeNode* node = queue[head++]; if (!node) continue; size_t slot = tree_slot(seen, bits, node); if (seen[slot]) error = "Returned tree must not reach a node twice."; else if (++nodes > 100000) error = "Returned tree must not have more than 100000 nodes."; else { seen[slot] = node; if (tail + 2 > capacity) { capacity = 1 << ++bits; queue = grow_tree_queue(queue, capacity); free(seen); seen = calloc((size_t)capacity, sizeof(*seen)); if (!seen) exit(EXIT_FAILURE); for (int i = 0; i < head; i++) if (queue[i]) seen[tree_slot(seen, bits, queue[i])] = queue[i]; } queue[tail++] = node->left; queue[tail++] = node->right; } } free(seen); if (error) { free(queue); fputs("null,\\"error\\":", out); json_string(out, error); return; } while (tail > 0 && !queue[tail - 1]) tail--; fputc('[', out); for (int i = 0; i < tail; i++) { if (i) fputc(',', out); if (queue[i]) fprintf(out, "%d", queue[i]->val); else fputs("null", out); } fputc(']', out); free(queue); } static void json_random_list(FILE* out, struct Node* node) { int limit = originalRandomNodesSize, count = 0; struct Node** nodes = malloc((size_t)(limit + 1) * sizeof(*nodes)); int* randoms = malloc((size_t)(limit + 1) * sizeof(*randoms)); if (!nodes || !randoms) exit(EXIT_FAILURE); const char* error = NULL; for (struct Node* cur = node; cur && count <= limit; cur = cur->next) { if (isOriginalRandomNode(cur)) { error = "Returned list must be a deep copy."; break; } nodes[count++] = cur; } if (!error && count > limit) { error = "Returned list must not have more nodes than the input."; for (struct Node *slow = node, *fast = node; fast && fast->next; ) { slow = slow->next; fast = fast->next->next; if (slow == fast) { error = "Returned list must not reach a node twice."; break; } } } for (int i = 0; !error && i < count; i++) { randoms[i] = -1; for (int j = 0; j < count; j++) if (nodes[i]->random == nodes[j]) { randoms[i] = j; break; } if (nodes[i]->random && randoms[i] < 0) error = "Returned random pointer must stay inside the copied list."; } if (error) { fputs("null,\\"error\\":", out); json_string(out, error); free(nodes); free(randoms); return; } fputc('[', out); for (int i = 0; i < count; i++) { if (i) fputc(',', out); fprintf(out, "[%d,", nodes[i]->val); if (randoms[i] < 0) fputs("null", out); else fprintf(out, "%d", randoms[i]); fputc(']', out); } fputc(']', out); free(nodes); free(randoms); } static int compare_graph_neighbor_ids(const void* a, const void* b) { int left = *(const int*)a; int right = *(const int*)b; return (left > right) - (left < right); } -static void json_graph(FILE* out, struct Node* node) { if (!node) { fputs("[]", out); return; } struct Node* nodes[1024]; struct Node* seen[1024] = {0}; int count = 0; nodes[count++] = node; for (int i = 0; i < count && count < 1024; i++) { struct Node* cur = nodes[i]; if (isOriginalGraphNode(cur)) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph must be a deep copy."); return; } if (cur->val <= 0 || cur->val >= 1024) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph node IDs must be between 1 and 1023."); return; } seen[cur->val] = cur; for (int j = 0; j < cur->numNeighbors; j++) { struct Node* next = cur->neighbors[j]; if (!next) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph has a NULL neighbor."); return; } if (next->val <= 0 || next->val >= 1024) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph node IDs must be between 1 and 1023."); return; } if (isOriginalGraphNode(next)) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph must be a deep copy."); return; } if (seen[next->val] && seen[next->val] != next) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph must not contain distinct nodes with the same ID."); return; } if (!seen[next->val]) { seen[next->val] = next; nodes[count++] = next; } } } if (node->val != 1) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph must start at node 1."); return; } fputc('[', out); for (int value = 1, printed = 0; value < 1024; value++) { struct Node* cur = NULL; for (int i = 0; i < count; i++) if (nodes[i]->val == value) cur = nodes[i]; if (!cur) continue; if (printed++) fputc(',', out); int degree = cur->numNeighbors; int* neighborIds = NULL; if (degree > 0) { neighborIds = malloc((size_t)degree * sizeof(*neighborIds)); if (!neighborIds) exit(EXIT_FAILURE); for (int j = 0; j < degree; j++) neighborIds[j] = cur->neighbors[j]->val; qsort(neighborIds, (size_t)degree, sizeof(*neighborIds), compare_graph_neighbor_ids); } json_int_array(out, neighborIds, degree); free(neighborIds); } fputc(']', out); } +static void json_graph(FILE* out, struct Node* node) { if (!node) { fputs("[]", out); return; } struct Node* nodes[1024]; struct Node* seen[1024] = {0}; int count = 0; nodes[count++] = node; for (int i = 0; i < count && count < 1024; i++) { struct Node* cur = nodes[i]; if (isOriginalGraphNode(cur)) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph must be a deep copy."); return; } if (cur->val <= 0 || cur->val >= 1024) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph node IDs must be between 1 and 1023."); return; } seen[cur->val] = cur; for (int j = 0; cur->neighbors && j < cur->numNeighbors; j++) { struct Node* next = cur->neighbors[j]; if (!next) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph has a NULL neighbor."); return; } if (next->val <= 0 || next->val >= 1024) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph node IDs must be between 1 and 1023."); return; } if (isOriginalGraphNode(next)) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph must be a deep copy."); return; } if (seen[next->val] && seen[next->val] != next) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph must not contain distinct nodes with the same ID."); return; } if (!seen[next->val]) { seen[next->val] = next; nodes[count++] = next; } } } if (node->val != 1) { fputs("null,\\"error\\":", out); json_string(out, "Returned graph must start at node 1."); return; } fputc('[', out); for (int value = 1, printed = 0; value < 1024; value++) { struct Node* cur = NULL; for (int i = 0; i < count; i++) if (nodes[i]->val == value) cur = nodes[i]; if (!cur) continue; if (printed++) fputc(',', out); int degree = cur->neighbors ? cur->numNeighbors : 0; int* neighborIds = NULL; if (degree > 0) { neighborIds = malloc((size_t)degree * sizeof(*neighborIds)); if (!neighborIds) exit(EXIT_FAILURE); for (int j = 0; j < degree; j++) neighborIds[j] = cur->neighbors[j]->val; qsort(neighborIds, (size_t)degree, sizeof(*neighborIds), compare_graph_neighbor_ids); } json_int_array(out, neighborIds, degree); free(neighborIds); } fputc(']', out); } static void json_next_tree(FILE* out, struct Node* root) { if (!root) { fputs("[]", out); return; } int capacity = 64, head = 0, tail = 0, levels = 0; struct Node** queue = malloc(capacity * sizeof(*queue)); int* levelEnd = malloc(capacity * sizeof(*levelEnd)); if (!queue || !levelEnd) { free(queue); free(levelEnd); fputs("null,\\"error\\":", out); json_string(out, "Out of memory while checking next pointers."); return; } queue[tail++] = root; while (head < tail) { int end = tail; for (int i = head; i < end; i++) { if (queue[i]->next != (i + 1 < end ? queue[i + 1] : NULL)) { fputs("null,\\"error\\":", out); json_string(out, "next pointers do not match the tree level order."); free(queue); free(levelEnd); return; } for (int side = 0; side < 2; side++) { struct Node* child = side ? queue[i]->right : queue[i]->left; if (!child) continue; for (int seen = 0; seen < tail; seen++) if (queue[seen] == child) { fputs("null,\\"error\\":", out); json_string(out, "Returned tree must not reach a node twice."); free(queue); free(levelEnd); return; } if (tail == capacity) { struct Node** grownQueue = realloc(queue, 2 * capacity * sizeof(*queue)); if (grownQueue) queue = grownQueue; int* grownEnds = grownQueue ? realloc(levelEnd, 2 * capacity * sizeof(*levelEnd)) : NULL; if (grownEnds) levelEnd = grownEnds; if (!grownQueue || !grownEnds) { free(queue); free(levelEnd); fputs("null,\\"error\\":", out); json_string(out, "Out of memory while checking next pointers."); return; } capacity *= 2; } queue[tail++] = child; } } levelEnd[levels++] = end; head = end; } fputc('[', out); for (int level = 0, start = 0; level < levels; start = levelEnd[level++]) { if (level) fputc(',', out); fputc('[', out); for (int i = start; i < levelEnd[level]; i++) { if (i > start) fputc(',', out); fprintf(out, "%d", queue[i]->val); } fputc(']', out); } fputc(']', out); free(queue); free(levelEnd); } static void json_quad_tree_visit(FILE* out, struct Node* node, int* printed) { if (!node) return; if ((*printed)++) fputc(',', out); fprintf(out, "[%d,%d]", node->isLeaf ? 1 : 0, node->isLeaf ? (node->val ? 1 : 0) : 1); if (!node->isLeaf) { json_quad_tree_visit(out, node->topLeft, printed); json_quad_tree_visit(out, node->topRight, printed); json_quad_tree_visit(out, node->bottomLeft, printed); json_quad_tree_visit(out, node->bottomRight, printed); } } struct QuadTreePath { struct Node* node; const struct QuadTreePath* parent; }; @@ -780,7 +780,8 @@ 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 (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 List neighborsOf(Node node) { return node.neighbors == null ? Collections.emptyList() : node.neighbors; } + 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 : neighborsOf(cur)) { 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 : neighborsOf(cur)) 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 ec9440177..fe902fb52 100644 --- a/web/runners.js +++ b/web/runners.js @@ -1135,6 +1135,9 @@ def _random_list_to_array(node): rows.append([node.val, None if node.random is None else nodes.index(node.random)]) return rows +def _graph_neighbors(node): + return getattr(node, "neighbors", None) or [] + def _graph_to_adjacency(node): if node is None: return [] @@ -1148,13 +1151,13 @@ def _graph_to_adjacency(node): raise TypeError("Returned graph must not contain distinct nodes with the same ID.") continue by_value[current.val] = current - for neighbor in getattr(current, "neighbors", []) or []: + for neighbor in _graph_neighbors(current): 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)] + return [sorted(neighbor.val for neighbor in _graph_neighbors(by_value[value])) for value in sorted(by_value)] # The JavaScript runner turns a non-finite number into null, and so does the # Java harness. Here json.dumps would write a bare Infinity or NaN, which is not