User:Brian Schott/Incunabulum

From J Wiki
Jump to navigation Jump to search

This is a line numbered version of the code at Essays/Incunabulum

 1 typedef char C;typedef long I;
 2 typedef struct a{I t,r,d[3],p[2];}*A;
 3 #define P printf
 4 #define R return
 5 #define V1(f) A f(w)A w;
 6 #define V2(f) A f(a,w)A a,w;
 7 #define DO(n,x) {I i=0,_n=(n);for(;i<_n;++i){x;}}
 8 I *ma(n){R(I*)malloc(n*4);}mv(d,s,n)I *d,*s;{DO(n,d[i]=s[i]);}
 9 tr(r,d)I *d;{I z=1;DO(r,z=z*d[i]);R z;}
10 A ga(t,r,d)I *d;{A z=(A)ma(5+tr(r,d));z->t=t,z->r=r,mv(z->d,d,r);
11  R z;}
12 V1(iota){I n=*w->p;A z=ga(0,1,&n);DO(n,z->p[i]=i);R z;}
13 V2(plus){I r=w->r,*d=w->d,n=tr(r,d);A z=ga(0,r,d);
14  DO(n,z->p[i]=a->p[i]+w->p[i]);R z;}
15 V2(from){I r=w->r-1,*d=w->d+1,n=tr(r,d);
16  A z=ga(w->t,r,d);mv(z->p,w->p+(n**a->p),n);R z;}
17 V1(box){A z=ga(1,0,0);*z->p=(I)w;R z;}
18 V2(cat){I an=tr(a->r,a->d),wn=tr(w->r,w->d),n=an+wn;
19  A z=ga(w->t,1,&n);mv(z->p,a->p,an);mv(z->p+an,w->p,wn);R z;}
20 V2(find){}
21 V2(rsh){I r=a->r?*a->d:1,n=tr(r,a->p),wn=tr(w->r,w->d);
22  A z=ga(w->t,r,a->p);mv(z->p,w->p,wn=n>wn?wn:n);
23  if(n-=wn)mv(z->p+wn,z->p,n);R z;}
24 V1(sha){A z=ga(0,1,&w->r);mv(z->p,w->d,w->r);R z;}
25 V1(id){R w;}V1(size){A z=ga(0,0,0);*z->p=w->r?*w->d:1;R z;}
26 pi(i){P("%d ",i);}nl(){P("\n");}
27 pr(w)A w;{I r=w->r,*d=w->d,n=tr(r,d);DO(r,pi(d[i]));nl();
28  if(w->t)DO(n,P("< ");pr(w->p[i]))else DO(n,pi(w->p[i]));nl();}
29
30 C vt[]="+{~<#,";
31 A(*vd[])()={0,plus,from,find,0,rsh,cat},
32  (*vm[])()={0,id,size,iota,box,sha,0};
33 I st[26]; qp(a){R  a>='a'&&a<='z';}qv(a){R a<'a';}
34 A ex(e)I *e;{I a=*e;
35  if(qp(a)){if(e[1]=='=')R st[a-'a']=ex(e+2);a= st[ a-'a'];}
36  R qv(a)?(*vm[a])(ex(e+1)):e[1]?(*vd[e[1]])(a,ex(e+2)):(A)a;}
37 noun(c){A z;if(c<'0'||c>'9')R 0;z=ga(0,0,0);*z->p=c-'0';R z;}
38 verb(c){I i=0;for(;vt[i];)if(vt[i++]==c)R i;R 0;}
39 I *wd(s)C *s;{I a,n=strlen(s),*e=ma(n+1);C c;
40  DO(n,e[i]=(a=noun(c=s[i]))?a:(a=verb(c))?a:c);e[n]=0;R e;}
41
42 main(){C s[99];while(gets(s))pr(ex(wd(s)));}