• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

source-academy / py-slang / 24017548227

06 Apr 2026 03:32AM UTC coverage: 66.796% (+1.0%) from 65.827%
24017548227

push

github

web-flow
Python 4 support (#135)

1012 of 1747 branches covered (57.93%)

Branch coverage included in aggregate %.

228 of 310 new or added lines in 3 files covered. (73.55%)

3128 of 4451 relevant lines covered (70.28%)

5187.38 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

54.14
/src/utils/stringify.ts
1
import { StmtNS } from "../ast-types";
7 ✔
2
import { ListValue, Value } from "../cse-machine/stash";
3

4
const MAX_LIST_DISPLAY_LENGTH = 100;
7 ✔
5

6
/**
7
 * Converts a number to a string that mimics Python's float formatting behavior.
8
 */
9
function toPythonFloat(num: number): string {
10
  if (Object.is(num, -0)) {
1 !
NEW
11
    return "-0.0";
×
12
  }
13
  if (num === 0) {
1 !
NEW
14
    return "0.0";
×
15
  }
16

17
  if (num === Infinity) {
1 !
NEW
18
    return "inf";
×
19
  }
20
  if (num === -Infinity) {
1 !
NEW
21
    return "-inf";
×
22
  }
23

24
  if (Number.isNaN(num)) {
1 !
NEW
25
    return "nan";
×
26
  }
27

28
  if (Math.abs(num) >= 1e16 || (num !== 0 && Math.abs(num) < 1e-4)) {
1 !
NEW
29
    return num.toExponential().replace(/e([+-])(\d)$/, "e$10$2");
×
30
  }
31
  if (Number.isInteger(num)) {
1 !
NEW
32
    return num.toFixed(1).toString();
×
33
  }
34
  return num.toString();
1 ✔
35
}
36

37
/**
38
 * Escapes a string for Python's repr representation.
39
 */
40
function escape(str: string): string {
41
  let escaped = JSON.stringify(str);
328 ✔
42
  if (!(str.includes("'") && !str.includes('"'))) {
328 !
43
    escaped = `'${escaped.slice(1, -1).replace(/'/g, "\\'").replace(/\\"/g, '"')}'`;
328 ✔
44
  }
45
  return escaped;
328 ✔
46
}
47

48
/**
49
 * Port of js-slang's stringify for py-slang.
50
 * Provides structured (indented) output for nested lists.
51
 */
52
export const stringify = (
7 ✔
53
  value: Value,
54
  indent: number | string = 2,
75 ✔
55
  splitlineThreshold = 80,
75 ✔
56
): string => {
57
  if (typeof indent === "string") {
75 !
NEW
58
    throw new Error("stringify with arbitrary indent string not supported");
×
59
  }
60
  let indentN: number = indent;
75 ✔
61
  if (indent > 10) {
75 !
NEW
62
    indentN = 10;
×
63
  }
64
  return lineTreeToString(
75 ✔
65
    stringDagToLineTree(valueToStringDag(value), indentN, splitlineThreshold),
66
  );
67
};
68

69
interface TerminalStringDag {
70
  type: "terminal";
71
  str: string;
72
  length: number;
73
}
74

75
interface MultilineStringDag {
76
  type: "multiline";
77
  lines: string[];
78
  length: number;
79
}
80

81
interface PairStringDag {
82
  type: "pair";
83
  head: StringDag;
84
  tail: StringDag;
85
  length: number;
86
}
87

88
interface ArrayLikeStringDag {
89
  type: "arraylike";
90
  prefix: string;
91
  elems: StringDag[];
92
  suffix: string;
93
  length: number;
94
}
95

96
interface KvPairStringDag {
97
  type: "kvpair";
98
  key: string;
99
  value: StringDag;
100
  length: number;
101
}
102

103
type StringDag =
104
  | TerminalStringDag
105
  | MultilineStringDag
106
  | PairStringDag
107
  | ArrayLikeStringDag
108
  | KvPairStringDag;
109

110
export function valueToStringDag(value: Value): StringDag {
7 ✔
111
  const ancestors: Map<Value, number> = new Map();
75 ✔
112
  const memo: Map<Value, StringDag> = new Map();
75 ✔
113

114
  function convertPair(v: Value): [StringDag, boolean] {
115
    const memoResult = memo.get(v);
626 ✔
116
    if (memoResult !== undefined) {
626 !
NEW
117
      return [memoResult, false];
×
118
    }
119
    ancestors.set(v, ancestors.size);
626 ✔
120
    const elems = (v as ListValue).value;
626 ✔
121
    const [headDag, headIsCircular] = convert(elems[0]);
626 ✔
122
    const [tailDag, tailIsCircular] = convert(elems[1]);
626 ✔
123
    const isCircular = headIsCircular || tailIsCircular;
626 ✔
124
    ancestors.delete(v);
626 ✔
125
    const result: StringDag = {
626 ✔
126
      type: "pair",
127
      head: headDag,
128
      tail: tailDag,
129
      length: headDag.length + tailDag.length + 4,
130
    };
131
    if (!isCircular) {
626 ✔
132
      memo.set(v, result);
626 ✔
133
    }
134
    return [result, isCircular];
626 ✔
135
  }
136

137
  function convertArrayLike(
138
    v: Value,
139
    elems: Value[],
140
    prefix: string,
141
    suffix: string,
142
  ): [StringDag, boolean] {
NEW
143
    const memoResult = memo.get(v);
×
NEW
144
    if (memoResult !== undefined) {
×
NEW
145
      return [memoResult, false];
×
146
    }
NEW
147
    ancestors.set(v, ancestors.size);
×
NEW
148
    const converted = elems.map(convert);
×
NEW
149
    let length = prefix.length + suffix.length + Math.max(0, converted.length - 1) * 2;
×
NEW
150
    let isCircular = false;
×
NEW
151
    for (let i = 0; i < converted.length; i++) {
×
NEW
152
      length += converted[i][0].length;
×
NEW
153
      isCircular ||= converted[i][1];
×
154
    }
NEW
155
    ancestors.delete(v);
×
NEW
156
    const result: StringDag = {
×
157
      type: "arraylike",
NEW
158
      elems: converted.map(c => c[0]),
×
159
      prefix,
160
      suffix,
161
      length,
162
    };
NEW
163
    if (!isCircular) {
×
NEW
164
      memo.set(v, result);
×
165
    }
NEW
166
    return [result, isCircular];
×
167
  }
168

169
  function convertRepr(repr: string): [StringDag, boolean] {
NEW
170
    const lines: string[] = repr.split("\n");
×
NEW
171
    return lines.length === 1
×
172
      ? [{ type: "terminal", str: lines[0], length: lines[0].length }, false]
173
      : [{ type: "multiline", lines, length: Infinity }, false];
174
  }
175

176
  function convert(v: Value): [StringDag, boolean] {
177
    if (v.type === "none") {
1,327 ✔
178
      return [{ type: "terminal", str: "None", length: 4 }, false];
284 ✔
179
    } else if (ancestors.has(v)) {
1,043 !
NEW
180
      return [{ type: "terminal", str: "...<circular>", length: 13 }, true];
×
181
    } else if (v.type === "bool") {
1,043 ✔
182
      const s = v.value ? "True" : "False";
15 ✔
183
      return [{ type: "terminal", str: s, length: s.length }, false];
15 ✔
184
    } else if (v.type === "number") {
1,028 ✔
185
      const s = toPythonFloat(v.value);
1 ✔
186
      return [{ type: "terminal", str: s, length: s.length }, false];
1 ✔
187
    } else if (v.type === "bigint" || v.type === "complex") {
1,027 ✔
188
      const s = v.value.toString();
73 ✔
189
      return [{ type: "terminal", str: s, length: s.length }, false];
73 ✔
190
    } else if (v.type === "string") {
954 ✔
191
      const s = escape(v.value);
328 ✔
192
      return [{ type: "terminal", str: s, length: s.length }, false];
328 ✔
193
    } else if (v.type === "list") {
626 !
194
      if (ancestors.size > MAX_LIST_DISPLAY_LENGTH) {
626 !
NEW
195
        return [{ type: "terminal", str: "...<truncated>", length: 14 }, false];
×
196
      }
197
      if (v.value.length === 2) {
626 !
198
        return convertPair(v);
626 ✔
199
      } else {
NEW
200
        return convertArrayLike(v, v.value, "[", "]");
×
201
      }
NEW
202
    } else if (v.type === "closure" || v.type === "function") {
×
NEW
203
      let funcName = "(anonymous)";
×
NEW
204
      if (v.type === "closure") {
×
NEW
205
        const node = v.closure.node;
×
NEW
206
        funcName = node instanceof StmtNS.FunctionDef ? node.name.lexeme : "(anonymous)";
×
207
      } else {
NEW
208
        funcName = v.name || "(anonymous)";
×
209
      }
NEW
210
      const s = `<function ${funcName}>`;
×
NEW
211
      return [{ type: "terminal", str: s, length: s.length }, false];
×
NEW
212
    } else if (v.type === "builtin") {
×
NEW
213
      const s = `<built-in function ${v.name}>`;
×
NEW
214
      return [{ type: "terminal", str: s, length: s.length }, false];
×
215
    } else {
NEW
216
      return convertRepr(`<${v.type} object>`);
×
217
    }
218
  }
219

220
  return convert(value)[0];
75 ✔
221
}
222

223
interface BlockLineTree {
224
  type: "block";
225
  prefixFirst: string;
226
  prefixRest: string;
227
  block: LineTree[];
228
  suffixRest: string;
229
  suffixLast: string;
230
}
231

232
interface LineLineTree {
233
  type: "line";
234
  line: StringDag;
235
}
236

237
type LineTree = BlockLineTree | LineLineTree;
238

239
export function stringDagToLineTree(
7 ✔
240
  dag: StringDag,
241
  indent: number,
242
  splitlineThreshold: number,
243
): LineTree {
244
  const indentSpacesMinusOne = " ".repeat(Math.max(0, indent - 1));
75 ✔
245
  const bracketAndIndentSpacesMinusOne = "[" + indentSpacesMinusOne;
75 ✔
246
  const memo: Map<StringDag, LineTree> = new Map();
75 ✔
247

248
  function format(dag: StringDag): LineTree {
249
    const memoResult = memo.get(dag);
1,327 ✔
250
    if (memoResult !== undefined) {
1,327 !
NEW
251
      return memoResult;
×
252
    }
253
    let result: LineTree;
254
    if (dag.type === "terminal") {
1,327 ✔
255
      result = { type: "line", line: dag };
701 ✔
256
    } else if (dag.type === "multiline") {
626 !
NEW
257
      result = {
×
258
        type: "block",
259
        prefixFirst: "",
260
        prefixRest: "",
NEW
261
        block: dag.lines.map(s => ({
×
262
          type: "line",
263
          line: { type: "terminal", str: s, length: s.length },
264
        })),
265
        suffixRest: "",
266
        suffixLast: "",
267
      };
268
    } else if (dag.type === "pair") {
626 !
269
      const headTree = format(dag.head);
626 ✔
270
      const tailTree = format(dag.tail);
626 ✔
271
      if (
626 ✔
272
        dag.length - 2 > splitlineThreshold ||
1,666 ✔
273
        headTree.type !== "line" ||
274
        tailTree.type !== "line"
275
      ) {
276
        result = {
106 ✔
277
          type: "block",
278
          prefixFirst: bracketAndIndentSpacesMinusOne,
279
          prefixRest: "",
280
          block: [headTree, tailTree],
281
          suffixRest: ",",
282
          suffixLast: "]",
283
        };
284
      } else {
285
        result = {
520 ✔
286
          type: "line",
287
          line: dag,
288
        };
289
      }
NEW
290
    } else if (dag.type === "arraylike") {
×
NEW
291
      const elemTrees = dag.elems.map(format);
×
NEW
292
      if (
×
293
        dag.length - dag.prefix.length - dag.suffix.length > splitlineThreshold ||
×
NEW
294
        elemTrees.some(t => t.type !== "line")
×
295
      ) {
NEW
296
        result = {
×
297
          type: "block",
298
          prefixFirst: dag.prefix + " ".repeat(Math.max(0, indent - dag.prefix.length)),
299
          prefixRest: " ".repeat(Math.max(dag.prefix.length, indent)),
300
          block: elemTrees,
301
          suffixRest: ",",
302
          suffixLast: dag.suffix,
303
        };
304
      } else {
NEW
305
        result = {
×
306
          type: "line",
307
          line: dag,
308
        };
309
      }
NEW
310
    } else if (dag.type === "kvpair") {
×
NEW
311
      const valueTree = format(dag.value);
×
NEW
312
      if (dag.length > splitlineThreshold || valueTree.type !== "line") {
×
NEW
313
        result = {
×
314
          type: "block",
315
          prefixFirst: "",
316
          prefixRest: "",
317
          block: [
318
            { type: "line", line: { type: "terminal", str: JSON.stringify(dag.key), length: 0 } },
319
            valueTree,
320
          ],
321
          suffixRest: ":",
322
          suffixLast: "",
323
        };
324
      } else {
NEW
325
        result = {
×
326
          type: "line",
327
          line: dag,
328
        };
329
      }
330
    } else {
NEW
331
      throw new Error("Unreachable");
×
332
    }
333
    memo.set(dag, result);
1,327 ✔
334
    return result;
1,327 ✔
335
  }
336

337
  return format(dag);
75 ✔
338
}
339

340
export function stringDagToSingleLine(dag: StringDag): string {
7 ✔
341
  function print(dag: StringDag, total: string[]): string[] {
342
    if (dag.type === "multiline") {
1,221 !
NEW
343
      throw new Error("Tried to format multiline string as single line string");
×
344
    } else if (dag.type === "terminal") {
1,221 ✔
345
      total.push(dag.str);
701 ✔
346
    } else if (dag.type === "pair") {
520 !
347
      total.push("[");
520 ✔
348
      print(dag.head, total);
520 ✔
349
      total.push(", ");
520 ✔
350
      print(dag.tail, total);
520 ✔
351
      total.push("]");
520 ✔
NEW
352
    } else if (dag.type === "kvpair") {
×
NEW
353
      total.push(JSON.stringify(dag.key));
×
NEW
354
      total.push(": ");
×
NEW
355
      print(dag.value, total);
×
NEW
356
    } else if (dag.type === "arraylike") {
×
NEW
357
      total.push(dag.prefix);
×
NEW
358
      if (dag.elems.length > 0) {
×
NEW
359
        print(dag.elems[0], total);
×
360
      }
NEW
361
      for (let i = 1; i < dag.elems.length; i++) {
×
NEW
362
        total.push(", ");
×
NEW
363
        print(dag.elems[i], total);
×
364
      }
NEW
365
      total.push(dag.suffix);
×
366
    }
367
    return total;
1,221 ✔
368
  }
369

370
  return print(dag, []).join("");
181 ✔
371
}
372

373
export function lineTreeToString(tree: LineTree): string {
7 ✔
374
  let total = "";
75 ✔
375
  const stringDagToLineMemo: Map<StringDag, string> = new Map();
75 ✔
376
  const stringDagToMultilineMemo: Map<LineTree, Map<number, [number, number]>> = new Map();
75 ✔
377

378
  function print(tree: LineTree, lineSep: string) {
379
    const multilineMemoResult = stringDagToMultilineMemo.get(tree);
287 ✔
380
    if (multilineMemoResult !== undefined) {
287 !
NEW
381
      const startEnd = multilineMemoResult.get(lineSep.length);
×
NEW
382
      if (startEnd !== undefined) {
×
NEW
383
        total += total.substring(startEnd[0], startEnd[1]);
×
NEW
384
        return;
×
385
      }
386
    }
387
    const start = total.length;
287 ✔
388
    if (tree.type === "line") {
287 ✔
389
      if (!stringDagToLineMemo.has(tree.line)) {
181 ✔
390
        stringDagToLineMemo.set(tree.line, stringDagToSingleLine(tree.line));
181 ✔
391
      }
392
      total += stringDagToLineMemo.get(tree.line)!;
181 ✔
393
    } else if (tree.type === "block") {
106 ✔
394
      total += tree.prefixFirst;
106 ✔
395
      const indentedLineSepFirst = lineSep + " ".repeat(tree.prefixFirst.length);
106 ✔
396
      const indentedLineSepRest = lineSep + tree.prefixRest;
106 ✔
397
      print(tree.block[0], indentedLineSepFirst);
106 ✔
398
      for (let i = 1; i < tree.block.length; i++) {
106 ✔
399
        total += tree.suffixRest;
106 ✔
400
        total += indentedLineSepRest;
106 ✔
401
        print(tree.block[i], indentedLineSepRest);
106 ✔
402
      }
403
      total += tree.suffixLast;
106 ✔
404
    }
405
    const end = total.length;
287 ✔
406
    if (multilineMemoResult === undefined) {
287 !
407
      const newmap = new Map<number, [number, number]>();
287 ✔
408
      newmap.set(lineSep.length, [start, end]);
287 ✔
409
      stringDagToMultilineMemo.set(tree, newmap);
287 ✔
410
    } else {
NEW
411
      multilineMemoResult.set(lineSep.length, [start, end]);
×
412
    }
413
  }
414

415
  print(tree, "\n");
75 ✔
416
  return total;
75 ✔
417
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc