runreel 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- runreel/__init__.py +8 -0
- runreel/__main__.py +3 -0
- runreel/_player/player.js +113 -0
- runreel/cli.py +307 -0
- runreel/py.typed +0 -0
- runreel/reel.py +56 -0
- runreel/trace/__init__.py +40 -0
- runreel/trace/codec.py +355 -0
- runreel/trace/deadline.py +151 -0
- runreel/trace/events.py +260 -0
- runreel/trace/model.py +114 -0
- runreel/trace/serialize.py +371 -0
- runreel/trace/tracer.py +435 -0
- runreel-0.1.0.dist-info/METADATA +111 -0
- runreel-0.1.0.dist-info/RECORD +18 -0
- runreel-0.1.0.dist-info/WHEEL +4 -0
- runreel-0.1.0.dist-info/entry_points.txt +3 -0
- runreel-0.1.0.dist-info/licenses/LICENSE +21 -0
runreel/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""RunReel: turn any algorithm into an interactive step-through reel."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("runreel")
|
|
7
|
+
except PackageNotFoundError: # running from a source tree that isn't installed, e.g. in Pyodide
|
|
8
|
+
__version__ = "0.0.0+unknown"
|
runreel/__main__.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"use strict";var RunReelPlayer=(()=>{var Q=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ke=Object.prototype.hasOwnProperty;var Ye=(e,t)=>{for(var n in t)Q(e,n,{get:t[n],enumerable:!0})},Ze=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Xe(t))!Ke.call(e,s)&&s!==n&&Q(e,s,{get:()=>t[s],enumerable:!(r=We(t,s))||r.enumerable});return e};var Ue=e=>Ze(Q({},"__esModule",{value:!0}),e);var Pt={};Ye(Pt,{PLAYER_VERSION:()=>Gt,applyStep:()=>de,emptyState:()=>ce,mount:()=>Be,stateAt:()=>W});function ce(){return{ev:"line",line:0,stack:[],heap:{}}}function W(e,t){if(!Number.isInteger(t)||t<0||t>=e.length)throw new RangeError(`step ${t} is out of range for ${e.length} steps`);let n=t;for(;!e[n]?.key;){if(n===0)throw new Error("the first step must be a keyframe");n-=1}let r=ce();for(let s of e.slice(n,t+1))de(r,s);return r}function de(e,t){if(t.key&&(e.stack=[],e.heap={}),e.ev=t.ev,e.line=t.line,delete e.ret,delete e.exc,t.stack){let s=new Map(e.stack.map(o=>[o.fid,o]));e.stack=t.stack.map(o=>s.get(o)??{fid:o,fn:"",line:0,locals:{}})}let n=e.stack[e.stack.length-1];n&&(n.line=t.line);let r=new Map(e.stack.map(s=>[s.fid,s]));for(let[s,o]of Object.entries(t.frames??{})){let i=r.get(Number(s));if(!i)throw new Error(`frame ${s} is not on the stack`);o.fn!==void 0&&(i.fn=o.fn),o.line!==void 0&&(i.line=o.line),o.set&&(i.locals={...i.locals,...o.set});for(let a of o.del??[])delete i.locals[a]}for(let[s,o]of Object.entries(t.heap??{}))"t"in o?e.heap[s]=Qe(o):Je(e.heap[s],o);for(let s of t.gc??[])delete e.heap[String(s)];t.ret!==void 0&&(e.ret=t.ret),t.exc!==void 0&&(e.exc=t.exc)}function Je(e,t){if(!e)throw new Error("a patch needs an existing object");if(t.ops){let n=e.items;if(!n)throw new Error("ops need a seq or map");for(let r of t.ops.slice().reverse())r.length===2?n[r[0]]=r[1]:n.splice(r[0],r[1],...r[2])}if(t.set||t.del){if(!e.fields)throw new Error("set and del need an obj");let n={...e.fields,...t.set};for(let r of t.del??[])delete n[r];e.fields=n}t.more!==void 0&&(t.more>0?e.more=t.more:delete e.more)}function Qe(e){let t={...e};return e.items&&(t.items=e.items.slice()),e.fields&&(t.fields={...e.fields}),t}var le=e=>Math.max(44,Math.ceil(e.length*8.6+16));function ue(e,t,n){let r=[],s=[],o=t;e.cells.forEach((u,g)=>{let h=le(u.text);s.push(o),r.push({key:u.key,type:"box",x:o,y:n,w:h,h:36,text:u.text,cls:u.changed?"rr-changed":""}),r.push({key:`${u.key}:index`,type:"label",x:o+h/2,y:n-6,text:String(g),cls:"rr-index",anchor:"middle"}),o+=h+4}),s.push(o),e.more&&r.push({key:`${e.key}:more`,type:"label",x:o,y:n+36/2+4,text:`+${e.more} more`,cls:"rr-more"});let i=new Map;for(let u of e.pointers){let g=i.get(u.index)??0;i.set(u.index,g+1);let h=s[u.index]+(u.index<e.cells.length?le(e.cells[u.index].text):44)/2;r.push({key:`${e.key}:ptr:${u.name}`,type:"label",x:h,y:n+36+18+g*16,text:`\u2191 ${u.name}`,cls:"rr-pointer",anchor:"middle"})}let a=Math.max(0,...i.values()),c=Math.max(o-t,44)+(e.more?80:0);return{items:r,width:c,height:46+a*16}}function fe(e,t,n){let r=e.nodes.length,s=new Map;for(let l of e.edges){if(l.from===l.to)continue;let f=[l.from,l.to].sort().join("|");s.set(f,[...s.get(f)??[],l])}for(let[l,f]of s){let m=l.split("|")[0];f.sort((k,x)=>+(k.from!==m)-+(x.from!==m))}let o=Math.min(4,Math.max(0,Math.floor(2*e.edges.length/Math.max(r,1))-2)),i=Math.max(1,...[...s.values()].map(l=>l.length)),a=66+o*12+(i-1)*10,c=Math.max(80+o*15,r*a/(2*Math.PI)),u=(i-1)*26/2,g=t+c+18+20+u,h=n+c+18+u,d=new Map;e.nodes.forEach((l,f)=>{let m=-Math.PI/2+2*Math.PI*f/Math.max(r,1);d.set(l.key,{x:g+c*Math.cos(m),y:h+c*Math.sin(m)})});let p=[];for(let l of e.edges){let f=d.get(l.from),m=d.get(l.to),k=l.active?"rr-edge rr-active":"rr-edge",x={arrow:e.directed,...l.weight!==void 0?{text:l.weight}:{}};if(l.from===l.to){p.push(...et(l.key,f,{x:g,y:h},l.nth,k,x));continue}let S=[l.from,l.to].sort(),w=s.get(S.join("|")),$=d.get(S[0]),H=d.get(S[1]),y=Math.hypot(H.x-$.x,H.y-$.y),v=Math.min(26,.3*y/Math.max((w.length-1)/2,1)),E=(w.indexOf(l)-(w.length-1)/2)*v;if(E===0){let A=(m.x-f.x)/y,G=(m.y-f.y)/y;p.push({key:`edge:${l.key}`,type:"line",x1:f.x+A*18,y1:f.y+G*18,x2:m.x-A*20,y2:m.y-G*20,cls:k,...x});continue}let O={x:($.x+H.x)/2-(H.y-$.y)/y*2*E,y:($.y+H.y)/2+(H.x-$.x)/y*2*E},b=(A,G)=>{let C=Math.hypot(O.x-A.x,O.y-A.y);return{x:A.x+(O.x-A.x)/C*G,y:A.y+(O.y-A.y)/C*G}},M=b(f,18),I=b(m,e.directed?20:18);p.push({key:`edge:${l.key}`,type:"line",x1:M.x,y1:M.y,x2:I.x,y2:I.y,via:O,cls:k,...x})}for(let l of e.nodes){let f=d.get(l.key);p.push({key:`node:${l.key}`,type:"circle",x:f.x,y:f.y,r:18,text:l.text,cls:l.state==="none"?"":`rr-${l.state}`,...l.sub!==void 0?{sub:l.sub}:{}})}return{items:p,width:2*(c+18+20+u),height:2*(c+18+u)+20}}function et(e,t,n,r,s,o){let i=Math.hypot(t.x-n.x,t.y-n.y)||1,a=(t.x-n.x)/i||0,c=i===1?-1:(t.y-n.y)/i,u=38+r*10,g=8+r*3,h=(m,k)=>({x:t.x+a*m-c*k,y:t.y+c*m+a*k}),[d,p,l,f]=[h(18,-g),h(u,-g),h(u,g),h(20,g)];return[{key:`edge:${e}:out`,type:"line",x1:d.x,y1:d.y,x2:p.x,y2:p.y,cls:s},{key:`edge:${e}:across`,type:"line",x1:p.x,y1:p.y,x2:l.x,y2:l.y,cls:s,...o.text!==void 0?{text:o.text}:{}},{key:`edge:${e}`,type:"line",x1:l.x,y1:l.y,x2:f.x,y2:f.y,cls:s,arrow:o.arrow}]}function pe(e,t,n){let r=e.rows.length,s=e.rows[0]?.length??0,o=Math.max(1,...e.rows.flat().map(m=>m.text.length)),i=Math.max(30,Math.ceil(o*8.6+10)),a=30,c=Math.ceil(String(e.top+r-1).length*7+10),u=t+c,g=n+16,h=(m,k)=>({x:u+(k-e.left)*(i+2),y:g+(m-e.top)*(a+2)}),d=[],p=new Set(e.focus?e.deps.map(m=>`${m.row}:${m.col}`):[]);for(let m=0;m<s;m++){let k=e.left+m;d.push({key:`${e.key}:col:${k}`,type:"label",x:h(e.top,k).x+i/2,y:g-5,text:String(k),cls:"rr-index",anchor:"middle"})}e.rows.forEach((m,k)=>{let x=e.top+k;d.push({key:`${e.key}:row:${x}`,type:"label",x:u-6,y:h(x,e.left).y+a/2+4,text:String(x),cls:"rr-index",anchor:"end"}),m.forEach((S,w)=>{let $=h(x,e.left+w),H=S.changed?"rr-changed":p.has(`${x}:${e.left+w}`)?"rr-read":"";d.push({key:S.key,type:"box",x:$.x,y:$.y,w:i,h:a,text:S.text,cls:H})})});let l=m=>m.row>=e.top&&m.row<e.top+r&&m.col>=e.left&&m.col<e.left+s;if(e.focus&&l(e.focus)){let m=h(e.focus.row,e.focus.col),k=m.x+i/2,x=m.y+a/2,S=w=>Math.max(Math.abs(w.row-e.focus.row),Math.abs(w.col-e.focus.col))>1;e.deps.filter(w=>l(w)&&S(w)).forEach((w,$)=>{let H=h(w.row,w.col),y=H.x+i/2,v=H.y+a/2,E=Math.hypot(k-y,x-v)||1,O=(k-y)/E,b=(x-v)/E,M=Math.min(i,a)/2+2;d.push({key:`${e.key}:dep:${$}`,type:"line",x1:y+O*M,y1:v+b*M,x2:k-O*M,y2:x-b*M,cls:"rr-dep",arrow:!0})}),d.push({key:`${e.key}:focus`,type:"box",x:m.x-2,y:m.y-2,w:i+4,h:a+4,text:"",cls:"rr-focus"})}let f=e.top>0||e.left>0||e.top+r<e.height||e.left+s<e.width;if(f){let m=`rows ${e.top}\u2013${e.top+r-1} of ${e.height} \xB7 columns ${e.left}\u2013${e.left+s-1} of ${e.width}`;d.push({key:`${e.key}:window`,type:"label",x:u,y:g+r*(a+2)+14,text:m,cls:"rr-more"})}return{items:d,width:c+s*(i+2),height:16+r*(a+2)+(f?20:0)}}var tt=e=>Math.max(44,Math.ceil(e.length*8.6+16)),ge=e=>Math.ceil(e.length*7.3);function be(e,t,n){let r=[],s=new Map,i=Object.values(e.nodes).some(f=>f.prev)?36/3:36/2,a=72/3,c=new Map;for(let f of e.pointers)c.set(f.node,(c.get(f.node)??0)+1);let u=new Map;e.rows.forEach((f,m)=>f.nodes.forEach(k=>u.set(k,m)));let g=(f,m,k)=>!!m&&m!==k&&u.get(m)===u.get(f),h=[],d=n,p=0;e.rows.forEach((f,m)=>{let k=f.end.kind==="node"&&u.get(f.end.to)===m,x=f.nodes.some((y,v)=>g(y,e.nodes[y].prev?.to,f.nodes[v-1])),S=d+12*(x?2:k?1:0);h.push(S);let w=t+(f.skipped?ge(he(f.skipped))+30:0);for(let y of f.nodes){let v=tt(e.nodes[y].text);s.set(y,{x:w,y:S,w:v}),w+=v+30}let $=me(f.end);p=Math.max(p,($?w+ge($):w-30)-t);let H=Math.max(0,...f.nodes.map(y=>c.get(y)??0));d=S+36+(H?10+H*16:0)+16}),e.rows.forEach((f,m)=>{let k=h[m];if(f.skipped){let x=s.get(f.nodes[0]);r.push({key:`list:skipped:${m}`,type:"label",x:t,y:k+i+4,text:he(f.skipped),cls:"rr-null"}),r.push(N(`list:skipped:${m}:next`,{x:x.x-30+6,y:k+i},{x:x.x-2,y:k+i},"rr-edge"))}f.nodes.forEach((x,S)=>{let w=e.nodes[x],$=s.get(x);r.push({key:`list:${x}`,type:"box",x:$.x,y:$.y,w:$.w,h:36,text:w.text,cls:w.changed?"rr-changed":""});let H=w.relinked?"rr-edge rr-active":"rr-edge",y={x:$.x+$.w,y:$.y+i},v=f.nodes[S+1]??(f.end.kind==="node"?f.end.to:void 0),E=v!==void 0?s.get(v):void 0;E&&v===f.nodes[S+1]?r.push(N(`list:next:${x}`,y,{x:E.x-2,y:E.y+i},H)):E&&u.get(v)===m?r.push(...xe(`list:next:${x}`,$,E,k-12+2,H,x===v)):E?r.push(N(`list:next:${x}`,y,ye(y,E),H)):(r.push(N(`list:next:${x}`,y,{x:y.x+30-6,y:y.y},H)),r.push({key:`list:end:${x}`,type:"label",x:y.x+30-2,y:y.y+4,text:me(f.end)||"\u2026",cls:"rr-null"}));let O=w.prev?.to,b=O?s.get(O):void 0;if(!b)return;let M=w.prev.relinked?"rr-edge rr-active":"rr-edge",I={x:$.x,y:$.y+a};f.nodes[S-1]===O?r.push(N(`list:prev:${x}`,I,{x:b.x+b.w+2,y:b.y+a},M)):u.get(O)===m?r.push(...xe(`list:prev:${x}`,$,b,k-24+2,M,x===O)):r.push(N(`list:prev:${x}`,I,ye(I,b),M))})});let l=new Map;for(let f of e.pointers){let m=s.get(f.node);if(!m)continue;let k=l.get(f.node)??0;l.set(f.node,k+1),r.push({key:`list:ptr:${f.name}`,type:"label",x:m.x+m.w/2,y:m.y+36+18+k*16,text:`\u2191 ${f.name}`,cls:"rr-pointer",anchor:"middle"})}return e.more&&(r.push({key:"list:more",type:"label",x:t,y:d+2,text:`${e.more} more ${e.more===1?"list":"lists"} not shown`,cls:"rr-more"}),d+=22),{items:r,width:Math.max(p,44),height:d-n-16}}function me(e){return e.kind==="none"?"None":e.kind==="more"?e.count?`${e.count} more`:"\u2026":""}var he=e=>`${e} more`;function N(e,t,n,r){return{key:e,type:"line",x1:t.x,y1:t.y,x2:n.x,y2:n.y,cls:r,arrow:!0}}function xe(e,t,n,r,s,o){let i=t.x+t.w*(o?.7:.5),a=n.x+n.w*(o?.3:.5);return[{key:`${e}:up`,type:"line",x1:i,y1:t.y,x2:i,y2:r,cls:s},{key:`${e}:over`,type:"line",x1:i,y1:r,x2:a,y2:r,cls:s},N(e,{x:a,y:r},{x:a,y:n.y-2},s)]}function ye(e,t){let n=t.x+t.w/2,r=t.y+36/2,s=e.x-n,o=e.y-r,i=Math.min(1,1/Math.max(Math.abs(s)/(t.w/2+2),Math.abs(o)/(36/2+2),1e-9));return{x:n+s*i,y:r+o*i}}function ke(e,t,n){let r=new Map,s=0,o=0,i=(c,u,g)=>{if(!c||g.has(c)||!e.nodes[c])return;g.add(c);let h=e.nodes[c];i(h.left,u+1,g),r.set(c,{x:t+17+s*44,y:n+17+u*60}),s+=1,o=Math.max(o,u),i(h.right,u+1,g)};i(e.root,0,new Set);let a=[];for(let[c,u]of r){let g=e.nodes[c];for(let h of[g.left,g.right]){let d=h?r.get(h):void 0;if(!d)continue;let p=Math.hypot(d.x-u.x,d.y-u.y),l=(d.x-u.x)/p,f=(d.y-u.y)/p;a.push({key:`edge:${c}->${h}`,type:"line",x1:u.x+l*17,y1:u.y+f*17,x2:d.x-l*17,y2:d.y-f*17,cls:"rr-edge"})}}for(let[c,u]of r){let g=e.nodes[c],h=g.marks.length>0;a.push({key:`node:${c}`,type:"circle",x:u.x,y:u.y,r:17,text:g.text,cls:h?"rr-current":"",...h?{sub:g.marks.join(", ")}:{}})}return{items:a,width:Math.max(s,1)*44,height:(o+1)*60}}var D=16,rt=22;function we(e){let t=[],n=D,r=0;for(let s of e){t.push({key:`title:${s.key}`,type:"label",x:D,y:n+12,text:s.label,cls:"rr-title"}),n+=rt+(s.kind==="array"?14:4);let o=nt(s,D,n);t.push(...o.items),r=Math.max(r,o.width+2*D),n+=o.height+D}return{width:Math.max(r,200),height:Math.max(n,60),items:t}}function nt(e,t,n){switch(e.kind){case"array":return ue(e,t,n);case"grid":return pe(e,t,n);case"tree":return ke(e,t,n);case"list":return be(e,t,n);case"graph":return fe(e,t,n)}}var $e='<defs><marker id="rr-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="9" markerHeight="9" markerUnits="userSpaceOnUse" orient="auto-start-reverse"><path d="M0,0L10,5L0,10z" class="rr-arrowhead"/></marker></defs>';function ve(e){switch(e.type){case"box":return`<rect width="${e.w}" height="${e.h}" rx="4"/><text x="${e.w/2}" y="${e.h/2}" dy="0.35em" text-anchor="middle">${L(e.text)}</text>`;case"circle":return`<circle r="${e.r}"/><text dy="0.35em" text-anchor="middle">${L(e.text)}</text>`+(e.sub!==void 0?`<text class="rr-sub" y="${e.r+14}" text-anchor="middle">${L(e.sub)}</text>`:"");case"label":return`<text text-anchor="${e.anchor??"start"}">${L(e.text)}</text>`;case"line":{if(e.via)return st(e,e.via);let t=Math.hypot(e.x2-e.x1,e.y2-e.y1)||1,n=e.x1+(e.x2-e.x1)*.4+(e.y2-e.y1)/t*9,r=e.y1+(e.y2-e.y1)*.4-(e.x2-e.x1)/t*9,s=e.text!==void 0?`<text class="rr-weight" x="${T(n)}" y="${T(r)}" dy="0.35em" text-anchor="middle">${L(e.text)}</text>`:"",o=e.arrow?' marker-end="url(#rr-arrow)"':"";return`<line x1="${T(e.x1)}" y1="${T(e.y1)}" x2="${T(e.x2)}" y2="${T(e.y2)}"${o}/>${s}`}}}function st(e,t){let n=e.arrow?' marker-end="url(#rr-arrow)"':"",r=`<path d="M${T(e.x1)} ${T(e.y1)}Q${T(t.x)} ${T(t.y)} ${T(e.x2)} ${T(e.y2)}"${n}/>`;if(e.text===void 0)return r;let s={x:(e.x1+e.x2)/4+t.x/2,y:(e.y1+e.y2)/4+t.y/2},o={x:(e.x1+e.x2)/2,y:(e.y1+e.y2)/2},i=Math.hypot(s.x-o.x,s.y-o.y)||1,a=s.x+(s.x-o.x)/i*9,c=s.y+(s.y-o.y)/i*9;return`${r}<text class="rr-weight" x="${T(a)}" y="${T(c)}" dy="0.35em" text-anchor="middle">${L(e.text)}</text>`}function L(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function T(e){return Math.round(e*10)/10}function V(e,t,n=0){let r=X(e,t,n);return r.length<=40?r:`${r.slice(0,39)}\u2026`}function X(e,t,n){if(e===null)return"None";if(typeof e=="boolean")return e?"True":"False";if(typeof e=="number")return String(e);if(typeof e=="string")return n===0?e:JSON.stringify(e);if(Array.isArray(e))return e.map(s=>X(s,t,n+1)).join(": ");if(typeof e!="object")return String(e);let r=e;return"inf"in r?r.inf===1?"\u221E":"-\u221E":"nan"in r?"nan":"bigint"in r?String(r.bigint):"float"in r?String(r.float):"ref"in r?ot(t[String(r.ref)],t,n):"?"}function ot(e,t,n){if(!e)return"\u2026";if(n>1)return e.t==="repr"?e.cls:`${e.cls}(\u2026)`;let r=e.more?", \u2026":"",s=(e.items??[]).map(o=>X(o,t,n+1)).join(", ");switch(e.t){case"seq":return e.cls==="tuple"?`(${s}${e.items?.length===1?",":""}${r})`:e.cls==="set"||e.cls==="frozenset"?`{${s}${r}}`:`[${s}${r}]`;case"map":return`{${s}${r}}`;case"obj":{let o=Object.entries(e.fields??{}).map(([i,a])=>`${i}=${X(a,t,n+1)}`);return`${e.cls}(${o.join(", ")})`}default:return e.v??e.cls}}function R(e,t){if(e===null||typeof e!="object"||Array.isArray(e)||!("ref"in e))return;let n=String(e.ref),r=t[n];return r?[n,r]:void 0}function j(e,t){return e===null||typeof e!="object"?!0:!Array.isArray(e)&&!R(e,t)}var Se=new Set(["i","j","k","l","r","lo","hi","mid","left","right","low","high","start","end"]),it=new Set(["node","u","cur","current","v","x"]),at=new Set(["neighbour","neighbor","nbr","w","nxt","next_node"]),Ae=["next","_next"],Ie=["prev","_prev"],Me=/^_*(prev|prv|previous|pred|predecessor|back|backward|bwd|before)($|[_\dA-Z])/,ee=/^_*(parent|par|up)($|[_\dA-Z])/,ct=2500,Ee={rows:40,cols:60},Y=30,dt=5,lt=10;function Ve(e,t,n=[]){let r=e.heap,s=ft(e),o=[],i=new Set;for(let{name:c,value:u}of s){let g=R(u,r);if(!g)continue;let[h,d]=g;if(B(d,r)){let p=je(h,r);if(i.has(`tree:${p}`))continue;i.add(`tree:${p}`),o.push($t(p,c,s,r))}else if(P(d,r)||oe(d,r)){if(i.has("list"))continue;i.add("list"),o.push(vt(e,t))}else{if(i.has(h))continue;Ot(d,r)?(i.add(h),o.push(Tt(h,c,d,s,r,n,e.line))):te(d,r,c,n)?(i.add(h),o.push(xt(h,c,d,e,t,n,s))):pt(d,r)&&(i.add(h),o.push(mt(h,c,d,e,t,n)))}}let a=new Map;for(let c of e.stack)for(let u of Object.values(c.locals)){let g=ut(u,r);g!==void 0&&!a.has(g)&&a.set(g,a.size)}return o.sort((c,u)=>(a.get(c.key)??0)-(a.get(u.key)??0))}function ut(e,t){let n=R(e,t);if(n)return B(n[1],t)?`tree:${je(n[0],t)}`:P(n[1],t)||oe(n[1],t)?"list":n[0]}function ft(e){let t=[];for(let n of[...e.stack].reverse())for(let[r,s]of Object.entries(n.locals))t.push({name:r,value:s});return t}function pt(e,t){return e.t!=="seq"||e.cls==="set"||e.cls==="frozenset"?!1:(e.items??[]).every(n=>j(n,t)||gt(n,t))}function gt(e,t){let n=R(e,t);return!!n&&n[1].t==="seq"&&n[1].cls==="tuple"&&(n[1].items??[]).every(r=>j(r,t))}function mt(e,t,n,r,s,o){let i=n.items??[],a=s?.heap[e],c=i.map((h,d)=>{let p=V(h,r.heap,1),l=a?.items?.[d],f=!!a&&(d>=(a.items?.length??0)||V(l,s.heap,1)!==p);return{key:`${e}:${d}`,text:p,changed:f}}),u=[],g=r.stack[r.stack.length-1];for(let[h,d]of Object.entries(g?.locals??{}))typeof d=="number"&&Number.isInteger(d)&&d>=0&&d<=i.length&&ht(h,t,o)&&u.push({name:h,index:d});return{kind:"array",key:e,label:t,cells:c,pointers:u,more:n.more??0}}function ht(e,t,n){if(!n.length)return Se.has(e);let r=Z(n),s=r.names.get(t);return!!s&&(s.has(e)||Se.has(e)&&!r.all.has(e))}var He=new WeakMap;function Z(e){let t=He.get(e);if(t)return t;let n=new Map,r=new Set;for(let o of e)for(let i of o.matchAll(/(?<![\w.])([A-Za-z_]\w*)\s*\[/g)){let a="",c=0;for(let g of o.slice(i.index+i[0].length)){if(g==="]"&&c===0)break;g==="["&&c++,g==="]"&&c--,a+=c===0&&g!=="]"?g:" "}let u=n.get(i[1])??new Set;for(let g of a.matchAll(/(?<![\w.])([A-Za-z_]\w*)\b(?!\s*\()/g))u.add(g[1]),r.add(g[1]);n.set(i[1],u)}let s={names:n,all:r};return He.set(e,s),s}function te(e,t,n,r){if(e.t!=="seq"||e.cls==="set"||e.cls==="frozenset"||!e.items?.length)return;let s=e.items.every(a=>typeof a=="string");if(s&&(e.items.length<2||!r.some(a=>se(n,a).length)))return;let o=[],i=-1;for(let a of e.items){let c,u;if(s)c=[...a],u=c.length;else{let g=R(a,t)?.[1];if(!g||g.t!=="seq"||g.cls!=="list")return;let h=g.items??[];if(!h.every(d=>j(d,t)))return;c=h.map(d=>V(d,t)),u=h.length+(g.more??0)}if(u===0||i!==-1&&u!==i)return;i=u,o.push(c)}return{cells:o,height:e.items.length+(e.more??0),width:i}}function se(e,t){let n=String.raw`\[\s*([A-Za-z_]\w*)\s*(?:([+-])\s*(\d+)\s*)?\]`,r=[];for(let s of t.matchAll(new RegExp(String.raw`(?<![\w.])${e}\s*${n}\s*${n}`,"g"))){let o=(i,a)=>(i==="-"?-1:1)*Number(a??0);r.push({row:s[1],rowShift:o(s[2],s[3]),col:s[4],colShift:o(s[5],s[6])})}return r}function xt(e,t,n,r,s,o,i){let{cells:a,height:c,width:u}=te(n,r.heap,t,o),g=s?.heap[e]?te(s.heap[e],s.heap,t,o)?.cells:void 0,{focus:h,deps:d}=yt(t,r,o,i,a.length,a[0].length),p=0,l=0,f=a.length,m=a[0].length;if(f*m>ct){f=Math.min(f,Ee.rows),m=Math.min(m,Ee.cols);let x=(S,w,$)=>Math.min(Math.max((S??0)-Math.floor(w/2),0),$-w);p=x(h?.row,f,a.length),l=x(h?.col,m,a[0].length)}let k=a.slice(p,p+f).map((x,S)=>x.slice(l,l+m).map((w,$)=>{let H=g?.[p+S]?.[l+$];return{key:`${e}:${p+S}:${l+$}`,text:w,changed:g!==void 0&&H!==w}}));return{kind:"grid",key:e,label:t,rows:k,top:p,left:l,height:c,width:u,...h?{focus:h}:{},deps:d}}function yt(e,t,n,r,s,o){let i=d=>{let p=r.find(l=>l.name===d)?.value;return typeof p=="number"&&Number.isInteger(p)?p:void 0},a=d=>{let p=i(d.row),l=i(d.col);if(p===void 0||l===void 0)return;let f={row:p+d.rowShift,col:l+d.colShift};return f.row>=0&&f.row<s&&f.col>=0&&f.col<o?f:void 0},c=se(e,n[t.line-1]??""),u=c.find(d=>!d.rowShift&&!d.colShift),g=(u&&a(u))??c.map(a).find(d=>d!==void 0)??bt(e,n,a);if(!g)return{deps:[]};let h=[];for(let d of c.map(a))d&&(d.row!==g.row||d.col!==g.col)&&!h.some(p=>p.row===d.row&&p.col===d.col)&&h.push(d);return{focus:g,deps:h}}function bt(e,t,n){let r=new Map;for(let o of t)for(let i of se(e,o)){if(i.rowShift||i.colShift)continue;let a=`${i.row},${i.col}`;r.set(a,[(r.get(a)?.[0]??0)+1,i])}let s=[...r.values()].sort((o,i)=>i[0]-o[0])[0];return s?n(s[1]):void 0}function F(e,t){if(e.t!=="obj")return;let n=e.fields??{};if("left"in n||"right"in n)return{kind:"tree",left:"left",right:"right"};let r=Re(e,Ae);if(r!==void 0){let s=Re(e,Ie);return{kind:"list",next:r,...s!==void 0?{prev:s}:{}}}return kt(t).get(e.cls)}var Oe=new WeakMap;function kt(e){let t=Oe.get(e);if(t)return t;t=new Map;let n=new Map;for(let[r,s]of Object.entries(e)){if(s.t!=="obj")continue;let o=n.get(s.cls);o?o.push([r,s]):n.set(s.cls,[[r,s]])}for(let[r,s]of n){let o=wt(r,s,e);o&&t.set(r,o)}return Oe.set(e,t),t}function wt(e,t,n){let r=[...new Set(t.flatMap(([,d])=>Object.keys(d.fields??{})))],s=(d,p)=>R(d.fields?.[p],n),o=r.filter(d=>{let p=!1;for(let[,l]of t){let f=l.fields?.[d];if(f==null)continue;let m=s(l,d);if(!m||m[1].cls!==e)return!1;m[1].t==="obj"&&(p=!0)}return p}),i=(d,p)=>t.some(([l,f])=>{let m=s(f,d);return!!m&&m[0]!==l&&R(m[1].fields?.[p],n)?.[0]===l});if(o.length===3){let d=o.find(l=>o.every(f=>f===l||i(l,f)||i(f,l))),p=o.filter(l=>l!==d);if(!d||i(p[0],p[1])||i(p[1],p[0]))return;o=p}if(o.length===1)return ee.test(o[0])?void 0:{kind:"list",next:o[0]};if(o.length!==2)return;let[a,c]=o,u=d=>/^_*r/i.test(d);if(i(a,c)||i(c,a)){let d=ee.test(c)?a:ee.test(a)?c:void 0;if(d!==void 0)return u(d)?{kind:"tree",right:d}:{kind:"tree",left:d};let[p,l]=Me.test(a)&&!Me.test(c)?[c,a]:[a,c];return{kind:"list",next:p,prev:l}}let[g,h]=u(a)&&/^_*l/i.test(c)?[c,a]:[a,c];return{kind:"tree",left:g,right:h}}function B(e,t){return F(e,t)?.kind==="tree"}function re(e,t,n){let r=e&&F(e,n),s=r?.kind==="tree"?r[t]:void 0;if(s===void 0)return;let o=R(e.fields?.[s],n);return o&&B(o[1],n)?o[0]:void 0}function je(e,t){let n=new Map;for(let[o,i]of Object.entries(t))if(B(i,t))for(let a of["left","right"]){let c=re(i,a,t);c&&n.set(c,o)}let r=e,s=new Set([r]);for(let o=n.get(r);o&&!s.has(o);o=n.get(r))r=o,s.add(o);return r}function $t(e,t,n,r){let s={},o=new Map;for(let{name:a,value:c}of n){let u=R(c,r);u&&B(u[1],r)&&o.set(u[0],[...o.get(u[0])??[],a])}let i=[e];for(;i.length;){let a=i.pop();if(s[a])continue;let c=r[a],u=re(c,"left",r),g=re(c,"right",r);s[a]={key:a,text:ne(c,r),marks:[...new Set(o.get(a)??[])],...u?{left:u}:{},...g?{right:g}:{}},u&&i.push(u),g&&i.push(g)}return{kind:"tree",key:`tree:${e}`,label:t,root:e,nodes:s}}function ne(e,t){let n=e.fields??{};for(let a of["key","val","value","data","item"])if(a in n)return V(n[a],t,1);let r=F(e,t),s=r?.kind==="tree"?[r.left,r.right]:r?[r.next,r.prev]:[],o=["left","right",...Ae,...Ie,...s],i=Object.entries(n).find(([a,c])=>!o.includes(a)&&j(c,t));return i?V(i[1],t,1):e.cls}function P(e,t){return F(e,t)?.kind==="list"}function Re(e,t){let n=e.fields??{};return t.find(r=>{let s=n[r];return s===null||typeof s=="object"&&"ref"in s})}function z(e,t,n){let r=F(e,n),s=r?.kind==="list"?r[t]:void 0,o=s===void 0?void 0:e.fields?.[s];if(o===void 0)return;if(o===null)return null;let i=R(o,n);return i&&P(i[1],n)?i[0]:void 0}function oe(e,t){if(!(e.t!=="obj"||F(e,t)))return Object.keys(e.fields??{}).find(n=>{let r=R(e.fields[n],t);return!!r&&P(r[1],t)})}function vt(e,t){let n=e.heap,r=new Map;for(let[p,l]of Object.entries(n))P(l,n)&&r.set(p,z(l,"next",n));let s=new Set([...r.values()].filter(p=>typeof p=="string")),o=new Set,i=[],a=p=>{let l=[],f=p;for(;typeof f=="string"&&!o.has(f);)o.add(f),l.push(f),f=r.get(f);i.push({nodes:l,end:f,oldest:Math.min(...l.map(Number))})};for(let p of r.keys())s.has(p)||a(p);for(let p of r.keys())o.has(p)||a(p);i.sort((p,l)=>p.oldest-l.oldest);let c=e.stack[e.stack.length-1],u=Ht(c?.locals??{},n),g=u.map(p=>p.node),h={},d=i.slice(0,lt).map(p=>{let l=St(p.nodes,g),f=p.nodes.slice(l,l+Y);for(let x of f)h[x]=Et(x,n,t);let m=p.nodes.length-l-f.length,k=m>0?{kind:"more",count:m}:p.end===null?{kind:"none"}:p.end===void 0?{kind:"more",count:0}:{kind:"node",to:p.end};return{nodes:f,skipped:l,end:k}});return{kind:"list",key:"list",label:Mt(e),rows:d,more:i.length-d.length,nodes:h,pointers:u.filter(p=>h[p.node])}}function St(e,t){if(e.length<=Y)return 0;let n=t.map(o=>e.indexOf(o)).filter(o=>o>=0),r=0,s=-1;for(let o of[0,...n.map(i=>Math.min(Math.max(i-dt,0),e.length-Y))]){let i=n.filter(a=>a>=o&&a<o+Y).length;(i>s||i===s&&o>r)&&([r,s]=[o,i])}return r}function Mt(e){for(let t of e.stack)for(let[n,r]of Object.entries(t.locals)){let s=R(r,e.heap);if(!s)continue;if(P(s[1],e.heap))return n;let o=oe(s[1],e.heap);if(o)return`${n}.${o}`}return"list"}function Et(e,t,n){let r=t[e],s=ne(r,t),o=n?.heap[e],i=o&&P(o,n.heap)?o:void 0,a={key:e,text:s,changed:!!n&&(!i||ne(i,n.heap)!==s),relinked:!!i&&z(i,"next",n.heap)!==z(r,"next",t)},c=z(r,"prev",t);return c!==void 0&&(a.prev={to:c,relinked:!!i&&z(i,"prev",n.heap)!==c}),a}function Ht(e,t){let n=[];for(let[r,s]of Object.entries(e)){let o=R(s,t);if(o){if(P(o[1],t))n.push({name:r,node:o[0]});else if(o[1].t==="obj")for(let[i,a]of Object.entries(o[1].fields??{})){let c=R(a,t);c&&P(c[1],t)&&n.push({name:`${r}.${i}`,node:c[0]})}}}return n}function Ge(e,t){if(e.t!=="map"||!e.items?.length)return;let n=[];for(let s of e.items){let[o,i]=s,a=R(i,t)?.[1];if(!j(o,t)||!a)return;let c=[];if(a.t==="seq")for(let u of a.items??[])if(j(u,t))c.push([u,void 0]);else if(Rt(u,t))c.push(R(u,t)[1].items);else return;else if(a.t==="map")for(let u of a.items??[]){let[g,h]=u;if(!j(g,t)||!j(h,t))return;c.push([g,h])}else return;n.push([o,c])}let r=new Set(n.map(([s])=>V(s,t,1)));return n.some(([,s])=>s.some(([o])=>r.has(V(o,t,1))))?n:void 0}function Ot(e,t){return Ge(e,t)!==void 0}function Rt(e,t){let n=R(e,t);return!!n&&n[1].t==="seq"&&n[1].items?.length===2&&j(n[1].items[0],t)}function Lt(e,t,n){let r=new Map,s=new Set,o=new RegExp(String.raw`\bfor\s+\(?\s*([A-Za-z_]\w*)[^:]*?\bin\s+${e}\s*(\[|\.get\()`);t.forEach((c,u)=>{let g=d=>r.set(d,Math.min(r.get(d)??1/0,Math.abs(u+1-n))),h=o.exec(c);h&&(s.add(h[1]),g(h[1]));for(let d of Z([c]).names.get(e)??[])g(d)});let i=c=>c.sort((u,g)=>r.get(u)-r.get(g));return{current:i([...Z(t).names.get(e)??[]].filter(c=>!s.has(c))),next:i([...s])}}var Le=["dist","distance","dists","cost"],K=["visited","seen","done"];function Tt(e,t,n,r,s,o,i){let a=Ge(n,s),c=y=>V(y,s,1),u=y=>`${e}:${c(y)}`,g=new Set(a.flatMap(([y,v])=>[c(y),...v.map(([E])=>c(E))])),h=y=>r.find(v=>v.name===y)?.value,d=y=>y!=null&&j(y,s)&&g.has(c(y)),p=Lt(t,o,i),l=[...p.current,...it].map(h).find(d),f=[...p.next,...at].map(h).find(d),m=It(t,r,s,o,g,[...p.current,...p.next]),k=new Map,x=[],S=y=>{let v=u(y);if(k.has(v))return v;let E=c(y),O=l!==void 0&&c(l)===E?"current":f!==void 0&&c(f)===E?"next":m.visited.has(E)?"visited":"none",b=m.values.get(E);return k.set(v,{key:v,text:E,state:O,...b!==void 0?{sub:`${m.label}=${b}`}:{}}),v};for(let[y,v]of a){let E=S(y);for(let[O,b]of v){let M=S(O),I=k.get(E).state==="current"&&k.get(M).state==="next",A=x.filter(G=>G.from===E&&G.to===M).length;x.push({key:A?`${E}->${M}#${A}`:`${E}->${M}`,from:E,to:M,active:I,nth:A,...b!==void 0?{weight:c(b)}:{}})}}let w=!At(x);if(w)return{kind:"graph",key:e,label:t,nodes:[...k.values()],edges:x,directed:w};let $=[...k.keys()],H=x.filter(y=>$.indexOf(y.from)<=$.indexOf(y.to)).map(y=>({...y,active:y.active||x.some(v=>v.from===y.to&&v.to===y.from&&v.nth===y.nth&&v.active)}));return{kind:"graph",key:e,label:t,nodes:[...k.values()],edges:H,directed:w}}function At(e){let t=new Map,n=(r,s,o,i)=>{let a=JSON.stringify([r,s,o??null]);t.set(a,(t.get(a)??0)+i)};for(let r of e)r.from!==r.to&&(n(r.from,r.to,r.weight,1),n(r.to,r.from,r.weight,-1));return t.size>0&&[...t.values()].every(r=>r===0)}function It(e,t,n,r,s,o){let i=new Set,a=t.filter(d=>d.name!==e&&!i.has(d.name)&&i.add(d.name)),c=d=>o.some(p=>Z(r).names.get(d)?.has(p)),u="",g=new Map,h=new Set;for(let{name:d,value:p}of[...a.filter(l=>Le.includes(l.name)),...a]){let l=Te(p,n,s);if(!(!l||l.bools||!(Le.includes(d)||c(d)))){[u,g]=[d,l.values];break}}for(let{name:d,value:p}of[...a.filter(l=>K.includes(l.name)),...a]){let l=R(p,n)?.[1];if(l?.t==="seq"&&(l.cls==="set"||l.cls==="frozenset")&&(K.includes(d)||l.items?.length&&l.items.every(m=>s.has(q(m,n))))){h=new Set((l.items??[]).map(m=>q(m,n)));break}let f=Te(p,n,s);if(f&&(f.bools||K.includes(d))&&(K.includes(d)||c(d))){h=new Set([...f.values].filter(([,m])=>m!=="False"&&m!=="0"&&m!=="None").map(([m])=>m));break}}return{label:u,values:g,visited:h}}var q=(e,t)=>V(e,t,1);function Te(e,t,n){let r=R(e,t)?.[1],s=new Map,o=!0,i=(a,c)=>j(c,t)?(s.set(a,q(c,t)),o&&(o=typeof c=="boolean"),!0):!1;if(r?.t==="map")for(let a of r.items??[]){let[c,u]=a;if(!n.has(q(c,t))||!i(q(c,t),u))return}else if(r?.t==="seq"&&r.cls==="list"){if(!(r.items??[]).every((a,c)=>i(String(c),a)))return}else return;return s.size&&[...s.keys()].some(a=>n.has(a))?{values:s,bools:o}:void 0}var U={timeout:{badge:"timed out",how:"at the time limit"},interrupt:{badge:"interrupted",how:"with Ctrl+C"}};function Pe(e){let t=e.stopped?U[e.stopped].how:"";return e.truncated?t?`The run went on past the step limit, so only the first steps were recorded, and it was stopped ${t}.`:"The run went on past the step limit; only the first steps were recorded.":t?`The run was stopped here, ${t}.`:""}var Ne=[.1,.2,.5,1,2,4,8],Vt=2,_=260;function _e(e){return 1e3/(Vt*e)}function Ce(e){return Math.round(_/Math.min(e,1))}function Fe(e){let t=new Map;return e.forEach((n,r)=>{t.has(n.line)||t.set(n.line,r)}),t}function De(e,t){return(e??[]).filter(([n])=>n<=t).map(([,n])=>n).join("")}function ie(e,t){let n=/(?:^#|&)step=(\d+)/.exec(e),r=n?Number(n[1]):0;return Math.min(Math.max(r,0),Math.max(t-1,0))}function ze(e){switch(e){case" ":return"toggle";case"ArrowLeft":case"j":case"J":return"back";case"ArrowRight":case"k":case"K":return"forward";case"Home":return"first";case"End":return"last";default:return}}var qe=`
|
|
2
|
+
:root {
|
|
3
|
+
--rr-bg: #fbfaf7; --rr-surface: #ffffff; --rr-ink: #1d2433; --rr-muted: #6b7280; --rr-line: #d6d3cc;
|
|
4
|
+
--rr-code-bg: #f3f1ec; --rr-hl: #fff1c2; --rr-ran: #e9e6de;
|
|
5
|
+
--rr-blue: #0072b2; --rr-orange: #e69f00; --rr-red: #d55e00; --rr-green: #009e73; --rr-sky: #56b4e9;
|
|
6
|
+
--rr-changed-bg: #fdecc8; --rr-current-bg: #fde2cf; --rr-next-bg: #dbeefa; --rr-visited-bg: #d4f0e5;
|
|
7
|
+
--rr-font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
|
8
|
+
--rr-mono: ui-monospace, "SF Mono", "Cascadia Mono", Menlo, Consolas, monospace;
|
|
9
|
+
}
|
|
10
|
+
@media (prefers-color-scheme: dark) {
|
|
11
|
+
:root:not([data-theme="light"]) {
|
|
12
|
+
--rr-bg: #14171f; --rr-surface: #1c2130; --rr-ink: #e6e8ee; --rr-muted: #9aa3b5; --rr-line: #343b4e;
|
|
13
|
+
--rr-code-bg: #181c27; --rr-hl: #4a3f12; --rr-ran: #222838;
|
|
14
|
+
--rr-changed-bg: #4d3a0b; --rr-current-bg: #50290d; --rr-next-bg: #10364f; --rr-visited-bg: #0e3d31;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
:root[data-theme="dark"] {
|
|
18
|
+
--rr-bg: #14171f; --rr-surface: #1c2130; --rr-ink: #e6e8ee; --rr-muted: #9aa3b5; --rr-line: #343b4e;
|
|
19
|
+
--rr-code-bg: #181c27; --rr-hl: #4a3f12; --rr-ran: #222838;
|
|
20
|
+
--rr-changed-bg: #4d3a0b; --rr-current-bg: #50290d; --rr-next-bg: #10364f; --rr-visited-bg: #0e3d31;
|
|
21
|
+
}
|
|
22
|
+
* { box-sizing: border-box; }
|
|
23
|
+
html, body { margin: 0; height: 100%; background: var(--rr-bg); color: var(--rr-ink); font-family: var(--rr-font); }
|
|
24
|
+
.rr-app { display: grid; grid-template-columns: minmax(280px, 2fr) 3fr; grid-template-rows: auto 1fr auto auto;
|
|
25
|
+
grid-template-areas: "head head" "code visual" "code vars" "time time"; height: 100vh; gap: 0; }
|
|
26
|
+
.rr-head { grid-area: head; display: flex; align-items: baseline; gap: 12px; padding: 10px 16px; border-bottom: 1px solid var(--rr-line); }
|
|
27
|
+
.rr-head h1 { font-size: 15px; margin: 0; font-weight: 600; }
|
|
28
|
+
.rr-head .rr-entry { font-family: var(--rr-mono); font-size: 13px; color: var(--rr-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
29
|
+
.rr-head .rr-brand { margin-left: auto; font-size: 12px; color: var(--rr-muted); text-decoration: none; white-space: nowrap; }
|
|
30
|
+
.rr-head .rr-brand b { color: var(--rr-blue); }
|
|
31
|
+
.rr-head .rr-brand:hover b { text-decoration: underline; }
|
|
32
|
+
.rr-head .rr-theme { margin-left: auto; }
|
|
33
|
+
.rr-head .rr-brand + .rr-theme { margin-left: 12px; }
|
|
34
|
+
.rr-code { grid-area: code; overflow: auto; background: var(--rr-code-bg); border-right: 1px solid var(--rr-line);
|
|
35
|
+
font-family: var(--rr-mono); font-size: 13px; line-height: 1.6; padding: 8px 0; }
|
|
36
|
+
.rr-code .rr-ln { display: grid; grid-template-columns: 3.2em 1fr; white-space: pre; padding-right: 12px; }
|
|
37
|
+
.rr-code .rr-ln > span:first-child { color: var(--rr-muted); text-align: right; padding-right: 12px; user-select: none; }
|
|
38
|
+
.rr-code .rr-ran { background: var(--rr-ran); }
|
|
39
|
+
.rr-code .rr-now { background: var(--rr-hl); box-shadow: inset 3px 0 0 var(--rr-orange); }
|
|
40
|
+
.rr-visual { grid-area: visual; overflow: auto; padding: 4px; }
|
|
41
|
+
.rr-visual svg { display: block; max-width: none; }
|
|
42
|
+
.rr-empty { color: var(--rr-muted); padding: 16px; font-size: 14px; }
|
|
43
|
+
.rr-vars { grid-area: vars; overflow: auto; max-height: 34vh; border-top: 1px solid var(--rr-line); padding: 8px 16px; font-size: 13px; }
|
|
44
|
+
.rr-frame { margin: 0 0 8px; }
|
|
45
|
+
.rr-frame h2 { font-size: 12px; font-weight: 600; margin: 0 0 4px; color: var(--rr-muted); font-family: var(--rr-mono); }
|
|
46
|
+
.rr-frame dl { display: grid; grid-template-columns: max-content 1fr; gap: 2px 12px; margin: 0; font-family: var(--rr-mono); }
|
|
47
|
+
.rr-frame dt { color: var(--rr-blue); } .rr-frame dd { margin: 0; overflow-wrap: anywhere; }
|
|
48
|
+
.rr-frame dd.rr-new { background: var(--rr-changed-bg); border-radius: 3px; }
|
|
49
|
+
.rr-event { font-family: var(--rr-mono); margin: 4px 0; }
|
|
50
|
+
.rr-event.rr-error { color: var(--rr-red); }
|
|
51
|
+
.rr-out { font-family: var(--rr-mono); white-space: pre-wrap; background: var(--rr-code-bg); padding: 6px 8px; border-radius: 4px; margin: 4px 0 0; }
|
|
52
|
+
.rr-time { grid-area: time; display: flex; align-items: center; gap: 8px; padding: 8px 16px; border-top: 1px solid var(--rr-line); flex-wrap: wrap; }
|
|
53
|
+
.rr-time input[type=range] { flex: 1; min-width: 160px; accent-color: var(--rr-blue); }
|
|
54
|
+
.rr-time button, .rr-time select, .rr-head button { font: inherit; font-size: 13px; padding: 4px 10px; border-radius: 6px;
|
|
55
|
+
border: 1px solid var(--rr-line); background: var(--rr-surface); color: var(--rr-ink); cursor: pointer; }
|
|
56
|
+
.rr-time button:focus-visible, .rr-time input:focus-visible, .rr-head button:focus-visible { outline: 2px solid var(--rr-blue); outline-offset: 2px; }
|
|
57
|
+
.rr-count { font-family: var(--rr-mono); font-size: 13px; color: var(--rr-muted); min-width: 9em; text-align: right; }
|
|
58
|
+
.rr-mark { font-size: 12px; color: var(--rr-muted); } .rr-mark a { color: inherit; }
|
|
59
|
+
/* Scene */
|
|
60
|
+
.rr-box rect { fill: var(--rr-surface); stroke: var(--rr-line); stroke-width: 1.5; }
|
|
61
|
+
.rr-box.rr-changed rect { fill: var(--rr-changed-bg); stroke: var(--rr-orange); stroke-width: 2; }
|
|
62
|
+
.rr-box.rr-read rect { fill: var(--rr-next-bg); stroke: var(--rr-sky); stroke-width: 2; }
|
|
63
|
+
.rr-box.rr-focus rect { fill: none; stroke: var(--rr-blue); stroke-width: 3; }
|
|
64
|
+
.rr-line.rr-dep line { stroke: var(--rr-blue); stroke-width: 2; }
|
|
65
|
+
.rr-box text, .rr-circle text { fill: var(--rr-ink); font: 600 14px var(--rr-mono); }
|
|
66
|
+
.rr-index text { fill: var(--rr-muted); font: 11px var(--rr-mono); }
|
|
67
|
+
.rr-pointer text { fill: var(--rr-blue); font: 600 12px var(--rr-mono); }
|
|
68
|
+
.rr-title text { fill: var(--rr-ink); font: 600 13px var(--rr-mono); }
|
|
69
|
+
.rr-more text { fill: var(--rr-muted); font: 12px var(--rr-font); }
|
|
70
|
+
.rr-null text { fill: var(--rr-muted); font: 12px var(--rr-mono); }
|
|
71
|
+
.rr-circle circle { fill: var(--rr-surface); stroke: var(--rr-line); stroke-width: 2; }
|
|
72
|
+
.rr-circle .rr-sub { fill: var(--rr-muted); font: 11px var(--rr-mono); }
|
|
73
|
+
.rr-circle.rr-current circle { fill: var(--rr-current-bg); stroke: var(--rr-red); stroke-width: 2.5; }
|
|
74
|
+
.rr-circle.rr-next circle { fill: var(--rr-next-bg); stroke: var(--rr-blue); stroke-width: 2.5; }
|
|
75
|
+
.rr-circle.rr-visited circle { fill: var(--rr-visited-bg); stroke: var(--rr-green); }
|
|
76
|
+
.rr-line line, .rr-line path { stroke: var(--rr-muted); stroke-width: 1.5; fill: none; }
|
|
77
|
+
.rr-line.rr-active line, .rr-line.rr-active path { stroke: var(--rr-red); stroke-width: 3; }
|
|
78
|
+
.rr-line .rr-weight { fill: var(--rr-muted); font: 11px var(--rr-mono); }
|
|
79
|
+
.rr-line.rr-active .rr-weight { fill: var(--rr-red); font-weight: 700; }
|
|
80
|
+
.rr-arrowhead { fill: var(--rr-muted); }
|
|
81
|
+
.rr-sub, .rr-weight, .rr-pointer text, .rr-index text { paint-order: stroke; stroke: var(--rr-bg); stroke-width: 4px; stroke-linejoin: round; }
|
|
82
|
+
.rr-scene g[data-key] { transition: transform var(--rr-move, ${_}ms) ease-out; }
|
|
83
|
+
.rr-scene line { transition: x1 var(--rr-move, ${_}ms), y1 var(--rr-move, ${_}ms), x2 var(--rr-move, ${_}ms), y2 var(--rr-move, ${_}ms); }
|
|
84
|
+
@media (prefers-reduced-motion: reduce) { .rr-scene g[data-key], .rr-scene line { transition: none; } }
|
|
85
|
+
@media (max-width: 760px) {
|
|
86
|
+
.rr-app { grid-template-columns: 1fr; grid-template-rows: auto auto 40vh auto auto; grid-template-areas: "head" "visual" "code" "vars" "time"; height: auto; }
|
|
87
|
+
.rr-code { border-right: 0; max-height: 40vh; } .rr-vars { max-height: none; }
|
|
88
|
+
}
|
|
89
|
+
`;function Be(e,t,n={}){let r=e.ownerDocument;if(!r.getElementById("rr-styles")){let b=r.createElement("style");b.id="rr-styles",b.textContent=qe,r.head.append(b)}let s=t.steps.length,o=t.source.text.split(`
|
|
90
|
+
`);e.innerHTML=`
|
|
91
|
+
<div class="rr-app">
|
|
92
|
+
<header class="rr-head">
|
|
93
|
+
<h1>${L(t.source.file)}</h1>
|
|
94
|
+
<span class="rr-entry">${L(t.source.entry)}</span>
|
|
95
|
+
${t.truncated?'<span class="rr-mark" title="The run went on past the step limit">truncated</span>':""}
|
|
96
|
+
${t.stopped?`<span class="rr-mark" title="The run was stopped ${U[t.stopped].how}">${U[t.stopped].badge}</span>`:""}
|
|
97
|
+
${n.mark===!1?"":'<a class="rr-brand" href="https://github.com/RunReel/RunReel" target="_blank" rel="noopener">made with <b>RunReel</b></a>'}
|
|
98
|
+
<button type="button" class="rr-theme" aria-label="Switch theme">Theme: auto</button>
|
|
99
|
+
</header>
|
|
100
|
+
<pre class="rr-code" aria-label="Source code">${o.map((b,M)=>`<div class="rr-ln" data-line="${M+1}"><span>${M+1}</span><span>${L(b)||" "}</span></div>`).join("")}</pre>
|
|
101
|
+
<section class="rr-visual" aria-label="Data structures"></section>
|
|
102
|
+
<section class="rr-vars" aria-label="Variables"></section>
|
|
103
|
+
<footer class="rr-time">
|
|
104
|
+
<button type="button" data-act="first" aria-label="First step">\u23EE</button>
|
|
105
|
+
<button type="button" data-act="back" aria-label="Step back">\u25C0</button>
|
|
106
|
+
<button type="button" data-act="toggle" aria-label="Play">\u25B6</button>
|
|
107
|
+
<button type="button" data-act="forward" aria-label="Step forward">\u25B6\u25B6</button>
|
|
108
|
+
<button type="button" data-act="last" aria-label="Last step">\u23ED</button>
|
|
109
|
+
<input type="range" min="0" max="${Math.max(s-1,0)}" value="0" aria-label="Step">
|
|
110
|
+
<select aria-label="Speed">${Ne.map(b=>`<option value="${b}"${b===1?" selected":""}>${b}\xD7</option>`).join("")}</select>
|
|
111
|
+
<span class="rr-count" aria-live="polite"></span>
|
|
112
|
+
</footer>
|
|
113
|
+
</div>`;let i=b=>e.querySelector(b),a=i(".rr-code"),c=i(".rr-visual"),u=i(".rr-vars"),g=i(".rr-time input"),h=i(".rr-time select"),d=i(".rr-count"),p=i('[data-act="toggle"]'),l=i(".rr-theme"),f=[...a.querySelectorAll(".rr-ln")],m=Fe(t.steps),k=new ae(c),x=0,S,w=b=>{if(s===0)return;x=Math.min(Math.max(b,0),s-1);let M=W(t.steps,x),I=x>0?W(t.steps,x-1):void 0;for(let C of f){let J=Number(C.dataset.line);C.classList.toggle("rr-now",J===M.line),C.classList.toggle("rr-ran",(m.get(J)??1/0)<=x&&J!==M.line)}f[M.line-1]?.scrollIntoView?.({block:"nearest"});let A=Ve(M,I,o);A.length?k.draw(we(A)):k.clear("No array, tree or graph at this step. The variables are below."),u.innerHTML=jt(M,I,t,x,x===s-1),g.value=String(x),d.textContent=`step ${x+1} / ${s} \xB7 line ${M.line}`;let G=`#step=${x}`;try{location.hash!==G&&history.replaceState(null,"",G)}catch{}},$=()=>{S!==void 0&&clearInterval(S),S=void 0,c.style.removeProperty("--rr-move"),p.textContent="\u25B6",p.setAttribute("aria-label","Play")},H=()=>x>=s-1?$():w(x+1),y=b=>{$();let M=Number(h.value);c.style.setProperty("--rr-move",`${Ce(M)}ms`),x>=s-1?w(0):b&&H(),S=setInterval(H,_e(M)),p.textContent="\u23F8",p.setAttribute("aria-label","Pause")},v=b=>{if(b==="toggle")return S===void 0?y(!0):$();b&&$(),b==="back"&&w(x-1),b==="forward"&&w(x+1),b==="first"&&w(0),b==="last"&&w(s-1)};e.querySelectorAll("[data-act]").forEach(b=>b.addEventListener("click",()=>v(b.dataset.act))),g.addEventListener("input",()=>{$(),w(Number(g.value))}),h.addEventListener("change",()=>S!==void 0&&y(!1)),r.addEventListener("keydown",b=>{let M=b.target;if(b.ctrlKey||b.metaKey||b.altKey||M?.matches?.("input, select, textarea"))return;let I=ze(b.key);I&&(b.preventDefault(),v(I))});let E=["auto","light","dark"],O=0;return l.addEventListener("click",()=>{O=(O+1)%E.length;let b=E[O];b==="auto"?delete r.documentElement.dataset.theme:r.documentElement.dataset.theme=b,l.textContent=`Theme: ${b}`}),addEventListener("hashchange",()=>w(ie(location.hash,s))),w(ie(location.hash,s)),{show:w,get step(){return x}}}function jt(e,t,n,r,s){let o=new Map(t?.stack.map(g=>[g.fid,g.locals])??[]),i=[...e.stack].reverse().map(g=>{let h=o.get(g.fid),d=Object.entries(g.locals).map(([p,l])=>{let f=V(l,e.heap,1),m=!!h&&(!(p in h)||V(h[p],t.heap,1)!==f);return`<dt>${L(p)}</dt><dd${m?' class="rr-new"':""}>${L(f)}</dd>`});return`<div class="rr-frame"><h2>${L(g.fn)}()</h2><dl>${d.join("")||"<dd>no variables yet</dd>"}</dl></div>`}),a=[];e.ev==="return"&&a.push(`<p class="rr-event">\u21A9 returns ${L(V(e.ret,e.heap,1))}</p>`),e.ev==="exception"&&a.push(`<p class="rr-event rr-error">\u26A0 ${L(e.exc??"exception")}</p>`),s&&n.error&&a.push(`<p class="rr-event rr-error">The run ended with ${L(n.error)}</p>`);let c=Pe(n);s&&c&&a.push(`<p class="rr-event">${L(c)}</p>`);let u=De(n.stdout,r);return u&&a.push(`<pre class="rr-out" aria-label="Printed output">${L(u)}</pre>`),a.join("")+i.join("")}var ae=class{constructor(t){this.host=t;this.items=new Map;this.ns="http://www.w3.org/2000/svg"}draw(t){let n=this.host.ownerDocument;this.svg||(this.host.innerHTML="",this.svg=n.createElementNS(this.ns,"svg"),this.svg.classList.add("rr-scene"),this.svg.innerHTML=$e,this.host.append(this.svg)),this.svg.setAttribute("viewBox",`0 0 ${t.width} ${t.height}`),this.svg.setAttribute("width",String(t.width)),this.svg.setAttribute("height",String(t.height));let r=new Set;for(let s of t.items){r.add(s.key);let o=this.items.get(s.key);o||(o=n.createElementNS(this.ns,"g"),o.dataset.key=s.key,this.items.set(s.key,o)),this.svg.append(o),o.setAttribute("class",`rr-${s.type} ${s.cls}`.trim()),s.type!=="line"&&(o.style.transform=`translate(${T(s.x)}px, ${T(s.y)}px)`);let i=ve(s);o.dataset.inner!==i&&(o.innerHTML=i,o.dataset.inner=i)}for(let[s,o]of this.items)r.has(s)||(o.remove(),this.items.delete(s))}clear(t){this.svg=void 0,this.items.clear(),this.host.innerHTML=`<p class="rr-empty">${L(t)}</p>`}};var Gt="0.0.0";return Ue(Pt);})();
|
runreel/cli.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""Command-line entry point for `runreel`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import shlex
|
|
7
|
+
import sys
|
|
8
|
+
import webbrowser
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from runreel import __version__
|
|
14
|
+
from runreel.reel import write_reel
|
|
15
|
+
from runreel.trace import MAX_STEPS, TIMEOUT, ExitedWhileLoading, Trace, record, state_at
|
|
16
|
+
|
|
17
|
+
RUN_HELP = """\
|
|
18
|
+
Run FILE, record every step and write the reel: one HTML file that opens offline.
|
|
19
|
+
|
|
20
|
+
This executes FILE's code on your machine, with your permissions, exactly as running it
|
|
21
|
+
yourself would. Only run code you trust.
|
|
22
|
+
|
|
23
|
+
After the step limit the program keeps running unrecorded until it ends or hits the time
|
|
24
|
+
limit. Ctrl+C stops it too, and the reel is still written.
|
|
25
|
+
|
|
26
|
+
Arguments after -- go to the program: runreel run app.py -- --n 5 runs it the way
|
|
27
|
+
python app.py --n 5 would.
|
|
28
|
+
"""
|
|
29
|
+
CALL_HINT = (
|
|
30
|
+
"With --call the file is loaded first, untraced, so it should only define functions;"
|
|
31
|
+
' put the code that runs the program under `if __name__ == "__main__":`'
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
36
|
+
# Options must be spelt out in full: otherwise a program's own option, such as --n 5, would
|
|
37
|
+
# pass for an abbreviation of one of runreel's (--no-mark).
|
|
38
|
+
parser = argparse.ArgumentParser(
|
|
39
|
+
prog="runreel",
|
|
40
|
+
description="Turn an algorithm into an interactive step-through reel.",
|
|
41
|
+
allow_abbrev=False,
|
|
42
|
+
)
|
|
43
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
44
|
+
commands = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
45
|
+
run = commands.add_parser(
|
|
46
|
+
"run",
|
|
47
|
+
help="run a Python file and write its reel",
|
|
48
|
+
description=RUN_HELP,
|
|
49
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
50
|
+
allow_abbrev=False,
|
|
51
|
+
)
|
|
52
|
+
run.add_argument("file", type=Path, help="Python file to run")
|
|
53
|
+
run.add_argument("args", nargs="*", metavar="ARGS", help="arguments for the program, after --")
|
|
54
|
+
run.add_argument(
|
|
55
|
+
"--call",
|
|
56
|
+
help='expression to trace, e.g. "dijkstra(G, 0)"; without it FILE runs as a script',
|
|
57
|
+
)
|
|
58
|
+
run.add_argument("--stdin", type=Path, metavar="FILE", help="file to give the program as input")
|
|
59
|
+
run.add_argument(
|
|
60
|
+
"--lines",
|
|
61
|
+
type=parse_lines,
|
|
62
|
+
metavar="RANGES",
|
|
63
|
+
help="record only these lines, e.g. 12-30 or 12-30,40",
|
|
64
|
+
)
|
|
65
|
+
run.add_argument(
|
|
66
|
+
"--max-steps",
|
|
67
|
+
type=positive,
|
|
68
|
+
default=MAX_STEPS,
|
|
69
|
+
metavar="N",
|
|
70
|
+
help=f"stop recording after N steps (default: {MAX_STEPS})",
|
|
71
|
+
)
|
|
72
|
+
run.add_argument(
|
|
73
|
+
"--timeout",
|
|
74
|
+
type=seconds,
|
|
75
|
+
default=TIMEOUT,
|
|
76
|
+
metavar="SECONDS",
|
|
77
|
+
help=f"stop the program once it has run for SECONDS (default: {TIMEOUT:g}; 0: no limit)",
|
|
78
|
+
)
|
|
79
|
+
run.add_argument("--out", type=Path, help="reel to write (default: FILE with .reel.html)")
|
|
80
|
+
run.add_argument("--open", action="store_true", help="open the reel in your browser")
|
|
81
|
+
run.add_argument("--no-mark", action="store_true", help='hide the "made with RunReel" link')
|
|
82
|
+
return parser
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def parse_lines(spec: str) -> tuple[tuple[int, int], ...]:
|
|
86
|
+
"""Line ranges like "12-30,40" as (first, last) pairs."""
|
|
87
|
+
ranges: list[tuple[int, int]] = []
|
|
88
|
+
try:
|
|
89
|
+
for part in spec.split(","):
|
|
90
|
+
first, dash, last = part.strip().partition("-")
|
|
91
|
+
start, end = int(first), int(last if dash else first)
|
|
92
|
+
if start < 1 or end < start:
|
|
93
|
+
raise ValueError
|
|
94
|
+
ranges.append((start, end))
|
|
95
|
+
except ValueError:
|
|
96
|
+
raise argparse.ArgumentTypeError(f"not a line range: {spec!r} (try 12-30,40)") from None
|
|
97
|
+
return tuple(ranges)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def lines_in(ranges: tuple[tuple[int, int], ...], file: Path) -> frozenset[int]:
|
|
101
|
+
"""The line numbers in ranges that file has, so a range like 1-99999999999 stays small."""
|
|
102
|
+
total = len(file.read_text(encoding="utf-8").splitlines())
|
|
103
|
+
return frozenset(n for start, end in ranges for n in range(start, min(end, total) + 1))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def positive(text: str) -> int:
|
|
107
|
+
try:
|
|
108
|
+
n = int(text)
|
|
109
|
+
except ValueError:
|
|
110
|
+
n = 0
|
|
111
|
+
if n < 1:
|
|
112
|
+
raise argparse.ArgumentTypeError(f"must be a whole number of at least 1: {text!r}")
|
|
113
|
+
return n
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def seconds(text: str) -> float:
|
|
117
|
+
try:
|
|
118
|
+
n = float(text)
|
|
119
|
+
except ValueError:
|
|
120
|
+
n = -1
|
|
121
|
+
if not n >= 0: # also refuses nan
|
|
122
|
+
raise argparse.ArgumentTypeError(f"must be a number of seconds, 0 or more: {text!r}")
|
|
123
|
+
return n
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
127
|
+
parser = build_parser()
|
|
128
|
+
words = list(sys.argv[1:] if argv is None else argv)
|
|
129
|
+
# Everything after the first -- is the program's, so it's split off before parsing. Left to
|
|
130
|
+
# argparse, Python 3.10 and 3.11 refuse it when an option comes between FILE and --.
|
|
131
|
+
program: list[str] = []
|
|
132
|
+
if "--" in words:
|
|
133
|
+
cut = words.index("--")
|
|
134
|
+
words, program = words[:cut], words[cut + 1 :]
|
|
135
|
+
args, unknown = parser.parse_known_args(words)
|
|
136
|
+
if unknown:
|
|
137
|
+
tip = hint(words, unknown, program, args)
|
|
138
|
+
parser.error(f"unrecognized arguments: {' '.join(unknown)}{tip}")
|
|
139
|
+
if args.command is None:
|
|
140
|
+
parser.print_help()
|
|
141
|
+
return 0
|
|
142
|
+
args.args = [*args.args, *program]
|
|
143
|
+
try:
|
|
144
|
+
return run(args)
|
|
145
|
+
except KeyboardInterrupt: # Ctrl+C before or after the run, e.g. while writing the reel
|
|
146
|
+
print("runreel: interrupted", file=sys.stderr)
|
|
147
|
+
return 130
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def hint(words: list[str], unknown: list[str], program: list[str], args: argparse.Namespace) -> str:
|
|
151
|
+
"""How to give unrecognized arguments to the program instead: the same command with -- put
|
|
152
|
+
before the first of them, when that comes after FILE."""
|
|
153
|
+
if args.command != "run":
|
|
154
|
+
return ""
|
|
155
|
+
at = words.index(unknown[0])
|
|
156
|
+
if not any(Path(word) == args.file for word in words[:at]):
|
|
157
|
+
return "; arguments for the program go after FILE and --"
|
|
158
|
+
example = shlex.join(["runreel", *words[:at], "--", *words[at:], *program])
|
|
159
|
+
return f"; if they're for the program, put them after --: {example}"
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def run(args: argparse.Namespace) -> int:
|
|
163
|
+
"""Record the file, write the reel and print a one-line summary that agents can read."""
|
|
164
|
+
file: Path = args.file
|
|
165
|
+
out: Path = args.out or file.with_suffix(".reel.html")
|
|
166
|
+
for kept, what in ((file, "the program itself"), (args.stdin, "the program's input")):
|
|
167
|
+
if kept is not None and same_file(out, kept):
|
|
168
|
+
return fail(f"--out {out} would overwrite {what}; give the reel another name")
|
|
169
|
+
target = out.absolute() # fixed now, in case the program changes the working directory
|
|
170
|
+
stdin = ""
|
|
171
|
+
if args.stdin:
|
|
172
|
+
try:
|
|
173
|
+
stdin = args.stdin.read_text(encoding="utf-8")
|
|
174
|
+
except OSError as error:
|
|
175
|
+
return fail(f"can't read {args.stdin}: {error.strerror or error}")
|
|
176
|
+
except UnicodeDecodeError:
|
|
177
|
+
return fail(f"can't read {args.stdin}: it isn't UTF-8 text")
|
|
178
|
+
try:
|
|
179
|
+
lines = None if args.lines is None else lines_in(args.lines, file)
|
|
180
|
+
trace = record(
|
|
181
|
+
file,
|
|
182
|
+
args.call,
|
|
183
|
+
lines=lines,
|
|
184
|
+
max_steps=args.max_steps,
|
|
185
|
+
args=args.args,
|
|
186
|
+
stdin=stdin,
|
|
187
|
+
timeout=args.timeout or None,
|
|
188
|
+
)
|
|
189
|
+
except OSError as error:
|
|
190
|
+
return fail(f"can't read {error.filename or file}: {error.strerror or error}")
|
|
191
|
+
except UnicodeDecodeError:
|
|
192
|
+
return fail(f"can't read {file}: it isn't UTF-8 text")
|
|
193
|
+
except SyntaxError as error:
|
|
194
|
+
return fail(f"{file} doesn't compile: {error.msg} (line {error.lineno})")
|
|
195
|
+
except ExitedWhileLoading as error:
|
|
196
|
+
return fail(f"{file} {error}. {CALL_HINT}")
|
|
197
|
+
except Exception as error: # raised while loading the file, before the traced call
|
|
198
|
+
return fail(f"{file} failed while loading: {type(error).__name__}: {error}")
|
|
199
|
+
if not trace["steps"] and "stopped" in trace:
|
|
200
|
+
message = f"{file} was {stopped(trace, args.timeout)} before any step was recorded"
|
|
201
|
+
return fail(f"{message}. {CALL_HINT}" if args.call else message)
|
|
202
|
+
if not trace["steps"]: # an empty reel would only puzzle, so say why there's nothing to show
|
|
203
|
+
if "error" in trace:
|
|
204
|
+
return fail(f"{args.call or file} failed before any of its code ran: {trace['error']}")
|
|
205
|
+
if lines is not None:
|
|
206
|
+
return fail("no step was recorded: none of the lines given with --lines ran")
|
|
207
|
+
if args.call:
|
|
208
|
+
return fail(
|
|
209
|
+
f"no step was recorded: {args.call} ran none of {file}'s own code;"
|
|
210
|
+
" call one of the functions it defines"
|
|
211
|
+
)
|
|
212
|
+
return fail(f"no step was recorded: {file} has no code to run")
|
|
213
|
+
try:
|
|
214
|
+
write_reel(trace, target, mark=not args.no_mark)
|
|
215
|
+
except FileNotFoundError as error:
|
|
216
|
+
return fail(str(error))
|
|
217
|
+
except OSError as error:
|
|
218
|
+
return fail(f"can't write {out}: {error.strerror or error}")
|
|
219
|
+
print(summary(trace, out, args.timeout))
|
|
220
|
+
if args.open:
|
|
221
|
+
webbrowser.open(target.resolve().as_uri())
|
|
222
|
+
return 0
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def fail(message: str) -> int:
|
|
226
|
+
print(f"runreel: {message}", file=sys.stderr)
|
|
227
|
+
return 1
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def same_file(a: Path, b: Path) -> bool:
|
|
231
|
+
"""Whether a and b name the same existing file, however each is spelt."""
|
|
232
|
+
try:
|
|
233
|
+
return a.samefile(b)
|
|
234
|
+
except OSError: # one of them doesn't exist
|
|
235
|
+
return False
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def summary(trace: Trace, out: Path, timeout: float | None = None) -> str:
|
|
239
|
+
"""E.g. "reel: dijkstra.reel.html (29 KB) · 63 steps · result {0: 0, 1: 3}"."""
|
|
240
|
+
steps = trace["steps"]
|
|
241
|
+
count = len(steps)
|
|
242
|
+
parts = [
|
|
243
|
+
f"reel: {out} ({max(out.stat().st_size // 1024, 1)} KB)",
|
|
244
|
+
f"{count} step{'s' if count != 1 else ''}",
|
|
245
|
+
]
|
|
246
|
+
if trace.get("truncated"):
|
|
247
|
+
parts[-1] += " (truncated: raise --max-steps to see more)"
|
|
248
|
+
if "stopped" in trace:
|
|
249
|
+
parts.append(stopped(trace, timeout))
|
|
250
|
+
if trace["stopped"] == "timeout":
|
|
251
|
+
parts[-1] += " (raise --timeout to let it run longer)"
|
|
252
|
+
if "error" in trace:
|
|
253
|
+
parts.append(f"error {trace['error']}")
|
|
254
|
+
elif "result" in trace:
|
|
255
|
+
heap = state_at(steps, len(steps) - 1)["heap"] if steps else {}
|
|
256
|
+
parts.append(f"result {describe(trace['result'], heap)}")
|
|
257
|
+
printed = sum(text.count("\n") for _, text in trace.get("stdout", []))
|
|
258
|
+
if printed:
|
|
259
|
+
parts.append(f"printed {printed} line{'s' if printed != 1 else ''}")
|
|
260
|
+
return " · ".join(parts)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def stopped(trace: Trace, timeout: float | None) -> str:
|
|
264
|
+
"""How the program was stopped, e.g. "stopped at the 60 s time limit"."""
|
|
265
|
+
if trace.get("stopped") == "interrupt":
|
|
266
|
+
return "stopped by Ctrl+C"
|
|
267
|
+
return f"stopped at the {timeout:g} s time limit" if timeout else "stopped at the time limit"
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def describe(value: Any, heap: dict[int, Any], depth: int = 0) -> str:
|
|
271
|
+
"""A short Python-like rendering of a trace value."""
|
|
272
|
+
text = _describe(value, heap, depth)
|
|
273
|
+
return text if len(text) <= 80 else text[:79] + "…"
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _describe(value: Any, heap: dict[int, Any], depth: int) -> str:
|
|
277
|
+
if not isinstance(value, dict):
|
|
278
|
+
return repr(value)
|
|
279
|
+
if "inf" in value:
|
|
280
|
+
return "inf" if value["inf"] == 1 else "-inf"
|
|
281
|
+
if "nan" in value:
|
|
282
|
+
return "nan"
|
|
283
|
+
if "bigint" in value:
|
|
284
|
+
return str(value["bigint"])
|
|
285
|
+
if "float" in value:
|
|
286
|
+
return str(value["float"])
|
|
287
|
+
obj = heap.get(value.get("ref", -1))
|
|
288
|
+
if obj is None or depth > 2:
|
|
289
|
+
return "…"
|
|
290
|
+
if obj["t"] == "repr":
|
|
291
|
+
return str(obj["v"])
|
|
292
|
+
if obj["t"] == "obj":
|
|
293
|
+
fields = ", ".join(f"{k}={_describe(v, heap, depth + 1)}" for k, v in obj["fields"].items())
|
|
294
|
+
return f"{obj['cls']}({fields})"
|
|
295
|
+
more = ", …" if obj.get("more") else ""
|
|
296
|
+
if obj["t"] == "map":
|
|
297
|
+
pairs = (
|
|
298
|
+
f"{_describe(k, heap, depth + 1)}: {_describe(v, heap, depth + 1)}"
|
|
299
|
+
for k, v in obj["items"]
|
|
300
|
+
)
|
|
301
|
+
return "{" + ", ".join(pairs) + more + "}"
|
|
302
|
+
items = ", ".join(_describe(v, heap, depth + 1) for v in obj["items"])
|
|
303
|
+
if obj["cls"] == "tuple":
|
|
304
|
+
return f"({items}{',' if len(obj['items']) == 1 else ''}{more})"
|
|
305
|
+
if obj["cls"] in ("set", "frozenset"):
|
|
306
|
+
return "{" + items + more + "}"
|
|
307
|
+
return f"[{items}{more}]"
|
runreel/py.typed
ADDED
|
File without changes
|
runreel/reel.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Write a trace and the player into one self-contained HTML file that works offline."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
from importlib import resources
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from runreel.trace import Trace, dumps
|
|
12
|
+
|
|
13
|
+
PLAYER = "_player/player.js" # copied into the package by `make build`
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def player_js() -> str:
|
|
17
|
+
"""The bundled player shipped inside the package."""
|
|
18
|
+
try:
|
|
19
|
+
return resources.files("runreel").joinpath(PLAYER).read_text(encoding="utf-8")
|
|
20
|
+
except FileNotFoundError:
|
|
21
|
+
raise FileNotFoundError("the player isn't built yet; run `make build`") from None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def render_reel(trace: Trace, *, player: str | None = None, mark: bool = True) -> str:
|
|
25
|
+
"""The reel's HTML. Nothing in it loads from the network."""
|
|
26
|
+
data = dumps(trace).replace("<", "\\u003c") # so the trace can never close its <script> tag
|
|
27
|
+
script = re.sub(
|
|
28
|
+
r"</(script)", r"<\\/\1", player if player is not None else player_js(), flags=re.I
|
|
29
|
+
)
|
|
30
|
+
source = trace["source"]
|
|
31
|
+
title = html.escape(
|
|
32
|
+
f"{source['file']} · {source['entry']}" if source["entry"] else source["file"]
|
|
33
|
+
)
|
|
34
|
+
options = json.dumps({"mark": mark})
|
|
35
|
+
return (
|
|
36
|
+
"<!doctype html>\n"
|
|
37
|
+
'<html lang="en">\n<head>\n<meta charset="utf-8">\n'
|
|
38
|
+
'<meta name="viewport" content="width=device-width, initial-scale=1">\n'
|
|
39
|
+
'<meta name="generator" content="RunReel">\n'
|
|
40
|
+
f"<title>{title} · RunReel</title>\n</head>\n<body>\n"
|
|
41
|
+
'<div id="runreel"></div>\n'
|
|
42
|
+
f'<script type="application/json" id="runreel-trace">{data}</script>\n'
|
|
43
|
+
f"<script>{script}</script>\n"
|
|
44
|
+
'<script>RunReelPlayer.mount(document.getElementById("runreel"), '
|
|
45
|
+
f'JSON.parse(document.getElementById("runreel-trace").textContent), {options});</script>\n'
|
|
46
|
+
"</body>\n</html>\n"
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def write_reel(
|
|
51
|
+
trace: Trace, path: str | Path, *, player: str | None = None, mark: bool = True
|
|
52
|
+
) -> Path:
|
|
53
|
+
"""Write the reel to path and return it."""
|
|
54
|
+
out = Path(path)
|
|
55
|
+
out.write_text(render_reel(trace, player=player, mark=mark), encoding="utf-8")
|
|
56
|
+
return out
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Trace format v1: the model types, the keyframe/delta codec and the Python tracer."""
|
|
2
|
+
|
|
3
|
+
from runreel.trace.codec import KEY_EVERY, dumps, encode, iter_states, state_at
|
|
4
|
+
from runreel.trace.model import (
|
|
5
|
+
SCHEMA_VERSION,
|
|
6
|
+
Event,
|
|
7
|
+
Frame,
|
|
8
|
+
FramePatch,
|
|
9
|
+
HeapObject,
|
|
10
|
+
ObjectPatch,
|
|
11
|
+
Source,
|
|
12
|
+
State,
|
|
13
|
+
Step,
|
|
14
|
+
Trace,
|
|
15
|
+
Value,
|
|
16
|
+
)
|
|
17
|
+
from runreel.trace.tracer import MAX_STEPS, TIMEOUT, ExitedWhileLoading, record
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"KEY_EVERY",
|
|
21
|
+
"MAX_STEPS",
|
|
22
|
+
"SCHEMA_VERSION",
|
|
23
|
+
"TIMEOUT",
|
|
24
|
+
"Event",
|
|
25
|
+
"ExitedWhileLoading",
|
|
26
|
+
"Frame",
|
|
27
|
+
"FramePatch",
|
|
28
|
+
"HeapObject",
|
|
29
|
+
"ObjectPatch",
|
|
30
|
+
"Source",
|
|
31
|
+
"State",
|
|
32
|
+
"Step",
|
|
33
|
+
"Trace",
|
|
34
|
+
"Value",
|
|
35
|
+
"dumps",
|
|
36
|
+
"encode",
|
|
37
|
+
"iter_states",
|
|
38
|
+
"record",
|
|
39
|
+
"state_at",
|
|
40
|
+
]
|