# HG changeset patch # User Mike Pavone # Date 1311827323 25200 # Node ID c6ba9fe45910c27fe211b58992ffe1b1c77ade44 # Parent 24c6f876719070afcd6948d0fd079955f598f787 Strip _c from filenames of current compiler diff -r 24c6f8767190 -r c6ba9fe45910 backendutils.rhope --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/backendutils.rhope Wed Jul 27 21:28:43 2011 -0700 @@ -0,0 +1,526 @@ + +Escape Rhope Name[name,p:out] +{ + escaped <- [name]Replace[p, + ("UN_","AT_","SP_","CN_","QN_","PL_","MN_","TM_","DV_","LT_","GT_","LP_","RP_","NT_","EQ_","PR_", + "DP_","TB_","CM_","PD_","NL_","LC_","RC_", "LS_", "RS_", "HS_", "BS_", "CR_", "SC_", "AM_", "PI_", "PC_", "CT_", "BT_", "TD_")] + + [("char","int","short","long","float","double","void","struct")]Find[=[escaped, ?]] + { + out <- ["ID_"]Append[escaped] + }{ + out <- Val[escaped] + } +} + +Blueprint Make Op Res +{ + Func + Val +} + +Make Op Res[func,val:out] +{ + out <- [[Build[Make Op Res()]]Func <<[func]]Val <<[val] +} + +Make Op Mod[func,val:out func,out val] +{ + nval <- [val]Make Op[func] + If[[Blueprint Of[nval]]=[Make Op Res()]] + { + out func <- Func >>[nval] + out val <- Val >>[nval] + }{ + out func <- func + out val <- Val[nval] + } +} + +Blueprint AddRef +{ + Value +} + +AddRef[value:out] +{ + out <- [Build[AddRef()]]Value <<[value] +} + +Make Op@AddRef[addref,func:out] +{ + out <- [func]Make AddRef Op[[addref]Value >>] +} + +Strip Addref@AddRef[op:out] +{ + out <- [[op]Value >>]Strip Addref +} + +=@AddRef[a,b(AddRef):out] +{ + out <- [[a]Value >>]==[[b]Value >>] +} + +Make Op@String[string,func:out] +{ + out <- [func]Resolve[string] +} + +Strip Addref@String[op:out] +{ + out <- op +} + +Get Type@String[op,func:out] +{ + out <- [func]Get Var Type[op] +} + +Make Op@String Cat[string,func:out] +{ + out <- [func]Resolve[string] +} + +Strip Addref@String Cat[op:out] +{ + out <- op +} + +Get Type@String Cat[op,func:out] +{ + out <- [func]Get Var Type[op] +} + +Make Op@String Slice[string,func:out] +{ + out <- [func]Resolve[string] +} + +Strip Addref@String Slice[op:out] +{ + out <- op +} + +Get Type@String Slice[op,func:out] +{ + out <- [func]Get Var Type[op] +} + +Blueprint Output +{ + Name +} + +Output[name:out] +{ + out <- [Build[Output()]]Name <<[name] +} + +Make Op@Output[op,func:out] +{ + out <- [func]Resolve Output[[op]Name >>] +} + +Strip Addref@Output[op:out] +{ + out <- op +} + +=@Output[a,b(Output):out] +{ + out <- [[a]Name >>]=[[b]Name >>] +} + + +Blueprint Constant +{ + Value + Need Addref +} + +Constant[var:out] +{ + out <- [[Build[Constant()]]Value <<[var]]Need Addref <<[Yes] +} + +Make Op@Constant[const,func:out] +{ + out <- [func]Lookup Constant[[const]Value >>, [const]Need Addref >>] +} + +Get Type@Constant[const,func:out] +{ + out <- [func]Get Constant Type[const] +} + +Strip Addref@Constant[op:out] +{ + out <- [op]Need Addref <<[No] +} + +=@Constant[a,b(Constant):out] +{ + out <- [[a]Value >>]=[[b]Value >>] +} + +Blueprint Result +{ + Output Num +} + +Result[num:out] +{ + out <- [Build[Result()]]Output Num <<[num] +} + +Make Op@Result[result,func:out] +{ + out <- [func]Result Reference[[result]Output Num>>] +} + +Strip Addref@Result[op:out] +{ + out <- op +} + +=@Result[a,b(Result):out] +{ + out <- [[a]Output Num >>]=[[b]Output Num >>] +} + +Blueprint Global Get +{ + Store + Var +} + +Global Get[store,var:out] +{ + out <- [[Build[Global Get()]]Store <<[store]]Var <<[var] +} + +Make Op@Global Get[get,func:out] +{ + out <- [func]Global Reference[[get]Store >>, [get]Var >>] +} + +Strip Addref@Global Get[get:out] +{ + out <- get +} + +=@Global Get[a,b(Global Get):out] +{ + ,out <- If[[[a]Store >>]=[[b]Store >>]] + { + out <- [[a]Var >>]=[[b]Var >>] + } +} + +Blueprint Check Result +{ + Output Num +} + +Check Result[num:out] +{ + out <- [Build[Check Result()]]Output Num <<[num] +} + +Make Op@Check Result[result,func:out] +{ + out <- [func]Checked Result Reference[[result]Output Num>>] +} + +Strip Addref@Check Result[op:out] +{ + out <- op +} + +Make Condition[op:out] +{ + If[[Blueprint Of[op]]=[OrValue()]] + { + out <- OrCond[Make Condition[[op]Left >>], Make Condition[[op]Right >>]] + }{ + out <- op + } +} + +=@Check Result[a,b(Check Result):out] +{ + out <- [[a]Output Num >>]=[[b]Output Num >>] +} + +Blueprint OrValue +{ + Left + Right +} + +OrValue[left,right:out] +{ + If[[left]==[right]] + { + out <- left + }{ + out <- [[Build[OrValue()]]Left <<[left]]Right <<[right] + } +} + +Make Op@OrValue[orval,func:out] +{ + out <- [func]If Null Else[[orval]Left >>, [orval]Right >>] +} + +Strip Addref@OrValue[op:out] +{ + out <- [[op]Left <<[ [[op]Left >>]Strip Addref ]]Right <<[ [[op]Right >>]Strip Addref ] +} + +=@OrValue[a,b(OrValue):out] +{ + ,out <- If[[[a]Left >>]==[[b]Left >>]] + { + out <- [[a]Right >>]==[[b]Right >>] + } +} + +Blueprint Cast +{ + Value + Type +} + +Cast[val,type:out] +{ + out <- [[Build[Cast()]]Value <<[val]]Type <<[type] +} + +Make Op@Cast[cast,func:out] +{ + out <- [func]Cast Value[[cast]Value >>, [cast]Type >>] +} + +Strip Addref@Cast[op:out] +{ + out <- [op]Value <<[[[op]Value >>]Strip Addref] +} + +=@Cast[a,b(Cast):out] +{ + ,out <- If[[[a]Value >>] == [[b]Value >>]] + { + out <- [[a]Type >>]=[[b]Type >>] + } +} + +Blueprint NotCond +{ + Condition +} + +NotCond[cond:out] +{ + If[[Blueprint Of[cond]]=[NotCond()]] + { + out <- [cond]Condition >> + }{ + out <- [Build[NotCond()]]Condition <<[[cond]Strip Addref] + } +} + +Make Op@NotCond[cond,func:out] +{ + out <- ["!"]Append[[[cond]Condition >>]Make Op[func]] +} + +Strip Addref@NotCond[op:out] +{ + out <- op +} + +=@NotCond[a,b(NotCond):out] +{ + out <- [[a]Condition >>]==[[b]Condition >>] +} + +Blueprint OrCond +{ + Condition1 + Condition2 +} + +OrCond[cond1,cond2:out] +{ + If[[cond1]==[cond2]] + { + out <- cond1 + }{ + out <- [[Build[OrCond()]]Condition1 <<[[cond1]Strip Addref]]Condition2 <<[[cond2]Strip Addref] + } +} + +Make Op@OrCond[cond,func:out] +{ + out <- ["("]Append[[[ [[cond]Condition1 >>]Make Op[func] ]Append[" || "]]Append[[ [[cond]Condition2 >>]Make Op[func] ]Append[")"]]] +} + +Strip Addref@OrCond[op:out] +{ + out <- op +} + +=@OrCond[a,b(OrCond):out] +{ + ,out <- If[[[a]Condition1 >>] == [[b]Condition1 >>]] + { + out <- [[a]Condition2 >>] == [[b]Condition2 >>] + } +} + +Blueprint AndCond +{ + Condition1 + Condition2 +} + +AndCond[cond1,cond2:out] +{ + If[[cond1]==[cond2]] + { + out <- cond1 + }{ + out <- [[Build[AndCond()]]Condition1 <<[[cond1]Strip Addref]]Condition2 <<[[cond2]Strip Addref] + } +} + +Make Op@AndCond[cond,func:out] +{ + out <- ["("]Append[[[ [[cond]Condition1 >>]Make Op[func] ]Append[" && "]]Append[[ [[cond]Condition2 >>]Make Op[func] ]Append[")"]]] +} + +Strip Addref@AndCond[op:out] +{ + out <- op +} + +=@AndCond[a,b(AndCond):out] +{ + ,out <- If[[[a]Condition1 >>] == [[b]Condition1 >>]] + { + out <- [[a]Condition2 >>] == [[b]Condition2 >>] + } +} + +Blueprint Field Ref +{ + Variable + Field +} + +Field Ref[var,field:out] +{ + out <- [[Build[Field Ref()]]Variable <<[var]]Field <<[field] +} + +Get Type@Field Ref[ref,func:out] +{ + out <- [func]Get Field Type[[[ref]Variable >>]Get Type[func], [ref]Field >>] +} + +Make Op@Field Ref[ref,func:out] +{ + out <- [func]Field Result[[ref]Variable >>,[ref]Field >>] +} + +Strip Addref@Field Ref[op:out] +{ + out <- op +} + +=@Field Ref[a,b(Field Ref):out] +{ + ,out <- If[[[a]Variable >>]==[[b]Variable >>]] + { + out <- [[a]Field >>]=[[b]Field >>] + } +} + +Blueprint Type Instance +{ + Name + Params + Variant + Mutable? +} + +Type Instance[raw name:out] +{ + If[[raw name]=[""]] + { + name <- "Any Type" + }{ + name <- raw name + } + out <- [[[[Build[Type Instance()]]Name <<[name]]Params <<[()]]Variant <<["Boxed"]]Mutable? <<[No] +} + +Set Variant@Type Instance[type,variant:out,invalid] +{ + [("Boxed","Naked","Pointer","Raw Pointer")]Find[=[variant,?]] + { + out <- [type]Variant <<[variant] + }{ + invalid <- type + } +} + +=@Type Instance[type,compare:out] +{ + If[[Blueprint Of[compare]] = [Type Instance()]] + { + //TODO: Compare parameters + ,out <- If[[[type]Name >>] = [[compare]Name >>]] + { out <- [[type]Variant >>] = [[compare]Variant >>] } + }{ + out <- [[type]Name >>] = [compare] + } +} + +String@Type Instance[type:out] +{ + typestr <- [[[[type]Name >> + ]Append["("] + ]Append[ [[type]Params >>]Join[", "] ] + ]Append[")"] + If[[type]Mutable? >>] + { + out <- [[ [["("]Append[typestr]]Append[", "] ]Append[[type]Variant >>]]Append[", Mutable)"] + }{ + If[[[type]Variant >>] = ["Boxed"]] + { + out <- Val[typestr] + }{ + out <- [[ [["("]Append[typestr]]Append[", "] ]Append[[type]Variant >>]]Append[", Mutable)"] + } + } +} + +Blueprint Worker Literal +{ + Name + Args +} + +Worker Literal[name:out] +{ + out <- [[Build[Worker Literal()]]Name <<[name]]Args <<[()] +} + +Set Input@Worker Literal[worker,argnum,val:out] +{ + out <- [worker]Args <<[ [[worker]Args >>]Set[argnum, val] ] +} + diff -r 24c6f8767190 -r c6ba9fe45910 backendutils_c.rhope --- a/backendutils_c.rhope Wed Jul 27 21:14:23 2011 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,526 +0,0 @@ - -Escape Rhope Name[name,p:out] -{ - escaped <- [name]Replace[p, - ("UN_","AT_","SP_","CN_","QN_","PL_","MN_","TM_","DV_","LT_","GT_","LP_","RP_","NT_","EQ_","PR_", - "DP_","TB_","CM_","PD_","NL_","LC_","RC_", "LS_", "RS_", "HS_", "BS_", "CR_", "SC_", "AM_", "PI_", "PC_", "CT_", "BT_", "TD_")] - - [("char","int","short","long","float","double","void","struct")]Find[=[escaped, ?]] - { - out <- ["ID_"]Append[escaped] - }{ - out <- Val[escaped] - } -} - -Blueprint Make Op Res -{ - Func - Val -} - -Make Op Res[func,val:out] -{ - out <- [[Build[Make Op Res()]]Func <<[func]]Val <<[val] -} - -Make Op Mod[func,val:out func,out val] -{ - nval <- [val]Make Op[func] - If[[Blueprint Of[nval]]=[Make Op Res()]] - { - out func <- Func >>[nval] - out val <- Val >>[nval] - }{ - out func <- func - out val <- Val[nval] - } -} - -Blueprint AddRef -{ - Value -} - -AddRef[value:out] -{ - out <- [Build[AddRef()]]Value <<[value] -} - -Make Op@AddRef[addref,func:out] -{ - out <- [func]Make AddRef Op[[addref]Value >>] -} - -Strip Addref@AddRef[op:out] -{ - out <- [[op]Value >>]Strip Addref -} - -=@AddRef[a,b(AddRef):out] -{ - out <- [[a]Value >>]==[[b]Value >>] -} - -Make Op@String[string,func:out] -{ - out <- [func]Resolve[string] -} - -Strip Addref@String[op:out] -{ - out <- op -} - -Get Type@String[op,func:out] -{ - out <- [func]Get Var Type[op] -} - -Make Op@String Cat[string,func:out] -{ - out <- [func]Resolve[string] -} - -Strip Addref@String Cat[op:out] -{ - out <- op -} - -Get Type@String Cat[op,func:out] -{ - out <- [func]Get Var Type[op] -} - -Make Op@String Slice[string,func:out] -{ - out <- [func]Resolve[string] -} - -Strip Addref@String Slice[op:out] -{ - out <- op -} - -Get Type@String Slice[op,func:out] -{ - out <- [func]Get Var Type[op] -} - -Blueprint Output -{ - Name -} - -Output[name:out] -{ - out <- [Build[Output()]]Name <<[name] -} - -Make Op@Output[op,func:out] -{ - out <- [func]Resolve Output[[op]Name >>] -} - -Strip Addref@Output[op:out] -{ - out <- op -} - -=@Output[a,b(Output):out] -{ - out <- [[a]Name >>]=[[b]Name >>] -} - - -Blueprint Constant -{ - Value - Need Addref -} - -Constant[var:out] -{ - out <- [[Build[Constant()]]Value <<[var]]Need Addref <<[Yes] -} - -Make Op@Constant[const,func:out] -{ - out <- [func]Lookup Constant[[const]Value >>, [const]Need Addref >>] -} - -Get Type@Constant[const,func:out] -{ - out <- [func]Get Constant Type[const] -} - -Strip Addref@Constant[op:out] -{ - out <- [op]Need Addref <<[No] -} - -=@Constant[a,b(Constant):out] -{ - out <- [[a]Value >>]=[[b]Value >>] -} - -Blueprint Result -{ - Output Num -} - -Result[num:out] -{ - out <- [Build[Result()]]Output Num <<[num] -} - -Make Op@Result[result,func:out] -{ - out <- [func]Result Reference[[result]Output Num>>] -} - -Strip Addref@Result[op:out] -{ - out <- op -} - -=@Result[a,b(Result):out] -{ - out <- [[a]Output Num >>]=[[b]Output Num >>] -} - -Blueprint Global Get -{ - Store - Var -} - -Global Get[store,var:out] -{ - out <- [[Build[Global Get()]]Store <<[store]]Var <<[var] -} - -Make Op@Global Get[get,func:out] -{ - out <- [func]Global Reference[[get]Store >>, [get]Var >>] -} - -Strip Addref@Global Get[get:out] -{ - out <- get -} - -=@Global Get[a,b(Global Get):out] -{ - ,out <- If[[[a]Store >>]=[[b]Store >>]] - { - out <- [[a]Var >>]=[[b]Var >>] - } -} - -Blueprint Check Result -{ - Output Num -} - -Check Result[num:out] -{ - out <- [Build[Check Result()]]Output Num <<[num] -} - -Make Op@Check Result[result,func:out] -{ - out <- [func]Checked Result Reference[[result]Output Num>>] -} - -Strip Addref@Check Result[op:out] -{ - out <- op -} - -Make Condition[op:out] -{ - If[[Blueprint Of[op]]=[OrValue()]] - { - out <- OrCond[Make Condition[[op]Left >>], Make Condition[[op]Right >>]] - }{ - out <- op - } -} - -=@Check Result[a,b(Check Result):out] -{ - out <- [[a]Output Num >>]=[[b]Output Num >>] -} - -Blueprint OrValue -{ - Left - Right -} - -OrValue[left,right:out] -{ - If[[left]==[right]] - { - out <- left - }{ - out <- [[Build[OrValue()]]Left <<[left]]Right <<[right] - } -} - -Make Op@OrValue[orval,func:out] -{ - out <- [func]If Null Else[[orval]Left >>, [orval]Right >>] -} - -Strip Addref@OrValue[op:out] -{ - out <- [[op]Left <<[ [[op]Left >>]Strip Addref ]]Right <<[ [[op]Right >>]Strip Addref ] -} - -=@OrValue[a,b(OrValue):out] -{ - ,out <- If[[[a]Left >>]==[[b]Left >>]] - { - out <- [[a]Right >>]==[[b]Right >>] - } -} - -Blueprint Cast -{ - Value - Type -} - -Cast[val,type:out] -{ - out <- [[Build[Cast()]]Value <<[val]]Type <<[type] -} - -Make Op@Cast[cast,func:out] -{ - out <- [func]Cast Value[[cast]Value >>, [cast]Type >>] -} - -Strip Addref@Cast[op:out] -{ - out <- [op]Value <<[[[op]Value >>]Strip Addref] -} - -=@Cast[a,b(Cast):out] -{ - ,out <- If[[[a]Value >>] == [[b]Value >>]] - { - out <- [[a]Type >>]=[[b]Type >>] - } -} - -Blueprint NotCond -{ - Condition -} - -NotCond[cond:out] -{ - If[[Blueprint Of[cond]]=[NotCond()]] - { - out <- [cond]Condition >> - }{ - out <- [Build[NotCond()]]Condition <<[[cond]Strip Addref] - } -} - -Make Op@NotCond[cond,func:out] -{ - out <- ["!"]Append[[[cond]Condition >>]Make Op[func]] -} - -Strip Addref@NotCond[op:out] -{ - out <- op -} - -=@NotCond[a,b(NotCond):out] -{ - out <- [[a]Condition >>]==[[b]Condition >>] -} - -Blueprint OrCond -{ - Condition1 - Condition2 -} - -OrCond[cond1,cond2:out] -{ - If[[cond1]==[cond2]] - { - out <- cond1 - }{ - out <- [[Build[OrCond()]]Condition1 <<[[cond1]Strip Addref]]Condition2 <<[[cond2]Strip Addref] - } -} - -Make Op@OrCond[cond,func:out] -{ - out <- ["("]Append[[[ [[cond]Condition1 >>]Make Op[func] ]Append[" || "]]Append[[ [[cond]Condition2 >>]Make Op[func] ]Append[")"]]] -} - -Strip Addref@OrCond[op:out] -{ - out <- op -} - -=@OrCond[a,b(OrCond):out] -{ - ,out <- If[[[a]Condition1 >>] == [[b]Condition1 >>]] - { - out <- [[a]Condition2 >>] == [[b]Condition2 >>] - } -} - -Blueprint AndCond -{ - Condition1 - Condition2 -} - -AndCond[cond1,cond2:out] -{ - If[[cond1]==[cond2]] - { - out <- cond1 - }{ - out <- [[Build[AndCond()]]Condition1 <<[[cond1]Strip Addref]]Condition2 <<[[cond2]Strip Addref] - } -} - -Make Op@AndCond[cond,func:out] -{ - out <- ["("]Append[[[ [[cond]Condition1 >>]Make Op[func] ]Append[" && "]]Append[[ [[cond]Condition2 >>]Make Op[func] ]Append[")"]]] -} - -Strip Addref@AndCond[op:out] -{ - out <- op -} - -=@AndCond[a,b(AndCond):out] -{ - ,out <- If[[[a]Condition1 >>] == [[b]Condition1 >>]] - { - out <- [[a]Condition2 >>] == [[b]Condition2 >>] - } -} - -Blueprint Field Ref -{ - Variable - Field -} - -Field Ref[var,field:out] -{ - out <- [[Build[Field Ref()]]Variable <<[var]]Field <<[field] -} - -Get Type@Field Ref[ref,func:out] -{ - out <- [func]Get Field Type[[[ref]Variable >>]Get Type[func], [ref]Field >>] -} - -Make Op@Field Ref[ref,func:out] -{ - out <- [func]Field Result[[ref]Variable >>,[ref]Field >>] -} - -Strip Addref@Field Ref[op:out] -{ - out <- op -} - -=@Field Ref[a,b(Field Ref):out] -{ - ,out <- If[[[a]Variable >>]==[[b]Variable >>]] - { - out <- [[a]Field >>]=[[b]Field >>] - } -} - -Blueprint Type Instance -{ - Name - Params - Variant - Mutable? -} - -Type Instance[raw name:out] -{ - If[[raw name]=[""]] - { - name <- "Any Type" - }{ - name <- raw name - } - out <- [[[[Build[Type Instance()]]Name <<[name]]Params <<[()]]Variant <<["Boxed"]]Mutable? <<[No] -} - -Set Variant@Type Instance[type,variant:out,invalid] -{ - [("Boxed","Naked","Pointer","Raw Pointer")]Find[=[variant,?]] - { - out <- [type]Variant <<[variant] - }{ - invalid <- type - } -} - -=@Type Instance[type,compare:out] -{ - If[[Blueprint Of[compare]] = [Type Instance()]] - { - //TODO: Compare parameters - ,out <- If[[[type]Name >>] = [[compare]Name >>]] - { out <- [[type]Variant >>] = [[compare]Variant >>] } - }{ - out <- [[type]Name >>] = [compare] - } -} - -String@Type Instance[type:out] -{ - typestr <- [[[[type]Name >> - ]Append["("] - ]Append[ [[type]Params >>]Join[", "] ] - ]Append[")"] - If[[type]Mutable? >>] - { - out <- [[ [["("]Append[typestr]]Append[", "] ]Append[[type]Variant >>]]Append[", Mutable)"] - }{ - If[[[type]Variant >>] = ["Boxed"]] - { - out <- Val[typestr] - }{ - out <- [[ [["("]Append[typestr]]Append[", "] ]Append[[type]Variant >>]]Append[", Mutable)"] - } - } -} - -Blueprint Worker Literal -{ - Name - Args -} - -Worker Literal[name:out] -{ - out <- [[Build[Worker Literal()]]Name <<[name]]Args <<[()] -} - -Set Input@Worker Literal[worker,argnum,val:out] -{ - out <- [worker]Args <<[ [[worker]Args >>]Set[argnum, val] ] -} - diff -r 24c6f8767190 -r c6ba9fe45910 cbackend.rhope --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/cbackend.rhope Wed Jul 27 21:28:43 2011 -0700 @@ -0,0 +1,1728 @@ +Import backendutils.rhope + +Blueprint C Method Registry +{ + Lookup + Next ID +} + +C Method Registry[:out] +{ + builtins <- [[[[[[[[[[[[[Dictionary[] + ]Set["+", "METHOD_ADD"] + ]Set["-", "METHOD_SUB"] + ]Set["/", "METHOD_DIV"] + ]Set["*", "METHOD_MUL"] + ]Set["LShift", "METHOD_LSHIFT"] + ]Set["RShift", "METHOD_RSHIFT"] + ]Set["=", "METHOD_EQUALS"] + ]Set[">", "METHOD_GREATER"] + ]Set["<", "METHOD_LESS"] + ]Set["If", "METHOD_IF"] + ]Set["Set Missing Field", "METHOD_SETFIELDMISSING"] + ]Set["Get Missing Field", "METHOD_GETFIELDMISSING"] + ]Set["Missing Method", "METHOD_MISSING"] + out <- [[Build[C Method Registry()]]Lookup <<[builtins]]Next ID<<[0] + +} + +Register Method@C Method Registry[reg,method:out] +{ + [[reg]Lookup >>]Index[method] + { + out <- reg + }{ + method ID <- [reg]Next ID>> + new lookup <- [[reg]Lookup >>]Set[method, ["METHOD_FIRST_USER+"]Append[String[method ID]]] + out <- [[reg]Lookup <<[new lookup]]Next ID <<[[method ID]+[1]] + } +} + +Method ID@C Method Registry[reg,method:out,notfound] +{ + out,notfound <- [[reg]Lookup >>]Index[method] +} + +Blueprint C Field Registry +{ + Lookup + Next ID +} + +C Field Registry[:out] +{ + out <- [[Build[C Field Registry()]]Lookup <<[Dictionary[]]]Next ID<<[1] + +} + +Register Field@C Field Registry[reg,field:out] +{ + [[reg]Lookup >>]Index[field] + { + out <- reg + }{ + field ID <- [reg]Next ID>> + new lookup <- [[reg]Lookup >>]Set[field, field ID] + out <- [[reg]Lookup <<[new lookup]]Next ID <<[[field ID]+[1]] + } +} + +Field ID@C Field Registry[reg,field:out,notfound] +{ + out,notfound <- [[reg]Lookup >>]Index[field] +} + +Blueprint C Type +{ + Name + Fields + Methods + Init + Copy + Cleanup + +} + +C Type[name:out] +{ + out <- [[[[[[Build[C Type()]]Name <<[name]]Fields <<[()]]Methods <<[()]]Init <<["NULL"]]Copy <<["NULL"]]Cleanup <<["NULL"] +} + +Add Field@C Type[ctype,name,type:out] +{ + out <- [ctype]Fields <<[ [[ctype]Fields >>]Append[ [[()]Append[name]]Append[type] ] ] +} + +Add Method@C Type[ctype,name:out] +{ + out <- [ctype]Methods <<[ [[ctype]Methods >>]Append[name] ] +} + +Register Methods@C Type[ctype,method reg:out] +{ + out <- Fold[Register Method[?], method reg, [ctype]Methods >>] +} + +_Register Field C[reg,field:out] +{ + name <- [field]Index[0] + out <- [reg]Register Field[name] +} + +Register Fields@C Type[ctype,field reg:out] +{ + out <- Fold[_Register Field C[?], field reg, [ctype]Fields >>] +} + +Rhope Type to C[type,p:out,array] +{ + If[[Blueprint Of[type]]=[Type Instance()]] + { + variant <- [type]Variant >> + If[[[type]Name >>] = ["Array"]] + { + [("Naked","Raw Pointer")]Find[=[variant,?]] + { + /* + //Below code assumes that paramaterized types are implemented + pre param <- [[type]Params >>]Index[0] {} + { pre param <- Type Instance["Any Type"] } + [[type]Params >>]Index[1] + { param,param <- [pre param]Set Variant[~] } + { param <- Val[pre param] } + child type <- Rhope Type to C[param] + If[[variant] = ["Naked"]] + { + out <- Val[child type] + array <- "[1]" + }{ + out <- [child type]Append[" *"] + array <- "" + } */ + out <- "void *" + array <- "" + }{ + typename <- "Array" + } + primitive <- No + }{ + ,regulartype <- [("Naked","Raw Pointer")]Find[=[variant,?]] + { + [("Int64","Int32","Int16","Int8")]Find[=[[type]Name >>,?]] + { + primitive <- Yes + [[type]Name >>]Slice[3] {} + { typename <- [["int"]Append[~]]Append["_t"] } + }{ + [("UInt64","UInt32","UInt16","UInt8")]Find[=[[type]Name >>,?]] + { + primitive <- Yes + [[type]Name >>]Slice[4] {} + { typename <- [["uint"]Append[~]]Append["_t"] } + }{ + ,regulartype <- If[[[type]Name >>]=["Context"]] + { + typename <- "context *" + primitive <- Yes + } + } + } + } + + Val[regulartype] + { + typename <- [type]Name >> + primitive <- No + } + } + }{ + typename <- type + param <- "Any Type" + variant <- "boxed" + primitive <- No + } + + Val[typename] + { array <- "" } + If[[typename] = ["Any Type"]] + { + out <- "struct object *" + }{ + [("Naked","Raw Pointer")]Find[=[variant,?]] + { + If[primitive] + { + prefix <- "" + }{ + prefix <- "nt_" + } + }{ + prefix <- "t_" + } + + If[[variant]=["Naked"]] + { + postfix <- "" + }{ + postfix <- " *" + } + } + If[primitive] + { + escaped <- Val[typename] + }{ + escaped <- Escape Rhope Name[typename,p] + } + out <- [[prefix]Append[escaped]]Append[postfix] +} + +_Type Def C Type[text,field,p:out] +{ + name <- [field]Index[0] + ,postfix <- Rhope Type to C[[field]Index[1],p] + { type <- ["\n\t"]Append[~] } + + out <- [[[[text]Append[type]]Append[" "]]Append[[Escape Rhope Name[name,p]]Append[postfix]]]Append[";"] +} + +Type Def@C Type[ctype,p:out] +{ + If[[[[ctype]Fields >>]Length] = [1]] + { + out <- [[[[_Type Def C Type["typedef struct {\n\tobject _SP_header;\n\t", [[ctype]Fields >>]Index[0], p]]Append["\n} t_"]]Append[Escape Rhope Name[[ctype]Name >>,p]]]Append[";"] + ]Append[ + [[[["typedef " + ]Append[Rhope Type to C[ [[[ctype]Fields >>]Index[0]]Index[1],p ]] + ]Append[" nt_"] + ]Append[Escape Rhope Name[[ctype]Name >>,p]] + ]Append[";"] ] + }{ + //HACK!!! + If[[[ctype]Name >>]=["Blueprint"]] + { + out <- "" + }{ + [("Array","Boxed Array","Worker")]Find[=[[ctype]Name >>,?]] + { oend <- "\nMObject(" } + { oend <- "\nObject(" } + out <- [Fold[_Type Def C Type[?,?,p], "OBegin", [ctype]Fields >>]]Append[ [[oend]Append[Escape Rhope Name[[ctype]Name >>,p]]]Append[")"] ] + } + } +} + +_Global Type Defs C[text,store,p:out] +{ + estore <- Escape Rhope Name[[store]Name >>, p] + varnames <- Map[Keys[[store]Vars >>], Escape Rhope Name[?, p]] + out <- [text]Append[ + [[[[[[[[["typedef struct {\n\tobject header;\n\t" + ]Append[ [[ Map[varnames, ["object * gs_"]Append[?]] ]Join[";\n\t"] + ]Append[";\n} mutt_"]] + ]Append[estore] + ]Append[[[";\nmutable_object * gs_"]Append[estore]]Append[";\n\n"]] + ]Append[[["void gscopy_"]Append[estore]]Append[[["(object * obj)\n{\n\tmutt_"]Append[estore]]Append[[[" *mutt_obj = (mutt_"]Append[estore]]Append[" *)obj;\n\t"]]]] + ]Append[ [Map[varnames, ["add_ref(mutt_obj->gs_"]Append[?]]]Join[");\n\t"] ] + ]Append[");\n}\n\n"] + ]Append[[["void gscleanup_"]Append[estore]]Append[[["(object * obj)\n{\n\tmutt_"]Append[estore]]Append[[[" *mutt_obj = (mutt_"]Append[estore]]Append[" *)obj;\n\t"]]]] + ]Append[ [Map[varnames, ["release_ref(mutt_obj->gs_"]Append[?]]]Join[");\n\t"] ] + ]Append[");\n}\n\n"] ] +} + +_Global Type Inits C[text,store,p:out] +{ + estore <- Escape Rhope Name[[store]Name >>, p] + out <- [text]Append[ [[[[[[[[["\tbp = register_type(sizeof(mutt_"]Append[estore]]Append[ [[[")-sizeof(object), NULL, gscopy_"]Append[estore]]Append[", gscleanup_"]]Append[estore] ]]Append[");\n\tgs_"]]Append[estore]]Append[" = (mutable_object *)new_object(TYPE_MUTABLEGLOBAL);\n\tgs_"]]Append[estore]]Append["->data = new_object_bp(bp);\n\tgs_"]]Append[estore]]Append["->version = 0;"] ] +} + +_Type Init C[type name,method reg,text,method,p:out] +{ + out <- [[text]Append[[["\n\tadd_method(bp, "]Append[ [method reg]Method ID[method] ]]Append[ [[", MethodName("]Append[Escape Rhope Name[method,p]]]Append[[","]Append[Escape Rhope Name[type name,p]]]]]]Append["));"] +} + +_Type Init C Field[type name,field reg,text,field,p:out] +{ + fname <- [field]Index[0] + out <- [[[[text]Append[[["\n\tadd_getter(bp, "]Append[ String[[field reg]Field ID[fname]] ]]Append[ [[", MethodName("]Append[Escape Rhope Name[[fname]Append[" >>"],p]]]Append[[","]Append[Escape Rhope Name[type name,p]]]]]]Append["));"] + ]Append[[["\n\tadd_setter(bp, "]Append[ String[[field reg]Field ID[fname]] ]]Append[ [[", MethodName("]Append[Escape Rhope Name[[fname]Append[" <<"],p]]]Append[[","]Append[Escape Rhope Name[type name,p]]]]]]Append["));"] +} + +Type Init@C Type[ctype,id,method reg,field reg,p:out] +{ + [("Array","Boxed Array", "Worker")]Find[=[[ctype]Name >>, ?]] + { size <- "-1" } + { + [("Int64","Int32","Int16","Int8")]Find[=[[ctype]Name >>, ?]] + { + [[ctype]Name >>]Slice[3] {} + { typename <- [["int"]Append[~]]Append["_t"] } + }{ + [("UInt64","UInt32","UInt16","UInt8")]Find[=[[ctype]Name >>, ?]] + { + [[ctype]Name >>]Slice[4] {} + { typename <- [["uint"]Append[~]]Append["_t"] } + }{ + If[[[ctype]Name >>]=["Blueprint"]] + { typename <- "blueprint *" } + { + If[[[ctype]Name >>]=["Boolean"]] + { typename <- "int32_t" } + { typename <- ["nt_"]Append[Escape Rhope Name[[ctype]Name >>,p]] } + } + } + } + size <- [["sizeof("]Append[typename]]Append[")"] + } + start <- [["\tbp = register_type_byid(" + ]Append[id] + ]Append[ + [[", "]Append[size] + ]Append[ + [", (special_func)"]Append[ + [ + [[[[Escape Rhope Name[[ctype]Init >>,p] + ]Append[", (special_func)"] + ]Append[Escape Rhope Name[[ctype]Copy >> ,p]] + ]Append[", (special_func)"] + ]Append[Escape Rhope Name[[ctype]Cleanup >>,p]] + ]Append[");"]]] ] + out <- Val[start]//Fold[[["_Type Init C Field"]Set Input[0, [ctype]Name >>]]Set Input[1, field reg], Fold[[["_Type Init C"]Set Input[0, [ctype]Name >>]]Set Input[1, method reg], start, [ctype]Methods >>], [ctype]Fields >>] +} + +Blueprint C Type Registry +{ + Lookup + Definitions + Next ID + Escape Pattern +} + +C Type Registry[p:out] +{ + out <- [[[[Build[C Type Registry()]]Lookup << [ + [[[[[[[[[[[[[[[[[[[Dictionary[] + ]Set["UInt8", "TYPE_UINT8"] //1 + ]Set["UInt16", "TYPE_UINT16"] //2 + ]Set["UInt32", "TYPE_UINT32"] //3 + ]Set["UInt64", "TYPE_UINT64"] //4 + ]Set["Int8", "TYPE_INT8"] //5 + ]Set["Int16", "TYPE_INT16"] //6 + ]Set["Int32", "TYPE_INT32"] //7 + ]Set["Int64", "TYPE_INT64"] //8 + ]Set["Boolean", "TYPE_BOOLEAN"] //9 + ]Set["Float32", "TYPE_FLOAT32"] //10 + ]Set["Float64", "TYPE_FLOAT64"] //11 + ]Set["Real Number", "TYPE_FLOAT64"] + ]Set["Blueprint", "TYPE_BLUEPRINT"] //12 + ]Set["Array", "TYPE_ARRAY"] //13 + ]Set["Boxed Array", "TYPE_BOXEDARRAY"]//14 + ]Set["Worker", "TYPE_WORKER"] //15 + ]Set["Method Missing Exception", "TYPE_METHODMISSINGEXCEPTION"] //16 + ]Set["Field Missing Exception", "TYPE_FIELDMISSINGEXCEPTION"] //17 + ]Set["Wrong Type Exception", "TYPE_WRONGTYPEEXCEPTION"]] //18 + ]Definitions << [Dictionary[]] + ]Next ID <<[0] + ]Escape Pattern <<[p] +} + +_Type Defs C[text,def,p:out] +{ + out <- [[text]Append[[def]Type Def[p]]]Append["\n\n"] +} + +Type Defs@C Type Registry[reg:out] +{ + out <- Fold[_Type Defs C[?,?,[reg]Escape Pattern >>], "", [reg]Definitions >>] +} + +_Type Inits C[reg,method reg,field reg,text,def,name:out] +{ + out <- [[text]Append[ [def]Type Init[[reg]Type ID[name], method reg, field reg,[reg]Escape Pattern >>] ]]Append["\n\n"] +} + +Type Inits@C Type Registry[reg,method reg,field reg:out] +{ + out <- Fold[_Type Inits C[reg, method reg, field reg, ?], "", [reg]Definitions >>] +} + +Register Type@C Type Registry[reg,def:out] +{ + name <- [def]Name >> + [[reg]Lookup >>]Index[name] + { + [[reg]Definitions >>]Index[name] + { + out <- reg + }{ + out <- [reg]Definitions <<[[[reg]Definitions >>]Set[name, def]] + } + }{ + out <- [[[reg]Lookup <<[ [[reg]Lookup >>]Set[name, ["TYPE_FIRST_USER+"]Append[String[[reg]Next ID >>]]] ] + ]Definitions <<[ [[reg]Definitions >>]Set[name, def] ] + ]Next ID <<[ [[reg]Next ID >>]+[1] ] + } +} + +Type ID@C Type Registry[reg,name:out,notfound] +{ + out <- [[reg]Lookup >>]Index[name] {} + { + ,notfound <- If[[name]=["Any Type"]] + { out <- "0" } + } +} + +Simple Type?@C Type Registry[reg,name:yep,nope,notfound] +{ + ,notfound <- [[reg]Definitions >>]Index[name] + { + yep,nope <- If[[[[~]Fields >>]Length] = [1]] + } +} + +Defined?@C Type Registry[reg,name:yep,nope] +{ + yep,nope <- [[reg]Definitions >>]Index[name] +} + +Blueprint C Function +{ + Name + Inputs + Outputs + Convention + Variables + Statements + Method Registry + Field Registry + Type Registry + Constants + Input Types + Output Types + Uses + Resume Index + Last NumParams + Escape Pattern +} + +C Function[name,inputs,outputs,convention,p:out] +{ + out <- C Function With Registry[name,inputs,outputs,convention, C Method Registry[], C Field Registry[], C Type Registry[p],p] +} + +C Function With Registry[name,inputs,outputs,convention,registry,field reg,type reg,p:out] +{ + out <- [[[[[[[[[[[[[[[[Build[C Function()] + ]Name <<[name] + ]Inputs <<[inputs] + ]Outputs <<[outputs] + ]Convention <<[convention] + ]Variables <<[Dictionary[]] + ]Statements <<[()] + ]Method Registry <<[registry] + ]Field Registry <<[field reg] + ]Type Registry <<[type reg] + ]Constants <<[Dictionary[]] + ]Input Types <<[ Fold[Append[?, "Any Type"], (), inputs] ] + ]Output Types <<[ Fold[Append[?, "Any Type"], (), outputs] ] + ]Resume Index <<[1] + ]Last NumParams <<[-1] + ]Escape Pattern <<[p] + ]Uses <<[()] +} + +Set Input Type@C Function[func,type,input num:out] +{ + out <- [func]Input Types <<[ [[func]Input Types >>]Set[input num, type] ] +} + +Set Output Type@C Function[func,type,output num:out] +{ + out <- [func]Output Types <<[ [[func]Output Types >>]Set[output num, type] ] +} + +Register Constant@C Function[func,name,constant:out] +{ + out <- [func]Constants <<[ [[func]Constants >>]Set[name, constant] ] +} + +Allocate Var@C Function[func,name,type:out] +{ + out <- [func]Variables <<[ [[func]Variables >>]Set[name,type] ] +} + +Add Statement@C Function[func,statement:out] +{ + out <- [func]Statements <<[ [[func]Statements >>]Append[["\t"]Append[[statement]Append[";\n"]]] ] +} + +Add Raw Line@C Function[func,line:out] +{ + out <- [func]Statements <<[ [[func]Statements >>]Append[["\t"]Append[[line]Append["\n"]]] ] +} + +Add Operator Statement@C Function[func,psource1,psource2,pdest,op:out] +{ + source1 <- [psource1]Make Op[func] + source2 <- [psource2]Make Op[func] + dest <- [pdest]Make Op[func] + out <- [func]Add Statement[[[[[dest]Append[" = "]]Append[source1]]Append[op]]Append[source2]] +} + +Make AddRef Op@C Function[func,val:out] +{ + out <- [["add_ref((object *)"]Append[ [val]Make Op[func] ]]Append[")"] +} + +Cast Value@C Function[func,op,type:out] +{ + tname <- Rhope Type to C[type, [func]Escape Pattern >>] + out <- [[[["(("]Append[tname]]Append[")"]]Append[Make Op[op, func]]]Append[")"] +} + +Add@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," + "] +} + +Sub@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," - "] +} + +Multiply@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," * "] +} + +Divide@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," / "] +} + +DoLShift@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," << "] +} + +DoRShift@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," >> "] +} + +BitAnd@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," & "] +} + +BitOr@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," | "] +} + +CompLess@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," < "] +} + +CompGreater@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," > "] +} + +CompEqual@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," == "] +} + +CompLessEqual@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," <= "] +} + +CompGreaterEqual@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," >= "] +} + +CompNotEqual@C Function[func,source1,source2,dest:out] +{ + out <- [func]Add Operator Statement[source1,source2,dest," != "] +} + +Move@C Function[func,psource,pdest:out] +{ + source <- [psource]Make Op[func] + dest <- [pdest]Make Op[func] + out <- [func]Add Statement[[[dest]Append[" = "]]Append[source]] +} + + + + + +Do AddRef@C Function[func,psource,pdest:out] +{ + source <- [psource]Make Op[func] + dest <- [pdest]Make Op[func] + out <- [func]Add Statement[[[[dest]Append[" = add_ref((object *)"]]Append[source]]Append[")"]] +} + +AddRef No Dest@C Function[func,psource:out] +{ + source <- [psource]Make Op[func] + out <- [func]Add Statement[[["add_ref((object *)"]Append[source]]Append[")"]] +} + +Release@C Function[func,psource:out] +{ + source <- [psource]Make Op[func] + out <- [func]Add Statement[[["release_ref((object *)"]Append[source]]Append[")"]] +} + +Set Null@C Function[func,pdest:out] +{ + dest <- [pdest]Make Op[func] + out <- [func]Add Statement[[dest]Append[" = NULL"]] +} + +Lookup Constant@C Function[func,const,doaddref:out] +{ + var <- ["_const_"]Append[Escape Rhope Name[const,[func]Escape Pattern >>]] + If[doaddref] + { + out <- [["add_ref("]Append[var]]Append[")"] + }{ + out <- Val[var] + } +} + +Field Result@C Function[func,var,field:out] +{ + as op <- [var]Make Op[func] + [(String(),String Cat(),String Slice())]Find[=[Blueprint Of[var],?]] + { + [[func]Inputs >>]Find[=[var,?]] + { + type <- [[func]Input Types >>]Index[~] + + }{ + type <- [[func]Variables >>]Index[var] {} + { + [[func]Outputs >>]Find[=[var,?]] + { + type <- [[func]Output Types >>]Index[~] + }{ + //Does it make sense for us to do this? + type <- Type Instance["Any Type"] + } + } + } + }{ + type <- Type Instance["Any Type"] + } + If[[[func]Convention >>] = ["rhope"]] + { + If[[type] = ["Any Type"]] + { + rvar <- Val[as op] + }{ + rvar <- [[[["(("]Append[ Rhope Type to C[type,[func]Escape Pattern >>] ]]Append[")("]]Append[as op]]Append["))"] + } + }{ + rvar <- Val[as op] + } + + [[func]Type Registry >>]Simple Type?[[type]Name >>] + { access <- "->" } + { access <- "->payload." } + { + //TODO: Generate some kind of error/exception in this case + access <- "->" + } + out <- [[rvar]Append[access]]Append[Escape Rhope Name[field,[func]Escape Pattern >>]] +} + +Read Field@C Function[func,var,field:out,result op] +{ + out <- func + result op <- Field Ref[var,field] +} + +Write Field@C Function[func,var,field:out,result op] +{ + out <- func + result op <- Field Ref[var,field] +} + +Global Reference@C Function[func,store,var:out] +{ + + estore <- Escape Rhope Name[store,[func]Escape Pattern >>] + out <- [[[[[ [["((mutt_"]Append[estore]]Append["*)lv_"]]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append["->gs_"]]Append[estore]]Append["->local_data)->gs_"]]Append[Escape Rhope Name[var,[func]Escape Pattern >>]] +} + +Set Global@C Function[func,store,var,src:out] +{ + estore <- Escape Rhope Name[store,[func]Escape Pattern >>] + cell pointer <- [[["lv_"]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append["->gs_"]]Append[estore] + out <- [[[[func]Add Statement[[["tmp = copy_object("]Append[[cell pointer]Append["->local_data"]]]Append[")"]] + ]Add Statement[ [[[["((mutt_"]Append[estore]]Append[" *)tmp)->gs_"]]Append[Escape Rhope Name[var, [func]Escape Pattern >>]]]Append[[" = "]Append[[src]Make Op[func]]] ] + ]Add Statement[[cell pointer]Append["->local_data = tmp"]] + ]Add Statement[[cell pointer]Append["->local_version++"]] +} + +Set Field Null@C Function[func,var,field:out] +{ + out <- [func]Add Statement[ [[func]Field Result[var,field]]Append[" = NULL"] ] +} + +Copy@C Function[func,pdest:out] +{ + dest <- [pdest]Make Op[func] + out <- [func]Add Statement[ [dest]Append[[[" = copy_object("]Append[dest]]Append[")"]] ] +} + +Box@C Function[func,psource,pdest,type:out] +{ + dest <- [pdest]Make Op[func] + source <- [psource]Make Op[func] + out <- [func]Add Statement[ + [[[[[dest + ]Append[" = naked_to_boxed("] + ]Append[ [[func]Type Registry >>]Type ID[[type]Name >>] ] + ]Append[", &"] + ]Append[source] + ]Append[")"] ] +} + +Unbox@C Function[func,psource,pdest:out] +{ + dest <- [pdest]Make Op[func] + source <- [psource]Make Op[func] + out <- [func]Add Statement[ + [[[["boxed_to_naked(" + ]Append[source] + ]Append[", &"] + ]Append[dest] + ]Append[")"] ] +} + +Get Raw Pointer@C Function[func,psource,pdest:out] +{ + dest <- [pdest]Make Op[func] + source <- [psource]Make Op[func] + out <- [func]Add Statement[ [[[dest]Append[" = (void*)("]]Append[source]]Append[" + 1)"] ] +} + +Array Raw Pointer@C Function[func,psource,pdest:out] +{ + dest <- [pdest]Make Op[func] + source <- [psource]Make Op[func] + out <- [func]Add Statement[ [[[dest]Append[" = ((char *)"]]Append[source]]Append[")+ sizeof(t_Array)"] ] +} + +_Function Arg C[func,val,inputnum:out] +{ + out <- [func]Add Raw Line[ + [[[["SetParam(" + ]Append[String[inputnum]] + ]Append[", "] + ]Append[val] + ]Append[")"] + ] +} + +_Val Function Arg C[func,val,inputnum,worker:out] +{ + out <- [func]Add Raw Line[ + [[[[[["VCSetParam(" + ]Append[worker] + ]Append[", "] + ]Append[String[inputnum]] + ]Append[", "] + ]Append[val] + ]Append[")"] + ] +} + +Method Call@C Function[func,method,args:out] +{ + out <- [func]Call[method,args] +} + +Val Call@C Function[func,to call,args:out] +{ + worker <- Make Op[Strip Addref[to call], func] + rargs <- Map[args, Make Op[?, func]] + + If[[[[func]Variables >>]Length]+[[[func]Outputs >>]Length]] + { + valcall <- "ValCall(" + postlude <- "ValCallPostlude(" + }{ + valcall <- "ValCallNoLocals(" + postlude <- "ValCallNoLocalsPostlude(" + } + + If[[[func]Last NumParams >>] = [-1]] + { + prepped <- [[func]Add Raw Line[ + [[[["VCPrepCall(" + ]Append[worker] + ]Append[", "] + ]Append[String[[rargs]Length]] + ]Append[")"] ] + ]Last NumParams <<[[rargs]Length] + }{ + prepped <- [[func]Add Raw Line[ + [[[[[["VCRePrepCall(" + ]Append[worker] + ]Append[", "] + ]Append[String[[rargs]Length]] + ]Append[", "] + ]Append[String[[func]Last NumParams >>]] + ]Append[")"] ] + ]Last NumParams <<[[rargs]Length] + } + + + out <- [[[[Fold[_Val Function Arg C[?, ?, ?, worker], prepped, rargs] + ]Add Raw Line[ + [[[[[[[[valcall + ]Append[worker] + ]Append[", "] + ]Append[String[[rargs]Length]] + ]Append[", "] + ]Append[String[[func]Resume Index >>]] + ]Append[", "] + ]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]] + ]Append[")"]] + ]Add Raw Line["DISPATCH"] + ]Add Raw Line[ + [[[[postlude + ]Append[String[[func]Resume Index >>]] + ]Append[", "] + ]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]] + ]Append[")"]] + ]Resume Index <<[ [[func]Resume Index >>]+[1] ] +} + +Call@C Function[func,name,args:out] +{ + If[[name]=["Call@Worker"]] + { + //TODO: Handle case when user explicitly calls the fully qualified version, but the type of the first arg isn't Worker + out <- [func]Val Call[[args]Index[0], Tail[args,1]] + }{ + If[[name]=["Call"]] + { + to call <- [args]Index[0] + last numparams <- [func]Last NumParams >> + out <- [[[[[[[func]Add Raw Line[[["if (get_blueprint("]Append[Make Op[Strip Addref[to call], func]]]Append[")->type_id == TYPE_WORKER) {"]] + ]Val Call[to call, Tail[args,1]] + ]Add Raw Line["} else {"] + ]Last NumParams <<[last numparams] + ]Func Base["Call",args, "Call"] + ]Add Raw Line["}"] + ]Last NumParams <<[[Length[args]]-[1]] + }{ + out <- [func]Func Base[Escape Rhope Name[name,[func]Escape Pattern >>],args, "Call"] + } + } +} + +Func Base@C Function[func,tocall,args,rtype:out] +{ + Print[ [[func]Name >>]Append[ [": Func Base("]Append[tocall] ] ] + rargs <- Map[args, Make Op[?, func]] + + If[[[[func]Variables >>]Length]+[[[func]Outputs >>]Length]] + { type <- Val[rtype] } + { type <- [rtype]Append["NoLocals"] } + + If[[[rargs]Length] > [[func]Last NumParams >>]] + { + If[[[func]Last NumParams >>] = [-1]] + { + freed <- Val[func] + }{ + freed <- [func]Add Raw Line["FreeCall"] + } + prepped <- [[freed]Add Raw Line[ [["PrepCall("]Append[String[[rargs]Length]]]Append[")"] ] + ]Last NumParams <<[[rargs]Length] + }{ + prepped <- Val[func] + } + + + out <- [[Fold[_Function Arg C[?], prepped, rargs] + ]Add Raw Line[ + [[[[[[[[[type]Append["("] + ]Append[tocall] + ]Append[", "] + ]Append[String[[rargs]Length]] + ]Append[", "] + ]Append[String[[func]Resume Index >>]] + ]Append[", "] + ]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]] + ]Append[")"]] + ]Resume Index <<[ [[func]Resume Index >>]+[1] ] +} + +Call Foreign@C Function[func,name,language,args,store result:out] +{ + rargs <- Map[args, Make Op[?, func]] + //Assume language = "C" for now + base <- [[[name]Append["("]]Append[ Join[rargs, ", "] ]]Append[")"] + ,do store <- [(String(), String Slice(), String Cat())]Find[=[Blueprint Of[store result], ?]] + { + ,do store <- If[[store result]=[""]] + { stmt <- Val[base] } + } + + Val[do store] + { stmt <- [[Make Op[store result, func]]Append[" = "]]Append[base] } + out <- [func]Add Statement[stmt] +} + +Get Field Call@C Function[func,field,source:out] +{ + out <- [func]Func Base[Escape Rhope Name[[field]Append[" >>"],[func]Escape Pattern >>], [()]Append[source], "Call"] +} + +Set Field Call@C Function[func,field,object,value:out] +{ + out <- [func]Func Base[Escape Rhope Name[[field]Append[" <<"],[func]Escape Pattern >>], [[()]Append[object]]Append[value], "Call"] +} + +Tail Method Call@C Function[func,method,args:out] +{ + out <- [func]Func Base[[[func]Method Registry >>]Method ID[method],args, "TMCall"] +} + +Tail Call@C Function[func,name,args:out] +{ + out <- [func]Func Base[Escape Rhope Name[name,[func]Escape Pattern >>],args, "TCall"] +} + +Resolve@C Function[func,op:out] +{ + If[[[func]Convention >>] = ["rhope"]] + { + [[func]Inputs >>]Find[=[op,?]] + { + out <- [["my_cdata->params["]Append[String[~]]]Append[" ]"] + }{ + out <- [[["lv_"]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append["->"]]Append[Escape Rhope Name[op,[func]Escape Pattern >>]] + } + }{ + out <- Escape Rhope Name[op,[func]Escape Pattern >>] + } +} + +Resolve Output@C Function[func,name:out] +{ + If[[[func]Convention >>] = ["rhope"]] + { + out <- [[["lv_"]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append["->"]]Append[Escape Rhope Name[name,[func]Escape Pattern >>]] + }{ + out <- Escape Rhope Name[name,[func]Escape Pattern >>] + } +} + +Instruction Stream@C Function[func:out] +{ + out <- [func]Statements <<[()] +} + +_If C[func, statement:out] +{ + out <- [func]Statements <<[ [[func]Statements >>]Append[ ["\t"]Append[statement] ] ] +} + +Do If@C Function[func,condition,stream:out] +{ + cond <- [condition]Make Op[func] + after statements <- Fold[_If C[?], [[func + ]Add Raw Line[ [["if("]Append[cond]]Append[")"] ] + ]Add Raw Line["{"], [stream]Statements >>] + + + If[[[[func]Last NumParams >>]=[-1]]And[[[stream]Last NumParams >>]>[-1]]] + { + after free <- [after statements]Add Raw Line["FreeCall"] + }{ + after free <- Val[after statements] + } + out <- [[[after free]Add Raw Line["}"] + ]Resume Index <<[[stream]Resume Index >>] + ]Variables <<[ Combine[[after free]Variables >>, [stream]Variables >>]] +} + +Discard Outputs@C Function[func,first to discard:out] +{ + out <- [[[[[func + ]Add Raw Line[[["for(idx = "]Append[String[first to discard]]]Append["; idx < cdata->num_params; ++idx)"]] + ]Add Raw Line["{"] + ]Add Raw Line[" if (cdata->params[idx])"] + ]Add Raw Line[" release_ref(cdata->params[idx]);"] + ]Add Raw Line["}"] +} + +Result Reference@C Function[func,output:out] +{ + out <- [["cdata->params["]Append[String[output]]]Append["]"] +} + +Checked Result Reference@C Function[func,output:out] +{ + out <- [[[["("]Append[String[output]]]Append[" < cdata->num_params ? cdata->params["]]Append[String[output]]]Append["] : NULL)"] +} + + +If Null Else@C Function[func,left,right:out] +{ + check <- [[Make Condition[left]]Strip Addref]Make Op[func] + l <- [left]Make Op[func] + r <- [right]Make Op[func] + out <- [[[[[["(" + ]Append[check] + ]Append[" ? "] + ]Append[l] + ]Append[" : "] + ]Append[r] + ]Append[")"] +} + +_Set Outputs C[string,inputname,inputnum,func:out] +{ + out <- [string]Append[[[ [ ["\tRet("]Append[String[inputnum]] ]Append[ [[", lv_"]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append["->"]]]Append[Escape Rhope Name[inputname,[func]Escape Pattern >>]]]Append[")\n"]] +} + +Set Outputs@C Function[func:out] +{ + If[[[func]Convention >>] = ["rhope"]] + { + out <- [[[Fold[_Set Outputs C[?, ?, ?, func], "", [func]Outputs >>]]Append["\tNumRet("]]Append[String[[[func]Outputs >>]Length]]]Append[")\n"] + }{ + [[func]Outputs >>]Index[0] + { + out <- [["\treturn "]Append[Escape Rhope Name[~,[func]Escape Pattern >>]]]Append[";\n"] + }{ + out <- "" + } + } +} +_Output Defs C[string,varname,index,func:out] +{ + out <- [[[string]Append[ ["\t"]Append[Rhope Type to C[[[func]Output Types >>]Index[index],[func]Escape Pattern >>]] ]]Append[[" "]Append[Escape Rhope Name[varname,[func]Escape Pattern >>]]]]Append[";\n"] +} +_Var Defs C[string,type,varname,p:out] +{ + out <- [[[string]Append[ ["\t"]Append[Rhope Type to C[type,p]] ]]Append[[" "]Append[Escape Rhope Name[varname,p]]]]Append[";\n"] +} +_Global Cell Defs C[func,p,string,store:out] +{ + out <- [string]Append[ [["\ttrans_cell *gs_"]Append[Escape Rhope Name[store,p]]]Append[";\n"] ] +} + + +Definitions@C Function[func:out] +{ + Print[["Definitions@C Function: "]Append[[func]Name >>]] + { + If[ [[[func]Convention >>] = ["rhope"]] And [[ [[[func]Variables >>]Length]+[[[func]Outputs >>]Length] ] > [0]] ] + { + localtype <- [[[Fold[_Global Cell Defs C[func,[func]Escape Pattern >>,?], Fold[_Output Defs C[?, ?, ?, func], Fold[_Var Defs C[?,?,?,[func]Escape Pattern >>],"typedef struct {\n", [func]Variables >>], [func]Outputs >>], [func]Uses >>]]Append["} lt_"]]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append[";\n"] + }{ + localtype <- "" + } + + If[ [[func]Convention >>] = ["rhope"] ] + { + /* parts <- [[func]Name >>]Split["@"] + [parts]Index[1] + { + proto <- [[[["MethodDef(" + ]Append[Escape Rhope Name[[parts]Index[0],[func]Escape Pattern >>]] + ]Append[", "] + ]Append[Escape Rhope Name[~,[func]Escape Pattern >>]] + ]Append[")\n"] + }{ + proto <- [["FuncDef("]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append[")\n"] + } */ + out <- Val[localtype] + }{ + out <- [[func]Naked Proto]Append[";\n"] + } + } +} + +_Proto Input[list,input,index,types,p:out] +{ + out <- [list]Append[ [[Rhope Type to C[[types]Index[index],p]]Append[" "]]Append[Escape Rhope Name[input,p]] ] +} + +Naked Proto@C Function[func:out] +{ + [[func]Output Types >>]Index[0] + { + outtype <- [Rhope Type to C[~,[func]Escape Pattern >>]]Append[" "] + }{ + outtype <- "void " + } + out <- [[[[outtype + ]Append[ Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]] + ]Append["("] + ]Append[ [Fold[_Proto Input[?, ?, ?, [func]Input Types >>,[func]Escape Pattern >>], (), [func]Inputs >>]]Join[", "] ] + ]Append[")"] +} + +Type Check@C Function[func,text,type,input num:out] +{ + If[[type] = ["Any Type"]] + { + out <- text + }{ + out <- [text]Append[ [["\tParam("]Append[input num]]Append[ [[", "]Append[ [[func]Type Registry >>]Type ID[type] ]]Append[")"] ] ] + } +} + +Check Param Type C[text,type,input num,func:out] +{ + [(String(),String Cat(),String Slice())]Find[=[Blueprint Of[type],?]] + { + typename <- type + }{ + typename <- [type]Name >> + } + If[[typename] = ["Any Type"]] + { + out <- text + }{ + out <- [text]Append[[[["\tParam("]Append[String[input num]]]Append[ [","]Append[ [[func]Type Registry >>]Type ID[typename] ] ]]Append[")\n"]] + } +} + +Find Trans Cell@C Function[func,text,store:out] +{ + estore <- Escape Rhope Name[store,[func]Escape Pattern >>] + out <- [text]Append[ [[[["lv_"]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append["->gs_"]]Append[estore]]Append[[[" = find_obj_cell(ct->transaction, gs_"]Append[estore]]Append[");\n"]] ] +} + +Text@C Function[func:out] +{ + Print[["Text@C Function: "]Append[[func]Name >>]] + If[ [[func]Convention >>] = ["rhope"] ] + { + before <- [[func]Name >>]Partition["@"] {} {} + { + type <- "MethodImpl" + cname <- [[[[Escape Rhope Name[before,[func]Escape Pattern >>] + ]Append[", "] + ]Append[Escape Rhope Name[~,[func]Escape Pattern >>]] + ]Append[", "] + ]Append[ [[func]Type Registry >>]Type ID[~] ] + }{ + type <- "Func" + cname <- Val[fname] + } + fname <- Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>] + param check <- Fold[Check Param Type C[?, ?, ?, func], "", [func]Input Types >>] + If[[[func]Last NumParams >>] = [-1]] + { + freecall <- "" + }{ + freecall <- "\n\tFreeCall\n" + } + If[ [ [[[[func]Variables >>]Length]+[[[func]Outputs >>]Length]]+[[[func]Uses >>]Length] ] = [0] ] + { + out <- [[[[[[[[[ [type]Append["NoLocals("] + ]Append[cname] + ]Append[",\n\tNumParams "] + ]Append[ String[[[func]Inputs >>]Length] ] + ]Append[")\n\n"] + ]Append[param check] + ]Append[ [[func]Statements >>]Join[""] ] + ]Append[freecall] + ]Append["EndFuncNoLocals\n"] + ]Append["DISPATCH"] + }{ + If[[[func]Uses >>]Length] + { + begin trans <- [[[["\tbegin_transaction(ct, "]Append[ String[[[func]Uses >>]Length] ]]Append[", "]]Append[ [Map[Map[[func]Uses >>, Escape Rhope Name[?, [func]Escape Pattern >>]], ["gs_"]Append[?]]]Join[", "] ]]Append[");\n"] + init trans <- [[Fold[Find Trans Cell[func,?], begin trans, [func]Uses >>] + ]Append[[["transretry_"]Append[fname]]Append[":\n"]] + ]Append["\tfor(idx = 0; idx < cdata->num_params; ++idx) { add_ref(cdata->params[idx]); }\n"] + //TODO: Figure out whether this is a readonly or write transaction + commit trans <- [[["\tif(!commit_transaction(ct, 0)) { prep_retry(ct); goto transretry_"]Append[fname]]Append["; }\n"] + ]Append["\tfor(idx = 0; idx < cdata->num_params; ++idx) { release_ref(cdata->params[idx]); }\n"] + }{ + init trans <- "" + commit trans <- "" + } + out <- [[[[[[[[[[[[ [type]Append["("] + ]Append[cname] + ]Append[",\n\tNumParams "] + ]Append[ String[[[func]Inputs >>]Length] ] + ]Append[")\n\n"] + ]Append[param check] + ]Append[init trans] + ]Append[ [[func]Statements >>]Join[""] ] + ]Append[freecall] + ]Append[commit trans] + ]Append[[func]Set Outputs] + ]Append[[["EndFunc("]Append[fname]]Append[")\n"]] + ]Append["DISPATCH"] + } + }{ + + out <- [[[ + Fold[_Output Defs C[?, ?, ?, func], + Fold[_Var Defs C[?], [[func]Naked Proto]Append["\n{"], [func]Variables >>], [func]Outputs >>] + ]Append[[[func]Statements >>]Join[""]] + ]Append[[func]Set Outputs] + ]Append["}"] + } +} + +Blueprint C Program +{ + Functions + Method Registry + Field Registry + Type Registry + Libraries + Global Stores + Escape Pattern +} + +C Program[:out] +{ + p <- Pattern[("_", "@", " ", ":", "?", "+", "-", "*", "/", "<", ">", "(", ")", "!", "=", "'", + "\"", "\t", ",", ".", "\n", "{", "}", "[", "]", "#", "\\", "\r", ";", "&", "|", "%", "^", "`", "~")] + out <- [[[[[[[Build[C Program()]]Functions <<[Dictionary[]]]Method Registry <<[C Method Registry[]]]Type Registry <<[C Type Registry[p]]]Field Registry <<[C Field Registry[]]]Libraries <<[Dictionary[]]]Escape Pattern <<[p]]Global Stores <<[Dictionary[]] +} + +Supported Number Types@C Program[program:out] +{ + out <- ("Int8","Int16","Int32","Int64","UInt8","UInt16","UInt32","UInt64") +} + +Needed Specials@C Program[program,typename,makespecial:out] +{ + init name <- [" init "]Append[typename] + with init <- [()]Append[ [[()]Append[init name]]Append[[makespecial]Index["init"]] ] + [("Array","Boxed Array","Worker")]Find[=[?,typename]] + { + out <- Val[with init] + }{ + copy name <- [" copy "]Append[typename] + cleanup name <- [" cleanup "]Append[typename] + out <- [[with init]Append[ [[()]Append[copy name]]Append[[makespecial]Index["copy"]] ] + ]Append[ [[()]Append[cleanup name]]Append[[makespecial]Index["cleanup"]] ] + } +} + +Set Stdlib Imports@C Program[program,parser:out] +{ + out <- [parser]Imports <<[ [[parser]Imports >>]Set["kernel.rhope", Yes] ] +} + +Link@C Program[program,language,library:out] +{ + If[[library] = ["runtime"]] + { + out <- program + }{ + langlibs <- [[program]Libraries >>]Index[language] {} + { langlibs <- Dictionary[] } + out <- [program]Libraries <<[ [[program]Libraries >>]Set[language, [langlibs]Set[library, Yes]] ] + } +} + +Register Type@C Program[program,def:out] +{ + out <- [[[program]Type Registry <<[ [[program]Type Registry >>]Register Type[def] ] + ]Method Registry <<[ [def]Register Methods[[program]Method Registry >>] ] + ]Field Registry <<[ [def]Register Fields[[program]Field Registry >>] ] +} + +Create Type@C Program[program,name:out] +{ + out <- C Type[name] +} + +Create Function@C Program[program,name,inputs,outputs,convention:out] +{ + out <- C Function With Registry[name,inputs,outputs,convention, [program]Method Registry >>, [program]Field Registry >>, [program]Type Registry >>, [program]Escape Pattern >>] +} + +Store Function@C Program[program,func:out] +{ + out <- [program]Functions <<[ [[program]Functions >>]Set[ [func]Name >>, func] ] +} + +Method?@C Program[program,funcname:is,isnot] +{ + is,isnot <- [[program]Method Registry >>]Method ID[funcname] +} + +_Defs C Program[text,func:out] +{ + def <- [func]Definitions + If[[def]=[""]] + { + out <- text + }{ + out <- [text]Append[[def]Append["\n\n"]] + } +} + +_Text C Program[text,func,type reg:out] +{ + out <- [text]Append[[[ [func]Type Registry <<[type reg] ]Text]Append["\n\n"]] +} + +Combine Consts[consts,func:out] +{ + out <- Combine[[func]Constants >>, consts] +} + +_Consts C Program[text,value,name,p:out] +{ + out <- [text]Append[ [["object * _const_"]Append[Escape Rhope Name[name,p]]]Append[";\n"] ] +} + +_Consts C Release[text,value,name,p:out] +{ + out <- [text]Append[ [["\trelease_ref(_const_"]Append[Escape Rhope Name[name,p]]]Append[");\n"] ] +} + +_List Literal El[text,val,index,type reg:out] +{ + out <- [[[[text + ]Append[", "] + ]Append[index] + ]Append[", "] + ]Append[Const Construct C[val, type reg]] +} + +Const Construct C[value,type reg:out] +{ + valtype <- Blueprint Of[value] + [(Int8(),UInt8(),Int16(),UInt16(),Int32(),UInt32(),Int64(),UInt64())]Find[=[valtype,?]] + { + size <- [("8","16","32","64")]Index[[~]/[2]] + If[[~]Mod[2]] + { s <- "UI" } + { s <- "I" } + + out <- [[[[[["make_" + ]Append[s] + ]Append["nt"] + ]Append[size] + ]Append["("] + ]Append[String[value]] + ]Append[")"] + }{ + If[[valtype] = [Type Instance()]] + { + //TODO: Support parametric types + typeid <- [type reg]Type ID[[value]Name >>] + + out <- [["make_Blueprint("]Append[typeid]]Append[")"] + }{ + If[[valtype] = [Boolean()]] + { + If[value] + { + out <- "make_Bool(1)" + }{ + out <- "make_Bool(0)" + } + }{ + + [(String(),String Slice(),String Cat())]Find[=[valtype,?]] + { + out <- [["make_String(\""]Append[ [[[[value]Replace["\\", "\\\\"]]Replace["\n", "\\n"]]Replace["\"", "\\\""]]Replace["\r", "\\r"] ]]Append["\")"] + }{ + If[[valtype]=[Worker Literal()]] + { + //TODO: Figure out how to fully support these in nested cases + //or workaround the problem higher up in the food chain + [[value]Args >>]Last + { size <- String[[~]+[1]] } + { size <- "0" } + out <- [[[[[["make_Worker(FUNC_" + ]Append[Escape Rhope Name[[value]Name >>,[type reg]Escape Pattern >>]] + ]Append[", "] + ]Append[size] + ]Append[", "] + ]Append[String[Fold[+[1,?], 0, [value]Args >>]]] + ]Append[")"] + }{ + [(List(), List Leaf())]Find[=[?,valtype]] + { + out <- [Fold[_List Literal El[?, ?, ?, type reg], ["make_List("]Append[String[[value]Length]], value]]Append[")"] + }{ + out <- "UnhandledLiteralType" + } + } + } + } + } + + } +} + +_Set Worker Params C[text,param,num,type reg,name:out] +{ + out <- [text]Append[ + [[[[[["\t((object **)(((t_Worker *)_const_" + ]Append[name] + ]Append[")+1))["] + ]Append[String[num]] + ]Append["] = "] + ]Append[Const Construct C[param, type reg]] + ]Append[";\n"] ] +} + +_Set Consts C Program[text,value,name,type reg:out] +{ + valtype <- Blueprint Of[value] + [(String(),String Cat(),String Slice(),Worker Literal(),List(),List Leaf())]Find[=[valtype,?]] + { + out <- text + }{ + Const Construct C[value,type reg] + { out <- [text]Append[ [[[["\t_const_"]Append[Escape Rhope Name[name,[type reg]Escape Pattern >>]]]Append[" = "]]Append[~]]Append[";\n"] ] } + } +} + +_Set List Els C[text,el,index,type reg:out] +{ + out <- [[text]Append[ + [["\tinout[1] = " + ]Append[Const Construct C[index,type reg]] + ]Append[ + [[";\n\tinout[2] = " + ]Append[Const Construct C[el, type reg]] + ]Append[";\n"] + ]]]Append["\trhope(FUNC_Set, inout, 3, 3);\n"] +} + +_Set Late Consts C[text,value,name,type reg:out] +{ + valtype <- Blueprint Of[value] + [(String(),String Cat(),String Slice(),Worker Literal(),List(),List Leaf())]Find[=[valtype,?]] + { + If[[~]>[3]] + { + out <- [Fold[_Set List Els C[?, ?, ?, type reg], [text]Append["\trhope(FUNC_List, inout, 0, 1);\n"], value] + ]Append[[["\t_const_"]Append[Escape Rhope Name[name,[type reg]Escape Pattern >>]]]Append[" = inout[0];\n"]] + }{ + Const Construct C[value,type reg] + { init <- [text]Append[ [[[["\t_const_"]Append[Escape Rhope Name[name,[type reg]Escape Pattern >>]]]Append[" = "]]Append[~]]Append[";\n"] ] } + + If[[valtype]=[Worker Literal()]] + { + out <- Fold[_Set Worker Params C[?, ?, ?, type reg, Escape Rhope Name[name,[type reg]Escape Pattern >>]], init, [value]Args >>] + }{ + out <- Val[init] + } + } + }{ + out <- text + } +} + +_Global Var Init C[text,value,name,storevar,type reg:out] +{ + out <- [[[[[text]Append[storevar]]Append[Escape Rhope Name[name, [type reg]Escape Pattern >>]]]Append[" = "]]Append[Const Construct C[value, type reg]]]Append[";\n"] +} + +_Global Store Inits C[text,store,type reg:out] +{ + estore <- Escape Rhope Name[[store]Name >>, [type reg]Escape Pattern >>] + out <- Fold[_Global Var Init C[?,?,?, [[[["\t((mutt_"]Append[estore]]Append[" *)(gs_"]]Append[estore]]Append["->data))->gs_"], type reg], text, [store]Vars >>] +} + +_Dispatch Switch Sub[text, num, name:out] +{ + out <- [[[[[text + ]Append["\tResumeEntry("] + ]Append[String[num]] + ]Append[","] + ]Append[name] + ]Append[")\\\n"] +} + +_Dispatch Switch[text,func,raw name:out] +{ + If[[[func]Convention >>] = ["rhope"]] + { + name <- Escape Rhope Name[raw name,[func]Escape Pattern >>] + out <- [[text]Append[ [["\tDispatchEntry("]Append[name]]Append[")\\\n"] ] + ]Append[Fold[_Dispatch Switch Sub[?, ?, name], "", Range[1, [func]Resume Index >>]]] + }{ + out <- text + } +} + +_Dispatch Switch Methods[p,text,id,raw name:out] +{ + name <- Escape Rhope Name[raw name,p] + out <- [text]Append[ [["\tDispatchEntry("]Append[name]]Append[")\\\n"] ] +} + +_Dispatch Enum Sub[text, num, name:out] +{ + out <- [[[[[text + ]Append["\tRES_"] + ]Append[String[num]] + ]Append["_"] + ]Append[name] + ]Append[",\n"] +} + +_Dispatch Enum[text,func,raw name:out] +{ + If[[[func]Convention >>] = ["rhope"]] + { + name <- Escape Rhope Name[raw name,[func]Escape Pattern >>] + out <- [[text]Append[ [["\tFUNC_"]Append[name]]Append[",\n"] ] + ]Append[Fold[_Dispatch Enum Sub[?, ?, name], "", Range[1, [func]Resume Index >>]]] + }{ + out <- text + } +} + +_Dispatch Enum Methods[p,text,types,name:out] +{ + out <- [text]Append[ [["\tFUNC_"]Append[Escape Rhope Name[name,p]]]Append[",\n"] ] +} + +Dispatch@C Program[program,all methods:out] +{ + out <- [[[[["typedef enum {\n" + ]Append[Fold[_Dispatch Enum[?], + [Fold[_Dispatch Enum Methods[[program]Escape Pattern >>,?], "", all methods]]Append["\tFUNC_Build,\n\tFUNC_BlueprintSP_Of,\n\tFUNC_ID,\n\tFUNC_BlueprintSP_FromSP_ID,\n\tFUNC_Pause,\n\tRES_1_Pause,\n\tFUNC_Resume,\n\tFUNC_RunSP_Bytecode,\n\tRES_1_RunSP_Bytecode,\n"], + [program]Functions >>]] + ]Append["\tEND,\n\tEND_THREAD\n} funcids;\n\n"] + ]Append["#define DispatchEntries \\\n"] + ]Append[Fold[_Dispatch Switch[?], + [Fold[_Dispatch Switch Methods[[program]Escape Pattern >>,?], "", all methods]]Append["\tDispatchEntry(Build)\\\n\tDispatchEntry(BlueprintSP_Of)\\\n\tDispatchEntry(ID)\\\n\tDispatchEntry(BlueprintSP_FromSP_ID)\\\n\tDispatchEntry(Pause)\\\n\tResumeEntry(1,Pause)\\\n\tDispatchEntry(Resume)\\\n\tDispatchEntry(RunSP_Bytecode)\\\n\tResumeEntry(1,RunSP_Bytecode)\\\n"], + [program]Functions >>]] + ]Append["\tEndEntry\\\n\tEndThreadEntry\n\n"] +} + +Not Native[func:out] +{ + If[[[func]Convention >>] = ["rhope"]] + { out <- No } + { out <- Yes } +} + +Native[func:out] +{ + out <- [[func]Convention >>] = ["rhope"] +} + +Local Pointers[text,func:out] +{ + If[ [ [[[func]Variables >>]Length]+[[[func]Outputs >>]Length] ] = [0] ] + { + out <- text + }{ + out <- [text]Append[[["\tFuncDef("]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append[")\n"]] + } +} + +_Method to Types[dict,name,type:out] +{ + typelist <- [dict]Index[name] {} + { typelist <- () } + + out <- [dict]Set[name, [typelist]Append[[type]Name >>]] + +} + +_Field to Types[dict,field,type:out] +{ + name <- [field]Index[0] + out <- _Method to Types[_Method to Types[dict, [name]Append[" >>"], type], [name]Append[" <<"], type] + +} + +Method to Types[dict,type:out] +{ + out <- Fold[_Method to Types[?, ?, type], dict, [type]Methods >>] +} + +Field to Types[dict,type:out] +{ + out <- Fold[_Field to Types[?, ?, type], dict, [type]Fields >>] +} + +_Method Dispatch[text, type, method, reg: out] +{ + out <- [[[[[[[text]Append["\tMethodDispatch("]]Append[ [reg]Type ID[type] ]]Append[","]]Append[Escape Rhope Name[method,[reg]Escape Pattern >>]]]Append[","]]Append[Escape Rhope Name[type,[reg]Escape Pattern >>]]]Append[")\n"] +} + +Method Dispatch[text, types, method, reg: out] +{ + out <- [[[Fold[_Method Dispatch[?, ?, method, reg], [[[text]Append["Method("]]Append[ Escape Rhope Name[method,[reg]Escape Pattern >>] ]]Append[")\n"], types] + ]Append["EndMethod("] + ]Append[Escape Rhope Name[method,[reg]Escape Pattern >>]] + ]Append[")\n\n"] +} + +Init Type Names[text,typeid,name,reg:out] +{ + [reg]Defined?[name] + { out <- [text]Append[ [[[["\tregistered_types["]Append[typeid]]Append["]->name = "]]Append[Const Construct C[name, reg]]]Append[";\n"] ] } + { out <- text } +} + +Text Filename@C Program[program,source name:out] +{ + out <- [source name]Append[".c"] +} + +Text@C Program[program:out] +{ + p <- [program]Escape Pattern >> + type defs <- [[program]Type Registry >>]Definitions >> + constants <- Fold[Combine Consts[?], Dictionary[], [program]Functions >>] + all methods <- Fold[Field to Types[?], Fold[Method to Types[?], Dictionary[], type defs], type defs] + headers <- "#include +#include +#include +#include \"builtin.h\" +#include \"object.h\" +#include \"context.h\" +#include \"func.h\" +#include \"integer.h\" +#include \"blueprint.h\" +#include \"array.h\" +#include \"worker.h\" +#include \"bool.h\" +#include \n\n" + out <- [[[[[[[[[[[[[[[[[[[[[headers + ]Append[[program]Dispatch[all methods]] + ]Append[[[program]Type Registry >>]Type Defs] + ]Append[Fold[_Global Type Defs C[?,?,p], "", [program]Global Stores >>]] + ]Append[Fold[_Consts C Program[?,?,?,p], + Fold[_Defs C Program[?], "", [program]Functions >>], + constants]] + ]Append[Fold[_Text C Program[?, ?, [program]Type Registry >>], "", Filter[[program]Functions >>, Not Native[?]]]] + ]Append["\n +#include \"rhopefuncs_prolog.c\"\n"] + ]Append[Fold[Local Pointers[?], "", [program]Functions >>]] + ]Append[" +#include \"localpointers_fragment.c\"\n"] + ]Append[Fold[Method Dispatch[?, ?, ?, [program]Type Registry >>], "", all methods]] + ]Append[" +#include \"builtinworkers.c\"\n"] + ]Append[Fold[_Text C Program[?, ?, [program]Type Registry >>], "", Filter[[program]Functions >>, Native[?]]]] + ]Append[" +#include \"rhopefuncs_epilog.c\" + +#include \"builtin.c\" +#include \"array.c\" +#include \"worker.c\" + +int main(int argc, char **argv) +{ + blueprint * bp; + int numret; + int idx; + object * inout[3]; + register_builtin_types(); + register_type_byid(TYPE_MUTABLEGLOBAL, sizeof(mutable_object)-sizeof(object), NULL, NULL, NULL);\n\n"] + ]Append[ [[program]Type Registry >>]Type Inits[[program]Method Registry >>, [program]Field Registry >>] ] + ]Append[Fold[_Global Type Inits C[?, ?, p], "", [program]Global Stores >>]] + ]Append[Fold[_Set Consts C Program[?, ?, ?, [program]Type Registry >>], "", constants]] + ]Append[Fold[_Set Late Consts C[?, ?, ?, [program]Type Registry >>], "", constants]] + ]Append[Fold[_Global Store Inits C[?, ?, [program]Type Registry >>], "", [program]Global Stores >>]] + ]Append[Fold[Init Type Names[?, ?, ?, [program]Type Registry >>], "", [[program]Type Registry >>]Lookup >>]] + ]Append[" + rhope(FUNC_List, inout, 0, 1); + for (idx = 0; idx < argc; ++idx) + { + inout[1] = make_String(argv[idx]); + rhope(FUNC_Append, inout, 2, 2); + } + numret = rhope(FUNC_Main, inout, 1, 1); +#ifdef ENABLE_LEAK_DETECTION\n"] + ]Append[Fold[_Consts C Release[?, ?, ?, p], "", constants]] + ]Append[ + " + print_mem_info(manager); + print_live_object_types(manager); +#endif //ENABLE_LEAK_DETECTION + +#ifdef ENABLE_PROFILING + for (idx = 0; idx < END; ++idx) + { + if(profile_counts[idx]) + printf(\"Func: %d\tCount: %llu\tTime: %llu\tAvg: %f\tSelf: %llu\tAvg: %f\tNested Count: %llu\\n\", idx, profile_counts[idx], profile_totals[idx], ((double)profile_totals[idx])/((double)profile_counts[idx]), profile_selftotals[idx], ((double)profile_selftotals[idx])/((double)profile_counts[idx]), profile_nestedcounts[idx]); + } +#endif + if (!numret) + return 0; + if (numret < 0) + return numret; + if (get_blueprint(inout[0])->type_id == TYPE_INT32) + return ((t_Int32 *)inout[0])->Num; + + rhope(FUNC_If, inout, 1, 2); + if (inout[0]) + return 0; + return 1; +}\n\n"] + +} + + diff -r 24c6f8767190 -r c6ba9fe45910 cbackend_c.rhope --- a/cbackend_c.rhope Wed Jul 27 21:14:23 2011 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1727 +0,0 @@ -Import backendutils_c.rhope - -Blueprint C Method Registry -{ - Lookup - Next ID -} - -C Method Registry[:out] -{ - builtins <- [[[[[[[[[[[[[Dictionary[] - ]Set["+", "METHOD_ADD"] - ]Set["-", "METHOD_SUB"] - ]Set["/", "METHOD_DIV"] - ]Set["*", "METHOD_MUL"] - ]Set["LShift", "METHOD_LSHIFT"] - ]Set["RShift", "METHOD_RSHIFT"] - ]Set["=", "METHOD_EQUALS"] - ]Set[">", "METHOD_GREATER"] - ]Set["<", "METHOD_LESS"] - ]Set["If", "METHOD_IF"] - ]Set["Set Missing Field", "METHOD_SETFIELDMISSING"] - ]Set["Get Missing Field", "METHOD_GETFIELDMISSING"] - ]Set["Missing Method", "METHOD_MISSING"] - out <- [[Build[C Method Registry()]]Lookup <<[builtins]]Next ID<<[0] - -} - -Register Method@C Method Registry[reg,method:out] -{ - [[reg]Lookup >>]Index[method] - { - out <- reg - }{ - method ID <- [reg]Next ID>> - new lookup <- [[reg]Lookup >>]Set[method, ["METHOD_FIRST_USER+"]Append[String[method ID]]] - out <- [[reg]Lookup <<[new lookup]]Next ID <<[[method ID]+[1]] - } -} - -Method ID@C Method Registry[reg,method:out,notfound] -{ - out,notfound <- [[reg]Lookup >>]Index[method] -} - -Blueprint C Field Registry -{ - Lookup - Next ID -} - -C Field Registry[:out] -{ - out <- [[Build[C Field Registry()]]Lookup <<[Dictionary[]]]Next ID<<[1] - -} - -Register Field@C Field Registry[reg,field:out] -{ - [[reg]Lookup >>]Index[field] - { - out <- reg - }{ - field ID <- [reg]Next ID>> - new lookup <- [[reg]Lookup >>]Set[field, field ID] - out <- [[reg]Lookup <<[new lookup]]Next ID <<[[field ID]+[1]] - } -} - -Field ID@C Field Registry[reg,field:out,notfound] -{ - out,notfound <- [[reg]Lookup >>]Index[field] -} - -Blueprint C Type -{ - Name - Fields - Methods - Init - Copy - Cleanup - -} - -C Type[name:out] -{ - out <- [[[[[[Build[C Type()]]Name <<[name]]Fields <<[()]]Methods <<[()]]Init <<["NULL"]]Copy <<["NULL"]]Cleanup <<["NULL"] -} - -Add Field@C Type[ctype,name,type:out] -{ - out <- [ctype]Fields <<[ [[ctype]Fields >>]Append[ [[()]Append[name]]Append[type] ] ] -} - -Add Method@C Type[ctype,name:out] -{ - out <- [ctype]Methods <<[ [[ctype]Methods >>]Append[name] ] -} - -Register Methods@C Type[ctype,method reg:out] -{ - out <- Fold[Register Method[?], method reg, [ctype]Methods >>] -} - -_Register Field C[reg,field:out] -{ - name <- [field]Index[0] - out <- [reg]Register Field[name] -} - -Register Fields@C Type[ctype,field reg:out] -{ - out <- Fold[_Register Field C[?], field reg, [ctype]Fields >>] -} - -Rhope Type to C[type,p:out,array] -{ - If[[Blueprint Of[type]]=[Type Instance()]] - { - variant <- [type]Variant >> - If[[[type]Name >>] = ["Array"]] - { - [("Naked","Raw Pointer")]Find[=[variant,?]] - { - /* - //Below code assumes that paramaterized types are implemented - pre param <- [[type]Params >>]Index[0] {} - { pre param <- Type Instance["Any Type"] } - [[type]Params >>]Index[1] - { param,param <- [pre param]Set Variant[~] } - { param <- Val[pre param] } - child type <- Rhope Type to C[param] - If[[variant] = ["Naked"]] - { - out <- Val[child type] - array <- "[1]" - }{ - out <- [child type]Append[" *"] - array <- "" - } */ - out <- "void *" - array <- "" - }{ - typename <- "Array" - } - primitive <- No - }{ - ,regulartype <- [("Naked","Raw Pointer")]Find[=[variant,?]] - { - [("Int64","Int32","Int16","Int8")]Find[=[[type]Name >>,?]] - { - primitive <- Yes - [[type]Name >>]Slice[3] {} - { typename <- [["int"]Append[~]]Append["_t"] } - }{ - [("UInt64","UInt32","UInt16","UInt8")]Find[=[[type]Name >>,?]] - { - primitive <- Yes - [[type]Name >>]Slice[4] {} - { typename <- [["uint"]Append[~]]Append["_t"] } - }{ - ,regulartype <- If[[[type]Name >>]=["Context"]] - { - typename <- "context *" - primitive <- Yes - } - } - } - } - - Val[regulartype] - { - typename <- [type]Name >> - primitive <- No - } - } - }{ - typename <- type - param <- "Any Type" - variant <- "boxed" - primitive <- No - } - - Val[typename] - { array <- "" } - If[[typename] = ["Any Type"]] - { - out <- "struct object *" - }{ - [("Naked","Raw Pointer")]Find[=[variant,?]] - { - If[primitive] - { - prefix <- "" - }{ - prefix <- "nt_" - } - }{ - prefix <- "t_" - } - - If[[variant]=["Naked"]] - { - postfix <- "" - }{ - postfix <- " *" - } - } - If[primitive] - { - escaped <- Val[typename] - }{ - escaped <- Escape Rhope Name[typename,p] - } - out <- [[prefix]Append[escaped]]Append[postfix] -} - -_Type Def C Type[text,field,p:out] -{ - name <- [field]Index[0] - ,postfix <- Rhope Type to C[[field]Index[1],p] - { type <- ["\n\t"]Append[~] } - - out <- [[[[text]Append[type]]Append[" "]]Append[[Escape Rhope Name[name,p]]Append[postfix]]]Append[";"] -} - -Type Def@C Type[ctype,p:out] -{ - If[[[[ctype]Fields >>]Length] = [1]] - { - out <- [[[[_Type Def C Type["typedef struct {\n\tobject _SP_header;\n\t", [[ctype]Fields >>]Index[0], p]]Append["\n} t_"]]Append[Escape Rhope Name[[ctype]Name >>,p]]]Append[";"] - ]Append[ - [[[["typedef " - ]Append[Rhope Type to C[ [[[ctype]Fields >>]Index[0]]Index[1],p ]] - ]Append[" nt_"] - ]Append[Escape Rhope Name[[ctype]Name >>,p]] - ]Append[";"] ] - }{ - //HACK!!! - If[[[ctype]Name >>]=["Blueprint"]] - { - out <- "" - }{ - [("Array","Boxed Array","Worker")]Find[=[[ctype]Name >>,?]] - { oend <- "\nMObject(" } - { oend <- "\nObject(" } - out <- [Fold[_Type Def C Type[?,?,p], "OBegin", [ctype]Fields >>]]Append[ [[oend]Append[Escape Rhope Name[[ctype]Name >>,p]]]Append[")"] ] - } - } -} - -_Global Type Defs C[text,store,p:out] -{ - estore <- Escape Rhope Name[[store]Name >>, p] - varnames <- Map[Keys[[store]Vars >>], Escape Rhope Name[?, p]] - out <- [text]Append[ - [[[[[[[[["typedef struct {\n\tobject header;\n\t" - ]Append[ [[ Map[varnames, ["object * gs_"]Append[?]] ]Join[";\n\t"] - ]Append[";\n} mutt_"]] - ]Append[estore] - ]Append[[[";\nmutable_object * gs_"]Append[estore]]Append[";\n\n"]] - ]Append[[["void gscopy_"]Append[estore]]Append[[["(object * obj)\n{\n\tmutt_"]Append[estore]]Append[[[" *mutt_obj = (mutt_"]Append[estore]]Append[" *)obj;\n\t"]]]] - ]Append[ [Map[varnames, ["add_ref(mutt_obj->gs_"]Append[?]]]Join[");\n\t"] ] - ]Append[");\n}\n\n"] - ]Append[[["void gscleanup_"]Append[estore]]Append[[["(object * obj)\n{\n\tmutt_"]Append[estore]]Append[[[" *mutt_obj = (mutt_"]Append[estore]]Append[" *)obj;\n\t"]]]] - ]Append[ [Map[varnames, ["release_ref(mutt_obj->gs_"]Append[?]]]Join[");\n\t"] ] - ]Append[");\n}\n\n"] ] -} - -_Global Type Inits C[text,store,p:out] -{ - estore <- Escape Rhope Name[[store]Name >>, p] - out <- [text]Append[ [[[[[[[[["\tbp = register_type(sizeof(mutt_"]Append[estore]]Append[ [[[")-sizeof(object), NULL, gscopy_"]Append[estore]]Append[", gscleanup_"]]Append[estore] ]]Append[");\n\tgs_"]]Append[estore]]Append[" = (mutable_object *)new_object(TYPE_MUTABLEGLOBAL);\n\tgs_"]]Append[estore]]Append["->data = new_object_bp(bp);\n\tgs_"]]Append[estore]]Append["->version = 0;"] ] -} - -_Type Init C[type name,method reg,text,method,p:out] -{ - out <- [[text]Append[[["\n\tadd_method(bp, "]Append[ [method reg]Method ID[method] ]]Append[ [[", MethodName("]Append[Escape Rhope Name[method,p]]]Append[[","]Append[Escape Rhope Name[type name,p]]]]]]Append["));"] -} - -_Type Init C Field[type name,field reg,text,field,p:out] -{ - fname <- [field]Index[0] - out <- [[[[text]Append[[["\n\tadd_getter(bp, "]Append[ String[[field reg]Field ID[fname]] ]]Append[ [[", MethodName("]Append[Escape Rhope Name[[fname]Append[" >>"],p]]]Append[[","]Append[Escape Rhope Name[type name,p]]]]]]Append["));"] - ]Append[[["\n\tadd_setter(bp, "]Append[ String[[field reg]Field ID[fname]] ]]Append[ [[", MethodName("]Append[Escape Rhope Name[[fname]Append[" <<"],p]]]Append[[","]Append[Escape Rhope Name[type name,p]]]]]]Append["));"] -} - -Type Init@C Type[ctype,id,method reg,field reg,p:out] -{ - [("Array","Boxed Array", "Worker")]Find[=[[ctype]Name >>, ?]] - { size <- "-1" } - { - [("Int64","Int32","Int16","Int8")]Find[=[[ctype]Name >>, ?]] - { - [[ctype]Name >>]Slice[3] {} - { typename <- [["int"]Append[~]]Append["_t"] } - }{ - [("UInt64","UInt32","UInt16","UInt8")]Find[=[[ctype]Name >>, ?]] - { - [[ctype]Name >>]Slice[4] {} - { typename <- [["uint"]Append[~]]Append["_t"] } - }{ - If[[[ctype]Name >>]=["Blueprint"]] - { typename <- "blueprint *" } - { - If[[[ctype]Name >>]=["Boolean"]] - { typename <- "int32_t" } - { typename <- ["nt_"]Append[Escape Rhope Name[[ctype]Name >>,p]] } - } - } - } - size <- [["sizeof("]Append[typename]]Append[")"] - } - start <- [["\tbp = register_type_byid(" - ]Append[id] - ]Append[ - [[", "]Append[size] - ]Append[ - [", (special_func)"]Append[ - [ - [[[[Escape Rhope Name[[ctype]Init >>,p] - ]Append[", (special_func)"] - ]Append[Escape Rhope Name[[ctype]Copy >> ,p]] - ]Append[", (special_func)"] - ]Append[Escape Rhope Name[[ctype]Cleanup >>,p]] - ]Append[");"]]] ] - out <- Val[start]//Fold[[["_Type Init C Field"]Set Input[0, [ctype]Name >>]]Set Input[1, field reg], Fold[[["_Type Init C"]Set Input[0, [ctype]Name >>]]Set Input[1, method reg], start, [ctype]Methods >>], [ctype]Fields >>] -} - -Blueprint C Type Registry -{ - Lookup - Definitions - Next ID - Escape Pattern -} - -C Type Registry[p:out] -{ - out <- [[[[Build[C Type Registry()]]Lookup << [ - [[[[[[[[[[[[[[[[[[[Dictionary[] - ]Set["UInt8", "TYPE_UINT8"] //1 - ]Set["UInt16", "TYPE_UINT16"] //2 - ]Set["UInt32", "TYPE_UINT32"] //3 - ]Set["UInt64", "TYPE_UINT64"] //4 - ]Set["Int8", "TYPE_INT8"] //5 - ]Set["Int16", "TYPE_INT16"] //6 - ]Set["Int32", "TYPE_INT32"] //7 - ]Set["Int64", "TYPE_INT64"] //8 - ]Set["Boolean", "TYPE_BOOLEAN"] //9 - ]Set["Float32", "TYPE_FLOAT32"] //10 - ]Set["Float64", "TYPE_FLOAT64"] //11 - ]Set["Real Number", "TYPE_FLOAT64"] - ]Set["Blueprint", "TYPE_BLUEPRINT"] //12 - ]Set["Array", "TYPE_ARRAY"] //13 - ]Set["Boxed Array", "TYPE_BOXEDARRAY"]//14 - ]Set["Worker", "TYPE_WORKER"] //15 - ]Set["Method Missing Exception", "TYPE_METHODMISSINGEXCEPTION"] //16 - ]Set["Field Missing Exception", "TYPE_FIELDMISSINGEXCEPTION"] //17 - ]Set["Wrong Type Exception", "TYPE_WRONGTYPEEXCEPTION"]] //18 - ]Definitions << [Dictionary[]] - ]Next ID <<[0] - ]Escape Pattern <<[p] -} - -_Type Defs C[text,def,p:out] -{ - out <- [[text]Append[[def]Type Def[p]]]Append["\n\n"] -} - -Type Defs@C Type Registry[reg:out] -{ - out <- Fold[_Type Defs C[?,?,[reg]Escape Pattern >>], "", [reg]Definitions >>] -} - -_Type Inits C[reg,method reg,field reg,text,def,name:out] -{ - out <- [[text]Append[ [def]Type Init[[reg]Type ID[name], method reg, field reg,[reg]Escape Pattern >>] ]]Append["\n\n"] -} - -Type Inits@C Type Registry[reg,method reg,field reg:out] -{ - out <- Fold[_Type Inits C[reg, method reg, field reg, ?], "", [reg]Definitions >>] -} - -Register Type@C Type Registry[reg,def:out] -{ - name <- [def]Name >> - [[reg]Lookup >>]Index[name] - { - [[reg]Definitions >>]Index[name] - { - out <- reg - }{ - out <- [reg]Definitions <<[[[reg]Definitions >>]Set[name, def]] - } - }{ - out <- [[[reg]Lookup <<[ [[reg]Lookup >>]Set[name, ["TYPE_FIRST_USER+"]Append[String[[reg]Next ID >>]]] ] - ]Definitions <<[ [[reg]Definitions >>]Set[name, def] ] - ]Next ID <<[ [[reg]Next ID >>]+[1] ] - } -} - -Type ID@C Type Registry[reg,name:out,notfound] -{ - out <- [[reg]Lookup >>]Index[name] {} - { - ,notfound <- If[[name]=["Any Type"]] - { out <- "0" } - } -} - -Simple Type?@C Type Registry[reg,name:yep,nope,notfound] -{ - ,notfound <- [[reg]Definitions >>]Index[name] - { - yep,nope <- If[[[[~]Fields >>]Length] = [1]] - } -} - -Defined?@C Type Registry[reg,name:yep,nope] -{ - yep,nope <- [[reg]Definitions >>]Index[name] -} - -Blueprint C Function -{ - Name - Inputs - Outputs - Convention - Variables - Statements - Method Registry - Field Registry - Type Registry - Constants - Input Types - Output Types - Uses - Resume Index - Last NumParams - Escape Pattern -} - -C Function[name,inputs,outputs,convention,p:out] -{ - out <- C Function With Registry[name,inputs,outputs,convention, C Method Registry[], C Field Registry[], C Type Registry[p],p] -} - -C Function With Registry[name,inputs,outputs,convention,registry,field reg,type reg,p:out] -{ - out <- [[[[[[[[[[[[[[[[Build[C Function()] - ]Name <<[name] - ]Inputs <<[inputs] - ]Outputs <<[outputs] - ]Convention <<[convention] - ]Variables <<[Dictionary[]] - ]Statements <<[()] - ]Method Registry <<[registry] - ]Field Registry <<[field reg] - ]Type Registry <<[type reg] - ]Constants <<[Dictionary[]] - ]Input Types <<[ Fold[Append[?, "Any Type"], (), inputs] ] - ]Output Types <<[ Fold[Append[?, "Any Type"], (), outputs] ] - ]Resume Index <<[1] - ]Last NumParams <<[-1] - ]Escape Pattern <<[p] - ]Uses <<[()] -} - -Set Input Type@C Function[func,type,input num:out] -{ - out <- [func]Input Types <<[ [[func]Input Types >>]Set[input num, type] ] -} - -Set Output Type@C Function[func,type,output num:out] -{ - out <- [func]Output Types <<[ [[func]Output Types >>]Set[output num, type] ] -} - -Register Constant@C Function[func,name,constant:out] -{ - out <- [func]Constants <<[ [[func]Constants >>]Set[name, constant] ] -} - -Allocate Var@C Function[func,name,type:out] -{ - out <- [func]Variables <<[ [[func]Variables >>]Set[name,type] ] -} - -Add Statement@C Function[func,statement:out] -{ - out <- [func]Statements <<[ [[func]Statements >>]Append[["\t"]Append[[statement]Append[";\n"]]] ] -} - -Add Raw Line@C Function[func,line:out] -{ - out <- [func]Statements <<[ [[func]Statements >>]Append[["\t"]Append[[line]Append["\n"]]] ] -} - -Add Operator Statement@C Function[func,psource1,psource2,pdest,op:out] -{ - source1 <- [psource1]Make Op[func] - source2 <- [psource2]Make Op[func] - dest <- [pdest]Make Op[func] - out <- [func]Add Statement[[[[[dest]Append[" = "]]Append[source1]]Append[op]]Append[source2]] -} - -Make AddRef Op@C Function[func,val:out] -{ - out <- [["add_ref((object *)"]Append[ [val]Make Op[func] ]]Append[")"] -} - -Cast Value@C Function[func,op,type:out] -{ - tname <- Rhope Type to C[type, [func]Escape Pattern >>] - out <- [[[["(("]Append[tname]]Append[")"]]Append[Make Op[op, func]]]Append[")"] -} - -Add@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," + "] -} - -Sub@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," - "] -} - -Multiply@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," * "] -} - -Divide@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," / "] -} - -DoLShift@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," << "] -} - -DoRShift@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," >> "] -} - -BitAnd@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," & "] -} - -BitOr@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," | "] -} - -CompLess@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," < "] -} - -CompGreater@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," > "] -} - -CompEqual@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," == "] -} - -CompLessEqual@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," <= "] -} - -CompGreaterEqual@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," >= "] -} - -CompNotEqual@C Function[func,source1,source2,dest:out] -{ - out <- [func]Add Operator Statement[source1,source2,dest," != "] -} - -Move@C Function[func,psource,pdest:out] -{ - source <- [psource]Make Op[func] - dest <- [pdest]Make Op[func] - out <- [func]Add Statement[[[dest]Append[" = "]]Append[source]] -} - - - - -Do AddRef@C Function[func,psource,pdest:out] -{ - source <- [psource]Make Op[func] - dest <- [pdest]Make Op[func] - out <- [func]Add Statement[[[[dest]Append[" = add_ref((object *)"]]Append[source]]Append[")"]] -} - -AddRef No Dest@C Function[func,psource:out] -{ - source <- [psource]Make Op[func] - out <- [func]Add Statement[[["add_ref((object *)"]Append[source]]Append[")"]] -} - -Release@C Function[func,psource:out] -{ - source <- [psource]Make Op[func] - out <- [func]Add Statement[[["release_ref((object *)"]Append[source]]Append[")"]] -} - -Set Null@C Function[func,pdest:out] -{ - dest <- [pdest]Make Op[func] - out <- [func]Add Statement[[dest]Append[" = NULL"]] -} - -Lookup Constant@C Function[func,const,doaddref:out] -{ - var <- ["_const_"]Append[Escape Rhope Name[const,[func]Escape Pattern >>]] - If[doaddref] - { - out <- [["add_ref("]Append[var]]Append[")"] - }{ - out <- Val[var] - } -} - -Field Result@C Function[func,var,field:out] -{ - as op <- [var]Make Op[func] - [(String(),String Cat(),String Slice())]Find[=[Blueprint Of[var],?]] - { - [[func]Inputs >>]Find[=[var,?]] - { - type <- [[func]Input Types >>]Index[~] - - }{ - type <- [[func]Variables >>]Index[var] {} - { - [[func]Outputs >>]Find[=[var,?]] - { - type <- [[func]Output Types >>]Index[~] - }{ - //Does it make sense for us to do this? - type <- Type Instance["Any Type"] - } - } - } - }{ - type <- Type Instance["Any Type"] - } - If[[[func]Convention >>] = ["rhope"]] - { - If[[type] = ["Any Type"]] - { - rvar <- Val[as op] - }{ - rvar <- [[[["(("]Append[ Rhope Type to C[type,[func]Escape Pattern >>] ]]Append[")("]]Append[as op]]Append["))"] - } - }{ - rvar <- Val[as op] - } - - [[func]Type Registry >>]Simple Type?[[type]Name >>] - { access <- "->" } - { access <- "->payload." } - { - //TODO: Generate some kind of error/exception in this case - access <- "->" - } - out <- [[rvar]Append[access]]Append[Escape Rhope Name[field,[func]Escape Pattern >>]] -} - -Read Field@C Function[func,var,field:out,result op] -{ - out <- func - result op <- Field Ref[var,field] -} - -Write Field@C Function[func,var,field:out,result op] -{ - out <- func - result op <- Field Ref[var,field] -} - -Global Reference@C Function[func,store,var:out] -{ - - estore <- Escape Rhope Name[store,[func]Escape Pattern >>] - out <- [[[[[ [["((mutt_"]Append[estore]]Append["*)lv_"]]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append["->gs_"]]Append[estore]]Append["->local_data)->gs_"]]Append[Escape Rhope Name[var,[func]Escape Pattern >>]] -} - -Set Global@C Function[func,store,var,src:out] -{ - estore <- Escape Rhope Name[store,[func]Escape Pattern >>] - cell pointer <- [[["lv_"]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append["->gs_"]]Append[estore] - out <- [[[[func]Add Statement[[["tmp = copy_object("]Append[[cell pointer]Append["->local_data"]]]Append[")"]] - ]Add Statement[ [[[["((mutt_"]Append[estore]]Append[" *)tmp)->gs_"]]Append[Escape Rhope Name[var, [func]Escape Pattern >>]]]Append[[" = "]Append[[src]Make Op[func]]] ] - ]Add Statement[[cell pointer]Append["->local_data = tmp"]] - ]Add Statement[[cell pointer]Append["->local_version++"]] -} - -Set Field Null@C Function[func,var,field:out] -{ - out <- [func]Add Statement[ [[func]Field Result[var,field]]Append[" = NULL"] ] -} - -Copy@C Function[func,pdest:out] -{ - dest <- [pdest]Make Op[func] - out <- [func]Add Statement[ [dest]Append[[[" = copy_object("]Append[dest]]Append[")"]] ] -} - -Box@C Function[func,psource,pdest,type:out] -{ - dest <- [pdest]Make Op[func] - source <- [psource]Make Op[func] - out <- [func]Add Statement[ - [[[[[dest - ]Append[" = naked_to_boxed("] - ]Append[ [[func]Type Registry >>]Type ID[[type]Name >>] ] - ]Append[", &"] - ]Append[source] - ]Append[")"] ] -} - -Unbox@C Function[func,psource,pdest:out] -{ - dest <- [pdest]Make Op[func] - source <- [psource]Make Op[func] - out <- [func]Add Statement[ - [[[["boxed_to_naked(" - ]Append[source] - ]Append[", &"] - ]Append[dest] - ]Append[")"] ] -} - -Get Raw Pointer@C Function[func,psource,pdest:out] -{ - dest <- [pdest]Make Op[func] - source <- [psource]Make Op[func] - out <- [func]Add Statement[ [[[dest]Append[" = (void*)("]]Append[source]]Append[" + 1)"] ] -} - -Array Raw Pointer@C Function[func,psource,pdest:out] -{ - dest <- [pdest]Make Op[func] - source <- [psource]Make Op[func] - out <- [func]Add Statement[ [[[dest]Append[" = ((char *)"]]Append[source]]Append[")+ sizeof(t_Array)"] ] -} - -_Function Arg C[func,val,inputnum:out] -{ - out <- [func]Add Raw Line[ - [[[["SetParam(" - ]Append[String[inputnum]] - ]Append[", "] - ]Append[val] - ]Append[")"] - ] -} - -_Val Function Arg C[func,val,inputnum,worker:out] -{ - out <- [func]Add Raw Line[ - [[[[[["VCSetParam(" - ]Append[worker] - ]Append[", "] - ]Append[String[inputnum]] - ]Append[", "] - ]Append[val] - ]Append[")"] - ] -} - -Method Call@C Function[func,method,args:out] -{ - out <- [func]Call[method,args] -} - -Val Call@C Function[func,to call,args:out] -{ - worker <- Make Op[Strip Addref[to call], func] - rargs <- Map[args, Make Op[?, func]] - - If[[[[func]Variables >>]Length]+[[[func]Outputs >>]Length]] - { - valcall <- "ValCall(" - postlude <- "ValCallPostlude(" - }{ - valcall <- "ValCallNoLocals(" - postlude <- "ValCallNoLocalsPostlude(" - } - - If[[[func]Last NumParams >>] = [-1]] - { - prepped <- [[func]Add Raw Line[ - [[[["VCPrepCall(" - ]Append[worker] - ]Append[", "] - ]Append[String[[rargs]Length]] - ]Append[")"] ] - ]Last NumParams <<[[rargs]Length] - }{ - prepped <- [[func]Add Raw Line[ - [[[[[["VCRePrepCall(" - ]Append[worker] - ]Append[", "] - ]Append[String[[rargs]Length]] - ]Append[", "] - ]Append[String[[func]Last NumParams >>]] - ]Append[")"] ] - ]Last NumParams <<[[rargs]Length] - } - - - out <- [[[[Fold[_Val Function Arg C[?, ?, ?, worker], prepped, rargs] - ]Add Raw Line[ - [[[[[[[[valcall - ]Append[worker] - ]Append[", "] - ]Append[String[[rargs]Length]] - ]Append[", "] - ]Append[String[[func]Resume Index >>]] - ]Append[", "] - ]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]] - ]Append[")"]] - ]Add Raw Line["DISPATCH"] - ]Add Raw Line[ - [[[[postlude - ]Append[String[[func]Resume Index >>]] - ]Append[", "] - ]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]] - ]Append[")"]] - ]Resume Index <<[ [[func]Resume Index >>]+[1] ] -} - -Call@C Function[func,name,args:out] -{ - If[[name]=["Call@Worker"]] - { - //TODO: Handle case when user explicitly calls the fully qualified version, but the type of the first arg isn't Worker - out <- [func]Val Call[[args]Index[0], Tail[args,1]] - }{ - If[[name]=["Call"]] - { - to call <- [args]Index[0] - last numparams <- [func]Last NumParams >> - out <- [[[[[[[func]Add Raw Line[[["if (get_blueprint("]Append[Make Op[Strip Addref[to call], func]]]Append[")->type_id == TYPE_WORKER) {"]] - ]Val Call[to call, Tail[args,1]] - ]Add Raw Line["} else {"] - ]Last NumParams <<[last numparams] - ]Func Base["Call",args, "Call"] - ]Add Raw Line["}"] - ]Last NumParams <<[[Length[args]]-[1]] - }{ - out <- [func]Func Base[Escape Rhope Name[name,[func]Escape Pattern >>],args, "Call"] - } - } -} - -Func Base@C Function[func,tocall,args,rtype:out] -{ - Print[ [[func]Name >>]Append[ [": Func Base("]Append[tocall] ] ] - rargs <- Map[args, Make Op[?, func]] - - If[[[[func]Variables >>]Length]+[[[func]Outputs >>]Length]] - { type <- Val[rtype] } - { type <- [rtype]Append["NoLocals"] } - - If[[[rargs]Length] > [[func]Last NumParams >>]] - { - If[[[func]Last NumParams >>] = [-1]] - { - freed <- Val[func] - }{ - freed <- [func]Add Raw Line["FreeCall"] - } - prepped <- [[freed]Add Raw Line[ [["PrepCall("]Append[String[[rargs]Length]]]Append[")"] ] - ]Last NumParams <<[[rargs]Length] - }{ - prepped <- Val[func] - } - - - out <- [[Fold[_Function Arg C[?], prepped, rargs] - ]Add Raw Line[ - [[[[[[[[[type]Append["("] - ]Append[tocall] - ]Append[", "] - ]Append[String[[rargs]Length]] - ]Append[", "] - ]Append[String[[func]Resume Index >>]] - ]Append[", "] - ]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]] - ]Append[")"]] - ]Resume Index <<[ [[func]Resume Index >>]+[1] ] -} - -Call Foreign@C Function[func,name,language,args,store result:out] -{ - rargs <- Map[args, Make Op[?, func]] - //Assume language = "C" for now - base <- [[[name]Append["("]]Append[ Join[rargs, ", "] ]]Append[")"] - ,do store <- [(String(), String Slice(), String Cat())]Find[=[Blueprint Of[store result], ?]] - { - ,do store <- If[[store result]=[""]] - { stmt <- Val[base] } - } - - Val[do store] - { stmt <- [[Make Op[store result, func]]Append[" = "]]Append[base] } - out <- [func]Add Statement[stmt] -} - -Get Field Call@C Function[func,field,source:out] -{ - out <- [func]Func Base[Escape Rhope Name[[field]Append[" >>"],[func]Escape Pattern >>], [()]Append[source], "Call"] -} - -Set Field Call@C Function[func,field,object,value:out] -{ - out <- [func]Func Base[Escape Rhope Name[[field]Append[" <<"],[func]Escape Pattern >>], [[()]Append[object]]Append[value], "Call"] -} - -Tail Method Call@C Function[func,method,args:out] -{ - out <- [func]Func Base[[[func]Method Registry >>]Method ID[method],args, "TMCall"] -} - -Tail Call@C Function[func,name,args:out] -{ - out <- [func]Func Base[Escape Rhope Name[name,[func]Escape Pattern >>],args, "TCall"] -} - -Resolve@C Function[func,op:out] -{ - If[[[func]Convention >>] = ["rhope"]] - { - [[func]Inputs >>]Find[=[op,?]] - { - out <- [["my_cdata->params["]Append[String[~]]]Append[" ]"] - }{ - out <- [[["lv_"]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append["->"]]Append[Escape Rhope Name[op,[func]Escape Pattern >>]] - } - }{ - out <- Escape Rhope Name[op,[func]Escape Pattern >>] - } -} - -Resolve Output@C Function[func,name:out] -{ - If[[[func]Convention >>] = ["rhope"]] - { - out <- [[["lv_"]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append["->"]]Append[Escape Rhope Name[name,[func]Escape Pattern >>]] - }{ - out <- Escape Rhope Name[name,[func]Escape Pattern >>] - } -} - -Instruction Stream@C Function[func:out] -{ - out <- [func]Statements <<[()] -} - -_If C[func, statement:out] -{ - out <- [func]Statements <<[ [[func]Statements >>]Append[ ["\t"]Append[statement] ] ] -} - -Do If@C Function[func,condition,stream:out] -{ - cond <- [condition]Make Op[func] - after statements <- Fold[_If C[?], [[func - ]Add Raw Line[ [["if("]Append[cond]]Append[")"] ] - ]Add Raw Line["{"], [stream]Statements >>] - - - If[[[[func]Last NumParams >>]=[-1]]And[[[stream]Last NumParams >>]>[-1]]] - { - after free <- [after statements]Add Raw Line["FreeCall"] - }{ - after free <- Val[after statements] - } - out <- [[[after free]Add Raw Line["}"] - ]Resume Index <<[[stream]Resume Index >>] - ]Variables <<[ Combine[[after free]Variables >>, [stream]Variables >>]] -} - -Discard Outputs@C Function[func,first to discard:out] -{ - out <- [[[[[func - ]Add Raw Line[[["for(idx = "]Append[String[first to discard]]]Append["; idx < cdata->num_params; ++idx)"]] - ]Add Raw Line["{"] - ]Add Raw Line[" if (cdata->params[idx])"] - ]Add Raw Line[" release_ref(cdata->params[idx]);"] - ]Add Raw Line["}"] -} - -Result Reference@C Function[func,output:out] -{ - out <- [["cdata->params["]Append[String[output]]]Append["]"] -} - -Checked Result Reference@C Function[func,output:out] -{ - out <- [[[["("]Append[String[output]]]Append[" < cdata->num_params ? cdata->params["]]Append[String[output]]]Append["] : NULL)"] -} - - -If Null Else@C Function[func,left,right:out] -{ - check <- [[Make Condition[left]]Strip Addref]Make Op[func] - l <- [left]Make Op[func] - r <- [right]Make Op[func] - out <- [[[[[["(" - ]Append[check] - ]Append[" ? "] - ]Append[l] - ]Append[" : "] - ]Append[r] - ]Append[")"] -} - -_Set Outputs C[string,inputname,inputnum,func:out] -{ - out <- [string]Append[[[ [ ["\tRet("]Append[String[inputnum]] ]Append[ [[", lv_"]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append["->"]]]Append[Escape Rhope Name[inputname,[func]Escape Pattern >>]]]Append[")\n"]] -} - -Set Outputs@C Function[func:out] -{ - If[[[func]Convention >>] = ["rhope"]] - { - out <- [[[Fold[_Set Outputs C[?, ?, ?, func], "", [func]Outputs >>]]Append["\tNumRet("]]Append[String[[[func]Outputs >>]Length]]]Append[")\n"] - }{ - [[func]Outputs >>]Index[0] - { - out <- [["\treturn "]Append[Escape Rhope Name[~,[func]Escape Pattern >>]]]Append[";\n"] - }{ - out <- "" - } - } -} -_Output Defs C[string,varname,index,func:out] -{ - out <- [[[string]Append[ ["\t"]Append[Rhope Type to C[[[func]Output Types >>]Index[index],[func]Escape Pattern >>]] ]]Append[[" "]Append[Escape Rhope Name[varname,[func]Escape Pattern >>]]]]Append[";\n"] -} -_Var Defs C[string,type,varname,p:out] -{ - out <- [[[string]Append[ ["\t"]Append[Rhope Type to C[type,p]] ]]Append[[" "]Append[Escape Rhope Name[varname,p]]]]Append[";\n"] -} -_Global Cell Defs C[func,p,string,store:out] -{ - out <- [string]Append[ [["\ttrans_cell *gs_"]Append[Escape Rhope Name[store,p]]]Append[";\n"] ] -} - - -Definitions@C Function[func:out] -{ - Print[["Definitions@C Function: "]Append[[func]Name >>]] - { - If[ [[[func]Convention >>] = ["rhope"]] And [[ [[[func]Variables >>]Length]+[[[func]Outputs >>]Length] ] > [0]] ] - { - localtype <- [[[Fold[_Global Cell Defs C[func,[func]Escape Pattern >>,?], Fold[_Output Defs C[?, ?, ?, func], Fold[_Var Defs C[?,?,?,[func]Escape Pattern >>],"typedef struct {\n", [func]Variables >>], [func]Outputs >>], [func]Uses >>]]Append["} lt_"]]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append[";\n"] - }{ - localtype <- "" - } - - If[ [[func]Convention >>] = ["rhope"] ] - { - /* parts <- [[func]Name >>]Split["@"] - [parts]Index[1] - { - proto <- [[[["MethodDef(" - ]Append[Escape Rhope Name[[parts]Index[0],[func]Escape Pattern >>]] - ]Append[", "] - ]Append[Escape Rhope Name[~,[func]Escape Pattern >>]] - ]Append[")\n"] - }{ - proto <- [["FuncDef("]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append[")\n"] - } */ - out <- Val[localtype] - }{ - out <- [[func]Naked Proto]Append[";\n"] - } - } -} - -_Proto Input[list,input,index,types,p:out] -{ - out <- [list]Append[ [[Rhope Type to C[[types]Index[index],p]]Append[" "]]Append[Escape Rhope Name[input,p]] ] -} - -Naked Proto@C Function[func:out] -{ - [[func]Output Types >>]Index[0] - { - outtype <- [Rhope Type to C[~,[func]Escape Pattern >>]]Append[" "] - }{ - outtype <- "void " - } - out <- [[[[outtype - ]Append[ Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]] - ]Append["("] - ]Append[ [Fold[_Proto Input[?, ?, ?, [func]Input Types >>,[func]Escape Pattern >>], (), [func]Inputs >>]]Join[", "] ] - ]Append[")"] -} - -Type Check@C Function[func,text,type,input num:out] -{ - If[[type] = ["Any Type"]] - { - out <- text - }{ - out <- [text]Append[ [["\tParam("]Append[input num]]Append[ [[", "]Append[ [[func]Type Registry >>]Type ID[type] ]]Append[")"] ] ] - } -} - -Check Param Type C[text,type,input num,func:out] -{ - [(String(),String Cat(),String Slice())]Find[=[Blueprint Of[type],?]] - { - typename <- type - }{ - typename <- [type]Name >> - } - If[[typename] = ["Any Type"]] - { - out <- text - }{ - out <- [text]Append[[[["\tParam("]Append[String[input num]]]Append[ [","]Append[ [[func]Type Registry >>]Type ID[typename] ] ]]Append[")\n"]] - } -} - -Find Trans Cell@C Function[func,text,store:out] -{ - estore <- Escape Rhope Name[store,[func]Escape Pattern >>] - out <- [text]Append[ [[[["lv_"]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append["->gs_"]]Append[estore]]Append[[[" = find_obj_cell(ct->transaction, gs_"]Append[estore]]Append[");\n"]] ] -} - -Text@C Function[func:out] -{ - Print[["Text@C Function: "]Append[[func]Name >>]] - If[ [[func]Convention >>] = ["rhope"] ] - { - before <- [[func]Name >>]Partition["@"] {} {} - { - type <- "MethodImpl" - cname <- [[[[Escape Rhope Name[before,[func]Escape Pattern >>] - ]Append[", "] - ]Append[Escape Rhope Name[~,[func]Escape Pattern >>]] - ]Append[", "] - ]Append[ [[func]Type Registry >>]Type ID[~] ] - }{ - type <- "Func" - cname <- Val[fname] - } - fname <- Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>] - param check <- Fold[Check Param Type C[?, ?, ?, func], "", [func]Input Types >>] - If[[[func]Last NumParams >>] = [-1]] - { - freecall <- "" - }{ - freecall <- "\n\tFreeCall\n" - } - If[ [ [[[[func]Variables >>]Length]+[[[func]Outputs >>]Length]]+[[[func]Uses >>]Length] ] = [0] ] - { - out <- [[[[[[[[[ [type]Append["NoLocals("] - ]Append[cname] - ]Append[",\n\tNumParams "] - ]Append[ String[[[func]Inputs >>]Length] ] - ]Append[")\n\n"] - ]Append[param check] - ]Append[ [[func]Statements >>]Join[""] ] - ]Append[freecall] - ]Append["EndFuncNoLocals\n"] - ]Append["DISPATCH"] - }{ - If[[[func]Uses >>]Length] - { - begin trans <- [[[["\tbegin_transaction(ct, "]Append[ String[[[func]Uses >>]Length] ]]Append[", "]]Append[ [Map[Map[[func]Uses >>, Escape Rhope Name[?, [func]Escape Pattern >>]], ["gs_"]Append[?]]]Join[", "] ]]Append[");\n"] - init trans <- [[Fold[Find Trans Cell[func,?], begin trans, [func]Uses >>] - ]Append[[["transretry_"]Append[fname]]Append[":\n"]] - ]Append["\tfor(idx = 0; idx < cdata->num_params; ++idx) { add_ref(cdata->params[idx]); }\n"] - //TODO: Figure out whether this is a readonly or write transaction - commit trans <- [[["\tif(!commit_transaction(ct, 0)) { prep_retry(ct); goto transretry_"]Append[fname]]Append["; }\n"] - ]Append["\tfor(idx = 0; idx < cdata->num_params; ++idx) { release_ref(cdata->params[idx]); }\n"] - }{ - init trans <- "" - commit trans <- "" - } - out <- [[[[[[[[[[[[ [type]Append["("] - ]Append[cname] - ]Append[",\n\tNumParams "] - ]Append[ String[[[func]Inputs >>]Length] ] - ]Append[")\n\n"] - ]Append[param check] - ]Append[init trans] - ]Append[ [[func]Statements >>]Join[""] ] - ]Append[freecall] - ]Append[commit trans] - ]Append[[func]Set Outputs] - ]Append[[["EndFunc("]Append[fname]]Append[")\n"]] - ]Append["DISPATCH"] - } - }{ - - out <- [[[ - Fold[_Output Defs C[?, ?, ?, func], - Fold[_Var Defs C[?], [[func]Naked Proto]Append["\n{"], [func]Variables >>], [func]Outputs >>] - ]Append[[[func]Statements >>]Join[""]] - ]Append[[func]Set Outputs] - ]Append["}"] - } -} - -Blueprint C Program -{ - Functions - Method Registry - Field Registry - Type Registry - Libraries - Global Stores - Escape Pattern -} - -C Program[:out] -{ - p <- Pattern[("_", "@", " ", ":", "?", "+", "-", "*", "/", "<", ">", "(", ")", "!", "=", "'", - "\"", "\t", ",", ".", "\n", "{", "}", "[", "]", "#", "\\", "\r", ";", "&", "|", "%", "^", "`", "~")] - out <- [[[[[[[Build[C Program()]]Functions <<[Dictionary[]]]Method Registry <<[C Method Registry[]]]Type Registry <<[C Type Registry[p]]]Field Registry <<[C Field Registry[]]]Libraries <<[Dictionary[]]]Escape Pattern <<[p]]Global Stores <<[Dictionary[]] -} - -Supported Number Types@C Program[program:out] -{ - out <- ("Int8","Int16","Int32","Int64","UInt8","UInt16","UInt32","UInt64") -} - -Needed Specials@C Program[program,typename,makespecial:out] -{ - init name <- [" init "]Append[typename] - with init <- [()]Append[ [[()]Append[init name]]Append[[makespecial]Index["init"]] ] - [("Array","Boxed Array","Worker")]Find[=[?,typename]] - { - out <- Val[with init] - }{ - copy name <- [" copy "]Append[typename] - cleanup name <- [" cleanup "]Append[typename] - out <- [[with init]Append[ [[()]Append[copy name]]Append[[makespecial]Index["copy"]] ] - ]Append[ [[()]Append[cleanup name]]Append[[makespecial]Index["cleanup"]] ] - } -} - -Set Stdlib Imports@C Program[program,parser:out] -{ - out <- [parser]Imports <<[ [[parser]Imports >>]Set["kernel.rhope", Yes] ] -} - -Link@C Program[program,language,library:out] -{ - If[[library] = ["runtime"]] - { - out <- program - }{ - langlibs <- [[program]Libraries >>]Index[language] {} - { langlibs <- Dictionary[] } - out <- [program]Libraries <<[ [[program]Libraries >>]Set[language, [langlibs]Set[library, Yes]] ] - } -} - -Register Type@C Program[program,def:out] -{ - out <- [[[program]Type Registry <<[ [[program]Type Registry >>]Register Type[def] ] - ]Method Registry <<[ [def]Register Methods[[program]Method Registry >>] ] - ]Field Registry <<[ [def]Register Fields[[program]Field Registry >>] ] -} - -Create Type@C Program[program,name:out] -{ - out <- C Type[name] -} - -Create Function@C Program[program,name,inputs,outputs,convention:out] -{ - out <- C Function With Registry[name,inputs,outputs,convention, [program]Method Registry >>, [program]Field Registry >>, [program]Type Registry >>, [program]Escape Pattern >>] -} - -Store Function@C Program[program,func:out] -{ - out <- [program]Functions <<[ [[program]Functions >>]Set[ [func]Name >>, func] ] -} - -Method?@C Program[program,funcname:is,isnot] -{ - is,isnot <- [[program]Method Registry >>]Method ID[funcname] -} - -_Defs C Program[text,func:out] -{ - def <- [func]Definitions - If[[def]=[""]] - { - out <- text - }{ - out <- [text]Append[[def]Append["\n\n"]] - } -} - -_Text C Program[text,func,type reg:out] -{ - out <- [text]Append[[[ [func]Type Registry <<[type reg] ]Text]Append["\n\n"]] -} - -Combine Consts[consts,func:out] -{ - out <- Combine[[func]Constants >>, consts] -} - -_Consts C Program[text,value,name,p:out] -{ - out <- [text]Append[ [["object * _const_"]Append[Escape Rhope Name[name,p]]]Append[";\n"] ] -} - -_Consts C Release[text,value,name,p:out] -{ - out <- [text]Append[ [["\trelease_ref(_const_"]Append[Escape Rhope Name[name,p]]]Append[");\n"] ] -} - -_List Literal El[text,val,index,type reg:out] -{ - out <- [[[[text - ]Append[", "] - ]Append[index] - ]Append[", "] - ]Append[Const Construct C[val, type reg]] -} - -Const Construct C[value,type reg:out] -{ - valtype <- Blueprint Of[value] - [(Int8(),UInt8(),Int16(),UInt16(),Int32(),UInt32(),Int64(),UInt64())]Find[=[valtype,?]] - { - size <- [("8","16","32","64")]Index[[~]/[2]] - If[[~]Mod[2]] - { s <- "UI" } - { s <- "I" } - - out <- [[[[[["make_" - ]Append[s] - ]Append["nt"] - ]Append[size] - ]Append["("] - ]Append[String[value]] - ]Append[")"] - }{ - If[[valtype] = [Type Instance()]] - { - //TODO: Support parametric types - typeid <- [type reg]Type ID[[value]Name >>] - - out <- [["make_Blueprint("]Append[typeid]]Append[")"] - }{ - If[[valtype] = [Boolean()]] - { - If[value] - { - out <- "make_Bool(1)" - }{ - out <- "make_Bool(0)" - } - }{ - - [(String(),String Slice(),String Cat())]Find[=[valtype,?]] - { - out <- [["make_String(\""]Append[ [[[[value]Replace["\\", "\\\\"]]Replace["\n", "\\n"]]Replace["\"", "\\\""]]Replace["\r", "\\r"] ]]Append["\")"] - }{ - If[[valtype]=[Worker Literal()]] - { - //TODO: Figure out how to fully support these in nested cases - //or workaround the problem higher up in the food chain - [[value]Args >>]Last - { size <- String[[~]+[1]] } - { size <- "0" } - out <- [[[[[["make_Worker(FUNC_" - ]Append[Escape Rhope Name[[value]Name >>,[type reg]Escape Pattern >>]] - ]Append[", "] - ]Append[size] - ]Append[", "] - ]Append[String[Fold[+[1,?], 0, [value]Args >>]]] - ]Append[")"] - }{ - [(List(), List Leaf())]Find[=[?,valtype]] - { - out <- [Fold[_List Literal El[?, ?, ?, type reg], ["make_List("]Append[String[[value]Length]], value]]Append[")"] - }{ - out <- "UnhandledLiteralType" - } - } - } - } - } - - } -} - -_Set Worker Params C[text,param,num,type reg,name:out] -{ - out <- [text]Append[ - [[[[[["\t((object **)(((t_Worker *)_const_" - ]Append[name] - ]Append[")+1))["] - ]Append[String[num]] - ]Append["] = "] - ]Append[Const Construct C[param, type reg]] - ]Append[";\n"] ] -} - -_Set Consts C Program[text,value,name,type reg:out] -{ - valtype <- Blueprint Of[value] - [(String(),String Cat(),String Slice(),Worker Literal(),List(),List Leaf())]Find[=[valtype,?]] - { - out <- text - }{ - Const Construct C[value,type reg] - { out <- [text]Append[ [[[["\t_const_"]Append[Escape Rhope Name[name,[type reg]Escape Pattern >>]]]Append[" = "]]Append[~]]Append[";\n"] ] } - } -} - -_Set List Els C[text,el,index,type reg:out] -{ - out <- [[text]Append[ - [["\tinout[1] = " - ]Append[Const Construct C[index,type reg]] - ]Append[ - [[";\n\tinout[2] = " - ]Append[Const Construct C[el, type reg]] - ]Append[";\n"] - ]]]Append["\trhope(FUNC_Set, inout, 3, 3);\n"] -} - -_Set Late Consts C[text,value,name,type reg:out] -{ - valtype <- Blueprint Of[value] - [(String(),String Cat(),String Slice(),Worker Literal(),List(),List Leaf())]Find[=[valtype,?]] - { - If[[~]>[3]] - { - out <- [Fold[_Set List Els C[?, ?, ?, type reg], [text]Append["\trhope(FUNC_List, inout, 0, 1);\n"], value] - ]Append[[["\t_const_"]Append[Escape Rhope Name[name,[type reg]Escape Pattern >>]]]Append[" = inout[0];\n"]] - }{ - Const Construct C[value,type reg] - { init <- [text]Append[ [[[["\t_const_"]Append[Escape Rhope Name[name,[type reg]Escape Pattern >>]]]Append[" = "]]Append[~]]Append[";\n"] ] } - - If[[valtype]=[Worker Literal()]] - { - out <- Fold[_Set Worker Params C[?, ?, ?, type reg, Escape Rhope Name[name,[type reg]Escape Pattern >>]], init, [value]Args >>] - }{ - out <- Val[init] - } - } - }{ - out <- text - } -} - -_Global Var Init C[text,value,name,storevar,type reg:out] -{ - out <- [[[[[text]Append[storevar]]Append[Escape Rhope Name[name, [type reg]Escape Pattern >>]]]Append[" = "]]Append[Const Construct C[value, type reg]]]Append[";\n"] -} - -_Global Store Inits C[text,store,type reg:out] -{ - estore <- Escape Rhope Name[[store]Name >>, [type reg]Escape Pattern >>] - out <- Fold[_Global Var Init C[?,?,?, [[[["\t((mutt_"]Append[estore]]Append[" *)(gs_"]]Append[estore]]Append["->data))->gs_"], type reg], text, [store]Vars >>] -} - -_Dispatch Switch Sub[text, num, name:out] -{ - out <- [[[[[text - ]Append["\tResumeEntry("] - ]Append[String[num]] - ]Append[","] - ]Append[name] - ]Append[")\\\n"] -} - -_Dispatch Switch[text,func,raw name:out] -{ - If[[[func]Convention >>] = ["rhope"]] - { - name <- Escape Rhope Name[raw name,[func]Escape Pattern >>] - out <- [[text]Append[ [["\tDispatchEntry("]Append[name]]Append[")\\\n"] ] - ]Append[Fold[_Dispatch Switch Sub[?, ?, name], "", Range[1, [func]Resume Index >>]]] - }{ - out <- text - } -} - -_Dispatch Switch Methods[p,text,id,raw name:out] -{ - name <- Escape Rhope Name[raw name,p] - out <- [text]Append[ [["\tDispatchEntry("]Append[name]]Append[")\\\n"] ] -} - -_Dispatch Enum Sub[text, num, name:out] -{ - out <- [[[[[text - ]Append["\tRES_"] - ]Append[String[num]] - ]Append["_"] - ]Append[name] - ]Append[",\n"] -} - -_Dispatch Enum[text,func,raw name:out] -{ - If[[[func]Convention >>] = ["rhope"]] - { - name <- Escape Rhope Name[raw name,[func]Escape Pattern >>] - out <- [[text]Append[ [["\tFUNC_"]Append[name]]Append[",\n"] ] - ]Append[Fold[_Dispatch Enum Sub[?, ?, name], "", Range[1, [func]Resume Index >>]]] - }{ - out <- text - } -} - -_Dispatch Enum Methods[p,text,types,name:out] -{ - out <- [text]Append[ [["\tFUNC_"]Append[Escape Rhope Name[name,p]]]Append[",\n"] ] -} - -Dispatch@C Program[program,all methods:out] -{ - out <- [[[[["typedef enum {\n" - ]Append[Fold[_Dispatch Enum[?], - [Fold[_Dispatch Enum Methods[[program]Escape Pattern >>,?], "", all methods]]Append["\tFUNC_Build,\n\tFUNC_BlueprintSP_Of,\n\tFUNC_ID,\n\tFUNC_BlueprintSP_FromSP_ID,\n\tFUNC_Pause,\n\tRES_1_Pause,\n\tFUNC_Resume,\n\tFUNC_RunSP_Bytecode,\n\tRES_1_RunSP_Bytecode,\n"], - [program]Functions >>]] - ]Append["\tEND,\n\tEND_THREAD\n} funcids;\n\n"] - ]Append["#define DispatchEntries \\\n"] - ]Append[Fold[_Dispatch Switch[?], - [Fold[_Dispatch Switch Methods[[program]Escape Pattern >>,?], "", all methods]]Append["\tDispatchEntry(Build)\\\n\tDispatchEntry(BlueprintSP_Of)\\\n\tDispatchEntry(ID)\\\n\tDispatchEntry(BlueprintSP_FromSP_ID)\\\n\tDispatchEntry(Pause)\\\n\tResumeEntry(1,Pause)\\\n\tDispatchEntry(Resume)\\\n\tDispatchEntry(RunSP_Bytecode)\\\n\tResumeEntry(1,RunSP_Bytecode)\\\n"], - [program]Functions >>]] - ]Append["\tEndEntry\\\n\tEndThreadEntry\n\n"] -} - -Not Native[func:out] -{ - If[[[func]Convention >>] = ["rhope"]] - { out <- No } - { out <- Yes } -} - -Native[func:out] -{ - out <- [[func]Convention >>] = ["rhope"] -} - -Local Pointers[text,func:out] -{ - If[ [ [[[func]Variables >>]Length]+[[[func]Outputs >>]Length] ] = [0] ] - { - out <- text - }{ - out <- [text]Append[[["\tFuncDef("]Append[Escape Rhope Name[[func]Name >>,[func]Escape Pattern >>]]]Append[")\n"]] - } -} - -_Method to Types[dict,name,type:out] -{ - typelist <- [dict]Index[name] {} - { typelist <- () } - - out <- [dict]Set[name, [typelist]Append[[type]Name >>]] - -} - -_Field to Types[dict,field,type:out] -{ - name <- [field]Index[0] - out <- _Method to Types[_Method to Types[dict, [name]Append[" >>"], type], [name]Append[" <<"], type] - -} - -Method to Types[dict,type:out] -{ - out <- Fold[_Method to Types[?, ?, type], dict, [type]Methods >>] -} - -Field to Types[dict,type:out] -{ - out <- Fold[_Field to Types[?, ?, type], dict, [type]Fields >>] -} - -_Method Dispatch[text, type, method, reg: out] -{ - out <- [[[[[[[text]Append["\tMethodDispatch("]]Append[ [reg]Type ID[type] ]]Append[","]]Append[Escape Rhope Name[method,[reg]Escape Pattern >>]]]Append[","]]Append[Escape Rhope Name[type,[reg]Escape Pattern >>]]]Append[")\n"] -} - -Method Dispatch[text, types, method, reg: out] -{ - out <- [[[Fold[_Method Dispatch[?, ?, method, reg], [[[text]Append["Method("]]Append[ Escape Rhope Name[method,[reg]Escape Pattern >>] ]]Append[")\n"], types] - ]Append["EndMethod("] - ]Append[Escape Rhope Name[method,[reg]Escape Pattern >>]] - ]Append[")\n\n"] -} - -Init Type Names[text,typeid,name,reg:out] -{ - [reg]Defined?[name] - { out <- [text]Append[ [[[["\tregistered_types["]Append[typeid]]Append["]->name = "]]Append[Const Construct C[name, reg]]]Append[";\n"] ] } - { out <- text } -} - -Text Filename@C Program[program,source name:out] -{ - out <- [source name]Append[".c"] -} - -Text@C Program[program:out] -{ - p <- [program]Escape Pattern >> - type defs <- [[program]Type Registry >>]Definitions >> - constants <- Fold[Combine Consts[?], Dictionary[], [program]Functions >>] - all methods <- Fold[Field to Types[?], Fold[Method to Types[?], Dictionary[], type defs], type defs] - headers <- "#include -#include -#include -#include \"builtin.h\" -#include \"object.h\" -#include \"context.h\" -#include \"func.h\" -#include \"integer.h\" -#include \"blueprint.h\" -#include \"array.h\" -#include \"worker.h\" -#include \"bool.h\" -#include \n\n" - out <- [[[[[[[[[[[[[[[[[[[[[headers - ]Append[[program]Dispatch[all methods]] - ]Append[[[program]Type Registry >>]Type Defs] - ]Append[Fold[_Global Type Defs C[?,?,p], "", [program]Global Stores >>]] - ]Append[Fold[_Consts C Program[?,?,?,p], - Fold[_Defs C Program[?], "", [program]Functions >>], - constants]] - ]Append[Fold[_Text C Program[?, ?, [program]Type Registry >>], "", Filter[[program]Functions >>, Not Native[?]]]] - ]Append["\n -#include \"rhopefuncs_prolog.c\"\n"] - ]Append[Fold[Local Pointers[?], "", [program]Functions >>]] - ]Append[" -#include \"localpointers_fragment.c\"\n"] - ]Append[Fold[Method Dispatch[?, ?, ?, [program]Type Registry >>], "", all methods]] - ]Append[" -#include \"builtinworkers.c\"\n"] - ]Append[Fold[_Text C Program[?, ?, [program]Type Registry >>], "", Filter[[program]Functions >>, Native[?]]]] - ]Append[" -#include \"rhopefuncs_epilog.c\" - -#include \"builtin.c\" -#include \"array.c\" -#include \"worker.c\" - -int main(int argc, char **argv) -{ - blueprint * bp; - int numret; - int idx; - object * inout[3]; - register_builtin_types(); - register_type_byid(TYPE_MUTABLEGLOBAL, sizeof(mutable_object)-sizeof(object), NULL, NULL, NULL);\n\n"] - ]Append[ [[program]Type Registry >>]Type Inits[[program]Method Registry >>, [program]Field Registry >>] ] - ]Append[Fold[_Global Type Inits C[?, ?, p], "", [program]Global Stores >>]] - ]Append[Fold[_Set Consts C Program[?, ?, ?, [program]Type Registry >>], "", constants]] - ]Append[Fold[_Set Late Consts C[?, ?, ?, [program]Type Registry >>], "", constants]] - ]Append[Fold[_Global Store Inits C[?, ?, [program]Type Registry >>], "", [program]Global Stores >>]] - ]Append[Fold[Init Type Names[?, ?, ?, [program]Type Registry >>], "", [[program]Type Registry >>]Lookup >>]] - ]Append[" - rhope(FUNC_List, inout, 0, 1); - for (idx = 0; idx < argc; ++idx) - { - inout[1] = make_String(argv[idx]); - rhope(FUNC_Append, inout, 2, 2); - } - numret = rhope(FUNC_Main, inout, 1, 1); -#ifdef ENABLE_LEAK_DETECTION\n"] - ]Append[Fold[_Consts C Release[?, ?, ?, p], "", constants]] - ]Append[ - " - print_mem_info(manager); - print_live_object_types(manager); -#endif //ENABLE_LEAK_DETECTION - -#ifdef ENABLE_PROFILING - for (idx = 0; idx < END; ++idx) - { - if(profile_counts[idx]) - printf(\"Func: %d\tCount: %llu\tTime: %llu\tAvg: %f\tSelf: %llu\tAvg: %f\tNested Count: %llu\\n\", idx, profile_counts[idx], profile_totals[idx], ((double)profile_totals[idx])/((double)profile_counts[idx]), profile_selftotals[idx], ((double)profile_selftotals[idx])/((double)profile_counts[idx]), profile_nestedcounts[idx]); - } -#endif - if (!numret) - return 0; - if (numret < 0) - return numret; - if (get_blueprint(inout[0])->type_id == TYPE_INT32) - return ((t_Int32 *)inout[0])->Num; - - rhope(FUNC_If, inout, 1, 2); - if (inout[0]) - return 0; - return 1; -}\n\n"] - -} - - diff -r 24c6f8767190 -r c6ba9fe45910 compile_old.rhope --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/compile_old.rhope Wed Jul 27 21:28:43 2011 -0700 @@ -0,0 +1,113 @@ + +Import parser_old.rhope +Import cbackend.rhope +Import jsbackend.rhope + +Other Short[arg,list:out] +{ + If[[arg]=["-"]] + { + out <- list + }{ + rest,last <- [arg]Slice[ [[arg]Length]-[1] ] + out <- Other Short[rest, [list]Append[last]] + } +} + +Check Short Val[short,args,cur,shortopts,curopts:fname,opts,next,nofname] +{ + If[[cur]<[[[args]Length]-[1]]] + { + val <- [args]Index[cur] + nidx <- [cur]+[1] + }{ + val <- Yes + nidx <- Val[cur] + } + fname,opts,next,nofname <- Parse Args[args,nidx,shortopts,_Set Short[shortopts,curopts,short,val]] +} + +_Set Short[shortopts,dict,short,val:out] +{ + [shortopts]Index[short] + { + out <- [dict]Set[~, val] + }{ + Print[["Unrecognized short option: "]Append[short]] + out <- dict + } +} + +Parse Args[args,cur,shortopts,curopts:fname,opts,next,nofname] +{ + arg,nofname <- [args]Index[cur] + { + If[[~]Starts With["-"]] + { + If[[arg]Starts With["--"]] + { + ,,after <- [arg]Partition["="] + { + [~]Slice[2] {} + { nextopts <- [curopts]Set[~, after] } + } {} {} { + [arg]Slice[2] {} + { nextopts <- [curopts]Set[~, Yes] } + } + fname,opts,next,nofname <- Parse Args[args,[cur]+[1],shortopts,nextopts] + }{ + rest,last <- [arg]Slice[ [[arg]Length]-[1] ] + fname,opts,next,nofname <- Check Short Val[last,args, [cur]+[1], shortopts, + Fold[_Set Short[shortopts,?,?,Yes], curopts, Other Short[rest, ()]]] + } + }{ + fname <- Val[arg] + opts <- curopts + next <- [cur]+[1] + } + } +} + +Main[args] +{ + + fname,options <- Parse Args[args,1,[Dictionary[]]Set["b", "backend"],Dictionary[]] + { + backmap <- [[Dictionary[] + ]Set["javascript", JS Program[?]] + ]Set["c", C Program[?]] + sel <- [options]Index["backend"] + { + makeback <- [backmap]Index[~]{} + { + Print[[["Unknown backend '"]Append[sel]]Append["' selected. Defaulting to C backend."]] + makeback <- C Program[?] + } + }{ makeback <- Val[C Program[?]] } + backend <- Call[makeback] + + file <- [File[~]]Open["r"] + text <- String[[file]Read[[file]Length]] + params <- Parser[] + Print[["Parsing "]Append[fname]] + Null[text, params, [backend]Set Stdlib Imports[Parse Program[]], 0] + { + Print["Parsing imports"] + Process Imports[~, params] + { + tree <- [~]Workers << [ Map[[~]Workers >>, Check Worker Literals[?, ~]] ] + { Print["Compiling"] } + } + + compiled <- [Tree to Program Native[tree, [backend]Supported Number Types]]Compile Program[backend] + { Print["Compiled program to backend"] } + outfname <- [compiled]Text Filename[fname] + outfile <- [File[outfname]]Truncate + [[compiled]Text]Write to File[outfile] + { Print[["Wrote output to "]Append[outfname]] } + } + }{}{}{ + Print["You must provide a file name to compile"] + } +} + diff -r 24c6f8767190 -r c6ba9fe45910 compile_old_c.rhope --- a/compile_old_c.rhope Wed Jul 27 21:14:23 2011 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,113 +0,0 @@ - -Import parser_old_c.rhope -Import cbackend_c.rhope -Import jsbackend.rhope - -Other Short[arg,list:out] -{ - If[[arg]=["-"]] - { - out <- list - }{ - rest,last <- [arg]Slice[ [[arg]Length]-[1] ] - out <- Other Short[rest, [list]Append[last]] - } -} - -Check Short Val[short,args,cur,shortopts,curopts:fname,opts,next,nofname] -{ - If[[cur]<[[[args]Length]-[1]]] - { - val <- [args]Index[cur] - nidx <- [cur]+[1] - }{ - val <- Yes - nidx <- Val[cur] - } - fname,opts,next,nofname <- Parse Args[args,nidx,shortopts,_Set Short[shortopts,curopts,short,val]] -} - -_Set Short[shortopts,dict,short,val:out] -{ - [shortopts]Index[short] - { - out <- [dict]Set[~, val] - }{ - Print[["Unrecognized short option: "]Append[short]] - out <- dict - } -} - -Parse Args[args,cur,shortopts,curopts:fname,opts,next,nofname] -{ - arg,nofname <- [args]Index[cur] - { - If[[~]Starts With["-"]] - { - If[[arg]Starts With["--"]] - { - ,,after <- [arg]Partition["="] - { - [~]Slice[2] {} - { nextopts <- [curopts]Set[~, after] } - } {} {} { - [arg]Slice[2] {} - { nextopts <- [curopts]Set[~, Yes] } - } - fname,opts,next,nofname <- Parse Args[args,[cur]+[1],shortopts,nextopts] - }{ - rest,last <- [arg]Slice[ [[arg]Length]-[1] ] - fname,opts,next,nofname <- Check Short Val[last,args, [cur]+[1], shortopts, - Fold[_Set Short[shortopts,?,?,Yes], curopts, Other Short[rest, ()]]] - } - }{ - fname <- Val[arg] - opts <- curopts - next <- [cur]+[1] - } - } -} - -Main[args] -{ - - fname,options <- Parse Args[args,1,[Dictionary[]]Set["b", "backend"],Dictionary[]] - { - backmap <- [[Dictionary[] - ]Set["javascript", JS Program[?]] - ]Set["c", C Program[?]] - sel <- [options]Index["backend"] - { - makeback <- [backmap]Index[~]{} - { - Print[[["Unknown backend '"]Append[sel]]Append["' selected. Defaulting to C backend."]] - makeback <- C Program[?] - } - }{ makeback <- Val[C Program[?]] } - backend <- Call[makeback] - - file <- [File[~]]Open["r"] - text <- String[[file]Read[[file]Length]] - params <- Parser[] - Print[["Parsing "]Append[fname]] - Null[text, params, [backend]Set Stdlib Imports[Parse Program[]], 0] - { - Print["Parsing imports"] - Process Imports[~, params] - { - tree <- [~]Workers << [ Map[[~]Workers >>, Check Worker Literals[?, ~]] ] - { Print["Compiling"] } - } - - compiled <- [Tree to Program Native[tree, [backend]Supported Number Types]]Compile Program[backend] - { Print["Compiled program to backend"] } - outfname <- [compiled]Text Filename[fname] - outfile <- [File[outfname]]Truncate - [[compiled]Text]Write to File[outfile] - { Print[["Wrote output to "]Append[outfname]] } - } - }{}{}{ - Print["You must provide a file name to compile"] - } -} - diff -r 24c6f8767190 -r c6ba9fe45910 number.rhope --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/number.rhope Wed Jul 27 21:28:43 2011 -0700 @@ -0,0 +1,283 @@ + + +Compile Number Method[backend, op, type:out] +{ + name <- [[[op]Index[0]]Append["@"]]Append[type] + backend func <- [op]Index[1] + type inst <- Type Instance[type] + func <- [[[[backend]Create Function[name,("a","b"), ("out"), "rhope"] + ]Set Input Type[type inst, 0] + ]Set Input Type[type inst, 1] + ]Set Output Type[type inst, 0] + + ,ina <- [[func]Copy["a"] + ]Read Field["a", "Num"] + { ,inb <- [~]Read Field["b", "Num"] + { ,outa <- [~]Write Field["a", "Num"] + { after op <- [backend func]Call[~, ina, inb, outa] }}} + + out <- [backend]Store Function[ [[after op]Move["a","out"]]Release["b"] ] + +} + +Compile Number Inline[func,op,type,a,b,outvar:out] +{ + ,ina <- [ + [[func]Move[a, outvar] + ]Copy[outvar] + ]Read Field[Cast[outvar, type], "Num"] + { ,inb <- [~]Read Field[Cast[Strip Addref[b], type], "Num"] + { ,outa <- [~]Write Field[Cast[outvar, type], "Num"] + { out <- [op]Call[~, ina, inb, outa] }}} +} + +Compile Number Comp Inline[func,op,type,a,b,outvar:out] +{ + ,ina <- [ + [func]Allocate Var["compres", [Type Instance["Int32"]]Set Variant["Naked"]] + ]Read Field[Cast[Strip Addref[a], type], "Num"] + { ,inb <- [~]Read Field[Cast[Strip Addref[b], type], "Num"] + { after op <- [op]Call[~, ina, inb, "compres"] }} + + [after op]Do If["compres", [[after op]Instruction Stream]Move[Constant["Boolean_Yes"], outvar]] + { out <- [~]Do If[NotCond["compres"], [[after op]Instruction Stream]Move[Constant["Boolean_No"], outvar]] } +} + +Compile Number Inline Check[func,op,type a,type b,a,b,outvar:out,no inline] +{ + opmap <- [[[[[[[[Dictionary[] + ]Set["+", Add[?]] + ]Set["-", Sub[?]] + ]Set["*", Multiply[?]] + ]Set["/", Divide[?]] + ]Set["LShift", DoLShift[?]] + ]Set["RShift", DoRShift[?]] + ]Set["&", BitAnd[?]] + ]Set["|", BitOr[?]] + backend op <- [opmap]Index[op] + { inline func <- Val[Compile Number Inline[?]] } + { + comp opmap <- [[[[[[Dictionary[] + ]Set["<", CompLess[?]] + ]Set[">", CompGreater[?]] + ]Set["=", CompEqual[?]] + ]Set["<=", CompLessEqual[?]] + ]Set[">=", CompGreaterEqual[?]] + ]Set["!=", CompNotEqual[?]] + backend op, no inline <- [comp opmap]Index[op] + { inline func <- Val[Compile Number Comp Inline[?]] } + } + + + Val[backend op] + { + signed?,int,size,no inline <- [[type a]Name >>]Partition["Int"] + { + ,no inline <- If[[[signed?] = ["U"]] Or [[signed?] = [""]]] + { + ,no inline <- [("8","16","32","64")]Find[=[size, ?]] + { + //TODO: Do an inline type check/conversion rather than falling back on a standard call + ,no inline <- If[[type b] = [type a]] + { + out <- [inline func]Call[func, backend op, type a, a, b, outvar] + } + } + } + } + } +} + +Compile Number Comp Method[backend, op, type:out] +{ + name <- [ [ [op]Index[0] ]Append["@"] ]Append[type] + backend func <- [op]Index[1] + type inst <- Type Instance[type] + func <- [[[[[[ [backend]Create Function[name,("a","b"), ("out"), "rhope"] + ]Set Input Type[type inst, 0] + ]Set Input Type[type inst, 1] + ]Set Output Type[Type Instance["Boolean"], 0] + ]Register Constant["Boolean_Yes", Yes] + ]Register Constant["Boolean_No", No] + ]Allocate Var["compres", [Type Instance["Int32"]]Set Variant["Naked"]] + + ,ina <- [func]Read Field["a", "Num"] + { ,inb <- [~]Read Field["b", "Num"] + { after op <- [backend func]Call[~, ina, inb, "compres"] }} + + [after op]Do If["compres", [[after op]Instruction Stream]Move[Constant["Boolean_Yes"], "out"]] + { after out <- [~]Do If[NotCond["compres"], [[after op]Instruction Stream]Move[Constant["Boolean_No"], "out"]] } + + out <- [backend]Store Function[ [[after out]Release["a"]]Release["b"] ] + +} + +Compile Conversion Method[backend,intype,outtype,prefix:out] +{ + func <- [[[[[[backend]Create Function[[prefix]Append[[[outtype]Append["@"]]Append[intype]], ("in"), ("out"), "rhope"] + ]Set Input Type[Type Instance[intype], 0] + ]Set Output Type[Type Instance[outtype], 0] + ]Register Constant[["Blueprint_"]Append[outtype], Type Instance[outtype]] + ]Call["Build", [()]Append[ Constant[["Blueprint_"]Append[outtype]] ]] + ]Move[Result[0], "out"] + + ,src <- [func]Read Field["in", "Num"] + { ,dst <- [~]Write Field["out", "Num"] + { ffunc <- [[~]Move[src, dst]]Release["in"] }} + + out <- [backend]Store Function[ffunc] +} + +Compile Abs UInt Method[backend,type:out] +{ + outtype <- ["U"]Append[type] + func <- [[[[[[[[[backend]Create Function[["Abs UInt@"]Append[type], ("in"), ("out"), "rhope"] + ]Set Input Type[Type Instance[type], 0] + ]Set Output Type[Type Instance[["U"]Append[type]], 0] + ]Register Constant[["Blueprint_"]Append[outtype], Type Instance[outtype]] + ]Allocate Var["abs", Type Instance[type]] + ]Call["Build", [()]Append[ Constant[["Blueprint_"]Append[outtype]] ]] + ]Move[Result[0], "out"] + ]Call["Abs", [()]Append["in"]] + ]Move[Result[0], "abs"] + { Print["After Call to Abs"] } + + ,src <- [func]Read Field["abs", "Num"] + { ,dst <- [~]Write Field["out", "Num"] + { ffunc <- [[~]Move[src, dst]]Release["abs"] }} + + out <- [backend]Store Function[ffunc] +} + +Supports Type?[backend,type:out] +{ + [[backend]Supported Number Types]Find[=[type,?]] + { out <- Yes } + { out <- No } +} + +_Generate Number Methods[backend, type:out] +{ + //Old crappy parser doesn't like Worker literals in List literals, work around for now + opmap <- [[[[[[[[() + ]Append[ [("+")]Append[Add[?]] ] + ]Append[ [("-")]Append[Sub[?]] ] + ]Append[ [("*")]Append[Multiply[?]] ] + ]Append[ [("/")]Append[Divide[?]] ] + ]Append[ [("LShift")]Append[DoLShift[?]] ] + ]Append[ [("RShift")]Append[DoRShift[?]] ] + ]Append[ [("&")]Append[BitAnd[?]] ] + ]Append[ [("|")]Append[BitOr[?]] ] + //(("+", Add[?]), ("-", Sub[?]), ("*", Multiply[?]), ("/", Divide[?]), ("LShift", DoLShift[?]), ("RShift", DoRShift[?])) + compops <- [[[[[[() + ]Append[ [("<")]Append[CompLess[?]] ] + ]Append[ [(">")]Append[CompGreater[?]] ] + ]Append[ [("=")]Append[CompEqual[?]] ] + ]Append[ [("<=")]Append[CompLessEqual[?]] ] + ]Append[ [(">=")]Append[CompGreaterEqual[?]] ] + ]Append[ [("!=")]Append[CompNotEqual[?]] ] + //(("<", CompLess[?]), (">", CompGreater[?]), ("=", CompEqual[?]), ("<=", CompLessEqual[?]), (">=", CompGreaterEqual[?]), ("!=", CompNotEqual[?])) + + Fold[Compile Number Method[?, ?, type], backend, opmap] + { Fold[Compile Number Comp Method[?, ?, type], ~, compops] + { Fold[Compile Conversion Method[?, type, ?, ""], ~, Filter[Legal Conversions[type], [backend]Supports Type?[?]]] + { + almost <- Fold[Compile Conversion Method[?, type, ?, "Trunc "], ~, Filter[Truncations[type], [backend]Supports Type?[?]]] + If[[type]Starts With["I"]] + { + out <- Compile Abs UInt Method[almost,type] + }{ + out <- Val[almost] + } + }}} +} + +Generate Number Methods[backend:out] +{ + out <- Fold[_Generate Number Methods[?], backend, [backend]Supported Number Types] +} + +Register Number Method[program, method, type, outtype:out] +{ + name <- [[method]Append["@"]]Append[type] + out <- [[program]Register Worker[name, "rhope", 2, 1] + ]Bind Worker[name, + [[[[[NWorker["rhope"] + ]Inputs <<[("left","right")] + ]Input Types <<[ [[()]Append[ Type Instance[type]]]Append[Type Instance[type]] ] + ]Outputs <<[("out")] + ]Output Types <<[ [()]Append[Type Instance[outtype]] ] + ]Builtin? <<[Yes] + ] +} + +Register Conversion Method[program, intype, outtype,prefix:out] +{ + name <- [prefix]Append[[[outtype]Append["@"]]Append[intype]] + out <- [[program]Register Worker[name, "rhope", 1, 1] + ]Bind Worker[name, + [[[[[NWorker["rhope"] + ]Inputs <<[("in")] + ]Input Types <<[ [()]Append[Type Instance[intype]] ] + ]Outputs <<[("out")] + ]Output Types <<[ [()]Append[Type Instance[outtype]] ] + ]Builtin? <<[Yes] + ] +} + +Legal Conversions[type:convs] +{ + bigger <- Map[Filter[(16,32,64), >[?, size]], String[?]] + base convs <- Map[bigger, Append["Int", ?]] + If[[type]Starts With["U"]] + { + [type]Slice[4] {} + { size <- Int32[~] } + convs <- Concatenate[base convs, Map[bigger, Append["UInt", ?]]] + }{ + [type]Slice[3] {} + { size <- Int32[~] } + convs <- Val[base convs] + } +} + +Truncations[type:truncs] +{ + u <- [type]Partition["Int"] {} {} + { size <- Int32[~] } + truncs <- Map[Map[Filter[(8,16,32), <[?, size]], String[?]] Append[[u]Append["Int"], ?]] +} + +_Register Number Methods[program,type:out] +{ + methods <- ("+", "-", "*", "/", "LShift", "RShift", "&", "|") + compmethods <- ("<", ">", "=", "<=", ">=", "!=") + register <- Val[Register Number Method[?, ?, type]] + Fold[[register]Set Input[3, type], program, methods] + { Fold[[register]Set Input[3, "Boolean"], ~, compmethods] + { Fold[Register Conversion Method[?, type, ?, ""], ~, Legal Conversions[type]] + { + almost <- Fold[Register Conversion Method[?, type, ?, "Trunc "], ~, Truncations[type]] + If[[type]Starts With["I"]] + { + name <- ["Abs UInt@"]Append[type] + out <- [[almost]Register Worker[name, "rhope", 1, 1] + ]Bind Worker[name + [[[[[NWorker["rhope"] + ]Inputs <<[("in")] + ]Input Types <<[ [()]Append[Type Instance[type]] ] + ]Outputs <<[("out")] + ]Output Types <<[ [()]Append[Type Instance[["U"]Append[type]]] ] + ]Builtin? <<[Yes] + ] + }{ + out <- Val[almost] + } + }}} +} + +Register Number Methods[program:out] +{ + out <- Fold[_Register Number Methods[?], program, [program]Supported Number Types] +} + diff -r 24c6f8767190 -r c6ba9fe45910 number_c.rhope --- a/number_c.rhope Wed Jul 27 21:14:23 2011 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,283 +0,0 @@ - - -Compile Number Method[backend, op, type:out] -{ - name <- [[[op]Index[0]]Append["@"]]Append[type] - backend func <- [op]Index[1] - type inst <- Type Instance[type] - func <- [[[[backend]Create Function[name,("a","b"), ("out"), "rhope"] - ]Set Input Type[type inst, 0] - ]Set Input Type[type inst, 1] - ]Set Output Type[type inst, 0] - - ,ina <- [[func]Copy["a"] - ]Read Field["a", "Num"] - { ,inb <- [~]Read Field["b", "Num"] - { ,outa <- [~]Write Field["a", "Num"] - { after op <- [backend func]Call[~, ina, inb, outa] }}} - - out <- [backend]Store Function[ [[after op]Move["a","out"]]Release["b"] ] - -} - -Compile Number Inline[func,op,type,a,b,outvar:out] -{ - ,ina <- [ - [[func]Move[a, outvar] - ]Copy[outvar] - ]Read Field[Cast[outvar, type], "Num"] - { ,inb <- [~]Read Field[Cast[Strip Addref[b], type], "Num"] - { ,outa <- [~]Write Field[Cast[outvar, type], "Num"] - { out <- [op]Call[~, ina, inb, outa] }}} -} - -Compile Number Comp Inline[func,op,type,a,b,outvar:out] -{ - ,ina <- [ - [func]Allocate Var["compres", [Type Instance["Int32"]]Set Variant["Naked"]] - ]Read Field[Cast[Strip Addref[a], type], "Num"] - { ,inb <- [~]Read Field[Cast[Strip Addref[b], type], "Num"] - { after op <- [op]Call[~, ina, inb, "compres"] }} - - [after op]Do If["compres", [[after op]Instruction Stream]Move[Constant["Boolean_Yes"], outvar]] - { out <- [~]Do If[NotCond["compres"], [[after op]Instruction Stream]Move[Constant["Boolean_No"], outvar]] } -} - -Compile Number Inline Check[func,op,type a,type b,a,b,outvar:out,no inline] -{ - opmap <- [[[[[[[[Dictionary[] - ]Set["+", Add[?]] - ]Set["-", Sub[?]] - ]Set["*", Multiply[?]] - ]Set["/", Divide[?]] - ]Set["LShift", DoLShift[?]] - ]Set["RShift", DoRShift[?]] - ]Set["&", BitAnd[?]] - ]Set["|", BitOr[?]] - backend op <- [opmap]Index[op] - { inline func <- Val[Compile Number Inline[?]] } - { - comp opmap <- [[[[[[Dictionary[] - ]Set["<", CompLess[?]] - ]Set[">", CompGreater[?]] - ]Set["=", CompEqual[?]] - ]Set["<=", CompLessEqual[?]] - ]Set[">=", CompGreaterEqual[?]] - ]Set["!=", CompNotEqual[?]] - backend op, no inline <- [comp opmap]Index[op] - { inline func <- Val[Compile Number Comp Inline[?]] } - } - - - Val[backend op] - { - signed?,int,size,no inline <- [[type a]Name >>]Partition["Int"] - { - ,no inline <- If[[[signed?] = ["U"]] Or [[signed?] = [""]]] - { - ,no inline <- [("8","16","32","64")]Find[=[size, ?]] - { - //TODO: Do an inline type check/conversion rather than falling back on a standard call - ,no inline <- If[[type b] = [type a]] - { - out <- [inline func]Call[func, backend op, type a, a, b, outvar] - } - } - } - } - } -} - -Compile Number Comp Method[backend, op, type:out] -{ - name <- [ [ [op]Index[0] ]Append["@"] ]Append[type] - backend func <- [op]Index[1] - type inst <- Type Instance[type] - func <- [[[[[[ [backend]Create Function[name,("a","b"), ("out"), "rhope"] - ]Set Input Type[type inst, 0] - ]Set Input Type[type inst, 1] - ]Set Output Type[Type Instance["Boolean"], 0] - ]Register Constant["Boolean_Yes", Yes] - ]Register Constant["Boolean_No", No] - ]Allocate Var["compres", [Type Instance["Int32"]]Set Variant["Naked"]] - - ,ina <- [func]Read Field["a", "Num"] - { ,inb <- [~]Read Field["b", "Num"] - { after op <- [backend func]Call[~, ina, inb, "compres"] }} - - [after op]Do If["compres", [[after op]Instruction Stream]Move[Constant["Boolean_Yes"], "out"]] - { after out <- [~]Do If[NotCond["compres"], [[after op]Instruction Stream]Move[Constant["Boolean_No"], "out"]] } - - out <- [backend]Store Function[ [[after out]Release["a"]]Release["b"] ] - -} - -Compile Conversion Method[backend,intype,outtype,prefix:out] -{ - func <- [[[[[[backend]Create Function[[prefix]Append[[[outtype]Append["@"]]Append[intype]], ("in"), ("out"), "rhope"] - ]Set Input Type[Type Instance[intype], 0] - ]Set Output Type[Type Instance[outtype], 0] - ]Register Constant[["Blueprint_"]Append[outtype], Type Instance[outtype]] - ]Call["Build", [()]Append[ Constant[["Blueprint_"]Append[outtype]] ]] - ]Move[Result[0], "out"] - - ,src <- [func]Read Field["in", "Num"] - { ,dst <- [~]Write Field["out", "Num"] - { ffunc <- [[~]Move[src, dst]]Release["in"] }} - - out <- [backend]Store Function[ffunc] -} - -Compile Abs UInt Method[backend,type:out] -{ - outtype <- ["U"]Append[type] - func <- [[[[[[[[[backend]Create Function[["Abs UInt@"]Append[type], ("in"), ("out"), "rhope"] - ]Set Input Type[Type Instance[type], 0] - ]Set Output Type[Type Instance[["U"]Append[type]], 0] - ]Register Constant[["Blueprint_"]Append[outtype], Type Instance[outtype]] - ]Allocate Var["abs", Type Instance[type]] - ]Call["Build", [()]Append[ Constant[["Blueprint_"]Append[outtype]] ]] - ]Move[Result[0], "out"] - ]Call["Abs", [()]Append["in"]] - ]Move[Result[0], "abs"] - { Print["After Call to Abs"] } - - ,src <- [func]Read Field["abs", "Num"] - { ,dst <- [~]Write Field["out", "Num"] - { ffunc <- [[~]Move[src, dst]]Release["abs"] }} - - out <- [backend]Store Function[ffunc] -} - -Supports Type?[backend,type:out] -{ - [[backend]Supported Number Types]Find[=[type,?]] - { out <- Yes } - { out <- No } -} - -_Generate Number Methods[backend, type:out] -{ - //Old crappy parser doesn't like Worker literals in List literals, work around for now - opmap <- [[[[[[[[() - ]Append[ [("+")]Append[Add[?]] ] - ]Append[ [("-")]Append[Sub[?]] ] - ]Append[ [("*")]Append[Multiply[?]] ] - ]Append[ [("/")]Append[Divide[?]] ] - ]Append[ [("LShift")]Append[DoLShift[?]] ] - ]Append[ [("RShift")]Append[DoRShift[?]] ] - ]Append[ [("&")]Append[BitAnd[?]] ] - ]Append[ [("|")]Append[BitOr[?]] ] - //(("+", Add[?]), ("-", Sub[?]), ("*", Multiply[?]), ("/", Divide[?]), ("LShift", DoLShift[?]), ("RShift", DoRShift[?])) - compops <- [[[[[[() - ]Append[ [("<")]Append[CompLess[?]] ] - ]Append[ [(">")]Append[CompGreater[?]] ] - ]Append[ [("=")]Append[CompEqual[?]] ] - ]Append[ [("<=")]Append[CompLessEqual[?]] ] - ]Append[ [(">=")]Append[CompGreaterEqual[?]] ] - ]Append[ [("!=")]Append[CompNotEqual[?]] ] - //(("<", CompLess[?]), (">", CompGreater[?]), ("=", CompEqual[?]), ("<=", CompLessEqual[?]), (">=", CompGreaterEqual[?]), ("!=", CompNotEqual[?])) - - Fold[Compile Number Method[?, ?, type], backend, opmap] - { Fold[Compile Number Comp Method[?, ?, type], ~, compops] - { Fold[Compile Conversion Method[?, type, ?, ""], ~, Filter[Legal Conversions[type], [backend]Supports Type?[?]]] - { - almost <- Fold[Compile Conversion Method[?, type, ?, "Trunc "], ~, Filter[Truncations[type], [backend]Supports Type?[?]]] - If[[type]Starts With["I"]] - { - out <- Compile Abs UInt Method[almost,type] - }{ - out <- Val[almost] - } - }}} -} - -Generate Number Methods[backend:out] -{ - out <- Fold[_Generate Number Methods[?], backend, [backend]Supported Number Types] -} - -Register Number Method[program, method, type, outtype:out] -{ - name <- [[method]Append["@"]]Append[type] - out <- [[program]Register Worker[name, "rhope", 2, 1] - ]Bind Worker[name, - [[[[[NWorker["rhope"] - ]Inputs <<[("left","right")] - ]Input Types <<[ [[()]Append[ Type Instance[type]]]Append[Type Instance[type]] ] - ]Outputs <<[("out")] - ]Output Types <<[ [()]Append[Type Instance[outtype]] ] - ]Builtin? <<[Yes] - ] -} - -Register Conversion Method[program, intype, outtype,prefix:out] -{ - name <- [prefix]Append[[[outtype]Append["@"]]Append[intype]] - out <- [[program]Register Worker[name, "rhope", 1, 1] - ]Bind Worker[name, - [[[[[NWorker["rhope"] - ]Inputs <<[("in")] - ]Input Types <<[ [()]Append[Type Instance[intype]] ] - ]Outputs <<[("out")] - ]Output Types <<[ [()]Append[Type Instance[outtype]] ] - ]Builtin? <<[Yes] - ] -} - -Legal Conversions[type:convs] -{ - bigger <- Map[Filter[(16,32,64), >[?, size]], String[?]] - base convs <- Map[bigger, Append["Int", ?]] - If[[type]Starts With["U"]] - { - [type]Slice[4] {} - { size <- Int32[~] } - convs <- Concatenate[base convs, Map[bigger, Append["UInt", ?]]] - }{ - [type]Slice[3] {} - { size <- Int32[~] } - convs <- Val[base convs] - } -} - -Truncations[type:truncs] -{ - u <- [type]Partition["Int"] {} {} - { size <- Int32[~] } - truncs <- Map[Map[Filter[(8,16,32), <[?, size]], String[?]] Append[[u]Append["Int"], ?]] -} - -_Register Number Methods[program,type:out] -{ - methods <- ("+", "-", "*", "/", "LShift", "RShift", "&", "|") - compmethods <- ("<", ">", "=", "<=", ">=", "!=") - register <- Val[Register Number Method[?, ?, type]] - Fold[[register]Set Input[3, type], program, methods] - { Fold[[register]Set Input[3, "Boolean"], ~, compmethods] - { Fold[Register Conversion Method[?, type, ?, ""], ~, Legal Conversions[type]] - { - almost <- Fold[Register Conversion Method[?, type, ?, "Trunc "], ~, Truncations[type]] - If[[type]Starts With["I"]] - { - name <- ["Abs UInt@"]Append[type] - out <- [[almost]Register Worker[name, "rhope", 1, 1] - ]Bind Worker[name - [[[[[NWorker["rhope"] - ]Inputs <<[("in")] - ]Input Types <<[ [()]Append[Type Instance[type]] ] - ]Outputs <<[("out")] - ]Output Types <<[ [()]Append[Type Instance[["U"]Append[type]]] ] - ]Builtin? <<[Yes] - ] - }{ - out <- Val[almost] - } - }}} -} - -Register Number Methods[program:out] -{ - out <- Fold[_Register Number Methods[?], program, [program]Supported Number Types] -} - diff -r 24c6f8767190 -r c6ba9fe45910 nworker.rhope --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nworker.rhope Wed Jul 27 21:28:43 2011 -0700 @@ -0,0 +1,1787 @@ +Import number.rhope +Import boolean.rhope + +Blueprint Condition Set +{ + Variables + Subsets + Condition Type +} + +AndSet[:out] +{ + out <- [[[Build[Condition Set()]]Variables <<[Dictionary[]]]Subsets <<[()]]Condition Type <<["And"] +} + +OrSet[:out] +{ + out <- [[[Build[Condition Set()]]Variables <<[Dictionary[]]]Subsets <<[()]]Condition Type <<["Or"] +} + +To String@Condition Set[set:out] +{ + out <- [[[[[set]Condition Type >> + ]Append["Set:\n\tVariables:\n\t\t"] + ]Append[ Join[Keys[[set]Variables >>], "\n\t\t"] ] + ]Append["\n\tSubsets:\n\t\t"] + ]Append[ Join[Keys[[set]Subsets >>], "\n\t\t"] ] +} + +Add Condition@Condition Set[set,cond:out] +{ + If[[Blueprint Of[cond]] = [Condition Set()]] + { + If[[[set]Condition Type >>]=[[cond]Condition Type >>]] + { + out <- [[set]Variables <<[ Combine[[set]Variables >>, [cond]Variables >>] ] + ]Subsets <<[ Concatenate[[set]Subsets >>, [cond]Subsets >>] ] + }{ + [cond]Empty? + { + [cond]Simple? + { out <- [set]Variables <<[ Combine[[set]Variables >>, [cond]Variables >>] ] } + { out <- [set]Subsets <<[ [[set]Subsets>>]Append[cond] ] } + }{ + out <- set + } + } + }{ + out <- [set]Variables <<[ [[set]Variables >>]Set[cond, Yes] ] + } +} + +=@Condition Set[set1,set2:out] +{ + ,out <- If[[[set1]Condition Type >>] = [[set2]Condition Type >>]] + { + ,out <- If[[[set1]Variables >>] = [[set2]Variables >>]] + { + out,out <- If[[[set1]Subsets >>] = [[set2]Subsets >>]] + } + } +} + +_For Backend Var[current,junk,variable,type:out] +{ + If[[type]=["And"]] + { cond <- Val[AndCond[?]] } + { cond <- Val[OrCond[?]] } + out <- [cond]Call[current, variable] +} + +_For Backend Subset[current,subset,type:out] +{ + [subset]For Backend + { + If[[type]=["And"]] + { cond <- Val[AndCond[?]] } + { cond <- Val[OrCond[?]] } + out <- out <- [cond]Call[current, ~] + }{ + out <- current + } +} + +Empty?@Condition Set[set:not empty,empty] +{ + [[set]Variables >>]First + { + not empty <- Yes + }{ + ,empty <- [[set]Subsets >>]First + { + not empty <- Yes + } + } +} + +Simple?@Condition Set[set:simple,not simple] +{ + ,not simple <- If[[Length[[set]Variables >>]]=[1]] + { + simple,not simple <- If[[Blueprint Of[[set]Subsets >>]]=[Empty Dictionary()]] + } +} + +For Backend@Condition Set[set:out,none] +{ + firstvar <- [[set]Variables >>]First + { + [[set]Variables >>]Next[~] + { + vars <- _Fold[[set]Variables >>, ~, firstvar, _For Backend Var[?, ?, ?, [set]Condition Type >>]] + }{ + vars <- Val[firstvar] + } + out <- Fold[_For Backend Subset[?, ?, [set]Condition Type >>], vars, [set]Subsets >>] + }{ + [[set]Subsets >>]First + { + firstsub <- [[[set]Subsets >>]Index[~]]For Backend + [[set]Subsets >>]Next[~] + { + out <- _Fold[[set]Subsets >>, ~, firstsub, _For Backend Subset[?, ?, [set]Condition Type >>]] + }{ + out <- Val[firstsub] + } + }{ + none <- Yes + } + } +} + +List of Lists[num:out] +{ + out <- Fold[Append[?, ()],(), Range[0,num]] +} + +Blueprint Worker Ref +{ + Name + Convention + Inputs + Min Inputs + Outputs + Min Outputs + Is Method? +} + +Worker Ref[name,convention,inputs,outputs,ismethod?:out] +{ + out <- [[[[[[[Build[Worker Ref()]]Name <<[name]]Convention <<[convention]]Inputs <<[inputs]]Outputs <<[outputs]]Is Method? <<[ismethod?]]Min Inputs <<[inputs]]Min Outputs <<[outputs] +} + +String@Worker Ref[ref:out] +{ + out <- [[[[[[[["Worker Ref[" + ]Append[[ref]Name >>] + ]Append[", "] + ]Append[[ref]Convention >>] + ]Append[", "] + ]Append[String[[ref]Inputs >>]] + ]Append[", "] + ]Append[String[[ref]Outputs >>]] + ]Append["]"] +} + +Blueprint Node Ref +{ + Index + IO Num +} + +Node Ref[index,ionum:out] +{ + out <- [[Build[Node Ref()]]Index <<[index]]IO Num <<[ionum] +} + +=@Node Ref[left,right:out] +{ + ,out <- If[[[left]Index >>] = [[right]Index >>]] + { + out <- [[left]IO Num>>] = [[right]IO Num >>] + } +} + +Blueprint NWorker Node +{ + Type + Data + Inputs + Min Inputs + Input Types + Outputs + Min Outputs + Output Types + Wires From + Wires To + Conditions +} + +Wire To@NWorker Node[node,from,output,pre input:out] +{ + existing cons <- [[node]Wires To >>]Index[input] {} + { existing cons <- () } + input <- [pre input]+[1] + out <- [node]Wires To <<[ + [[node]Wires To >>]Set[input, + [existing cons]Append[Node Ref[from,output]] + ] + ] +} + +Wire From@NWorker Node[node,to,input,output:out] +{ + existing cons <- [[node]Wires From >>]Index[output] {} + { existing cons <- () } + out <- [node]Wires From <<[ + [[node]Wires From >>]Set[output, + [existing cons]Append[Node Ref[to,input]] + ] + ] +} + +_Has Input Types@NWorker Node[node,input num:does,does not] +{ + does <- If[[input num] >= [[node]Inputs >>]] {} + { + ,does not <- [[node]Input Types >>]Index[input num] + { + count <- [~]Index[1] + ,does not <- If[[count] = [[[[node]Wires To >>]Index[[input num]+[1]]]Length]] + { + does,does not <- [node]_Has Input Types[[input num]+[1]] + } + } + } +} + +Has Input Types?@NWorker Node[node:does,does not] +{ + If[[[node]Inputs >>] > [0]] + { + does,does not <- _Has Input Types[node,0] + }{ + does <- Yes + } +} + +_Dependency[dlist,ref:out] +{ + [dlist]Find[=[ref, ?]] + { + out <- dlist + }{ + out <- [dlist]Append[ref] + } +} + +Dependencies@NWorker Node[node:out] +{ + out <- Fold[Fold[_Dependency[?], ?], (), [node]Wires To >>] +} + + +NWorker Node[type,data,inputs,outputs:out] +{ + out <- [[[[[[[[[[[Build[NWorker Node()] + ]Type <<[type] + ]Data <<[data] + ]Inputs <<[inputs] + ]Min Inputs <<[inputs] + ]Outputs <<[outputs] + ]Min Outputs <<[outputs] + ]Wires From <<[List of Lists[outputs]] + ]Wires To <<[List of Lists[[inputs]+[1]]] + ]Conditions <<[AndSet[]] + ]Input Types <<[()] + ]Output Types <<[()] +} + +Blueprint NWorker +{ + Convention + Nodes + Inputs + Input Types + Outputs + Output Types + Uses + NodeResults + Free Temps + Name + Builtin? + Library +} + +NWorker[convention:out] +{ + out <- [[[[[[[[[[Build[NWorker()]]Convention <<[convention]]Nodes <<[()]]Inputs <<[()]]Outputs <<[()]]Input Types <<[()]]Output Types <<[()]]Name <<["Anonymous"]]Builtin? <<[No]]Library << [""]]Uses <<[()] +} + +String@NWorker[worker:out] +{ + out <- ["NWorker"]Append[[worker]Name >>] +} + +Add Node@NWorker[worker,type,data,inputs,outputs:out,node index] +{ + out <- [worker]Nodes <<[[[worker]Nodes >>]Append[NWorker Node[type,data,inputs,outputs]]] + node index <- [[worker]Nodes >>]Length +} + +Add Full Node@NWorker[worker,type,data,inputs,min inputs,outputs,min outputs:out,node index] +{ + out <- [worker]Nodes <<[[[worker]Nodes >>]Append[ + [[[NWorker Node[type,data,inputs,outputs] + ]Min Inputs <<[min inputs] + ]Min Outputs <<[min outputs] + ]Wires To <<[List of Lists[[min inputs]+[1]]] + ]] + node index <- [[worker]Nodes >>]Length +} + +Propagate Type[nodelist,dest,prog,worker,type:out] +{ + If[[[dest]IO Num >>] >= [0]] + { + node <- [nodelist]Index[[dest]Index >>] + + [[node]Input Types >>]Index[[dest]IO Num >>] + { + existing type <- [~]Index[0] + new count <- [[~]Index[1]]+[1] + If[[[existing type]Name >>] = [[type]Name >>]] + { + If[[[existing type]Variant >>] = [[type]Variant >>]] + { + If[[[existing type]Params >>] = [[type]Params >>]] + { + new type <- Val[existing type] + }{ + new variant <- [existing type]Variant >> + new params <- () + } + }{ + new variant <- "Boxed" + If[[[existing type]Params >>] = [[type]Params >>]] + { + new params <- [existing type]Params >> + }{ + new params <- () + } + } + new type <- [[existing type]Set Variant[new variant]]Params <<[new params] + }{ + new type <- Type Instance["Any Type"] + } + }{ + new type <- Val[type] + new count <- 1 + } + new node <- [node]Input Types <<[ + [ [node]Input Types >> ]Set[ [dest]IO Num >>, [[()]Append[new type]]Append[new count] ] + ] + out <- Infer Types Node[[nodelist]Set[[dest]Index >>, new node], new node, [dest]Index >>, prog, worker] + }{ + out <- nodelist + } +} + +Propagate Types[nodelist,dests,output num,prog,worker,source node:out] +{ + [[source node]Output Types >>]Index[output num] + { + out <- Fold[Propagate Type[?, ?, prog, worker, ~], nodelist, dests] + }{ + out <- nodelist + } +} + +Infer Types Node[nodelist,node,index,prog,worker:out] +{ + If[[[node]Type >>]=["call"]] + { + extra <- [", worker: "]Append[[[node]Data >>]Name >>] + }{ + extra <- "" + } + If[[[node]Type >>] = ["const"]] + { + const type <- Blueprint Of[[node]Data >>] + [(Int8(),UInt8(),Int16(),UInt16(),Int32(),UInt32(),Int64(),UInt64(), + Type Instance(),Worker Literal(),List(),List Leaf(),String(),String Slice(),String Cat())]Find[=[const type, ?]] + { + outtype <- [("Int8","UInt8","Int16","UInt16","Int32","UInt32","Int64","UInt64", + "Blueprint","Worker","List","List Leaf","String","String","String")]Index[~] + }{ + outtype <- "Any Type" + } + nextnode <- [node]Output Types <<[ [()]Append[Type Instance[outtype]] ] + + }{ + If[[[node]Type >>] = ["setglobal"]] + { + out <- nodelist + }{ + If[[[node]Type >>] = ["input"]] + { + nextnode <- [node]Output Types <<[ [()]Append[ [[worker]Input Types >>]Index[[node]Data >>] ] ] + }{ + If[[[node]Type >>] = ["output"]] + { + out <- nodelist + + }{ + If[[[node]Type >>] = ["getglobal"]] + { + nextnode <- [node]Output Types <<[ [()]Append[Type Instance["Any Type"]] ] + }{ + [node]Has Input Types? + { + If[[[node]Type >>] = ["setfield"]] + { + nextnode <- [node]Output Types <<[ [()]Append[ [[[node]Input Types >>]Index[0]]Index[0] ] ] + }{ + If[[[node]Type >>] = ["getfield"]] + { + type <- [[[node]Input Types >>]Index[0]]Index[0] + If[[[type]Name >>] = ["Any Type"]] + { + outtype <- Val[type] + }{ + outtype <- [prog]Find Field[[node]Data >>, type] {} + { + //TODO: Return errors rather than printing them + Print[ + [[[[["Type " + ]Append[[type]Name >>] + ]Append[" does not have a field named "] + ]Append[[node]Data >>] + ]Append[" in worker "] + ]Append[worker name]] + } + } + nextnode <- [node]Output Types <<[ [()]Append[outtype] ] + }{ + worker name <- [[node]Data >>]Name >> + [prog]Is Method?[worker name] + { + first arg type <- [[[node]Input Types >>]Index[0]]Index[0] + If[[[first arg type]Name >>] = ["Any Type"]] + { + outtypes <- Fold[Append[?, Type Instance["Any Type"]], (), Range[0, [node]Inputs >>]] + nextnode <- [node]Output Types <<[ outtypes ] + }{ + worker def <- [prog]Find Method[worker name, first arg type] + { + new worker name <- [[worker name]Append["@"]]Append[[first arg type]Name >>] + new ref <- [prog]Find Worker[new worker name] {} { + Print[["Could not find worker ref for "]Append[new worker name]] + } + nextnode <- [[node]Output Types <<[outtypes] + ]Data <<[new ref] + }{ + //TODO: Return errors instead of printing them + Print[ + [[[[["Type " + ]Append[[first arg type]Name >>] + ]Append[" does not support method "] + ]Append[worker name] + ]Append[" in worker "] + ]Append[ [worker]Name >> ]] + } + } + }{ + worker def <- [prog]Find Worker Def[worker name] {} + { Print["Error, could not find worker def"] } + nextnode <- [node]Output Types <<[ outtypes ] + } + outtypes <- [worker def]Output Types >> + } + } + }{ + out <- nodelist + } + } + } + } + } + } + + Val[nextnode] + { + nextlist <- [nodelist]Set[index, nextnode] + out <- Fold[Propagate Types[?, ?, ?, prog, worker, nextnode], nextlist, [nextnode]Wires From >>] + } +} + +Infer Types@NWorker[worker,prog:out] +{ + out <- [worker]Nodes <<[Fold[Infer Types Node[?, ?, ?, prog, worker], [worker]Nodes >>, [worker]Nodes >>]] +} + +Add Worker Call@NWorker[worker,tocall:out,node index] +{ + out, node index <- [worker]Add Full Node["call",tocall,[tocall]Inputs >>, [tocall]Min Inputs >>,[tocall]Outputs >>, [tocall]Min Outputs >>] +} + +Add Constant@NWorker[worker,constant:out,node index] +{ + out, node index <- [worker]Add Node["const",constant,0,1] +} + +Add Input@NWorker[worker,name,number:out,node index] +{ + out,node index <- [worker]Add Typed Input[name,number,Type Instance["Any Type"]] +} + +Add Anon Input@NWorker[worker,number:out] +{ + If[[number]>[Length[[worker]Inputs >>]]] + { + prepped <- [worker]Add Anon Input[[number]-[1]] + }{ + prepped <- Val[worker] + } + out <- out <- [[prepped]Inputs <<[[[prepped]Inputs >>]Set[number,[" unnamed"]Append[String[number]]]] + ]Input Types <<[[[prepped]Input Types >>]Set[number,Type Instance["Any Type"]]] +} + +Add Typed Input@NWorker[worker,name,number,type:out,node index] +{ + If[[number]>[Length[[worker]Inputs >>]]] + { + prepped <- [worker]Add Anon Input[[number]-[1]] + }{ + prepped <- Val[worker] + } + ,node index <- [prepped]Add Node["input",number,0,1] + { + out <- [[~]Inputs <<[[[~]Inputs >>]Set[number,name]] + ]Input Types <<[[[~]Input Types >>]Set[number,type]] + } +} + +Add Output@NWorker[worker,name,number:out,node index] +{ + out,node index <- [worker]Add Typed Output[name,number,Type Instance["Any Type"]] +} + +Add Typed Output@NWorker[worker,name,number,type:out,node index] +{ + ,node index <- [worker]Add Node["output",number,1,0] + { + out <- [[~]Outputs <<[[[~]Outputs >>]Set[number,name]] + ]Output Types <<[[[~]Output Types >>]Set[number,type]] + } +} + +Add Object Get@NWorker[worker,fieldname:out,node index] +{ + out, node index <- [worker]Add Node["getfield",fieldname,1,1] +} + +Add Object Set@NWorker[worker,fieldname:out,node index] +{ + out, node index <- [worker]Add Node["setfield",fieldname,2,1] +} + +Add Global Get@NWorker[worker,store,var:out,node index] +{ + out, node index <- [worker]Add Node["getglobal",[[()]Append[store]]Append[var],0,1] +} + +Add Global Set@NWorker[worker,store,var:out,node index] +{ + out, node index <- [worker]Add Node["setglobal",[[()]Append[store]]Append[var],1,1] +} + +Add Wire@NWorker[worker,from,output,to,input:out] +{ + fromw <- [[[worker]Nodes >>]Index[from]]Wire From[to,input,output] + tow <- [[[worker]Nodes >>]Index[to]]Wire To[from,output,input] + nodes <- [[[worker]Nodes >>]Set[from, fromw]]Set[to, tow] + out <- [worker]Nodes <<[nodes] +} + +Uses@NWorker[worker,uses:out] +{ + out <- [worker]Uses <<[uses] +} + +_No Dependencies[list,node,index:out] +{ + [[node]Wires To>>]Index[1] + { + out <- Val[list] + }{ + [[[node]Wires To>>]Index[0]]First + { + out <- Val[list] + }{ + out <- [list]Append[index] + } + } +} + +No Dependencies@NWorker[worker:out] +{ + out <- Fold[_No Dependencies[?], (), [worker]Nodes >>] +} + +_Collect Dests[candidates,wire:out] +{ + out <- [candidates]Set[[wire]Index >>, Yes] +} + +Collect Dests@NWorker[worker,candidates,node index:out] +{ + out <- Fold[Fold[_Collect Dests[?], ?], candidates, [[[worker]Nodes >>]Index[node index]]Wires From >>] +} + +Check Dependency@NWorker[worker,nodes,wires,wire index:met?] +{ + ref <- [wires]Index[wire index] + [nodes]Find[=[[ref]Index >>, ?]] + { + [wires]Next[wire index] + { + met? <- [worker]Check Dependency[nodes,wires,~] + }{ + met? <- Yes + } + }{ + met? <- No + } +} +_Check Dependencies@NWorker[worker,nodes,inputs,input index:met?] +{ + wires <- [inputs]Index[input index] + [wires]First + { + current met? <- [worker]Check Dependency[nodes, wires, ~] + }{ + current met? <- Yes + } + If[current met?] + { + [inputs]Next[input index] + { + met? <- [worker]_Check Dependencies[nodes,inputs,~] + }{ + met? <- Yes + } + }{ + met? <- No + } +} + +Check Dependencies@NWorker[worker,nodes,candidate:met?] +{ + inputs <- [[[worker]Nodes >>]Index[candidate]]Wires To >> + [inputs]First + { + met? <- [worker]_Check Dependencies[nodes, inputs, ~] + }{ + met? <- Yes + } +} + +Dependants@NWorker[worker,direct nodes,nodes:out] +{ + candidates <- Keys[Fold[Collect Dests[worker, ?], (), direct nodes]] + out <- Filter[candidates, Check Dependencies[worker, nodes, ?]] +} + +_Dependency Groups@NWorker[worker,last,all,grouped:out] +{ + current <- [worker]Dependants[last,all] + [current]First + { + out <- [worker]_Dependency Groups[current, [all]Concatenate[current], [grouped]Append[current]] + }{ + out <- grouped + } +} +Dependency Groups@NWorker[worker:out] +{ + no deps <- [worker]No Dependencies + out <- [worker]_Dependency Groups[no deps, no deps, [()]Append[no deps]] +} + +Const Name[val,node index,worker name:out] +{ + valtype <- Blueprint Of[val] + If[[valtype] = [Type Instance()]] + { + //TODO: Support parametric types + datstring <- [val]Name >> + typename <- "Blueprint" + }{ + [(Int8(),UInt8(),Int16(),UInt16(),Int32(),UInt32(),Int64(),UInt64())]Find[=[valtype,?]] + { + size <- [("8","16","32","64")]Index[[~]/[2]] + typename <- [("Int8","UInt8","Int16","UInt16","Int32","UInt32","Int64","UInt64")]Index[~] + If[[~]Mod[2]] + { s <- "UI" } + { s <- "I" } + datstring <- [[String[val]]Append[s]]Append[size] + }{ + If[[valtype] = [Worker Literal()]] + { + typename <- "Worker" + If[[[[val]Args >>]Length] > [0]] + { + datstring <- [[["Arg "]Append[String[node index]]]Append[" "]]Append[worker name] + }{ + datstring <- [val]Name >> + } + }{ + [(List(),List Leaf())]Find[=[valtype,?]] + { + typename <- "List" + If[[[val]Length] > [0]] + { + datstring <- [[["Arg "]Append[String[node index]]]Append[" "]]Append[worker name] + }{ + datstring <- "Empty" + } + }{ + [(String(),String Cat(),String Slice())]Find[=[valtype, ?]] + { + typename <- "String" + datstring <- val + }{ + typename <- "Unknown" + datstring <- String[val] + } + + } + } + } + } + out <- [[typename]Append["_"]]Append[datstring] +} + +Format Input@NWorker[worker,noderef:out] +{ + node <- [[worker]Nodes >>]Index[[noderef]Index >>] + + [("call","getfield","setfield")]Find[=[[node]Type >>, ?]] + { + maybe addref <- Result Var Name[[noderef]IO Num >>, [noderef]Index >>] + }{ + conditions <- [node]Conditions >> + + If[[[node]Type >>] = ["input"]] + { + input name <- [[worker]Inputs >>]Index[ [node]Data >> ] + [conditions]Empty? + { + out <- AddRef[Result Var Name[[noderef]IO Num >>, [noderef]Index >>]] + }{ + out <- AddRef[input name] + } + }{ + If[[[node]Type >>] = ["const"]] + { + [conditions]Empty? + { + out <- AddRef[Result Var Name[[noderef]IO Num >>, [noderef]Index >>]] + }{ + out <- Constant[Const Name[[node]Data >>, [noderef]Index >>, [worker]Name >>]] + } + }{ + If[[[node]Type >>]=["getglobal"]] + { + [conditions]Empty? + { + out <- AddRef[Result Var Name[[noderef]IO Num >>, [noderef]Index >>]] + }{ + out <- AddRef[Global Get[[[node]Data >>]Index[0], [[node]Data >>]Index[1]]] + } + } + } + } + } + + Val[maybe addref] + { + If[[Length[[[node]Wires From >>]Index[[noderef]IO Num >>]]] > [1]] + { + out <- AddRef[maybe addref] + }{ + out <- Val[maybe addref] + } + } +} + +Collect Input@NWorker[worker,nodeinput:out] +{ + inputchoices <- Map[nodeinput, Format Input[worker, ?]] + + [inputchoices]First + { + first <- [inputchoices]Index[~] + [inputchoices]Next[~] + { + out <- _Fold[inputchoices, ~, first, OrValue[?]] + }{ + out <- Val[first] + } + }{ + out <- "Missing" + } +} + +Collect Inputs@NWorker[worker,node:out] +{ + out <- Map[Tail[[node]Wires To>>, 1], Collect Input[worker, ?]] +} + +Collect Input Condition@NWorker[worker,set,noderef:out] +{ + node <- [[worker]Nodes >>]Index[ [noderef]Index >> ] + If[[[node]Outputs >>] > [1]] + { + out <- [set]Add Condition[ Result Var Name[[noderef]IO Num >>, [noderef]Index >>] ] + }{ + out <- [set]Add Condition[[node]Conditions >>] + } +} + +Collect Condition@NWorker[worker,set,nodeinput:out] +{ + out <- [set]Add Condition[Fold[Collect Input Condition[worker, ?], OrSet[], nodeinput]] +} + +Collect Conditions@NWorker[worker,node:out] +{ + out <- Fold[Collect Condition[worker, ?], AndSet[], [node]Wires To>>] +} + +Save Result[func,num,node index:out] +{ + out <- [func]Move[Result[num], Result Var Name[num, node index]] +} + +Save Maybe Result[func,num,node index:out] +{ + out <- [func]Move[Check Result[num], Result Var Name[num, node index]] +} + +Max Used Output[node,cur:out] +{ + If[[cur] < [0]] + { + out <- cur + }{ + [[[node]Wires From >>]Index[cur]]Index[0] + { + out <- cur + }{ + out <- Max Used Output[node, [cur]-[1]] + } + } +} + +Compile Call Node[node,program,func,inputs,node index:out] +{ + If[[[node]Type >>] = ["getfield"]] + { + with call <- [func]Get Field Call[[node]Data >>, [inputs]Index[0]] + save outs <- [node]Outputs >> + out <- Val[after save] + }{ + If[[[node]Type >>] = ["setfield"]] + { + with call <- [func]Set Field Call[[node]Data >>, [inputs]Index[0], [inputs]Index[1]] + save outs <- [node]Outputs >> + out <- Val[after save] + }{ + fname <- [[node]Data >>]Name >> + first unused <- [Max Used Output[node, [[node]Outputs >>]-[1]]]+[1] + [program]Method?[fname] + { + with call <- [func]Method Call[fname, inputs] + }{ + justfunc,,,normal call <- [fname]Partition["@"] + { + //Check for inline on static method calls + //TODO: Deal with unused output + If[[[inputs]Length]=[2]] + { + out,normal call <- Compile Number Inline Check[func, justfunc, [[[node]Input Types >>]Index[0]]Index[0], [[[node]Input Types >>]Index[1]]Index[0], [inputs]Index[0], [inputs]Index[1], Result Var Name[0, node index]] + }{ + ,normal call <- If[[[inputs]Length]=[1]] + { + //TODO: Inline a partial version of If when only one output is used + ,normal call <- If[[first unused]>[1]] + { + out,normal call <- Compile Boolean Inline Check[func, justfunc, [[[node]Input Types >>]Index[0]]Index[0], [inputs]Index[0], Result Var Name[0, node index], Result Var Name[1, node index]] + } + } + } + } + + Val[normal call] + { + with call <- [func]Call[fname, inputs] + } + } + If[[first unused] > [[node]Min Outputs >>]] + { + save outs <- [node]Min Outputs >> + after maybe <- Fold[Save Maybe Result[?, ?, node index], after save, Range[save outs, first unused]] + }{ + save outs <- Val[first unused] + after maybe <- Val[after save] + } + If[[first unused] < [[node]Outputs >>]] + { + out <- [after maybe]Discard Outputs[first unused] + }{ + out <- Val[after maybe] + } + } + } + after save <- Fold[Save Result[?, ?, node index], with call, Range[0, save outs]] +} + +Compile Node[worker,program,func,nodes,current:out,out worker] +{ + node index <- [nodes]Index[current] + node <- [[worker]Nodes >>]Index[node index] + conditions <- [node]Conditions >> + [("call","getfield","setfield")]Find[=[[node]Type >>, ?]] + { + inputs <- [worker]Collect Inputs[node] + [conditions]For Backend + { + stream <- [func]Instruction Stream + nfunc <- [func]Do If[~, nstream] + }{ + stream <- Val[func] + nfunc <- Val[nstream] + } + nstream <- Compile Call Node[node, program, stream, inputs, node index] + }{ + If[[[node]Type >>] = ["output"]] + { + inputs <- [worker]Collect Inputs[node] + [conditions]For Backend + { + stream <- [func]Instruction Stream + nfunc <- [func]Do If[~, nstream] + }{ + stream <- Val[func] + nfunc <- Val[nstream] + } + nstream <- [stream]Move[[inputs]Index[0], [[worker]Outputs >>]Index[ [node]Data >> ] ] + }{ + If[[[node]Type >>] = ["const"]] + { + constname <- Const Name[[node]Data >>, node index, [worker]Name >>] + withconst <- [func]Register Constant[constname, [node]Data >>] + [conditions]For Backend + { + stream <- [[withconst]Instruction Stream + ]Move[Strip Addref[Constant[constname]], Result Var Name[0, node index]] + nfunc <- [withconst]Do If[~, stream] + }{ + nfunc <- Val[withconst] + } + }{ + If[[[node]Type >>]=["getglobal"]] + { + [conditions]For Backend + { + stream <- [[func]Instruction Stream + ]Move[Global Get[[[node]Data >>]Index[0], [[node]Data >>]Index[1]], Result Var Name[0, node index]] + nfunc <- [func]Do If[~, stream] + }{ + nfunc <- Val[func] + } + }{ + If[[[node]Type >>]=["setglobal"]] + + { + inputs <- [worker]Collect Inputs[node] + [conditions]For Backend + { + stream <- [func]Instruction Stream + nfunc <- [func]Do If[~, nstream] + }{ + stream <- Val[func] + nfunc <- Val[nstream] + } + nstream <- [stream]Set Global[[[node]Data >>]Index[0], [[node]Data >>]Index[1], [inputs]Index[0]] + }{ + [conditions]For Backend + { + input name <- [[worker]Inputs >>]Index[ [node]Data >> ] + stream <- [[func]Instruction Stream + ]Move[input name, Result Var Name[0, node index]] + nfunc <- [func]Do If[~, stream] + }{ + nfunc <- Val[func] + } + } + } + } + + } + } + [nodes]Next[current] + { + out,out worker <- [worker]Compile Node[program,nfunc,nodes,~] + }{ + out <- Val[nfunc] + out worker <- Val[worker] + } +} + +Save Node Conditions[worker,node index:out] +{ + node <- [[worker]Nodes >>]Index[node index] + conditions <- [worker]Collect Conditions[node] + out <- [worker]Nodes <<[ [[worker]Nodes >>]Set[node index, [node]Conditions <<[conditions]] ] + +} + +Save Group Conditions[worker, groups,current:out] +{ + nodes <- [groups]Index[current] + nworker <- Fold[Save Node Conditions[?], worker, nodes] + + [groups]Next[current] + { + out <- [nworker]Save Group Conditions[groups,~] + }{ + out <- Val[nworker] + } +} + +Compile Group[worker,program,func,groups,current:out,out worker] +{ + nodes <- [groups]Index[current] + [nodes]First + { + nfunc,nworker <- [worker]Compile Node[program,func,nodes,~] + }{ + nfunc <- Val[func] + nworker <- Val[worker] + } + [groups]Next[current] + { + out,out worker <- [nworker]Compile Group[program,nfunc,groups,~] + }{ + out <- Val[nfunc] + out worker <- Val[nworker] + } +} + +Release Var@NWorker[worker,func,name:out] +{ + //__result_index_ionum + parts <- [name]Split["_"] + index <- Int32[ [parts]Index[3] ] + io num <- Int32[ [parts]Index[4] ] + node <- [[worker]Nodes >>]Index[index] + dests <- [[node]Wires From >>]Index[io num] {} + + ,normal <- If[[[dests]Length] = [1]] + { + [dests]Index[0] + { + dest index <- [~]Index >> + dest IO <- [~]IO Num >> + } + normal <- If[[dest IO] = [-1]] {} + { + dest node <- [[worker]Nodes >>]Index[dest index] + + [[dest node]Conditions >>]For Backend + { + out <- [func]Do If[AndCond[NotCond[~], name], [[func]Instruction Stream]Release[name]] + }{ + out <- func + } + } + } + + Val[normal] + { + do if <- If[[[node]Outputs >>] > [1]] {} + { + do if <- [[node]Conditions >>]Empty? {} + { + out <- [func]Release[name] + } + } + + Val[do if] + { + stream <- [[func]Instruction Stream]Release[name] + out <- [func]Do If[name, stream] + } + } +} + +Result Var Name[io num, index:out] +{ + out <- [[["__result_"]Append[String[index]]]Append["_"]]Append[String[io num]] +} + +Result Var[vars,io num,index:out] +{ + out <- [vars]Append[Result Var Name[io num, index]] +} + +Node Result Vars[vars,node,index:out] +{ + [("call","getfield","setfield","getglobal")]Find[=[[node]Type >>, ?]] + { + If[[[node]Type >>]=["call"]] + { + save outs <- [Max Used Output[node, [[node]Outputs >>]-[1]]]+[1] + }{ + save outs <- [node]Outputs >> + } + out <- Fold[Result Var[?, ?, index], vars, Range[0, save outs]] + }{ + out <- vars + } +} + +Result Vars@NWorker[worker:out] +{ + out <- Fold[Node Result Vars[?], (), [worker]Nodes >>] +} + +_No Release[vars,node,index,worker:out] +{ + [("const","input")]Find[=[[node]Type >>, ?]] + { + [[node]Conditions >>]Empty? + { + out <- Result Var[vars, 0, index] + }{ + out <- vars + } + }{ + out <- vars + } +} + +No Release Results@NWorker[worker:out] +{ + out <- Fold[_No Release[?, ?, ?, worker], (), [worker]Nodes >>] +} + +Make Basic Type[type:out] +{ + out <- [Type Instance[[type]Name >>]]Params <<[ [type]Params >> ] +} + +FInputs[ifunc, input type, index, inputs:out] +{ + func <- [ifunc]Set Input Type[Make Basic Type[input type], index] + name <- [inputs]Index[index] + If[[[input type]Variant >>] = ["Naked"]] + { + + naked <- [" naked"]Append[name] + + out <- [[[func]Allocate Var[naked, input type] + ]Unbox[name, naked] + ]Release[name] + }{ + If[[input type]Mutable? >>] + { + name <- [inputs]Index[index] + copied <- [func]Copy[name, name] + + }{ + copied <- Val[func] + } + If[[[input type]Variant >>] = ["Raw Pointer"]] + { + raw <- [" raw"]Append[name] + If[[[input type]Name >>]=["Array"]] + { + + out <- [[copied]Allocate Var[raw, input type] + ]Array Raw Pointer[name, raw] + }{ + out <- [[copied]Allocate Var[raw, input type] + ]Get Raw Pointer[name, raw] + } + }{ + out <- Val[copied] + } + } +} + +Release Raw Inputs[func,input type,index,inputs,outputs:out] +{ + If[[[input type]Variant >>] = ["Raw Pointer"]] + { + name <- [inputs]Index[index] + If[[input type]Mutable? >>] + { + [outputs]Find[=[?,[inputs]Index[index]]] + { + out <- func + }{ + out <- [func]Release[name] + } + }{ + out <- [func]Release[name] + } + }{ + out <- func + } +} + +FParams[input:out] +{ + iname <- [input]Index[0] + type <- [input]Index[1] + If[[[type]Variant >>] = ["Naked"]] + { out <- [" naked"]Append[iname] } + { + If[[[type]Variant >>] = ["Raw Pointer"]] + { out <- [" raw"]Append[iname] } + { out <- Val[iname] } + } +} +_Return Param[outputs, inputs, input types, index:out,none] +{ + output <- [outputs]Index[index] + [inputs]Find[=[output, ?]] + { + If[[[input types]Index[~]]Mutable? >>] + { + ,none <- [outputs]Next[index] + { + out,none <- _Return Param[outputs, inputs, input types, ~] + } + } { + out <- index + } + }{ + out <- index + } +} + +Return Param[outputs, inputs, input types:out,none] +{ + ,none <- [outputs]First + { out,none <- _Return Param[outputs, inputs, input types, ~] } + +} + +Save Foreign Result[func, output, index, output types, inputs, input types:out] +{ + type <- [output types]Index[index] + If[[[type]Variant >>] = ["Naked"]] + { + out <- [func]Box[[" naked"]Append[output], output, type] + }{ + [inputs]Find[=[output, ?]] + { + If[[[input types]Index[~]]Mutable? >>] + { + out <- [func]Move[output, Output[output]] + }{ + out <- func + } + }{ + out <- func + } + } +} + +Compile Foreign Stub[worker,program,name:out] +{ + ifunc <- [[program]Create Function[name, [worker]Inputs >>, [worker]Outputs >>, "rhope"] + ]Output Types <<[Map[[worker]Output Types >>, Make Basic Type[?]]] + + rp num <- Return Param[[worker]Outputs >>, [worker]Inputs >>, [worker]Input Types >>] + { + rbase <- [[worker]Outputs >>]Index[rp num] + If[[[[[worker]Output Types >>]Index[rp num]]Variant >>] = ["Naked"]] + { + rparam <- [" naked"]Append[rbase] + rfunc <- [ifunc]Allocate Var[rparam, [[worker]Output Types >>]Index[rp num]] + }{ + rparam <- Val[rbase] + rfunc <- Val[ifunc] + } + }{ + rparam <- "" + rfunc <- Val[ifunc] + } + + Fold[FInputs[?, ?, ?, [worker]Inputs >>], rfunc, [worker]Input Types >>] + { [~]Call Foreign[name, [worker]Convention >>, Map[Zip[[worker]Inputs >>, [worker]Input Types >>], FParams[?]], rparam] + { Fold[Release Raw Inputs[?, ?, ?, [worker]Inputs >>, [worker]Outputs >>], ~, [worker]Input Types >>] + { Fold[Save Foreign Result[?, ?, ?, [worker]Output Types >>, [worker]Inputs >>, [worker]Input Types >>], ~, [worker]Outputs >>] + { out <- [program]Store Function[~] }}}} +} + +Compile Worker@NWorker[worker,program,name:out] +{ + If[[worker]Builtin? >>] + { + out <- program + }{ + If[[[worker]Library >>] = [""]] + { + ifunc <- Fold[Set Output Type[?], Fold[Set Input Type[?], [[program]Create Function[name,[worker]Inputs >>, [worker]Outputs >>, [worker]Convention >>]]Uses <<[[worker]Uses >>], [worker]Input Types >>], [worker]Output Types >>] + + groups <- [worker]Dependency Groups + + fgroup <- [groups]First + { + with conds <- [worker]Save Group Conditions[groups, ~] + final func <- [with conds]Compile Group[program,func,groups, ~] + }{ + final func <- Val[func] + } + res vars <- [worker]Result Vars + init vars <- Concatenate[res vars, [with conds]No Release Results] + + func <- Fold[Set Null[?], Fold[Set Null[?], Fold[Allocate Var[?, ?, "Any Type"], ifunc, init vars], init vars], [worker]Outputs >>] + out <- [program]Store Function[Fold[Release[?], Fold[Release Var[with conds, ?], final func, res vars], [worker]Inputs >>]] + }{ + out <- Compile Foreign Stub[worker,[program]Link[[worker]Convention >>, [worker]Library >> ],name] + } + } +} + +Blueprint NBlueprint +{ + Fields + Methods +} + +String@NBlueprint[nbp:out] +{ + out <- [[[["NBlueprint: Fields(" + ]Append[Join[Map[[nbp]Fields >>, [?]Index[0]], ", "]] + ]Append["), Methods("] + ]Append[Join[Keys[[nbp]Methods >>], ", "]] + ]Append[")"] +} + +NBlueprint[:out] +{ + out <- [[Build[NBlueprint()]]Fields <<[()]]Methods <<[Dictionary[]] +} + +Add Field@NBlueprint[bp,name,type:out] +{ + out <- [bp]Fields <<[ [[bp]Fields >>]Append[ [[()]Append[name]]Append[type] ] ] +} + +Add Method@NBlueprint[bp,name:out] +{ + out <- [bp]Methods <<[ [[bp]Methods >>]Set[name, Yes] ] + +} + +Understands Method@NBlueprint[bp,name:out] +{ + out <- [[bp]Methods >>]Index[name] {} + { out <- No } +} + +Eq Field Name[field,name:out] +{ + out <- [[field]Index[0]]=[name] +} + +Get Field Type@NBlueprint[bp,name:out,notfound] +{ + ,not found <- [[bp]Fields >>]Find[Eq Field Name[?, name]] + { out <- [[[bp]Fields >>]Index[~]]Index[1] } +} + +_Compile Blueprint Fields[type,field:out] +{ + name <- [field]Index[0] + ftype <- [field]Index[1] + out <- [type]Add Field[name,ftype] +} + +_Compile Blueprint Methods[type,junk,name:out] +{ + If[[[name]=["Call"]] And [[[type]Name >>] = ["Worker"]]] + { + out <- type + }{ + out <- [type]Add Method[name] + } +} + +Make Init[func,field:out] +{ + name <- [field]Index[0] + variant <- [[field]Index[1]]Variant >> + If[[variant] = ["Boxed"]] + { + out <- [func]Set Field Null["obj", name] + }{ + out <- func + } +} + +Make Copy[func,field:out] +{ + name <- [field]Index[0] + variant <- [[field]Index[1]]Variant >> + If[[variant] = ["Boxed"]] + { + got <- [func]Read Field["obj", name] {} + { + stream <- [[got]Instruction Stream + ]AddRef No Dest[~] + out <- [got]Do If[~, stream] + } + }{ + out <- func + } +} + +Make Cleanup[func,field:out] +{ + name <- [field]Index[0] + variant <- [[field]Index[1]]Variant >> + If[[variant] = ["Boxed"]] + { + got <- [func]Read Field["obj", name] {} + { + stream <- [[got]Instruction Stream + ]Release[~] + out <- [got]Do If[~, stream] + } + }{ + out <- func + } +} + +Make Special@NBlueprint[bp,backend,info,bp name:out] +{ + func name <- [info]Index[0] + pop worker <- [info]Index[1] + func <- [[backend]Create Function[func name,("obj"),(),"cdecl"] + ]Set Input Type[Type Instance[bp name], 0] + out <- [backend]Store Function[Fold[pop worker, func, [bp]Fields >>]] +} + +Getters Setters[backend,field,type name:out] +{ + //TODO: Throw an exception or something if we read a field that is empty + name <- [field]Index[0] + type <- [field]Index[1] + mytype <- Type Instance[type name] + start getter,getref <- [[[[backend]Create Function[ [[[name]Append[" >>"]]Append["@"]]Append[type name], ("obj"), ("out"), "rhope"] + ]Set Input Type[mytype, 0] + ]Set Output Type[[type]Set Variant["Boxed"], 0] + ]Read Field["obj", name] + If[[[type]Variant >>] = ["Boxed"]] + { + getter <- [[start getter]Do AddRef[getref, "out"]]Release["obj"] + }{ + getter <- [[start getter]Box[getref, "out", type]]Release["obj"] + } + + begin setter <- [[[[[backend]Create Function[ [[[name]Append[" <<"]]Append["@"]]Append[type name], ("obj","newval"), ("out"), "rhope"] + ]Set Input Type[mytype, 0] + ]Set Input Type[[type]Set Variant["Boxed"], 1] + ]Set Output Type[mytype, 0] + ]Copy["obj"] + + If[[[type]Variant >>] = ["Boxed"]] + { + ,origref <- [begin setter]Read Field["obj", name] + { + stream <- [[~]Instruction Stream + ]Release[origref] + ,setref <- [[~]Do If[origref, stream] + ]Write Field["obj", name] + { + setter <- [[~]Move["newval", setref] + ]Move["obj", "out"] + } + } + }{ + ,setref <- [begin setter]Write Field["obj", name] + { + setter <- [[[~]Unbox["newval", setref] + ]Release["newval"] + ]Move["obj", "out"] + } + } + + out <- [[backend]Store Function[getter]]Store Function[setter] + +} + +Compile Blueprint@NBlueprint[bp,backend,name:out] +{ + //Rhope identifiers can't start with spaces, so we can use identifiers that start with spaces for special functions + init name <- [" init "]Append[name] + [("Array","Boxed Array","Worker")]Find[=[?,name]] + { + [("internalarraynaked","internalarrayboxed","internalworker")]Index[~] + { + copy name <- [~]Append["copy"] + cleanup name <- [~]Append["cleanup"] + } + }{ + copy name <- [" copy "]Append[name] + cleanup name <- [" cleanup "]Append[name] + } + type <- [[[Fold[_Compile Blueprint Methods[?], Fold[_Compile Blueprint Fields[?], [backend]Create Type[name], [bp]Fields >>], [bp]Methods >>] + ]Init <<[init name] + ]Copy <<[copy name] + ]Cleanup <<[cleanup name] + + out <- [backend]Register Type[type] +} + +Compile Special@NBlueprint[bp,backend,name:out] +{ + makespecial <- [[[Dictionary[] + ]Set["init", Make Init[?]] + ]Set["copy", Make Copy[?]] + ]Set["cleanup", Make Cleanup[?]] + + after specials <- Fold[[bp]Make Special[?, ?, name], backend, [backend]Needed Specials[name,makespecial]] + out <- Fold[Getters Setters[?, ?, name], after specials, [bp]Fields >>] +} + +Blueprint NProgram +{ + Blueprints + Workers + Worker Refs + Numtypes + Global Stores +} + +NProgram[:out] +{ + out <- [[[[[Build[NProgram()] + ]Blueprints <<[Dictionary[]] + ]Workers <<[Dictionary[]] + ]Worker Refs <<[Dictionary[]] + ]Numtypes << [("Int8","Int16","Int32","Int64","UInt8","UInt16","UInt32","UInt64")] + ]Global Stores <<[Dictionary[]] +} + +Supported Number Types@NProgram[program:out] +{ + out <- [program]Numtypes >> +} + +Bind Worker@NProgram[prog,name,worker:out] +{ + after bind <- [prog]Workers << [ [[prog]Workers >>]Set[name, [worker]Name <<[name]] ] + parts <- [name]Split["@"] + bpname <- [parts]Index[1] + { + If[[~]=[""]] + { + out <- Val[after bind] + }{ + orig bp <- [[after bind]Blueprints >>]Index[bpname] {} + { orig bp <- NBlueprint[] } + out <- [after bind]Blueprints <<[ [[after bind]Blueprints >>]Set[bpname, [orig bp]Add Method[[parts]Index[0]] ] ] + } + }{ + out <- Val[after bind] + } +} + +Bind Blueprint@NProgram[prog,name,blueprint:out] +{ + out <- [prog]Blueprints << [ [[prog]Blueprints >>]Set[name, blueprint] ] +} + +_Compile Program BP[backend, blueprint, name:out] +{ + out <- [blueprint]Compile Blueprint[backend, name] +} + +_Compile Program BP Special[backend, blueprint, name:out] +{ + out <- [blueprint]Compile Special[backend, name] +} + +_Compile Program[backend, worker, name:out] +{ + out <- [worker]Compile Worker[backend, name] +} + +Compile Program@NProgram[prog, backend:out] +{ + backend with bps <- Generate Boolean Methods[Generate Number Methods[Fold[_Compile Program BP Special[?], Fold[_Compile Program BP[?], [backend]Global Stores <<[[prog]Global Stores >>], [prog]Blueprints >>], [prog]Blueprints >>]]] + workers with infer <- Map[[prog]Workers >>, Infer Types[?, prog]] + out <- Fold[_Compile Program[?], backend with bps, workers with infer] +} + +Register Method@NProgram[prog, name, convention, inputs, outputs: out] +{ + [[prog]Worker Refs >>]Index[name] + { + ref <- [[[[[~]Inputs <<[ Max[[~]Inputs >>, inputs] ] + ]Min Inputs <<[ Min[[~]Min Inputs >>, inputs] ] + ]Outputs <<[ Max[[~]Outputs >>, outputs] ] + ]Min Outputs <<[ Min[[~]Min Outputs >>, outputs] ] + ]Is Method? <<[Yes] + }{ + ref <- Worker Ref[name, convention, inputs, outputs, Yes] + } + out <- [prog]Worker Refs <<[ [[prog]Worker Refs >>]Set[name, ref]] +} + +Register Worker@NProgram[prog, name, convention, inputs, outputs: out] +{ + [[prog]Worker Refs >>]Index[name] + { + ref <- [[[[~]Inputs <<[ Max[[~]Inputs >>, inputs] ] + ]Min Inputs <<[ Min[[~]Min Inputs >>, inputs] ] + ]Outputs <<[ Max[[~]Outputs >>, outputs] ] + ]Min Outputs <<[ Min[[~]Min Outputs >>, outputs] ] + }{ + ref <- Worker Ref[name, convention, inputs, outputs, No] + } + after reg <- [prog]Worker Refs <<[ + [ [prog]Worker Refs >> ]Set[name, ref] + ] + + parts <- [name]Split["@"] + [parts]Index[1] + { + If[[~]=[""]] + { + out <- [after reg]Register Worker[[parts]Index[0], convention, inputs, outputs] + }{ + out <- [after reg]Register Method@NProgram[[parts]Index[0], convention, inputs, outputs] + } + }{ + out <- Val[after reg] + } +} + +Register Builtins@NProgram[prog:out] +{ + registered <- [[[[[[[[[[[[prog]Register Worker["Print", "rhope", 1, 1] + ]Register Worker["If@Boolean", "rhope", 1, 2] + ]Register Worker["Build", "rhope", 1, 1] + ]Register Worker["Blueprint Of", "rhope", 1, 1] + ]Register Worker["Call", "rhope", 1, 1]//This will ensure that min outputs is 1 + ]Register Worker["Call@Worker", "rhope", 1, 10]//10 is a quick workaround for the lack of proper varargs + ]Register Worker["ID", "rhope", 1, 1] + ]Register Worker["Blueprint From ID", "rhope", 1, 2] + ]Register Worker["Pause", "rhope", 1, 1] + ]Register Worker["Resume", "rhope", 2, 2] + ]Register Worker["Run Bytecode", "rhope", 2, 1] + ]Register Number Methods + + out <- [[[[[[[[[[registered]Bind Worker["If@Boolean", + [[[[[NWorker["rhope"] + ]Inputs <<[("condition")] + ]Input Types <<[ [()]Append[Type Instance["Boolean"]] ] + ]Outputs <<[("isyes","isno")] + ]Output Types <<[ [[()]Append[Type Instance["Boolean"]]]Append[Type Instance["Boolean"]] ] + ]Builtin? <<[Yes]] + ]Bind Worker["Print", + [[[[[NWorker["rhope"] + ]Inputs <<[("value")] + ]Input Types <<[ [()]Append[Type Instance["Any Type"]] ] + ]Outputs <<[("out")] + ]Output Types <<[ [()]Append[Type Instance["Int32"]] ] + ]Builtin? <<[Yes]] + ]Bind Worker["Build", + [[[[[NWorker["rhope"] + ]Inputs <<[("type")] + ]Input Types <<[ [()]Append[Type Instance["Blueprint"]] ] + ]Outputs <<[("out")] + ]Output Types <<[ [()]Append[Type Instance["Any Type"]] ] + ]Builtin? <<[Yes]] + ]Bind Worker["Blueprint Of", + [[[[[NWorker["rhope"] + ]Inputs <<[("object")] + ]Input Types <<[ [()]Append[Type Instance["Any Type"]]] + ]Outputs <<[("type")] + ]Output Types <<[ [()]Append[Type Instance["Blueprint"]]] + ]Builtin? <<[Yes]] + ]Bind Worker["Call@Worker", + [[[[[NWorker["rhope"] + ]Inputs <<[("worker")] + ]Input Types <<[ [()]Append[Type Instance["Worker"]] ] + ]Outputs <<[("ret1","ret2","ret3","ret4","ret5","ret6","ret7","ret8","ret9","ret10")] + ]Output Types <<[ [[()]Append[Type Instance["Any Type"]]]Append[Type Instance["Any Type"]] ] + ]Builtin? << [Yes]] + ]Bind Worker["ID", + [[[[[NWorker["rhope"] + ]Inputs <<[("bp")] + ]Input Types <<[ [()]Append[Type Instance["Blueprint"]]] + ]Outputs <<[("id")] + ]Output Types <<[ [()]Append[Type Instance["UInt32"]]] + ]Builtin? << [Yes]] + ]Bind Worker["Blueprint From ID", + [[[[[NWorker["rhope"] + ]Inputs <<[("id")] + ]Input Types <<[ [()]Append[Type Instance["UInt32"]]] + ]Outputs <<[("bp","none")] + ]Output Types <<[ [[()]Append[Type Instance["Blueprint"]]]Append[Type Instance["Any Type"]]] + ]Builtin? << [Yes]] + ]Bind Worker["Pause", + [[[[[NWorker["rhope"] + ]Inputs <<[("tocall")] + ]Input Types <<[ [()]Append[Type Instance["Worker"]]] + ]Outputs <<[("resumeval")] + ]Output Types <<[ [()]Append[Type Instance["Any Type"]] ] + ]Builtin? <<[Yes]] + ]Bind Worker["Resume", + [[[[[NWorker["rhope"] + ]Inputs <<[("toresume","resumeval")] + ]Input Types <<[ [[()]Append[Type Instance["Contest"]]]Append[Type Instance["Any Type"]] ] + ]Outputs <<[("success","cantresume")] + ]Output Types <<[ [[()]Append[Type Instance["Any Type"]]]Append[Type Instance["Any Type"]] ] + ]Builtin? <<[Yes]] + ]Bind Worker["Run Bytecode", + [[[[[NWorker["rhope"] + ]Inputs <<[("bytecode","constants")] + ]Input Types <<[ [[()]Append[Type Instance["Array"]]]Append[Type Instance["Boxed Array"]] ] + ]Outputs <<[("ret1")] + ]Output Types <<[ [()]Append[Type Instance["Any Type"]] ] + ]Builtin? <<[Yes] + ] +} + +Find Worker@NProgram[prog, name:out,notfound] +{ + out,notfound <- [[prog]Worker Refs >>]Index[name] +} + +Find Worker Def@NProgram[prog,name:out,notfound] +{ + out,notfound <- [[prog]Workers >>]Index[name] +} + +Find Method@NProgram[prog, name, type:out,notfound] +{ + bp,notfound <- [[prog]Blueprints >>]Index[[type]Name >>] + ,notfound <- If[[bp]Understands Method[name]] + { + out <- [[prog]Workers >>]Index[[[name]Append["@"]]Append[[type]Name >>]] + } +} + +Find Field@NProgram[prog, name, type:fieldtype,notfound] +{ + bp,notfound <- [[prog]Blueprints >>]Index[[type]Name >>] + fieldtype,notfound <- [bp]Get Field Type[name] +} + +Implicit Conversion@NProgram[prog, fromtype, totype:func,notfound] +{ + notfound <- No +} + +Is Method?@NProgram[prog,name:is,is not] +{ + ,is not <- [[prog]Worker Refs>>]Index[name] + { + is,is not <- If[[~]Is Method? >>] + } +} + diff -r 24c6f8767190 -r c6ba9fe45910 nworker_c.rhope --- a/nworker_c.rhope Wed Jul 27 21:14:23 2011 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1787 +0,0 @@ -Import number_c.rhope -Import boolean.rhope - -Blueprint Condition Set -{ - Variables - Subsets - Condition Type -} - -AndSet[:out] -{ - out <- [[[Build[Condition Set()]]Variables <<[Dictionary[]]]Subsets <<[()]]Condition Type <<["And"] -} - -OrSet[:out] -{ - out <- [[[Build[Condition Set()]]Variables <<[Dictionary[]]]Subsets <<[()]]Condition Type <<["Or"] -} - -To String@Condition Set[set:out] -{ - out <- [[[[[set]Condition Type >> - ]Append["Set:\n\tVariables:\n\t\t"] - ]Append[ Join[Keys[[set]Variables >>], "\n\t\t"] ] - ]Append["\n\tSubsets:\n\t\t"] - ]Append[ Join[Keys[[set]Subsets >>], "\n\t\t"] ] -} - -Add Condition@Condition Set[set,cond:out] -{ - If[[Blueprint Of[cond]] = [Condition Set()]] - { - If[[[set]Condition Type >>]=[[cond]Condition Type >>]] - { - out <- [[set]Variables <<[ Combine[[set]Variables >>, [cond]Variables >>] ] - ]Subsets <<[ Concatenate[[set]Subsets >>, [cond]Subsets >>] ] - }{ - [cond]Empty? - { - [cond]Simple? - { out <- [set]Variables <<[ Combine[[set]Variables >>, [cond]Variables >>] ] } - { out <- [set]Subsets <<[ [[set]Subsets>>]Append[cond] ] } - }{ - out <- set - } - } - }{ - out <- [set]Variables <<[ [[set]Variables >>]Set[cond, Yes] ] - } -} - -=@Condition Set[set1,set2:out] -{ - ,out <- If[[[set1]Condition Type >>] = [[set2]Condition Type >>]] - { - ,out <- If[[[set1]Variables >>] = [[set2]Variables >>]] - { - out,out <- If[[[set1]Subsets >>] = [[set2]Subsets >>]] - } - } -} - -_For Backend Var[current,junk,variable,type:out] -{ - If[[type]=["And"]] - { cond <- Val[AndCond[?]] } - { cond <- Val[OrCond[?]] } - out <- [cond]Call[current, variable] -} - -_For Backend Subset[current,subset,type:out] -{ - [subset]For Backend - { - If[[type]=["And"]] - { cond <- Val[AndCond[?]] } - { cond <- Val[OrCond[?]] } - out <- out <- [cond]Call[current, ~] - }{ - out <- current - } -} - -Empty?@Condition Set[set:not empty,empty] -{ - [[set]Variables >>]First - { - not empty <- Yes - }{ - ,empty <- [[set]Subsets >>]First - { - not empty <- Yes - } - } -} - -Simple?@Condition Set[set:simple,not simple] -{ - ,not simple <- If[[Length[[set]Variables >>]]=[1]] - { - simple,not simple <- If[[Blueprint Of[[set]Subsets >>]]=[Empty Dictionary()]] - } -} - -For Backend@Condition Set[set:out,none] -{ - firstvar <- [[set]Variables >>]First - { - [[set]Variables >>]Next[~] - { - vars <- _Fold[[set]Variables >>, ~, firstvar, _For Backend Var[?, ?, ?, [set]Condition Type >>]] - }{ - vars <- Val[firstvar] - } - out <- Fold[_For Backend Subset[?, ?, [set]Condition Type >>], vars, [set]Subsets >>] - }{ - [[set]Subsets >>]First - { - firstsub <- [[[set]Subsets >>]Index[~]]For Backend - [[set]Subsets >>]Next[~] - { - out <- _Fold[[set]Subsets >>, ~, firstsub, _For Backend Subset[?, ?, [set]Condition Type >>]] - }{ - out <- Val[firstsub] - } - }{ - none <- Yes - } - } -} - -List of Lists[num:out] -{ - out <- Fold[Append[?, ()],(), Range[0,num]] -} - -Blueprint Worker Ref -{ - Name - Convention - Inputs - Min Inputs - Outputs - Min Outputs - Is Method? -} - -Worker Ref[name,convention,inputs,outputs,ismethod?:out] -{ - out <- [[[[[[[Build[Worker Ref()]]Name <<[name]]Convention <<[convention]]Inputs <<[inputs]]Outputs <<[outputs]]Is Method? <<[ismethod?]]Min Inputs <<[inputs]]Min Outputs <<[outputs] -} - -String@Worker Ref[ref:out] -{ - out <- [[[[[[[["Worker Ref[" - ]Append[[ref]Name >>] - ]Append[", "] - ]Append[[ref]Convention >>] - ]Append[", "] - ]Append[String[[ref]Inputs >>]] - ]Append[", "] - ]Append[String[[ref]Outputs >>]] - ]Append["]"] -} - -Blueprint Node Ref -{ - Index - IO Num -} - -Node Ref[index,ionum:out] -{ - out <- [[Build[Node Ref()]]Index <<[index]]IO Num <<[ionum] -} - -=@Node Ref[left,right:out] -{ - ,out <- If[[[left]Index >>] = [[right]Index >>]] - { - out <- [[left]IO Num>>] = [[right]IO Num >>] - } -} - -Blueprint NWorker Node -{ - Type - Data - Inputs - Min Inputs - Input Types - Outputs - Min Outputs - Output Types - Wires From - Wires To - Conditions -} - -Wire To@NWorker Node[node,from,output,pre input:out] -{ - existing cons <- [[node]Wires To >>]Index[input] {} - { existing cons <- () } - input <- [pre input]+[1] - out <- [node]Wires To <<[ - [[node]Wires To >>]Set[input, - [existing cons]Append[Node Ref[from,output]] - ] - ] -} - -Wire From@NWorker Node[node,to,input,output:out] -{ - existing cons <- [[node]Wires From >>]Index[output] {} - { existing cons <- () } - out <- [node]Wires From <<[ - [[node]Wires From >>]Set[output, - [existing cons]Append[Node Ref[to,input]] - ] - ] -} - -_Has Input Types@NWorker Node[node,input num:does,does not] -{ - does <- If[[input num] >= [[node]Inputs >>]] {} - { - ,does not <- [[node]Input Types >>]Index[input num] - { - count <- [~]Index[1] - ,does not <- If[[count] = [[[[node]Wires To >>]Index[[input num]+[1]]]Length]] - { - does,does not <- [node]_Has Input Types[[input num]+[1]] - } - } - } -} - -Has Input Types?@NWorker Node[node:does,does not] -{ - If[[[node]Inputs >>] > [0]] - { - does,does not <- _Has Input Types[node,0] - }{ - does <- Yes - } -} - -_Dependency[dlist,ref:out] -{ - [dlist]Find[=[ref, ?]] - { - out <- dlist - }{ - out <- [dlist]Append[ref] - } -} - -Dependencies@NWorker Node[node:out] -{ - out <- Fold[Fold[_Dependency[?], ?], (), [node]Wires To >>] -} - - -NWorker Node[type,data,inputs,outputs:out] -{ - out <- [[[[[[[[[[[Build[NWorker Node()] - ]Type <<[type] - ]Data <<[data] - ]Inputs <<[inputs] - ]Min Inputs <<[inputs] - ]Outputs <<[outputs] - ]Min Outputs <<[outputs] - ]Wires From <<[List of Lists[outputs]] - ]Wires To <<[List of Lists[[inputs]+[1]]] - ]Conditions <<[AndSet[]] - ]Input Types <<[()] - ]Output Types <<[()] -} - -Blueprint NWorker -{ - Convention - Nodes - Inputs - Input Types - Outputs - Output Types - Uses - NodeResults - Free Temps - Name - Builtin? - Library -} - -NWorker[convention:out] -{ - out <- [[[[[[[[[[Build[NWorker()]]Convention <<[convention]]Nodes <<[()]]Inputs <<[()]]Outputs <<[()]]Input Types <<[()]]Output Types <<[()]]Name <<["Anonymous"]]Builtin? <<[No]]Library << [""]]Uses <<[()] -} - -String@NWorker[worker:out] -{ - out <- ["NWorker"]Append[[worker]Name >>] -} - -Add Node@NWorker[worker,type,data,inputs,outputs:out,node index] -{ - out <- [worker]Nodes <<[[[worker]Nodes >>]Append[NWorker Node[type,data,inputs,outputs]]] - node index <- [[worker]Nodes >>]Length -} - -Add Full Node@NWorker[worker,type,data,inputs,min inputs,outputs,min outputs:out,node index] -{ - out <- [worker]Nodes <<[[[worker]Nodes >>]Append[ - [[[NWorker Node[type,data,inputs,outputs] - ]Min Inputs <<[min inputs] - ]Min Outputs <<[min outputs] - ]Wires To <<[List of Lists[[min inputs]+[1]]] - ]] - node index <- [[worker]Nodes >>]Length -} - -Propagate Type[nodelist,dest,prog,worker,type:out] -{ - If[[[dest]IO Num >>] >= [0]] - { - node <- [nodelist]Index[[dest]Index >>] - - [[node]Input Types >>]Index[[dest]IO Num >>] - { - existing type <- [~]Index[0] - new count <- [[~]Index[1]]+[1] - If[[[existing type]Name >>] = [[type]Name >>]] - { - If[[[existing type]Variant >>] = [[type]Variant >>]] - { - If[[[existing type]Params >>] = [[type]Params >>]] - { - new type <- Val[existing type] - }{ - new variant <- [existing type]Variant >> - new params <- () - } - }{ - new variant <- "Boxed" - If[[[existing type]Params >>] = [[type]Params >>]] - { - new params <- [existing type]Params >> - }{ - new params <- () - } - } - new type <- [[existing type]Set Variant[new variant]]Params <<[new params] - }{ - new type <- Type Instance["Any Type"] - } - }{ - new type <- Val[type] - new count <- 1 - } - new node <- [node]Input Types <<[ - [ [node]Input Types >> ]Set[ [dest]IO Num >>, [[()]Append[new type]]Append[new count] ] - ] - out <- Infer Types Node[[nodelist]Set[[dest]Index >>, new node], new node, [dest]Index >>, prog, worker] - }{ - out <- nodelist - } -} - -Propagate Types[nodelist,dests,output num,prog,worker,source node:out] -{ - [[source node]Output Types >>]Index[output num] - { - out <- Fold[Propagate Type[?, ?, prog, worker, ~], nodelist, dests] - }{ - out <- nodelist - } -} - -Infer Types Node[nodelist,node,index,prog,worker:out] -{ - If[[[node]Type >>]=["call"]] - { - extra <- [", worker: "]Append[[[node]Data >>]Name >>] - }{ - extra <- "" - } - If[[[node]Type >>] = ["const"]] - { - const type <- Blueprint Of[[node]Data >>] - [(Int8(),UInt8(),Int16(),UInt16(),Int32(),UInt32(),Int64(),UInt64(), - Type Instance(),Worker Literal(),List(),List Leaf(),String(),String Slice(),String Cat())]Find[=[const type, ?]] - { - outtype <- [("Int8","UInt8","Int16","UInt16","Int32","UInt32","Int64","UInt64", - "Blueprint","Worker","List","List Leaf","String","String","String")]Index[~] - }{ - outtype <- "Any Type" - } - nextnode <- [node]Output Types <<[ [()]Append[Type Instance[outtype]] ] - - }{ - If[[[node]Type >>] = ["setglobal"]] - { - out <- nodelist - }{ - If[[[node]Type >>] = ["input"]] - { - nextnode <- [node]Output Types <<[ [()]Append[ [[worker]Input Types >>]Index[[node]Data >>] ] ] - }{ - If[[[node]Type >>] = ["output"]] - { - out <- nodelist - - }{ - If[[[node]Type >>] = ["getglobal"]] - { - nextnode <- [node]Output Types <<[ [()]Append[Type Instance["Any Type"]] ] - }{ - [node]Has Input Types? - { - If[[[node]Type >>] = ["setfield"]] - { - nextnode <- [node]Output Types <<[ [()]Append[ [[[node]Input Types >>]Index[0]]Index[0] ] ] - }{ - If[[[node]Type >>] = ["getfield"]] - { - type <- [[[node]Input Types >>]Index[0]]Index[0] - If[[[type]Name >>] = ["Any Type"]] - { - outtype <- Val[type] - }{ - outtype <- [prog]Find Field[[node]Data >>, type] {} - { - //TODO: Return errors rather than printing them - Print[ - [[[[["Type " - ]Append[[type]Name >>] - ]Append[" does not have a field named "] - ]Append[[node]Data >>] - ]Append[" in worker "] - ]Append[worker name]] - } - } - nextnode <- [node]Output Types <<[ [()]Append[outtype] ] - }{ - worker name <- [[node]Data >>]Name >> - [prog]Is Method?[worker name] - { - first arg type <- [[[node]Input Types >>]Index[0]]Index[0] - If[[[first arg type]Name >>] = ["Any Type"]] - { - outtypes <- Fold[Append[?, Type Instance["Any Type"]], (), Range[0, [node]Inputs >>]] - nextnode <- [node]Output Types <<[ outtypes ] - }{ - worker def <- [prog]Find Method[worker name, first arg type] - { - new worker name <- [[worker name]Append["@"]]Append[[first arg type]Name >>] - new ref <- [prog]Find Worker[new worker name] {} { - Print[["Could not find worker ref for "]Append[new worker name]] - } - nextnode <- [[node]Output Types <<[outtypes] - ]Data <<[new ref] - }{ - //TODO: Return errors instead of printing them - Print[ - [[[[["Type " - ]Append[[first arg type]Name >>] - ]Append[" does not support method "] - ]Append[worker name] - ]Append[" in worker "] - ]Append[ [worker]Name >> ]] - } - } - }{ - worker def <- [prog]Find Worker Def[worker name] {} - { Print["Error, could not find worker def"] } - nextnode <- [node]Output Types <<[ outtypes ] - } - outtypes <- [worker def]Output Types >> - } - } - }{ - out <- nodelist - } - } - } - } - } - } - - Val[nextnode] - { - nextlist <- [nodelist]Set[index, nextnode] - out <- Fold[Propagate Types[?, ?, ?, prog, worker, nextnode], nextlist, [nextnode]Wires From >>] - } -} - -Infer Types@NWorker[worker,prog:out] -{ - out <- [worker]Nodes <<[Fold[Infer Types Node[?, ?, ?, prog, worker], [worker]Nodes >>, [worker]Nodes >>]] -} - -Add Worker Call@NWorker[worker,tocall:out,node index] -{ - out, node index <- [worker]Add Full Node["call",tocall,[tocall]Inputs >>, [tocall]Min Inputs >>,[tocall]Outputs >>, [tocall]Min Outputs >>] -} - -Add Constant@NWorker[worker,constant:out,node index] -{ - out, node index <- [worker]Add Node["const",constant,0,1] -} - -Add Input@NWorker[worker,name,number:out,node index] -{ - out,node index <- [worker]Add Typed Input[name,number,Type Instance["Any Type"]] -} - -Add Anon Input@NWorker[worker,number:out] -{ - If[[number]>[Length[[worker]Inputs >>]]] - { - prepped <- [worker]Add Anon Input[[number]-[1]] - }{ - prepped <- Val[worker] - } - out <- out <- [[prepped]Inputs <<[[[prepped]Inputs >>]Set[number,[" unnamed"]Append[String[number]]]] - ]Input Types <<[[[prepped]Input Types >>]Set[number,Type Instance["Any Type"]]] -} - -Add Typed Input@NWorker[worker,name,number,type:out,node index] -{ - If[[number]>[Length[[worker]Inputs >>]]] - { - prepped <- [worker]Add Anon Input[[number]-[1]] - }{ - prepped <- Val[worker] - } - ,node index <- [prepped]Add Node["input",number,0,1] - { - out <- [[~]Inputs <<[[[~]Inputs >>]Set[number,name]] - ]Input Types <<[[[~]Input Types >>]Set[number,type]] - } -} - -Add Output@NWorker[worker,name,number:out,node index] -{ - out,node index <- [worker]Add Typed Output[name,number,Type Instance["Any Type"]] -} - -Add Typed Output@NWorker[worker,name,number,type:out,node index] -{ - ,node index <- [worker]Add Node["output",number,1,0] - { - out <- [[~]Outputs <<[[[~]Outputs >>]Set[number,name]] - ]Output Types <<[[[~]Output Types >>]Set[number,type]] - } -} - -Add Object Get@NWorker[worker,fieldname:out,node index] -{ - out, node index <- [worker]Add Node["getfield",fieldname,1,1] -} - -Add Object Set@NWorker[worker,fieldname:out,node index] -{ - out, node index <- [worker]Add Node["setfield",fieldname,2,1] -} - -Add Global Get@NWorker[worker,store,var:out,node index] -{ - out, node index <- [worker]Add Node["getglobal",[[()]Append[store]]Append[var],0,1] -} - -Add Global Set@NWorker[worker,store,var:out,node index] -{ - out, node index <- [worker]Add Node["setglobal",[[()]Append[store]]Append[var],1,1] -} - -Add Wire@NWorker[worker,from,output,to,input:out] -{ - fromw <- [[[worker]Nodes >>]Index[from]]Wire From[to,input,output] - tow <- [[[worker]Nodes >>]Index[to]]Wire To[from,output,input] - nodes <- [[[worker]Nodes >>]Set[from, fromw]]Set[to, tow] - out <- [worker]Nodes <<[nodes] -} - -Uses@NWorker[worker,uses:out] -{ - out <- [worker]Uses <<[uses] -} - -_No Dependencies[list,node,index:out] -{ - [[node]Wires To>>]Index[1] - { - out <- Val[list] - }{ - [[[node]Wires To>>]Index[0]]First - { - out <- Val[list] - }{ - out <- [list]Append[index] - } - } -} - -No Dependencies@NWorker[worker:out] -{ - out <- Fold[_No Dependencies[?], (), [worker]Nodes >>] -} - -_Collect Dests[candidates,wire:out] -{ - out <- [candidates]Set[[wire]Index >>, Yes] -} - -Collect Dests@NWorker[worker,candidates,node index:out] -{ - out <- Fold[Fold[_Collect Dests[?], ?], candidates, [[[worker]Nodes >>]Index[node index]]Wires From >>] -} - -Check Dependency@NWorker[worker,nodes,wires,wire index:met?] -{ - ref <- [wires]Index[wire index] - [nodes]Find[=[[ref]Index >>, ?]] - { - [wires]Next[wire index] - { - met? <- [worker]Check Dependency[nodes,wires,~] - }{ - met? <- Yes - } - }{ - met? <- No - } -} -_Check Dependencies@NWorker[worker,nodes,inputs,input index:met?] -{ - wires <- [inputs]Index[input index] - [wires]First - { - current met? <- [worker]Check Dependency[nodes, wires, ~] - }{ - current met? <- Yes - } - If[current met?] - { - [inputs]Next[input index] - { - met? <- [worker]_Check Dependencies[nodes,inputs,~] - }{ - met? <- Yes - } - }{ - met? <- No - } -} - -Check Dependencies@NWorker[worker,nodes,candidate:met?] -{ - inputs <- [[[worker]Nodes >>]Index[candidate]]Wires To >> - [inputs]First - { - met? <- [worker]_Check Dependencies[nodes, inputs, ~] - }{ - met? <- Yes - } -} - -Dependants@NWorker[worker,direct nodes,nodes:out] -{ - candidates <- Keys[Fold[Collect Dests[worker, ?], (), direct nodes]] - out <- Filter[candidates, Check Dependencies[worker, nodes, ?]] -} - -_Dependency Groups@NWorker[worker,last,all,grouped:out] -{ - current <- [worker]Dependants[last,all] - [current]First - { - out <- [worker]_Dependency Groups[current, [all]Concatenate[current], [grouped]Append[current]] - }{ - out <- grouped - } -} -Dependency Groups@NWorker[worker:out] -{ - no deps <- [worker]No Dependencies - out <- [worker]_Dependency Groups[no deps, no deps, [()]Append[no deps]] -} - -Const Name[val,node index,worker name:out] -{ - valtype <- Blueprint Of[val] - If[[valtype] = [Type Instance()]] - { - //TODO: Support parametric types - datstring <- [val]Name >> - typename <- "Blueprint" - }{ - [(Int8(),UInt8(),Int16(),UInt16(),Int32(),UInt32(),Int64(),UInt64())]Find[=[valtype,?]] - { - size <- [("8","16","32","64")]Index[[~]/[2]] - typename <- [("Int8","UInt8","Int16","UInt16","Int32","UInt32","Int64","UInt64")]Index[~] - If[[~]Mod[2]] - { s <- "UI" } - { s <- "I" } - datstring <- [[String[val]]Append[s]]Append[size] - }{ - If[[valtype] = [Worker Literal()]] - { - typename <- "Worker" - If[[[[val]Args >>]Length] > [0]] - { - datstring <- [[["Arg "]Append[String[node index]]]Append[" "]]Append[worker name] - }{ - datstring <- [val]Name >> - } - }{ - [(List(),List Leaf())]Find[=[valtype,?]] - { - typename <- "List" - If[[[val]Length] > [0]] - { - datstring <- [[["Arg "]Append[String[node index]]]Append[" "]]Append[worker name] - }{ - datstring <- "Empty" - } - }{ - [(String(),String Cat(),String Slice())]Find[=[valtype, ?]] - { - typename <- "String" - datstring <- val - }{ - typename <- "Unknown" - datstring <- String[val] - } - - } - } - } - } - out <- [[typename]Append["_"]]Append[datstring] -} - -Format Input@NWorker[worker,noderef:out] -{ - node <- [[worker]Nodes >>]Index[[noderef]Index >>] - - [("call","getfield","setfield")]Find[=[[node]Type >>, ?]] - { - maybe addref <- Result Var Name[[noderef]IO Num >>, [noderef]Index >>] - }{ - conditions <- [node]Conditions >> - - If[[[node]Type >>] = ["input"]] - { - input name <- [[worker]Inputs >>]Index[ [node]Data >> ] - [conditions]Empty? - { - out <- AddRef[Result Var Name[[noderef]IO Num >>, [noderef]Index >>]] - }{ - out <- AddRef[input name] - } - }{ - If[[[node]Type >>] = ["const"]] - { - [conditions]Empty? - { - out <- AddRef[Result Var Name[[noderef]IO Num >>, [noderef]Index >>]] - }{ - out <- Constant[Const Name[[node]Data >>, [noderef]Index >>, [worker]Name >>]] - } - }{ - If[[[node]Type >>]=["getglobal"]] - { - [conditions]Empty? - { - out <- AddRef[Result Var Name[[noderef]IO Num >>, [noderef]Index >>]] - }{ - out <- AddRef[Global Get[[[node]Data >>]Index[0], [[node]Data >>]Index[1]]] - } - } - } - } - } - - Val[maybe addref] - { - If[[Length[[[node]Wires From >>]Index[[noderef]IO Num >>]]] > [1]] - { - out <- AddRef[maybe addref] - }{ - out <- Val[maybe addref] - } - } -} - -Collect Input@NWorker[worker,nodeinput:out] -{ - inputchoices <- Map[nodeinput, Format Input[worker, ?]] - - [inputchoices]First - { - first <- [inputchoices]Index[~] - [inputchoices]Next[~] - { - out <- _Fold[inputchoices, ~, first, OrValue[?]] - }{ - out <- Val[first] - } - }{ - out <- "Missing" - } -} - -Collect Inputs@NWorker[worker,node:out] -{ - out <- Map[Tail[[node]Wires To>>, 1], Collect Input[worker, ?]] -} - -Collect Input Condition@NWorker[worker,set,noderef:out] -{ - node <- [[worker]Nodes >>]Index[ [noderef]Index >> ] - If[[[node]Outputs >>] > [1]] - { - out <- [set]Add Condition[ Result Var Name[[noderef]IO Num >>, [noderef]Index >>] ] - }{ - out <- [set]Add Condition[[node]Conditions >>] - } -} - -Collect Condition@NWorker[worker,set,nodeinput:out] -{ - out <- [set]Add Condition[Fold[Collect Input Condition[worker, ?], OrSet[], nodeinput]] -} - -Collect Conditions@NWorker[worker,node:out] -{ - out <- Fold[Collect Condition[worker, ?], AndSet[], [node]Wires To>>] -} - -Save Result[func,num,node index:out] -{ - out <- [func]Move[Result[num], Result Var Name[num, node index]] -} - -Save Maybe Result[func,num,node index:out] -{ - out <- [func]Move[Check Result[num], Result Var Name[num, node index]] -} - -Max Used Output[node,cur:out] -{ - If[[cur] < [0]] - { - out <- cur - }{ - [[[node]Wires From >>]Index[cur]]Index[0] - { - out <- cur - }{ - out <- Max Used Output[node, [cur]-[1]] - } - } -} - -Compile Call Node[node,program,func,inputs,node index:out] -{ - If[[[node]Type >>] = ["getfield"]] - { - with call <- [func]Get Field Call[[node]Data >>, [inputs]Index[0]] - save outs <- [node]Outputs >> - out <- Val[after save] - }{ - If[[[node]Type >>] = ["setfield"]] - { - with call <- [func]Set Field Call[[node]Data >>, [inputs]Index[0], [inputs]Index[1]] - save outs <- [node]Outputs >> - out <- Val[after save] - }{ - fname <- [[node]Data >>]Name >> - first unused <- [Max Used Output[node, [[node]Outputs >>]-[1]]]+[1] - [program]Method?[fname] - { - with call <- [func]Method Call[fname, inputs] - }{ - justfunc,,,normal call <- [fname]Partition["@"] - { - //Check for inline on static method calls - //TODO: Deal with unused output - If[[[inputs]Length]=[2]] - { - out,normal call <- Compile Number Inline Check[func, justfunc, [[[node]Input Types >>]Index[0]]Index[0], [[[node]Input Types >>]Index[1]]Index[0], [inputs]Index[0], [inputs]Index[1], Result Var Name[0, node index]] - }{ - ,normal call <- If[[[inputs]Length]=[1]] - { - //TODO: Inline a partial version of If when only one output is used - ,normal call <- If[[first unused]>[1]] - { - out,normal call <- Compile Boolean Inline Check[func, justfunc, [[[node]Input Types >>]Index[0]]Index[0], [inputs]Index[0], Result Var Name[0, node index], Result Var Name[1, node index]] - } - } - } - } - - Val[normal call] - { - with call <- [func]Call[fname, inputs] - } - } - If[[first unused] > [[node]Min Outputs >>]] - { - save outs <- [node]Min Outputs >> - after maybe <- Fold[Save Maybe Result[?, ?, node index], after save, Range[save outs, first unused]] - }{ - save outs <- Val[first unused] - after maybe <- Val[after save] - } - If[[first unused] < [[node]Outputs >>]] - { - out <- [after maybe]Discard Outputs[first unused] - }{ - out <- Val[after maybe] - } - } - } - after save <- Fold[Save Result[?, ?, node index], with call, Range[0, save outs]] -} - -Compile Node[worker,program,func,nodes,current:out,out worker] -{ - node index <- [nodes]Index[current] - node <- [[worker]Nodes >>]Index[node index] - conditions <- [node]Conditions >> - [("call","getfield","setfield")]Find[=[[node]Type >>, ?]] - { - inputs <- [worker]Collect Inputs[node] - [conditions]For Backend - { - stream <- [func]Instruction Stream - nfunc <- [func]Do If[~, nstream] - }{ - stream <- Val[func] - nfunc <- Val[nstream] - } - nstream <- Compile Call Node[node, program, stream, inputs, node index] - }{ - If[[[node]Type >>] = ["output"]] - { - inputs <- [worker]Collect Inputs[node] - [conditions]For Backend - { - stream <- [func]Instruction Stream - nfunc <- [func]Do If[~, nstream] - }{ - stream <- Val[func] - nfunc <- Val[nstream] - } - nstream <- [stream]Move[[inputs]Index[0], [[worker]Outputs >>]Index[ [node]Data >> ] ] - }{ - If[[[node]Type >>] = ["const"]] - { - constname <- Const Name[[node]Data >>, node index, [worker]Name >>] - withconst <- [func]Register Constant[constname, [node]Data >>] - [conditions]For Backend - { - stream <- [[withconst]Instruction Stream - ]Move[Strip Addref[Constant[constname]], Result Var Name[0, node index]] - nfunc <- [withconst]Do If[~, stream] - }{ - nfunc <- Val[withconst] - } - }{ - If[[[node]Type >>]=["getglobal"]] - { - [conditions]For Backend - { - stream <- [[func]Instruction Stream - ]Move[Global Get[[[node]Data >>]Index[0], [[node]Data >>]Index[1]], Result Var Name[0, node index]] - nfunc <- [func]Do If[~, stream] - }{ - nfunc <- Val[func] - } - }{ - If[[[node]Type >>]=["setglobal"]] - - { - inputs <- [worker]Collect Inputs[node] - [conditions]For Backend - { - stream <- [func]Instruction Stream - nfunc <- [func]Do If[~, nstream] - }{ - stream <- Val[func] - nfunc <- Val[nstream] - } - nstream <- [stream]Set Global[[[node]Data >>]Index[0], [[node]Data >>]Index[1], [inputs]Index[0]] - }{ - [conditions]For Backend - { - input name <- [[worker]Inputs >>]Index[ [node]Data >> ] - stream <- [[func]Instruction Stream - ]Move[input name, Result Var Name[0, node index]] - nfunc <- [func]Do If[~, stream] - }{ - nfunc <- Val[func] - } - } - } - } - - } - } - [nodes]Next[current] - { - out,out worker <- [worker]Compile Node[program,nfunc,nodes,~] - }{ - out <- Val[nfunc] - out worker <- Val[worker] - } -} - -Save Node Conditions[worker,node index:out] -{ - node <- [[worker]Nodes >>]Index[node index] - conditions <- [worker]Collect Conditions[node] - out <- [worker]Nodes <<[ [[worker]Nodes >>]Set[node index, [node]Conditions <<[conditions]] ] - -} - -Save Group Conditions[worker, groups,current:out] -{ - nodes <- [groups]Index[current] - nworker <- Fold[Save Node Conditions[?], worker, nodes] - - [groups]Next[current] - { - out <- [nworker]Save Group Conditions[groups,~] - }{ - out <- Val[nworker] - } -} - -Compile Group[worker,program,func,groups,current:out,out worker] -{ - nodes <- [groups]Index[current] - [nodes]First - { - nfunc,nworker <- [worker]Compile Node[program,func,nodes,~] - }{ - nfunc <- Val[func] - nworker <- Val[worker] - } - [groups]Next[current] - { - out,out worker <- [nworker]Compile Group[program,nfunc,groups,~] - }{ - out <- Val[nfunc] - out worker <- Val[nworker] - } -} - -Release Var@NWorker[worker,func,name:out] -{ - //__result_index_ionum - parts <- [name]Split["_"] - index <- Int32[ [parts]Index[3] ] - io num <- Int32[ [parts]Index[4] ] - node <- [[worker]Nodes >>]Index[index] - dests <- [[node]Wires From >>]Index[io num] {} - - ,normal <- If[[[dests]Length] = [1]] - { - [dests]Index[0] - { - dest index <- [~]Index >> - dest IO <- [~]IO Num >> - } - normal <- If[[dest IO] = [-1]] {} - { - dest node <- [[worker]Nodes >>]Index[dest index] - - [[dest node]Conditions >>]For Backend - { - out <- [func]Do If[AndCond[NotCond[~], name], [[func]Instruction Stream]Release[name]] - }{ - out <- func - } - } - } - - Val[normal] - { - do if <- If[[[node]Outputs >>] > [1]] {} - { - do if <- [[node]Conditions >>]Empty? {} - { - out <- [func]Release[name] - } - } - - Val[do if] - { - stream <- [[func]Instruction Stream]Release[name] - out <- [func]Do If[name, stream] - } - } -} - -Result Var Name[io num, index:out] -{ - out <- [[["__result_"]Append[String[index]]]Append["_"]]Append[String[io num]] -} - -Result Var[vars,io num,index:out] -{ - out <- [vars]Append[Result Var Name[io num, index]] -} - -Node Result Vars[vars,node,index:out] -{ - [("call","getfield","setfield","getglobal")]Find[=[[node]Type >>, ?]] - { - If[[[node]Type >>]=["call"]] - { - save outs <- [Max Used Output[node, [[node]Outputs >>]-[1]]]+[1] - }{ - save outs <- [node]Outputs >> - } - out <- Fold[Result Var[?, ?, index], vars, Range[0, save outs]] - }{ - out <- vars - } -} - -Result Vars@NWorker[worker:out] -{ - out <- Fold[Node Result Vars[?], (), [worker]Nodes >>] -} - -_No Release[vars,node,index,worker:out] -{ - [("const","input")]Find[=[[node]Type >>, ?]] - { - [[node]Conditions >>]Empty? - { - out <- Result Var[vars, 0, index] - }{ - out <- vars - } - }{ - out <- vars - } -} - -No Release Results@NWorker[worker:out] -{ - out <- Fold[_No Release[?, ?, ?, worker], (), [worker]Nodes >>] -} - -Make Basic Type[type:out] -{ - out <- [Type Instance[[type]Name >>]]Params <<[ [type]Params >> ] -} - -FInputs[ifunc, input type, index, inputs:out] -{ - func <- [ifunc]Set Input Type[Make Basic Type[input type], index] - name <- [inputs]Index[index] - If[[[input type]Variant >>] = ["Naked"]] - { - - naked <- [" naked"]Append[name] - - out <- [[[func]Allocate Var[naked, input type] - ]Unbox[name, naked] - ]Release[name] - }{ - If[[input type]Mutable? >>] - { - name <- [inputs]Index[index] - copied <- [func]Copy[name, name] - - }{ - copied <- Val[func] - } - If[[[input type]Variant >>] = ["Raw Pointer"]] - { - raw <- [" raw"]Append[name] - If[[[input type]Name >>]=["Array"]] - { - - out <- [[copied]Allocate Var[raw, input type] - ]Array Raw Pointer[name, raw] - }{ - out <- [[copied]Allocate Var[raw, input type] - ]Get Raw Pointer[name, raw] - } - }{ - out <- Val[copied] - } - } -} - -Release Raw Inputs[func,input type,index,inputs,outputs:out] -{ - If[[[input type]Variant >>] = ["Raw Pointer"]] - { - name <- [inputs]Index[index] - If[[input type]Mutable? >>] - { - [outputs]Find[=[?,[inputs]Index[index]]] - { - out <- func - }{ - out <- [func]Release[name] - } - }{ - out <- [func]Release[name] - } - }{ - out <- func - } -} - -FParams[input:out] -{ - iname <- [input]Index[0] - type <- [input]Index[1] - If[[[type]Variant >>] = ["Naked"]] - { out <- [" naked"]Append[iname] } - { - If[[[type]Variant >>] = ["Raw Pointer"]] - { out <- [" raw"]Append[iname] } - { out <- Val[iname] } - } -} -_Return Param[outputs, inputs, input types, index:out,none] -{ - output <- [outputs]Index[index] - [inputs]Find[=[output, ?]] - { - If[[[input types]Index[~]]Mutable? >>] - { - ,none <- [outputs]Next[index] - { - out,none <- _Return Param[outputs, inputs, input types, ~] - } - } { - out <- index - } - }{ - out <- index - } -} - -Return Param[outputs, inputs, input types:out,none] -{ - ,none <- [outputs]First - { out,none <- _Return Param[outputs, inputs, input types, ~] } - -} - -Save Foreign Result[func, output, index, output types, inputs, input types:out] -{ - type <- [output types]Index[index] - If[[[type]Variant >>] = ["Naked"]] - { - out <- [func]Box[[" naked"]Append[output], output, type] - }{ - [inputs]Find[=[output, ?]] - { - If[[[input types]Index[~]]Mutable? >>] - { - out <- [func]Move[output, Output[output]] - }{ - out <- func - } - }{ - out <- func - } - } -} - -Compile Foreign Stub[worker,program,name:out] -{ - ifunc <- [[program]Create Function[name, [worker]Inputs >>, [worker]Outputs >>, "rhope"] - ]Output Types <<[Map[[worker]Output Types >>, Make Basic Type[?]]] - - rp num <- Return Param[[worker]Outputs >>, [worker]Inputs >>, [worker]Input Types >>] - { - rbase <- [[worker]Outputs >>]Index[rp num] - If[[[[[worker]Output Types >>]Index[rp num]]Variant >>] = ["Naked"]] - { - rparam <- [" naked"]Append[rbase] - rfunc <- [ifunc]Allocate Var[rparam, [[worker]Output Types >>]Index[rp num]] - }{ - rparam <- Val[rbase] - rfunc <- Val[ifunc] - } - }{ - rparam <- "" - rfunc <- Val[ifunc] - } - - Fold[FInputs[?, ?, ?, [worker]Inputs >>], rfunc, [worker]Input Types >>] - { [~]Call Foreign[name, [worker]Convention >>, Map[Zip[[worker]Inputs >>, [worker]Input Types >>], FParams[?]], rparam] - { Fold[Release Raw Inputs[?, ?, ?, [worker]Inputs >>, [worker]Outputs >>], ~, [worker]Input Types >>] - { Fold[Save Foreign Result[?, ?, ?, [worker]Output Types >>, [worker]Inputs >>, [worker]Input Types >>], ~, [worker]Outputs >>] - { out <- [program]Store Function[~] }}}} -} - -Compile Worker@NWorker[worker,program,name:out] -{ - If[[worker]Builtin? >>] - { - out <- program - }{ - If[[[worker]Library >>] = [""]] - { - ifunc <- Fold[Set Output Type[?], Fold[Set Input Type[?], [[program]Create Function[name,[worker]Inputs >>, [worker]Outputs >>, [worker]Convention >>]]Uses <<[[worker]Uses >>], [worker]Input Types >>], [worker]Output Types >>] - - groups <- [worker]Dependency Groups - - fgroup <- [groups]First - { - with conds <- [worker]Save Group Conditions[groups, ~] - final func <- [with conds]Compile Group[program,func,groups, ~] - }{ - final func <- Val[func] - } - res vars <- [worker]Result Vars - init vars <- Concatenate[res vars, [with conds]No Release Results] - - func <- Fold[Set Null[?], Fold[Set Null[?], Fold[Allocate Var[?, ?, "Any Type"], ifunc, init vars], init vars], [worker]Outputs >>] - out <- [program]Store Function[Fold[Release[?], Fold[Release Var[with conds, ?], final func, res vars], [worker]Inputs >>]] - }{ - out <- Compile Foreign Stub[worker,[program]Link[[worker]Convention >>, [worker]Library >> ],name] - } - } -} - -Blueprint NBlueprint -{ - Fields - Methods -} - -String@NBlueprint[nbp:out] -{ - out <- [[[["NBlueprint: Fields(" - ]Append[Join[Map[[nbp]Fields >>, [?]Index[0]], ", "]] - ]Append["), Methods("] - ]Append[Join[Keys[[nbp]Methods >>], ", "]] - ]Append[")"] -} - -NBlueprint[:out] -{ - out <- [[Build[NBlueprint()]]Fields <<[()]]Methods <<[Dictionary[]] -} - -Add Field@NBlueprint[bp,name,type:out] -{ - out <- [bp]Fields <<[ [[bp]Fields >>]Append[ [[()]Append[name]]Append[type] ] ] -} - -Add Method@NBlueprint[bp,name:out] -{ - out <- [bp]Methods <<[ [[bp]Methods >>]Set[name, Yes] ] - -} - -Understands Method@NBlueprint[bp,name:out] -{ - out <- [[bp]Methods >>]Index[name] {} - { out <- No } -} - -Eq Field Name[field,name:out] -{ - out <- [[field]Index[0]]=[name] -} - -Get Field Type@NBlueprint[bp,name:out,notfound] -{ - ,not found <- [[bp]Fields >>]Find[Eq Field Name[?, name]] - { out <- [[[bp]Fields >>]Index[~]]Index[1] } -} - -_Compile Blueprint Fields[type,field:out] -{ - name <- [field]Index[0] - ftype <- [field]Index[1] - out <- [type]Add Field[name,ftype] -} - -_Compile Blueprint Methods[type,junk,name:out] -{ - If[[[name]=["Call"]] And [[[type]Name >>] = ["Worker"]]] - { - out <- type - }{ - out <- [type]Add Method[name] - } -} - -Make Init[func,field:out] -{ - name <- [field]Index[0] - variant <- [[field]Index[1]]Variant >> - If[[variant] = ["Boxed"]] - { - out <- [func]Set Field Null["obj", name] - }{ - out <- func - } -} - -Make Copy[func,field:out] -{ - name <- [field]Index[0] - variant <- [[field]Index[1]]Variant >> - If[[variant] = ["Boxed"]] - { - got <- [func]Read Field["obj", name] {} - { - stream <- [[got]Instruction Stream - ]AddRef No Dest[~] - out <- [got]Do If[~, stream] - } - }{ - out <- func - } -} - -Make Cleanup[func,field:out] -{ - name <- [field]Index[0] - variant <- [[field]Index[1]]Variant >> - If[[variant] = ["Boxed"]] - { - got <- [func]Read Field["obj", name] {} - { - stream <- [[got]Instruction Stream - ]Release[~] - out <- [got]Do If[~, stream] - } - }{ - out <- func - } -} - -Make Special@NBlueprint[bp,backend,info,bp name:out] -{ - func name <- [info]Index[0] - pop worker <- [info]Index[1] - func <- [[backend]Create Function[func name,("obj"),(),"cdecl"] - ]Set Input Type[Type Instance[bp name], 0] - out <- [backend]Store Function[Fold[pop worker, func, [bp]Fields >>]] -} - -Getters Setters[backend,field,type name:out] -{ - //TODO: Throw an exception or something if we read a field that is empty - name <- [field]Index[0] - type <- [field]Index[1] - mytype <- Type Instance[type name] - start getter,getref <- [[[[backend]Create Function[ [[[name]Append[" >>"]]Append["@"]]Append[type name], ("obj"), ("out"), "rhope"] - ]Set Input Type[mytype, 0] - ]Set Output Type[[type]Set Variant["Boxed"], 0] - ]Read Field["obj", name] - If[[[type]Variant >>] = ["Boxed"]] - { - getter <- [[start getter]Do AddRef[getref, "out"]]Release["obj"] - }{ - getter <- [[start getter]Box[getref, "out", type]]Release["obj"] - } - - begin setter <- [[[[[backend]Create Function[ [[[name]Append[" <<"]]Append["@"]]Append[type name], ("obj","newval"), ("out"), "rhope"] - ]Set Input Type[mytype, 0] - ]Set Input Type[[type]Set Variant["Boxed"], 1] - ]Set Output Type[mytype, 0] - ]Copy["obj"] - - If[[[type]Variant >>] = ["Boxed"]] - { - ,origref <- [begin setter]Read Field["obj", name] - { - stream <- [[~]Instruction Stream - ]Release[origref] - ,setref <- [[~]Do If[origref, stream] - ]Write Field["obj", name] - { - setter <- [[~]Move["newval", setref] - ]Move["obj", "out"] - } - } - }{ - ,setref <- [begin setter]Write Field["obj", name] - { - setter <- [[[~]Unbox["newval", setref] - ]Release["newval"] - ]Move["obj", "out"] - } - } - - out <- [[backend]Store Function[getter]]Store Function[setter] - -} - -Compile Blueprint@NBlueprint[bp,backend,name:out] -{ - //Rhope identifiers can't start with spaces, so we can use identifiers that start with spaces for special functions - init name <- [" init "]Append[name] - [("Array","Boxed Array","Worker")]Find[=[?,name]] - { - [("internalarraynaked","internalarrayboxed","internalworker")]Index[~] - { - copy name <- [~]Append["copy"] - cleanup name <- [~]Append["cleanup"] - } - }{ - copy name <- [" copy "]Append[name] - cleanup name <- [" cleanup "]Append[name] - } - type <- [[[Fold[_Compile Blueprint Methods[?], Fold[_Compile Blueprint Fields[?], [backend]Create Type[name], [bp]Fields >>], [bp]Methods >>] - ]Init <<[init name] - ]Copy <<[copy name] - ]Cleanup <<[cleanup name] - - out <- [backend]Register Type[type] -} - -Compile Special@NBlueprint[bp,backend,name:out] -{ - makespecial <- [[[Dictionary[] - ]Set["init", Make Init[?]] - ]Set["copy", Make Copy[?]] - ]Set["cleanup", Make Cleanup[?]] - - after specials <- Fold[[bp]Make Special[?, ?, name], backend, [backend]Needed Specials[name,makespecial]] - out <- Fold[Getters Setters[?, ?, name], after specials, [bp]Fields >>] -} - -Blueprint NProgram -{ - Blueprints - Workers - Worker Refs - Numtypes - Global Stores -} - -NProgram[:out] -{ - out <- [[[[[Build[NProgram()] - ]Blueprints <<[Dictionary[]] - ]Workers <<[Dictionary[]] - ]Worker Refs <<[Dictionary[]] - ]Numtypes << [("Int8","Int16","Int32","Int64","UInt8","UInt16","UInt32","UInt64")] - ]Global Stores <<[Dictionary[]] -} - -Supported Number Types@NProgram[program:out] -{ - out <- [program]Numtypes >> -} - -Bind Worker@NProgram[prog,name,worker:out] -{ - after bind <- [prog]Workers << [ [[prog]Workers >>]Set[name, [worker]Name <<[name]] ] - parts <- [name]Split["@"] - bpname <- [parts]Index[1] - { - If[[~]=[""]] - { - out <- Val[after bind] - }{ - orig bp <- [[after bind]Blueprints >>]Index[bpname] {} - { orig bp <- NBlueprint[] } - out <- [after bind]Blueprints <<[ [[after bind]Blueprints >>]Set[bpname, [orig bp]Add Method[[parts]Index[0]] ] ] - } - }{ - out <- Val[after bind] - } -} - -Bind Blueprint@NProgram[prog,name,blueprint:out] -{ - out <- [prog]Blueprints << [ [[prog]Blueprints >>]Set[name, blueprint] ] -} - -_Compile Program BP[backend, blueprint, name:out] -{ - out <- [blueprint]Compile Blueprint[backend, name] -} - -_Compile Program BP Special[backend, blueprint, name:out] -{ - out <- [blueprint]Compile Special[backend, name] -} - -_Compile Program[backend, worker, name:out] -{ - out <- [worker]Compile Worker[backend, name] -} - -Compile Program@NProgram[prog, backend:out] -{ - backend with bps <- Generate Boolean Methods[Generate Number Methods[Fold[_Compile Program BP Special[?], Fold[_Compile Program BP[?], [backend]Global Stores <<[[prog]Global Stores >>], [prog]Blueprints >>], [prog]Blueprints >>]]] - workers with infer <- Map[[prog]Workers >>, Infer Types[?, prog]] - out <- Fold[_Compile Program[?], backend with bps, workers with infer] -} - -Register Method@NProgram[prog, name, convention, inputs, outputs: out] -{ - [[prog]Worker Refs >>]Index[name] - { - ref <- [[[[[~]Inputs <<[ Max[[~]Inputs >>, inputs] ] - ]Min Inputs <<[ Min[[~]Min Inputs >>, inputs] ] - ]Outputs <<[ Max[[~]Outputs >>, outputs] ] - ]Min Outputs <<[ Min[[~]Min Outputs >>, outputs] ] - ]Is Method? <<[Yes] - }{ - ref <- Worker Ref[name, convention, inputs, outputs, Yes] - } - out <- [prog]Worker Refs <<[ [[prog]Worker Refs >>]Set[name, ref]] -} - -Register Worker@NProgram[prog, name, convention, inputs, outputs: out] -{ - [[prog]Worker Refs >>]Index[name] - { - ref <- [[[[~]Inputs <<[ Max[[~]Inputs >>, inputs] ] - ]Min Inputs <<[ Min[[~]Min Inputs >>, inputs] ] - ]Outputs <<[ Max[[~]Outputs >>, outputs] ] - ]Min Outputs <<[ Min[[~]Min Outputs >>, outputs] ] - }{ - ref <- Worker Ref[name, convention, inputs, outputs, No] - } - after reg <- [prog]Worker Refs <<[ - [ [prog]Worker Refs >> ]Set[name, ref] - ] - - parts <- [name]Split["@"] - [parts]Index[1] - { - If[[~]=[""]] - { - out <- [after reg]Register Worker[[parts]Index[0], convention, inputs, outputs] - }{ - out <- [after reg]Register Method@NProgram[[parts]Index[0], convention, inputs, outputs] - } - }{ - out <- Val[after reg] - } -} - -Register Builtins@NProgram[prog:out] -{ - registered <- [[[[[[[[[[[[prog]Register Worker["Print", "rhope", 1, 1] - ]Register Worker["If@Boolean", "rhope", 1, 2] - ]Register Worker["Build", "rhope", 1, 1] - ]Register Worker["Blueprint Of", "rhope", 1, 1] - ]Register Worker["Call", "rhope", 1, 1]//This will ensure that min outputs is 1 - ]Register Worker["Call@Worker", "rhope", 1, 10]//10 is a quick workaround for the lack of proper varargs - ]Register Worker["ID", "rhope", 1, 1] - ]Register Worker["Blueprint From ID", "rhope", 1, 2] - ]Register Worker["Pause", "rhope", 1, 1] - ]Register Worker["Resume", "rhope", 2, 2] - ]Register Worker["Run Bytecode", "rhope", 2, 1] - ]Register Number Methods - - out <- [[[[[[[[[[registered]Bind Worker["If@Boolean", - [[[[[NWorker["rhope"] - ]Inputs <<[("condition")] - ]Input Types <<[ [()]Append[Type Instance["Boolean"]] ] - ]Outputs <<[("isyes","isno")] - ]Output Types <<[ [[()]Append[Type Instance["Boolean"]]]Append[Type Instance["Boolean"]] ] - ]Builtin? <<[Yes]] - ]Bind Worker["Print", - [[[[[NWorker["rhope"] - ]Inputs <<[("value")] - ]Input Types <<[ [()]Append[Type Instance["Any Type"]] ] - ]Outputs <<[("out")] - ]Output Types <<[ [()]Append[Type Instance["Int32"]] ] - ]Builtin? <<[Yes]] - ]Bind Worker["Build", - [[[[[NWorker["rhope"] - ]Inputs <<[("type")] - ]Input Types <<[ [()]Append[Type Instance["Blueprint"]] ] - ]Outputs <<[("out")] - ]Output Types <<[ [()]Append[Type Instance["Any Type"]] ] - ]Builtin? <<[Yes]] - ]Bind Worker["Blueprint Of", - [[[[[NWorker["rhope"] - ]Inputs <<[("object")] - ]Input Types <<[ [()]Append[Type Instance["Any Type"]]] - ]Outputs <<[("type")] - ]Output Types <<[ [()]Append[Type Instance["Blueprint"]]] - ]Builtin? <<[Yes]] - ]Bind Worker["Call@Worker", - [[[[[NWorker["rhope"] - ]Inputs <<[("worker")] - ]Input Types <<[ [()]Append[Type Instance["Worker"]] ] - ]Outputs <<[("ret1","ret2","ret3","ret4","ret5","ret6","ret7","ret8","ret9","ret10")] - ]Output Types <<[ [[()]Append[Type Instance["Any Type"]]]Append[Type Instance["Any Type"]] ] - ]Builtin? << [Yes]] - ]Bind Worker["ID", - [[[[[NWorker["rhope"] - ]Inputs <<[("bp")] - ]Input Types <<[ [()]Append[Type Instance["Blueprint"]]] - ]Outputs <<[("id")] - ]Output Types <<[ [()]Append[Type Instance["UInt32"]]] - ]Builtin? << [Yes]] - ]Bind Worker["Blueprint From ID", - [[[[[NWorker["rhope"] - ]Inputs <<[("id")] - ]Input Types <<[ [()]Append[Type Instance["UInt32"]]] - ]Outputs <<[("bp","none")] - ]Output Types <<[ [[()]Append[Type Instance["Blueprint"]]]Append[Type Instance["Any Type"]]] - ]Builtin? << [Yes]] - ]Bind Worker["Pause", - [[[[[NWorker["rhope"] - ]Inputs <<[("tocall")] - ]Input Types <<[ [()]Append[Type Instance["Worker"]]] - ]Outputs <<[("resumeval")] - ]Output Types <<[ [()]Append[Type Instance["Any Type"]] ] - ]Builtin? <<[Yes]] - ]Bind Worker["Resume", - [[[[[NWorker["rhope"] - ]Inputs <<[("toresume","resumeval")] - ]Input Types <<[ [[()]Append[Type Instance["Contest"]]]Append[Type Instance["Any Type"]] ] - ]Outputs <<[("success","cantresume")] - ]Output Types <<[ [[()]Append[Type Instance["Any Type"]]]Append[Type Instance["Any Type"]] ] - ]Builtin? <<[Yes]] - ]Bind Worker["Run Bytecode", - [[[[[NWorker["rhope"] - ]Inputs <<[("bytecode","constants")] - ]Input Types <<[ [[()]Append[Type Instance["Array"]]]Append[Type Instance["Boxed Array"]] ] - ]Outputs <<[("ret1")] - ]Output Types <<[ [()]Append[Type Instance["Any Type"]] ] - ]Builtin? <<[Yes] - ] -} - -Find Worker@NProgram[prog, name:out,notfound] -{ - out,notfound <- [[prog]Worker Refs >>]Index[name] -} - -Find Worker Def@NProgram[prog,name:out,notfound] -{ - out,notfound <- [[prog]Workers >>]Index[name] -} - -Find Method@NProgram[prog, name, type:out,notfound] -{ - bp,notfound <- [[prog]Blueprints >>]Index[[type]Name >>] - ,notfound <- If[[bp]Understands Method[name]] - { - out <- [[prog]Workers >>]Index[[[name]Append["@"]]Append[[type]Name >>]] - } -} - -Find Field@NProgram[prog, name, type:fieldtype,notfound] -{ - bp,notfound <- [[prog]Blueprints >>]Index[[type]Name >>] - fieldtype,notfound <- [bp]Get Field Type[name] -} - -Implicit Conversion@NProgram[prog, fromtype, totype:func,notfound] -{ - notfound <- No -} - -Is Method?@NProgram[prog,name:is,is not] -{ - ,is not <- [[prog]Worker Refs>>]Index[name] - { - is,is not <- If[[~]Is Method? >>] - } -} - diff -r 24c6f8767190 -r c6ba9fe45910 parser_old.rhope --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/parser_old.rhope Wed Jul 27 21:28:43 2011 -0700 @@ -0,0 +1,1683 @@ +Import nworker.rhope + +//Rather than rewrite the code that uses this +//let's implement Get DString using Partition +Get DString[str,delims:after,before,delim,not found] +{ + before,delim,after,not found <- [str]Partition[delims] {} {} {} + { + before <- str + } +} + + +Blueprint Parser +{ + Arg Begin + Arg End + Line Comment + Comment Begin + Comment End + Assign + Block Begin + Block End + Blueprint Type Delim + Empty Block + Binary Operator + String Begin + String End + String Escape + List Begin + List End + List Delim + In Out Delim + Index Begin + Index End + Previous + Block Val + Set Field + Get Field + Import + Blueprint + Global Separator + Uses + Hex Escape + Escape Map + Foreign + Globals +} + +Parser[:out] +{ + out <- [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[Build[Parser()] + ]Arg Begin << ["["] + ]Arg End <<["]"] + ]Line Comment <<["//"] + ]Comment Begin <<["/*"] + ]Comment End <<["*/"] + ]Assign <<["<-"] + ]Block Begin <<["{"] + ]Block End <<["}"] + ]Blueprint Type Delim <<[":"] + ]Empty Block <<[";"] + ]Binary Operator <<["`"] + ]String Begin <<["\""] + ]String End <<["\""] + ]String Escape <<["\\"] + ]List Begin <<["("] + ]List End <<[")"] + ]List Delim <<[","] + ]In Out Delim <<[":"] + ]Index Begin <<["("] + ]Index End <<[")"] + ]Previous <<["@"] + ]Set Field <<["<<"] + ]Get Field <<[">>"] + ]Import <<["Import"] + ]Blueprint <<["Blueprint"] + ]Global Separator <<["::"] + ]Hex Escape <<["x"] + ]Uses <<["uses"] + ]Escape Map <<[[[[Dictionary[]]Set["n","\n"]]Set["r","\r"]]Set["t","\t"]] + ]Foreign <<["Foreign"] + ]Globals <<["Globals"] +} + +Blueprint Output Reference +{ + Index + Output Number +} + +Output Reference[index,num:out] +{ + out <- [[Build[Output Reference()]]Index <<[index]]Output Number <<[num] +} + +Add Pipe Reference[refs,name,reference:out] +{ + reflist <- [refs]Index[name] {} + { + reflist <- () + } + out <- [refs]Set[name, [reflist]Append[reference]] +} + +Assignment Save Reference[refs,assignment,output num,parse worker,index:out] +{ + [[parse worker]Outputs >>]Find[=[assignment,?]] + { + out <- refs + }{ + out <- Add Pipe Reference[refs, assignment, Output Reference[index, output num]] + } +} + +Blueprint Foreign Lib +{ + Language + Name +} + +New Foreign Lib[language, library:out] +{ + out <- [[Build[Foreign Lib()] + ]Language <<[language] + ]Name <<[library] +} + +Blueprint Global Store +{ + Name + Vars +} + +Global Store[name:out] +{ + out <- [[Build[Global Store()]]Name <<[name]]Vars <<[Dictionary[]] +} + +Blueprint Parse Program +{ + Workers + Imports + Blueprints + Global Stores + Errors +} + +Parse Program[:out] +{ + out <- [[[[[Build[Parse Program()] + ]Workers <<[Dictionary[]] + ]Imports <<[Dictionary[]] + ]Blueprints <<[Dictionary[]] + ]Global Stores <<[Dictionary[]] + ]Errors <<[()] +} + +Add Global Store@Parse Program[tree,store:out] +{ + out <- [tree]Global Stores <<[ [[tree]Global Stores >>]Set[[store]Name >>, store] ] +} + +Blueprint Blueprint Definition +{ + Name + Fields +} + +New Blueprint Definition[name,fields:out] +{ + out <- [[Build[Blueprint Definition()]]Name << [name]]Fields <<[fields] +} + +Blueprint Parse Worker +{ + Name + Inputs + Outputs + Line Number + Trees + Uses Stores + Input Types + Output Types + Assigned +} + +Parse Worker[name,inputs,outputs,intypes,outtypes,line:out] +{ + out <- [[[[[[[[[Build[Parse Worker()]]Name <<[name]]Inputs <<[inputs]]Outputs <<[outputs]]Line Number <<[line]]Trees <<[()]]Uses Stores <<[()]]Input Types <<[intypes]]Output Types <<[outtypes]]Assigned <<[Dictionary[]] +} + +Blueprint Worker Node +{ + Name + Params + Assignments + Blocks + Index +} + +Worker Node[name,params:out] +{ + out <- [[[[Build[Worker Node()]]Name <<[name]]Params <<[params]]Assignments <<[()]]Blocks <<[()] +} + +_Get Assigned Pipes[pipe dict,node:out] +{ + out <- [node]Get Assigned Pipes[pipe dict] +} + +Get Assigned Pipes[node,pipe dict:out] +{ + Fold[Set[?,?,Yes], pipe dict, [node]Assignments >>] + { out <- Fold[Fold[_Get Assigned Pipes[?], ?], ~, [node]Blocks >>] } +} + +Add List Helper[inlist,worker,program,key,parse worker,refs:out list,out worker,out refs] +{ + ,nextworker,nextrefs <- [[inlist]Index[key]]Add to Worker[worker, program, parse worker, refs] + { nextlist <- [inlist]Set[key, ~] } + [inlist]Next[key] + { + out list,out worker,out refs <- Add List Helper[nextlist, nextworker, program, ~, parse worker, nextrefs] + }{ + out list <- Val[nextlist] + out worker <- Val[nextworker] + out refs <- Val[nextrefs] + } +} + +Add List to Worker[list,worker,program,parse worker,refs:out list,out worker,out refs] +{ + [list]First + { + out list,out worker,out refs <- Add List Helper[list, worker, program, ~, parse worker, refs] + }{ + out list <- list + out worker <- worker + out refs <- refs + } +} + +_Add Blocks to Worker[blocks,worker,program,parse worker,key,refs:out blocks,out worker,out refs] +{ + block, next worker, nextrefs <- Add List to Worker[[blocks]Index[key], worker, program, parse worker, refs] + next blocks <- [blocks]Set[key, block] + [blocks]Next[key] + { + out blocks,out worker,out refs <- _Add Blocks to Worker[next blocks, next worker, program, parse worker, ~, nextrefs] + }{ + out blocks <- Val[next blocks] + out worker <- Val[next worker] + out refs <- Val[nextrefs] + } +} + +Add Blocks to Worker[blocks,worker,program,parse worker,refs:out blocks,out worker,out refs] +{ + [blocks]First + { + out blocks, out worker, out refs <- _Add Blocks to Worker[blocks, worker, program, parse worker, ~, refs] + }{ + out blocks <- blocks + out worker <- worker + out refs <- refs + } +} + +Add to Worker@Worker Node[node,worker,program,parse worker,refs:out node,out worker,out refs] +{ + [program]Find Worker[[node]Name >>] + { + after worker <- [worker]Add Worker Call[~] {} + { + //Print[[[[node]Name >>]Append[" has index "]]Append[~]] + assignment refs <- Fold[Assignment Save Reference[?, ?, ?, parse worker, ~], refs, [node]Assignments >>] + [node]Index <<[~] + { + params list, params worker, params refs <- Add List to Worker[[~]Params >>, after worker, program, parse worker, assignment refs] + block list, out worker, out refs <- Add Blocks to Worker[[~]Blocks >>, params worker, program, parse worker, params refs] + out node <- [[~]Params <<[params list]]Blocks <<[block list] + } + } + }{ + make call <- [[parse worker]Assigned >>]Index[[node]Name >>] {} + { + make call <- [[parse worker]Inputs >>]Find[=[?,[node]Name >>]] {} + { + Print[["Error: Could not find a worker named "]Append[[node]Name >>]] + } + } + Val[make call] + { + new params <- Fold[Append[?], [()]Append[Named Pipe Node[[node]Name >>]], [node]Params >>] + out node, out worker, out refs <- [[[node]Params <<[new params]]Name <<["Call"]]Add to Worker[worker, program, parse worker, refs] + } + } +} + +Check Question Mark[params, index:has mark,no mark] +{ + param,no mark <-[params]Index[index] + { + If[[Blueprint Of[param]]=[Named Pipe Node()]] + { + has mark <-If[[[param]Name >>] = ["?"]] {} + { + has mark,no mark <- Check Question Mark[params, [index]+[1]] + } + }{ + has mark,no mark <- Check Question Mark[params, [index]+[1]] + } + } +} + +Collect Literal Inputs[literal, params, index, complex inputs:literal out,complex out] +{ + param <- [params]Index[index] + { + If[[Blueprint Of[param]]=[Literal Node()]] + { + next literal <- [literal]Set Input[index, [param]Value >>] + next complex <- Val[complex inputs] + }{ + ,doset <- If[[Blueprint Of[param]]=[Named Pipe Node()]] + { + ,doset <- If[[[param]Name >>] = ["?"]] + { + //Question mark indicates unpopulated input + next complex <- Val[complex inputs] + next literal <- Val[literal] + } + } + + Val[doset] + { + next complex <- [complex inputs]Set[index, param] + next literal <- Val[literal] + } + } + literal out, complex out <- Collect Literal Inputs[next literal, params, [index]+[1], next complex] + }{ + literal out <- literal + complex out <- complex inputs + } +} + +Do Set Input[literal,param,index:out] +{ + out <- Worker Node["Set Input", [[[()]Append[literal]]Append[Literal Node[index]]]Append[param]] +} + +Check Worker Literals@Worker Node[node,program:out] +{ + new params <- Map[[node]Params >>, Check Worker Literals[?, program]] + Check Question Mark[new params, 0] + { + base literal, complex inputs <- Collect Literal Inputs[Worker Literal[[node]Name >>], new params, 0, ()] + new node <- Fold[Do Set Input[?], Literal Node[base literal], complex inputs] + }{ + new node <- [node]Params <<[new params] + } + out <- [new node]Blocks <<[ Map[[node]Blocks >>, Map[?, Check Worker Literals[?, program]]] ] +} + +Add Multi Wire[worker,ref,junk,end index,input num:out] +{ + out <- [worker]Add Wire[[ref]Index >>, [ref]Output Number >>, end index, input num] +} + +Add Param Wire[worker,param,input num,end index,blocks,parse worker,assignments:out] +{ + param worker, start index, output num <- [param]Add Wires[worker, blocks, parse worker, assignments] {} + { + out <- [param worker]Add Wire[start index, output num, end index, input num] + }{}{ + out <- Fold[Add Multi Wire[?, ?, ?, end index, input num], param worker, ~] + } +} + +_Add Block Wire[worker,node,junk,blocks,parse worker,assignments:out] +{ + out <- [node]Add Wires[worker, blocks, parse worker, assignments] +} + +Add Block Wire[worker,block nodes,output num,parent index,existing blocks,parse worker,assignments:out] +{ + blocks <- [existing blocks]Append[Output Reference[parent index, output num]] + out <- Fold[_Add Block Wire[?, ?, ?, blocks, parse worker, assignments], worker, block nodes] +} + +Assignments Add Wires[worker,assignment,output num,parse worker,start index:out worker] +{ + [[parse worker]Outputs >>]Find[=[assignment,?]] + { + ,output index <- [worker]Add Typed Output[assignment, ~, [[parse worker]Output Types >>]Index[~]] + { + out worker <- [~]Add Wire[start index, output num, output index, 0] + } + }{ + //Ugly hack alert! + If[[assignment]Contains["::"]] + { + parts <- [assignment]Split["::"] + ,global index <- [worker]Add Global Set[[parts]Index[0], [parts]Index[1]] + { + out worker <- [~]Add Wire[start index, output num, global index, 0] + } + }{ + out worker <- worker + } + } +} + +Has Block@Worker Node[junk:out,unused] +{ + out <- Yes +} + +_Has Block Params[param list,key:out] +{ + param <- [param list]Index[key] + out <- [param]Has Block {} + { + [param list]Next[key] + { + out <- _Has Block Params[param list, ~] + }{ + out <- No + } + } + +} + +Has Block Params[param list:out] +{ + [param list]First + { + out <- _Has Block Params[param list, ~] + }{ + out <- No + } +} + +Add Wires@Worker Node[node,worker,blocks,parse worker,assignments:outworker,index,num,unused] +{ + outworker,index,num <- Add Wires Worker or Field[node, worker, blocks, parse worker, assignments] +} + +Add Wires Worker or Field[node,worker,blocks,parse worker,assignments:outworker,index,num,unused] +{ + Fold[Assignments Add Wires[?, ?, ?, parse worker, [node]Index >>], worker, [node]Assignments >>] + { + Fold[Add Block Wire[?, ?, ?, [node]Index >>, blocks, parse worker, assignments], ~, [node]Blocks >>] + { + params worker <- Fold[Add Param Wire[?, ?, ?, [node]Index >>, blocks, parse worker, assignments], ~, [node]Params >>] + { + index <- [node]Index >> + num <- 0 + } + } + } + If[Has Block Params[[node]Params >>]] + { + outworker <- Val[params worker] + }{ + [blocks]Peek + { + outworker <- [params worker]Add Wire[[~]Index >>, [~]Output Number >>, [node]Index >>, [0]-[1]] + }{ + outworker <- Val[params worker] + } + } +} + +Blueprint Field Node +{ + Name + Params + Assignments + Blocks + Index + Set? +} + +Has Block@Field Node[junk:has block,unused] +{ + has block <- Yes +} + +Field Node[name,params,set:out] +{ + out <- [[[[[Build[Field Node()]]Name <<[name]]Assignments <<[()]]Blocks <<[()]]Set? <<[set]]Params <<[params] +} + +Add to Worker@Field Node[node,worker,program,parse worker,refs:out node,out worker,out refs] +{ + If[[node]Set? >>] + { + after worker,index <- [worker]Add Object Set[[node]Name >>] + }{ + after worker,index <- [worker]Add Object Get[[node]Name >>] + } + Val[index] + { + assignment refs <- Fold[Assignment Save Reference[?, ?, ?, parse worker, ~], refs, [node]Assignments >>] + [node]Index <<[~] + { + params list, params worker, params refs <- Add List to Worker[[~]Params >>, after worker, program, parse worker, assignment refs] + block list, out worker, out refs <- Add Blocks to Worker[[~]Blocks >>, params worker, program, parse worker, params refs] + out node <- [[~]Params <<[params list]]Blocks <<[block list] + } + } +} + +Add Wires@Field Node[node,worker,blocks,parse worker,assignments:outworker,index,num] +{ + outworker,index,num <- Add Wires Worker or Field[node, worker, blocks, parse worker, assignments] +} + +Check Worker Literals@Field Node[node,program:out] +{ + new params <- Map[[node]Params >>, Check Worker Literals[?, program]] + out <- [[node]Blocks <<[ Map[[node]Blocks >>, Map[?, Check Worker Literals[?, program]]] ] + ]Params <<[new params] +} + +Blueprint Named Pipe Node +{ + Name + Assignments + Blocks + Index +} + +Has Block@Named Pipe Node[node:has block,no block] +{ + If[[[node]Index >>] < [0]] + { + //~ should really be a parser parameter + If[[[node]Name >>] = ["~"]] + { + has block <- Yes + }{ + no block <- No + } + }{ + has block <- Yes + } +} + +Named Pipe Node[name:out] +{ + out <- [[[Build[Named Pipe Node()]]Name <<[name]]Assignments <<[()]]Blocks <<[()] +} + +Add to Worker@Named Pipe Node[node,worker,program,parse worker,refs:out node,out worker,out refs] +{ + [[parse worker]Inputs >>]Find[=[[node]Name >>, ?]] + { + after add <- [worker]Add Typed Input[[node]Name >>, ~, [[parse worker]Input Types>>]Index[~]] {} + { + assign refs <- Fold[Assignment Save Reference[?, ?, ?, parse worker, ~], refs, [node]Assignments >>] + index node <- [node]Index <<[~] + } + }{ + after add <- worker + index node <- [node]Index <<[[0]-[1]] + //TODO: Handle assignments from a named pipe that isn't an input + assign refs <- refs + } + block list, out worker, out refs <- Add Blocks to Worker[[node]Blocks >>, after add, program, parse worker, assign refs] + out node <- [index node]Blocks <<[block list] +} + +Add Wires@Named Pipe Node[node,worker,blocks,parse worker,assignments:outworker,index,num,reflist] +{ + reflist <- [assignments]Index[[node]Name >>] + { + //TODO: Fix support for a named pipe with a block + outworker <- worker + }{ + If[[[node]Name >>] = ["~"]] + { + wires worker <- worker + [blocks]Peek + { + my index <- [~]Index >> + num <- [~]Output Number >> + }{ + //TODO: Propagate an error rather than printing it out + Print["Error, block reference symbol located outside of a block"] + } + }{ + If[[[node]Index >>] < [0]] + { + Print[[[["Error, reference to named pipe "]Append[[node]Name >>]]Append[" that was never assigned to in worker "]]Append[[parse worker]Name >>]] + }{ + my index <- [node]Index >> + num <- 0 + assignments worker <- Fold[Assignments Add Wires[?, ?, ?, parse worker, [node]Index >>], worker, [node]Assignments >>] + [blocks]Peek + { + wires worker <- [assignments worker]Add Wire[[~]Index >>, [~]Output Number >>, [node]Index >>, [0]-[1]] + }{ + wires worker <- Val[assignments worker] + } + } + } + } + index <- Val[my index] + + outworker <- Fold[Add Block Wire[?, ?, ?, my index, blocks, parse worker, assignments], wires worker, [node]Blocks >>] +} + +Check Worker Literals@Named Pipe Node[node,program:out] +{ + out <- [node]Blocks <<[ Map[[node]Blocks >>, Map[?, Check Worker Literals[?, program]]] ] +} + +Blueprint Global Node +{ + Store + Name + Assignments + Blocks + Index +} + +Global Node[store,name:out] +{ + out <- [[[[Build[Global Node()]]Store <<[store]]Name <<[name]]Assignments <<[()]]Blocks <<[()] +} + +Add to Worker@Global Node[node,worker,unused,parse worker,refs:out node,out worker,outrefs] +{ + out worker <- [worker]Add Global Get[[node]Store >>, [node]Name >>] {} + { + outrefs <- Fold[Assignment Save Reference[?, ?, ?, parse worker, ~], refs, [node]Assignments >>] + out node <- [node]Index <<[~] + } + outrefs <- refs +} + +Add Wires@Global Node[node,worker,blocks,parse worker,assignments:outworker,index,num,unused] +{ + outworker,index,num <- Add Wires Literal or Global[node, worker, blocks, parse worker, assignments] +} + +Has Block@Global Node[junk:out,unused] +{ + out <- Yes +} + +Check Worker Literals@Global Node[node,program:out] +{ + out <- [node]Blocks <<[ Map[[node]Blocks >>, Map[?, Check Worker Literals[?, program]]] ] +} + +Blueprint Literal Node +{ + Value + Assignments + Blocks + Index +} + +Has Block@Literal Node[junk:out,unused] +{ + out <- Yes +} + +Literal Node[value:out] +{ + out <- [[[Build[Literal Node()]]Value <<[value]]Assignments <<[()]]Blocks <<[()] +} + +Add to Worker@Literal Node[node,worker,unused,parse worker,refs:out node,out worker,out refs] +{ + out worker <- [worker]Add Constant[[node]Value >>] {} + { + out refs <- Fold[Assignment Save Reference[?, ?, ?, parse worker, ~], refs, [node]Assignments >>] + out node <- [node]Index <<[~] + } +} + +Add Wires@Literal Node[node,worker,blocks,parse worker,assignments:outworker,index,num,unused] +{ + outworker,index,num <- Add Wires Literal or Global[node, worker, blocks, parse worker, assignments] +} + +Check Worker Literals@Literal Node[node,program:out] +{ + out <- [node]Blocks <<[ Map[[node]Blocks >>, Map[?, Check Worker Literals[?, program]]] ] +} + +Add Wires Literal or Global[node,worker,blocks,parse worker,junk:outworker,index,num,unused] +{ + assignments worker <- Fold[Assignments Add Wires[?, ?, ?, parse worker, [node]Index >>], worker, [node]Assignments >>] + [blocks]Peek + { + outworker <- [assignments worker]Add Wire[[~]Index >>, [~]Output Number>>, [node]Index >>, [0]-[1]] + }{ + outworker <- Val[assignments worker] + } + index <- [node]Index >> + num <- 0 +} + +Blueprint Block Node +{ + Number +} + +Blueprint Parse Error +{ + Type + Text + Line Number +} + +Parse Error[type,text,number:out] +{ + out <- [[[Build[Parse Error()]]Type <<[type]]Text <<[text]]Line Number <<[number] +} + +Not Empty[string:out] +{ + If[[[string]Length] > [0]] + { + out <- Yes + }{ + out <- No + } +} + +Blueprint Blueprint Field +{ + Name + Type +} + +New Blueprint Field[name,type:out] +{ + out <- [[Build[Blueprint Field()]]Name <<[name]]Type <<[type] +} + +Process Blueprint Field[list,field,params:out] +{ + ,name <- [field]Get DString[[params]List Begin >>] + { + type info <- Parse List[~,params,()] + type <- [type info]Index[0] + { + If[[Blueprint Of[~]] = [Named Pipe Node()]] + { + before variant <- Type Instance[[type]Name >>] + }{ + before variant <- [type]Params <<[ Map[[type]Params >>, Remove Named Pipe Node[?]] ] + } + variant <- [type info]Index[1] + { + ,warn <- If[[Blueprint Of[~]] = [Named Pipe Node()]] + { + fieldtype,warn <- [before variant]Set Variant[[variant]Name >>] + } + Val[warn] + { + Print[[[["Warning: Invalid variant for type "]Append[[before variant]Name >>]]Append[" on field "]]Append[name]] + fieldtype <- Val[before variant] + } + }{ + fieldtype <- Val[before variant] + } + }{ + fieldtype <- Type Instance["Any Type"] + } + out <- [list]Append[New Blueprint Field[name, fieldtype]] + } {} {} { + out <- [list]Append[New Blueprint Field[name, Type Instance["Any Type"]]] + } +} + +Block Comment[string,begin comment,end comment,block count:out] +{ + If[[block count] > [0]] + { + after, before <- [string]Get DString[[[()]Append[begin comment]]Append[end comment]] {} {} + { + If[[~] = [begin comment]] + { + out <- Block Comment[after, begin comment, end comment, [block count]+[1]] + }{ + out <- Block Comment[after, begin comment, end comment, [block count]-[1]] + } + }{ + //No match + out <- "" + } + }{ + out <- string + } +} + +Line Comment[string:out] +{ + [string]Get DString["\n"] + { + out <- ["\n"]Append[~] + } {} {} { + out <- "" + } +} + +_Get Comment DString[string,delims,line comment,begin comment,end comment,prev before:rest,before,delim,nomatch] +{ + after,befored,used delim,nomatch <- [string]Get DString[delims] + { + If[[used delim] = [line comment]] + { + after comment <- Line Comment[after] + }{ + If[[used delim] = [begin comment]] + { + after comment <- Block Comment[after, begin comment, end comment, 1] + }{ + rest <- Val[after] + before <- [prev before]Append[befored] + delim <- Val[used delim] + } + } + } {} {} { + before <- [prev before]Append[befored] + } + + after comment + { + rest,more before,delim,nomatch <- _Get Comment DString[~, delims, line comment, begin comment, end comment, prev before] + before <- [before]Append[more before] + } + +} + +As List[val:out] +{ + [(List(),List Leaf())]Find[=[Blueprint Of[val], ?]] + { + out <- val + }{ + out <- [()]Append[val] + } +} + +Get Comment DString[string,delims,params:rest,before,delim,not found] +{ + line comment <- [params]Line Comment >> + begin comment <- [params]Comment Begin >> + end comment <- [params]Comment End >> + all delims <- [[[delims]As List]Append[begin comment]]Append[line comment] + rest, before, delim, not found <- _Get Comment DString[string, delims, line comment, begin comment, end comment, ""] +} + +Comment Left Trim[string,trim chars,params:out] +{ + line comment <- [params]Line Comment >> + + end comment <- [params]Comment End >> + trimmed <- Left Trim[string, trim chars] + If[[trimmed]Starts With[line comment]] + { + ,after delim <- [trimmed]Slice[[line comment]Length] + out <- Comment Left Trim[Line Comment[after delim], trim chars, params] + }{ + begin comment <- [params]Comment Begin >> + If[[trimmed]Starts With[begin comment]] + { + ,after delim <- [trimmed]Slice[[line comment]Length] + out <- Comment Left Trim[Block Comment[after delim, begin comment, end comment, 1], trim chars, params] + }{ + out <- Val[trimmed] + } + } +} + +PBlueprint[string,params,tree,lines:out] +{ + ,whitespace name <- [string]Get Comment DString[[params]Block Begin >>, params] + { + ,no blueprint <- [whitespace name]Slice[ [[params]Blueprint >>]Length ] + name <- Trim[no blueprint, "\r\n\t "] + name lines <- 0 + ,body <- [~]Get Comment DString[ [params]Block End >>, params] + { + body lines <- [body]Split["\n"] + more lines <- [[[body lines]Length] - [1]] + [name lines] + fields <- Fold[Process Blueprint Field[?, ?, params], (), Filter[Map[body lines, Trim[?,"\n\r\t "]], Not Empty[?]]] + new tree <- [tree]Blueprints << [ [[tree]Blueprints >>]Set[name, New Blueprint Definition[name, fields]] ] + out <- Null[~, params, new tree, [lines] + [more lines]] + } {} {} { + out <- [tree]Errors <<[ [[tree]Errors >>]Append[Parse Error["Error",[["Blueprint is missing an block close symbol \""]Append[[params]Block End >>]]Append["\""], lines]] ] + } + + } {} {} { + out <- [tree]Errors <<[ [[tree]Errors >>]Append[Parse Error["Error",[["Blueprint is missing an block open symbol \""]Append[[params]Block Begin >>]]Append["\""], lines]] ] + } +} + +Parse Import[string,params,tree,lines:out] +{ + [line]Slice[ [[params]Import >>]Length ] {} + { + filename <- Trim[~, " \n\r\t"] + } + + new tree <- [tree]Imports <<[[[tree]Imports >>]Set[filename, Yes]] + + ,line <- [string]Get Comment DString["\n", params] + { + out <- Null[~, params, new tree, [lines] + [1]] + } {} {} { + out <- Val[new tree] + } +} + +Get Expression Blocks[string,params,blocks:outblocks,after] +{ + check block <- Comment Left Trim[string, "\n\r\t ", params] + If[[check block]Starts With[[params]Block Begin >>]] + { + ,begin block <- [check block]Slice[[[params]Block Begin >>]Length] + trees, after block <- Worker Body[begin block, params, ()] + outblocks, after <- Get Expression Blocks[after block, params, [blocks]Append[trees]] + }{ + If[[check block]Starts With[[params]Empty Block >>]] + { + outblocks <- blocks + ,after <- [check block]Slice[[[params]Empty Block >>]Length] + }{ + outblocks <- blocks + after <- Val[check block] + } + } +} + +Parse Escape[string,params:char,after] +{ + code,rest <- [string]Slice[1] + If[[code] = [[params]Hex Escape >>]] + { + hex,after <- [rest]Slice[2] + char <- String[[Array[]]Append[Trunc UInt8[Abs UInt[Hex Int32[hex]]]]] + }{ + after <- Val[rest] + char <- [[params]Escape Map >>]Index[code] {} + { + char <- Val[code] + } + } +} + +Parse String[string,params,current:value,after] +{ + delims <- [[()]Append[[params]String End >>]]Append[[params]String Escape >>] + afters, before, delim <- [string]Get Comment DString[delims, params] + { + If[[delim] = [[params]String End >>]] + { + value <- [current]Append[before] + after <- Val[afters] + }{ + char,after escape <- Parse Escape[afters, params] + value,after <- Parse String[after escape, params, [[current]Append[before]]Append[char]] + } + } +} + +Parse List[string,params,list:value,after] +{ + trimmed <- Comment Left Trim[string, "\r\n\t ", params] + If[[trimmed]Starts With[[params]List End >>]] + { + value <- list + ,after <- [trimmed]Slice[[[params]List End >>]Length] + }{ + If[[trimmed]Starts With[[params]List Delim >>]] + { + ,el string <- [trimmed]Slice[[[params]List Delim >>]Length] + }{ + el string <- Val[trimmed] + } + element,after el <- Named Pipe or Literal[el string, params] + value,after <- Parse List[after el, params, [list]Append[[element]Get Value]] + } +} + +Get Value@Literal Node[node:out] +{ + out <- [node]Value >> +} + +Get Value@Named Pipe Node[node:out] +{ + out <- node +} + +Machine Integer[val, size, signed?:out] +{ + conv <- [[[[[[[[() + ]Append[UInt8[?]] + ]Append[Int8[?]] + ]Append[UInt16[?]] + ]Append[Int16[?]] + ]Append[UInt32[?]] + ]Append[Int32[?]] + ]Append[UInt64[?]] + ]Append[Int64[?]] + + base idx <- [[(8,16,32,64)]Find[=[size,?]]]*[2] + + If[signed?] + { + idx <- [base idx]+[1] + }{ + idx <- Val[base idx] + } + out <- [[conv]Index[idx]]Call[val] +} + +Parse Number[string,params:value,after] +{ + delims <- [[[[(" ","\t","\n","\r")]Append[[params]List Delim >>]]Append[[params]Block Begin >>]]Append[[params]Arg End >>]]Append[[params]List End >>] + after delim,valstring <- [string]Get Comment DString[delims, params] {} {} + { + after <- [~]Append[after delim] + }{ + after <- "" + } + first two,rest <- [valstring]Slice[2] + If[[first two] = ["0x"]] + { + value <- Hex Int32[rest] + }{ + If[[valstring]Contains["."]] + { + value <- Real64[valstring] + }{ + size, val, type <- [valstring]Get DString[("i","u")] + { + value <- Machine Integer[val, Int32[size], [type]=["i"]] + } {} {} { + value <- Int32[valstring] + } + } + } +} + +Parse Params@Type Instance[literal,params,string:out,after] +{ + plist,after <- Parse List[string,params,()] + out <- [literal]Params <<[plist] +} + +Named Pipe or Literal[string,params:out,after] +{ + name <- Comment Left Trim[string, "\n\r\t ", params] + If[[name]Starts With[[params]String Begin >>]] + { + ,string begin <- [name]Slice[[[params]String Begin >>]Length] + value,after <- Parse String[string begin, params, ""] + }{ + If[[name]Starts With[[params]List Begin >>]] + { + ,list start <- [name]Slice[[[params]List Begin >>]Length] + value,after <- Parse List[list start, params, ()] + }{ + If[[[name]Slice[1]]In["-0123456789"]] + { + value,after <- Parse Number[name, params] + }{ + delims <- [[[[[[[("\n")]Append[[params]Block Begin >>]]Append[[params]Block End >>]]Append[[params]Empty Block >>]]Append[[params]Arg End >>]]Append[[params]List Delim >>]]Append[[params]List End >>]]Append[[params]List Begin >>] + afterdelim,raw before,delim,nodelim <- [name]Get Comment DString[delims, params] {} {} {} + { delim <- "" } + + before <- Trim[raw before, "\r\n\t "] + If[[delim] = [[params]List Begin >>]] + { + value,after <- [Type Instance[before]]Parse Params[params,afterdelim] + }{ + Val[afterdelim] + { + after <- [delim]Append[~] + } + Val[nodelim] + { + after <- "" + } + If[[before] = ["Yes"]] + { + yesno <- Yes + }{ + If[[before] = ["No"]] + { + yesno <- No + }{ + If[[before] = [""]] + { + Print[[["Found "]Append[delim]]Append[" where a named pipe or literal was expected"]] + { Print[["Near: "]Append[ [afterdelim]Slice[80]]] } + }{ + If[[before]Contains[[params]Global Separator >>]] + { + parts <- [before]Split[[params]Global Separator >>] + out <- Global Node[Right Trim[[parts]Index[0],"\r\n\t "], Trim[[parts]Index[1], "\r\n\t "]] + }{ + out <- Named Pipe Node[Right Trim[before,"\r\n\t "]] + } + } + } + } + out <- Literal Node[yesno] + } + } + } + } + out <- Literal Node[value] +} + +Parse Arguments[string,params,arglist:args,after] +{ + targs <- Comment Left Trim[string, "\r\n\t ", params] + If[[targs]Starts With[[params]List Delim >>]] + { + [targs]Slice[[[params]List Delim >>]Length] {} + { + final args <- Comment Left Trim[~, "\r\n\t ", params] + } + }{ + If[[targs]Starts With[[params]Arg End >>]] + { + args <- arglist + ,after <- [targs]Slice[[[params]Arg End >>]Length] + }{ + final args <- Val[targs] + } + } + arg, after arg <- Parse Expression[final args, params] + args, after <- Parse Arguments[after arg, params, [arglist]Append[arg]] +} + +Worker or Field[name,args,params:out] +{ + get field <- [params]Get Field >> + If[[name]Ends With[get field]] + { + field <- Right Trim[[name]Slice[[[name]Length] - [[get field]Length]], "\n\r\t "] + out <- Field Node[field, args, No] + }{ + set field <- [params]Set Field >> + If[[name]Ends With[set field]] + { + field <- Right Trim[[name]Slice[[[name]Length] - [[set field]Length]], "\n\r\t "] + out <- Field Node[field, args, Yes] + }{ + out <- Worker Node[name, args] + } + } +} + +Prefix[string,params,name,existing args:expression,after] +{ + //Parse argument list + more args,after <- Parse Arguments[string, params, existing args] + expression <- Worker or Field[name, more args, params] +} + +Postfix or Infix[string,params:expression,after] +{ + args, after args <- Parse Arguments[string, params, ()] + delims <- [[[[[("\n")]Append[[params]Arg Begin >>]]Append[[params]Empty Block >>]]Append[[params]Block Begin >>]]Append[[params]Arg End >>]]Append[[params]List Delim >>] + aftere,before,delim <- [after args]Get Comment DString[delims, params] + { + If[[delim] = [[params]Arg Begin >>]] + { + expression, after <- Prefix[aftere, params, Trim[before,"\r\n\t "], args] + }{ + If[[delim] = [[params]Empty Block >>]] + { + after <- Val[aftere] + }{ + ,after <- [after args]Slice[[before]Length] + } + expression <- Worker or Field[Trim[before,"\r\n\t "], args, params] + } + } +} + +Parse Expression[trimmed,params:final expression,after blocks] +{ + delims <- [[[[[[[("\n")]Append[[params]Arg Begin >>]]Append[[params]Arg End >>]]Append[[params]Assign >>]]Append["\n"]]Append[[params]Empty Block >>]]Append[[params]Block End >>]]Append[[params]String Begin >>] + after, before, delim <- [trimmed]Get Comment DString[delims, params] + { + //If we find an arg begin token, we have a worker expression + If[[delim] = [[params]Arg Begin >>]] + { + maybe name <- Right Trim[before, "\r\t "] + //Prefix expressions will have the worker name before the first arg begin token + If[[maybe name] = [""]] + { + expression, after expression <- Postfix or Infix[after, params] + }{ + If[[maybe name]Contains[[params]List Delim >>]] + { + after expression <- [after literal]Append[[delim]Append[after]] + expression, after literal <- Named Pipe or Literal[Right Trim[before, "\r\n\t "], params] + }{ + expression, after expression <- Prefix[after, params, maybe name, ()] + } + } + }{ + If[[delim] = [[params]Assign >>]] + { + //Expressions starting with an assignment can be prefix, postfix or infix + //or they can be a simple literal or named pipe + assignments <- Map[[before]Split[[params]List Delim >>], Trim[?,"\n\r\t "]] + ,after blocks <- Parse Expression[Comment Left Trim[after, " \n\r\t", params], params] + { + final expression <- [~]Assignments <<[assignments] + } + }{ + //If[[delim] = [[params]String Begin >>]] + //{ + // If[[Trim[before, "\r\n\t "]] = [""]] + // { + // expression, after expression <- Named Pipe or Literal[[delim]Append[after], params] + // }{ + // after expression <- [after literal]Append[[delim]Append[after]] + // expression, after literal <- Named Pipe or Literal[Right Trim[before, "\r\n\t "], params] + // } + //}{ + // after expression <- [after literal]Append[[delim]Append[after]] + // expression, after literal <- Named Pipe or Literal[Right Trim[before, "\r\n\t "], params] + //} + expression, after expression <- Named Pipe or Literal[trimmed, params] + } + } + //Any expression can be followed by one or more blocks mapping the inputs of other expressions + //to the outputs of the current one + blocks,after blocks <- Get Expression Blocks[after expression, params, ()] + final expression <- [expression]Blocks <<[blocks] + } +} + +Worker Body[string,params,trees:outtrees,after end] +{ + trimmed <- Comment Left Trim[string, "\n\r\t ", params] + If[[trimmed]Starts With[[params]Block End >>]] + { + //We're done with this block, return + ,after end <- [trimmed]Slice[[[params]Block End >>]Length] + outtrees <- trees + }{ + expression, after expression <- Parse Expression[trimmed, params] + outtrees,after end <- Worker Body[after expression, params, [trees]Append[expression]] + } +} + +Process Modifiers[worker,params,modifiers:out] +{ + //Eventually this will need to be more sophisticated to handle more modifiers + trimmed <- Comment Left Trim[modifiers, "\n\r\t ", params] + If[[trimmed]Starts With[[params]Uses >>]] + { + ,after uses <- [trimmed]Slice[[[params]Uses >>]Length] + ,stores string <- [after uses]Get Comment DString["\n", params] + out <- [worker]Uses Stores <<[Map[[stores string]Split[[params]List Delim >>], Trim[?, "\r\n\t "]]] + }{ + out <- worker + } +} + +Remove Named Pipe Node[element:out] +{ + If[[Blueprint Of[element]] = [Named Pipe Node()]] + { + out <- [element]Name >> + }{ + If[[Blueprint Of[element]] = [Type Instance()]] + { + out <- [element]Params <<[ Map[[element]Params >>, Remove Named Pipe Node[?]] ] + }{ + out <- element + } + } +} + +Parse Param List[text,paramlist,typelist,params:out params,out types] +{ + delims <- [[()]Append[[params]List Begin >>]]Append[[params]List Delim >>] + after,param name <-[text]Get DString[delims] {} + { + tname <- Trim[~, "\r\n\t "] + If[[tname] = [""]] + { + nextlist <- Val[paramlist] + next types <- Val[typelist] + }{ + nextlist <- [paramlist]Append[tname] + next types <- [typelist]Append[paramtype] + } + }{ + If[[~] = [[params]List Begin >>]] + { + type info,after type <- Parse List[after,params,()] + type <- [type info]Index[0] + { + If[[Blueprint Of[~]] = [Named Pipe Node()]] + { + before variant <- Type Instance[[type]Name >>] + }{ + before variant <- <- [type]Params <<[ Map[[type]Params >>, Remove Named Pipe Node[?]] ] + } + variant <- [type info]Index[1] + { + ,warn <- If[[Blueprint Of[~]] = [Named Pipe Node()]] + { + before mutable,warn <- [before variant]Set Variant[[variant]Name >>] + } + Val[warn] + { + Print[[[["Warning: Invalid variant for type "]Append[[before variant]Name >>]]Append[" on input "]]Append[param name]] + before mutable <- Val[before variant] + } + }{ + before mutable <- Val[before variant] + } + [type info]Index[2] + { + paramtype <- [before mutable]Mutable? <<[ [[~]Name >>] = ["Mutable"] ] + }{ + paramtype <- Val[before mutable] + } + }{ + paramtype <- Type Instance["Any Type"] + } + [after type]Get DString[","] + { + out params,out types <- Parse Param List[~,nextlist,next types,params] + } {} {} { + out params <- Val[nextlist] + out types <- Val[next types] + } + }{ + paramtype <- Type Instance["Any Type"] + out params,out types <- Parse Param List[after,nextlist,next types,params] + } + + }{ + paramtype <- Type Instance["Any Type"] + out params <- Val[nextlist] + out types <- Val[next types] + } +} + +Worker Declaration[string,params:worker,rest,no match] +{ + ,whitespace name <- [string]Get Comment DString[[params]Arg Begin >>, params] + { + worker name <- Trim[whitespace name, "\n\r\t "] + in out <- [params]In Out Delim >> + arg end <- [params]Arg End >> + delims <- [[()]Append[in out]]Append[arg end] + after <- [~]Get Comment DString[delims, params] {} + { + arglist <- Trim[~,"\r\n\t "] + }{ + //check if there is an in/out separator + //if it isn't present, everything in the arglist is an input + If[[~] = [in out]] + { + rest <- [after]Get Comment DString[arg end, params] {} + { + outputs,output types <- Parse Param List[~, (), (), params] + } + }{ + rest <- Val[after] + outputs <- () + output types <- () + } + inputs,input types <- Parse Param List[arglist, (), (), params] + worker <- Parse Worker[worker name, inputs, outputs, input types, output types, 0] + } + }{}{}{ + no match <- string + } +} + +Worker Name[string,params,tree,lines:out] +{ + ,after arglist <- Worker Declaration[string, params] + { + worker name <- [~]Name >> + body text, modifiers <- [after arglist]Get Comment DString[[params]Block Begin >>, params] + modified <- Process Modifiers[~, params, modifiers] + expression trees, after body <- Worker Body[body text, params, ()] + worker <- [modified]Trees <<[expression trees] + new worker dict <- [[tree]Workers >>]Set[worker name, worker] + out <- Null[after body, params, [tree]Workers <<[new worker dict], 0] + } {} { + out <- tree + } +} + +Parse Foreign Worker[tree, string, lib, params:out] +{ + ,rest <- Worker Declaration[string, params] + { + foreign <- [~]Trees << [lib] + next <- [tree]Workers << [[[tree]Workers >>]Set[[foreign]Name >>, foreign]] + out <- Parse Foreign Worker[next, rest, lib, params] + } {} { + out <- tree + } +} + +Parse Foreign[string,params,tree,lines:out] +{ + ,after foreign <- [string]Slice[[[params]Foreign >>]Length] + [after foreign]Get Comment DString[[params]Blueprint Type Delim >>, params] + { + [~]Get Comment DString[[params]Block Begin >>, params] + { + rest, body <- [~]Get Comment DString[[params]Block End >>, params] + } + { lib <- Trim[~, "\r\n\t "] } + } + { language <- Trim[~, "\r\n\t "] } + Parse Foreign Worker[tree, body, New Foreign Lib[language, lib], params] + { + out <- Null[rest, params, ~, 0] + } +} + +Parse Global Vars[string,params,store:out] +{ + trimmed <- Left Trim[string, "\r\n\t "] + If[trimmed] + { + ,,after <- [trimmed]Partition[[params]Assign >>] + { + varname <- Right Trim[~, "\r\n\t "] + } {} { + valstring <- [~]Partition["\n"] {} {} + { + out <- Parse Global Vars[~,params,next store] + }{ + valstring <- Val[after] + out <- Val[next store] + } + Val[valstring] + { + Print[["Parsing initial value: "]Append[valstring]] + value <- [Named Pipe or Literal[Trim[~, "\r\n\t "], params]]Value >> + next store <- [store]Vars <<[ [[store]Vars >>]Set[varname, value] ] + } + }{ + Print[["Expected assignment operator in global var block, found "]Append[trimmed]] + } + }{ + out <- store + } +} + +Parse Globals[string,params,tree,lines:out] +{ + ,after globals <- [string]Slice[[[params]Globals >>]Length] + [after globals]Partition[[params]Block Begin >>] + { + store <- Global Store[Trim[~, "\r\n\t "]] + } {} { + + [~]Partition[[params]Block End >>] + { + next tree <- [tree]Add Global Store[Parse Global Vars[~, params, store]] + } {} { + out <- Null[~,params,next tree,lines] + }{ + Print["Error: Globals declaration missing block close symbol"] + out <- tree + } + } { + Print["Error: Globals declaration without block"] + out <- tree + } +} + + +Null[string,params,tree,lines:out] +{ + trimmed <- Comment Left Trim[string, " \n\r\t", params] + current line <- 0 + If[[trimmed]Starts With[ [params]Blueprint >> ]] + { + out <- PBlueprint[trimmed, params, tree, current line] + }{ + If[[trimmed]Starts With[ [params]Import >> ]] + { + out <- Parse Import[trimmed, params, tree, current line] + }{ + If[[trimmed]Starts With[ [params]Foreign >> ]] + { + out <- Parse Foreign[trimmed, params, tree, current line] + }{ + If[[trimmed]Starts With[[params]Globals >>]] + { + out <- Parse Globals[trimmed, params, tree, current line] + }{ + If[trimmed] + { + out <- Worker Name[trimmed, params, tree, current line] + }{ + out <- tree + } + } + } + } + } +} + +Check Worker Literals@Parse Worker[worker,program:out] +{ + [(List(),List Leaf())]Find[=[Blueprint Of[[worker]Trees >>], ?]] + { + out <- [worker]Trees <<[ Map[[worker]Trees >>, Check Worker Literals[?, program]] ] + }{ + out <- worker + } +} + +Register Workers Compile[prog, worker, name:out] +{ + //Print[["Registering "]Append[name]] + If[[ Blueprint Of[[worker]Trees >>] ] = [Foreign Lib()]] + { convention <- Val[[[worker]Trees >>]Language >>] } + { convention <- "rhope" } + out <- [prog]Register Worker[name, convention, [[worker]Inputs >>]Length, [[worker]Outputs >>]Length] +} + +Add Workers Compile[prog, worker, name:out] +{ + Print[["Transforming "]Append[name]] + If[[Blueprint Of[[worker]Trees >>]] = [Foreign Lib()]] + { + //TODO: Handle foreign func + final nworker <- [[[[[NWorker[[[worker]Trees >>]Language >>] + ]Inputs <<[ [worker]Inputs >> ] + ]Input Types <<[ [worker]Input Types >> ] + ]Outputs <<[ [worker]Outputs >> ] + ]Output Types <<[ [worker]Output Types >> ] + ]Library <<[ [[worker]Trees >>]Name >> ] + + }{ + assigned <- Fold[_Get Assigned Pipes[?], Dictionary[], [worker]Trees >>] + trees, nworker, refs <- Add List to Worker[[worker]Trees >>, [[NWorker["rhope"]]Uses[[worker]Uses Stores >>]]Outputs <<[ [worker]Outputs >> ], prog, [worker]Assigned <<[assigned], Dictionary[]] + { + final nworker <- Fold[Add Wires Helper[?, ?, ?, worker, refs], nworker, trees] + } + + } + out <- [prog]Bind Worker[name, final nworker] +} + +Add Wires Helper[worker,node,unused,parse worker,assignments:out] +{ + out <- [node]Add Wires[worker, (), parse worker, assignments] +} + +Add Blueprint Field[blueprint,field,unused:out] +{ + out <- [blueprint]Add Field[[field]Name >>, [field]Type >>] +} + +Add Blueprint Compile[prog,def:out] +{ + out <- [prog]Bind Blueprint[[def]Name >>, Fold[Add Blueprint Field[?], NBlueprint[], [def]Fields >>]] +} + +Tree to Program Native[parse tree,number types:out] +{ + registered <- Fold[Register Workers Compile[?], [Fold[Add Blueprint Compile[?], [[NProgram[]]Numtypes <<[number types]]Global Stores <<[[parse tree]Global Stores >>], [parse tree]Blueprints >>]]Register Builtins, [parse tree]Workers >>] + out <- Fold[Add Workers Compile[?], registered, [parse tree]Workers >>] + { Print["Transformed AST to dataflow graph "] } +} + +Needs Imports[needs import,not imported?,name:out] +{ + If[not imported?] + { + out <- [needs import]Append[name] + }{ + out <- needs import + } +} + +Do Import[tree,file name,unused,params:out] +{ + Print[["Parsing: "]Append[file name]] + file <- [File[file name]]Open["r"] + text <- String[[file]Read[[file]Length]] + after import <- Null[text, params, tree, 0] + + out <- [after import]Imports <<[[[after import]Imports >>]Set[file name, No]] +} + +Process Imports[parse tree,params:out] +{ + needs import <- Fold[Needs Imports[?], (), [parse tree]Imports >>] + If[[[needs import]Length] > [0]] + { + import tree <- Fold[Do Import[?, ?, ?, params], parse tree, needs import] + out <- Process Imports[import tree, params] + }{ + out <- parse tree + } +} + +Until End[text:out] +{ + line <- Get Input[] + If[[line] = ["End"]] + { + out <- [text]Append["\n"] + }{ + out <- Until End[[[text]Append["\n"]]Append[line]] + } +} + +Add If Store[stores,name,params:out] +{ + If[[name]Contains[[params]Global Separator >>]] + { + parts <- [name]Split[[params]Global Separator >>] + out <- [stores]Set[[parts]Index[0], Yes] + }{ + out <- stores + } +} + +Param Gather Stores[stores,node,params:out] +{ + out <- [node]Gather Stores[params, stores] +} + +Gather Stores@Named Pipe Node[node,params,stores:out] +{ + out <- Fold[Add If Store[?, ?, params], stores, [node]Assignments >>] +} + +Gather Stores@Global Node[node,params,stores:out] +{ + out <- [stores]Set[[node]Store >>, Yes] +} + +Gather Stores@Worker Node[node,params,stores:out] +{ + //TODO: Handle blocks + store list <- Fold[Param Gather Stores[?, ?, params], stores, [node]Params >>] + out <- Fold[Add If Store[?, ?, params], store list, [node]Assignments >>] +} + +Gather Stores@Field Node[node,params,stores:out] +{ + //TODO: Handle blocks + store list <- Fold[Param Gather Stores[?, ?, params], stores, [node]Params >>] + out <- Fold[Add If Store[?, ?, params], store list, [node]Assignments >>] +} + +Gather Stores@Literal Node[node,params,stores:out] +{ + out <- Fold[Add If Store[?, ?, params], stores, [node]Assignments >>] +} + + diff -r 24c6f8767190 -r c6ba9fe45910 parser_old_c.rhope --- a/parser_old_c.rhope Wed Jul 27 21:14:23 2011 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1683 +0,0 @@ -Import nworker_c.rhope - -//Rather than rewrite the code that uses this -//let's implement Get DString using Partition -Get DString[str,delims:after,before,delim,not found] -{ - before,delim,after,not found <- [str]Partition[delims] {} {} {} - { - before <- str - } -} - - -Blueprint Parser -{ - Arg Begin - Arg End - Line Comment - Comment Begin - Comment End - Assign - Block Begin - Block End - Blueprint Type Delim - Empty Block - Binary Operator - String Begin - String End - String Escape - List Begin - List End - List Delim - In Out Delim - Index Begin - Index End - Previous - Block Val - Set Field - Get Field - Import - Blueprint - Global Separator - Uses - Hex Escape - Escape Map - Foreign - Globals -} - -Parser[:out] -{ - out <- [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[Build[Parser()] - ]Arg Begin << ["["] - ]Arg End <<["]"] - ]Line Comment <<["//"] - ]Comment Begin <<["/*"] - ]Comment End <<["*/"] - ]Assign <<["<-"] - ]Block Begin <<["{"] - ]Block End <<["}"] - ]Blueprint Type Delim <<[":"] - ]Empty Block <<[";"] - ]Binary Operator <<["`"] - ]String Begin <<["\""] - ]String End <<["\""] - ]String Escape <<["\\"] - ]List Begin <<["("] - ]List End <<[")"] - ]List Delim <<[","] - ]In Out Delim <<[":"] - ]Index Begin <<["("] - ]Index End <<[")"] - ]Previous <<["@"] - ]Set Field <<["<<"] - ]Get Field <<[">>"] - ]Import <<["Import"] - ]Blueprint <<["Blueprint"] - ]Global Separator <<["::"] - ]Hex Escape <<["x"] - ]Uses <<["uses"] - ]Escape Map <<[[[[Dictionary[]]Set["n","\n"]]Set["r","\r"]]Set["t","\t"]] - ]Foreign <<["Foreign"] - ]Globals <<["Globals"] -} - -Blueprint Output Reference -{ - Index - Output Number -} - -Output Reference[index,num:out] -{ - out <- [[Build[Output Reference()]]Index <<[index]]Output Number <<[num] -} - -Add Pipe Reference[refs,name,reference:out] -{ - reflist <- [refs]Index[name] {} - { - reflist <- () - } - out <- [refs]Set[name, [reflist]Append[reference]] -} - -Assignment Save Reference[refs,assignment,output num,parse worker,index:out] -{ - [[parse worker]Outputs >>]Find[=[assignment,?]] - { - out <- refs - }{ - out <- Add Pipe Reference[refs, assignment, Output Reference[index, output num]] - } -} - -Blueprint Foreign Lib -{ - Language - Name -} - -New Foreign Lib[language, library:out] -{ - out <- [[Build[Foreign Lib()] - ]Language <<[language] - ]Name <<[library] -} - -Blueprint Global Store -{ - Name - Vars -} - -Global Store[name:out] -{ - out <- [[Build[Global Store()]]Name <<[name]]Vars <<[Dictionary[]] -} - -Blueprint Parse Program -{ - Workers - Imports - Blueprints - Global Stores - Errors -} - -Parse Program[:out] -{ - out <- [[[[[Build[Parse Program()] - ]Workers <<[Dictionary[]] - ]Imports <<[Dictionary[]] - ]Blueprints <<[Dictionary[]] - ]Global Stores <<[Dictionary[]] - ]Errors <<[()] -} - -Add Global Store@Parse Program[tree,store:out] -{ - out <- [tree]Global Stores <<[ [[tree]Global Stores >>]Set[[store]Name >>, store] ] -} - -Blueprint Blueprint Definition -{ - Name - Fields -} - -New Blueprint Definition[name,fields:out] -{ - out <- [[Build[Blueprint Definition()]]Name << [name]]Fields <<[fields] -} - -Blueprint Parse Worker -{ - Name - Inputs - Outputs - Line Number - Trees - Uses Stores - Input Types - Output Types - Assigned -} - -Parse Worker[name,inputs,outputs,intypes,outtypes,line:out] -{ - out <- [[[[[[[[[Build[Parse Worker()]]Name <<[name]]Inputs <<[inputs]]Outputs <<[outputs]]Line Number <<[line]]Trees <<[()]]Uses Stores <<[()]]Input Types <<[intypes]]Output Types <<[outtypes]]Assigned <<[Dictionary[]] -} - -Blueprint Worker Node -{ - Name - Params - Assignments - Blocks - Index -} - -Worker Node[name,params:out] -{ - out <- [[[[Build[Worker Node()]]Name <<[name]]Params <<[params]]Assignments <<[()]]Blocks <<[()] -} - -_Get Assigned Pipes[pipe dict,node:out] -{ - out <- [node]Get Assigned Pipes[pipe dict] -} - -Get Assigned Pipes[node,pipe dict:out] -{ - Fold[Set[?,?,Yes], pipe dict, [node]Assignments >>] - { out <- Fold[Fold[_Get Assigned Pipes[?], ?], ~, [node]Blocks >>] } -} - -Add List Helper[inlist,worker,program,key,parse worker,refs:out list,out worker,out refs] -{ - ,nextworker,nextrefs <- [[inlist]Index[key]]Add to Worker[worker, program, parse worker, refs] - { nextlist <- [inlist]Set[key, ~] } - [inlist]Next[key] - { - out list,out worker,out refs <- Add List Helper[nextlist, nextworker, program, ~, parse worker, nextrefs] - }{ - out list <- Val[nextlist] - out worker <- Val[nextworker] - out refs <- Val[nextrefs] - } -} - -Add List to Worker[list,worker,program,parse worker,refs:out list,out worker,out refs] -{ - [list]First - { - out list,out worker,out refs <- Add List Helper[list, worker, program, ~, parse worker, refs] - }{ - out list <- list - out worker <- worker - out refs <- refs - } -} - -_Add Blocks to Worker[blocks,worker,program,parse worker,key,refs:out blocks,out worker,out refs] -{ - block, next worker, nextrefs <- Add List to Worker[[blocks]Index[key], worker, program, parse worker, refs] - next blocks <- [blocks]Set[key, block] - [blocks]Next[key] - { - out blocks,out worker,out refs <- _Add Blocks to Worker[next blocks, next worker, program, parse worker, ~, nextrefs] - }{ - out blocks <- Val[next blocks] - out worker <- Val[next worker] - out refs <- Val[nextrefs] - } -} - -Add Blocks to Worker[blocks,worker,program,parse worker,refs:out blocks,out worker,out refs] -{ - [blocks]First - { - out blocks, out worker, out refs <- _Add Blocks to Worker[blocks, worker, program, parse worker, ~, refs] - }{ - out blocks <- blocks - out worker <- worker - out refs <- refs - } -} - -Add to Worker@Worker Node[node,worker,program,parse worker,refs:out node,out worker,out refs] -{ - [program]Find Worker[[node]Name >>] - { - after worker <- [worker]Add Worker Call[~] {} - { - //Print[[[[node]Name >>]Append[" has index "]]Append[~]] - assignment refs <- Fold[Assignment Save Reference[?, ?, ?, parse worker, ~], refs, [node]Assignments >>] - [node]Index <<[~] - { - params list, params worker, params refs <- Add List to Worker[[~]Params >>, after worker, program, parse worker, assignment refs] - block list, out worker, out refs <- Add Blocks to Worker[[~]Blocks >>, params worker, program, parse worker, params refs] - out node <- [[~]Params <<[params list]]Blocks <<[block list] - } - } - }{ - make call <- [[parse worker]Assigned >>]Index[[node]Name >>] {} - { - make call <- [[parse worker]Inputs >>]Find[=[?,[node]Name >>]] {} - { - Print[["Error: Could not find a worker named "]Append[[node]Name >>]] - } - } - Val[make call] - { - new params <- Fold[Append[?], [()]Append[Named Pipe Node[[node]Name >>]], [node]Params >>] - out node, out worker, out refs <- [[[node]Params <<[new params]]Name <<["Call"]]Add to Worker[worker, program, parse worker, refs] - } - } -} - -Check Question Mark[params, index:has mark,no mark] -{ - param,no mark <-[params]Index[index] - { - If[[Blueprint Of[param]]=[Named Pipe Node()]] - { - has mark <-If[[[param]Name >>] = ["?"]] {} - { - has mark,no mark <- Check Question Mark[params, [index]+[1]] - } - }{ - has mark,no mark <- Check Question Mark[params, [index]+[1]] - } - } -} - -Collect Literal Inputs[literal, params, index, complex inputs:literal out,complex out] -{ - param <- [params]Index[index] - { - If[[Blueprint Of[param]]=[Literal Node()]] - { - next literal <- [literal]Set Input[index, [param]Value >>] - next complex <- Val[complex inputs] - }{ - ,doset <- If[[Blueprint Of[param]]=[Named Pipe Node()]] - { - ,doset <- If[[[param]Name >>] = ["?"]] - { - //Question mark indicates unpopulated input - next complex <- Val[complex inputs] - next literal <- Val[literal] - } - } - - Val[doset] - { - next complex <- [complex inputs]Set[index, param] - next literal <- Val[literal] - } - } - literal out, complex out <- Collect Literal Inputs[next literal, params, [index]+[1], next complex] - }{ - literal out <- literal - complex out <- complex inputs - } -} - -Do Set Input[literal,param,index:out] -{ - out <- Worker Node["Set Input", [[[()]Append[literal]]Append[Literal Node[index]]]Append[param]] -} - -Check Worker Literals@Worker Node[node,program:out] -{ - new params <- Map[[node]Params >>, Check Worker Literals[?, program]] - Check Question Mark[new params, 0] - { - base literal, complex inputs <- Collect Literal Inputs[Worker Literal[[node]Name >>], new params, 0, ()] - new node <- Fold[Do Set Input[?], Literal Node[base literal], complex inputs] - }{ - new node <- [node]Params <<[new params] - } - out <- [new node]Blocks <<[ Map[[node]Blocks >>, Map[?, Check Worker Literals[?, program]]] ] -} - -Add Multi Wire[worker,ref,junk,end index,input num:out] -{ - out <- [worker]Add Wire[[ref]Index >>, [ref]Output Number >>, end index, input num] -} - -Add Param Wire[worker,param,input num,end index,blocks,parse worker,assignments:out] -{ - param worker, start index, output num <- [param]Add Wires[worker, blocks, parse worker, assignments] {} - { - out <- [param worker]Add Wire[start index, output num, end index, input num] - }{}{ - out <- Fold[Add Multi Wire[?, ?, ?, end index, input num], param worker, ~] - } -} - -_Add Block Wire[worker,node,junk,blocks,parse worker,assignments:out] -{ - out <- [node]Add Wires[worker, blocks, parse worker, assignments] -} - -Add Block Wire[worker,block nodes,output num,parent index,existing blocks,parse worker,assignments:out] -{ - blocks <- [existing blocks]Append[Output Reference[parent index, output num]] - out <- Fold[_Add Block Wire[?, ?, ?, blocks, parse worker, assignments], worker, block nodes] -} - -Assignments Add Wires[worker,assignment,output num,parse worker,start index:out worker] -{ - [[parse worker]Outputs >>]Find[=[assignment,?]] - { - ,output index <- [worker]Add Typed Output[assignment, ~, [[parse worker]Output Types >>]Index[~]] - { - out worker <- [~]Add Wire[start index, output num, output index, 0] - } - }{ - //Ugly hack alert! - If[[assignment]Contains["::"]] - { - parts <- [assignment]Split["::"] - ,global index <- [worker]Add Global Set[[parts]Index[0], [parts]Index[1]] - { - out worker <- [~]Add Wire[start index, output num, global index, 0] - } - }{ - out worker <- worker - } - } -} - -Has Block@Worker Node[junk:out,unused] -{ - out <- Yes -} - -_Has Block Params[param list,key:out] -{ - param <- [param list]Index[key] - out <- [param]Has Block {} - { - [param list]Next[key] - { - out <- _Has Block Params[param list, ~] - }{ - out <- No - } - } - -} - -Has Block Params[param list:out] -{ - [param list]First - { - out <- _Has Block Params[param list, ~] - }{ - out <- No - } -} - -Add Wires@Worker Node[node,worker,blocks,parse worker,assignments:outworker,index,num,unused] -{ - outworker,index,num <- Add Wires Worker or Field[node, worker, blocks, parse worker, assignments] -} - -Add Wires Worker or Field[node,worker,blocks,parse worker,assignments:outworker,index,num,unused] -{ - Fold[Assignments Add Wires[?, ?, ?, parse worker, [node]Index >>], worker, [node]Assignments >>] - { - Fold[Add Block Wire[?, ?, ?, [node]Index >>, blocks, parse worker, assignments], ~, [node]Blocks >>] - { - params worker <- Fold[Add Param Wire[?, ?, ?, [node]Index >>, blocks, parse worker, assignments], ~, [node]Params >>] - { - index <- [node]Index >> - num <- 0 - } - } - } - If[Has Block Params[[node]Params >>]] - { - outworker <- Val[params worker] - }{ - [blocks]Peek - { - outworker <- [params worker]Add Wire[[~]Index >>, [~]Output Number >>, [node]Index >>, [0]-[1]] - }{ - outworker <- Val[params worker] - } - } -} - -Blueprint Field Node -{ - Name - Params - Assignments - Blocks - Index - Set? -} - -Has Block@Field Node[junk:has block,unused] -{ - has block <- Yes -} - -Field Node[name,params,set:out] -{ - out <- [[[[[Build[Field Node()]]Name <<[name]]Assignments <<[()]]Blocks <<[()]]Set? <<[set]]Params <<[params] -} - -Add to Worker@Field Node[node,worker,program,parse worker,refs:out node,out worker,out refs] -{ - If[[node]Set? >>] - { - after worker,index <- [worker]Add Object Set[[node]Name >>] - }{ - after worker,index <- [worker]Add Object Get[[node]Name >>] - } - Val[index] - { - assignment refs <- Fold[Assignment Save Reference[?, ?, ?, parse worker, ~], refs, [node]Assignments >>] - [node]Index <<[~] - { - params list, params worker, params refs <- Add List to Worker[[~]Params >>, after worker, program, parse worker, assignment refs] - block list, out worker, out refs <- Add Blocks to Worker[[~]Blocks >>, params worker, program, parse worker, params refs] - out node <- [[~]Params <<[params list]]Blocks <<[block list] - } - } -} - -Add Wires@Field Node[node,worker,blocks,parse worker,assignments:outworker,index,num] -{ - outworker,index,num <- Add Wires Worker or Field[node, worker, blocks, parse worker, assignments] -} - -Check Worker Literals@Field Node[node,program:out] -{ - new params <- Map[[node]Params >>, Check Worker Literals[?, program]] - out <- [[node]Blocks <<[ Map[[node]Blocks >>, Map[?, Check Worker Literals[?, program]]] ] - ]Params <<[new params] -} - -Blueprint Named Pipe Node -{ - Name - Assignments - Blocks - Index -} - -Has Block@Named Pipe Node[node:has block,no block] -{ - If[[[node]Index >>] < [0]] - { - //~ should really be a parser parameter - If[[[node]Name >>] = ["~"]] - { - has block <- Yes - }{ - no block <- No - } - }{ - has block <- Yes - } -} - -Named Pipe Node[name:out] -{ - out <- [[[Build[Named Pipe Node()]]Name <<[name]]Assignments <<[()]]Blocks <<[()] -} - -Add to Worker@Named Pipe Node[node,worker,program,parse worker,refs:out node,out worker,out refs] -{ - [[parse worker]Inputs >>]Find[=[[node]Name >>, ?]] - { - after add <- [worker]Add Typed Input[[node]Name >>, ~, [[parse worker]Input Types>>]Index[~]] {} - { - assign refs <- Fold[Assignment Save Reference[?, ?, ?, parse worker, ~], refs, [node]Assignments >>] - index node <- [node]Index <<[~] - } - }{ - after add <- worker - index node <- [node]Index <<[[0]-[1]] - //TODO: Handle assignments from a named pipe that isn't an input - assign refs <- refs - } - block list, out worker, out refs <- Add Blocks to Worker[[node]Blocks >>, after add, program, parse worker, assign refs] - out node <- [index node]Blocks <<[block list] -} - -Add Wires@Named Pipe Node[node,worker,blocks,parse worker,assignments:outworker,index,num,reflist] -{ - reflist <- [assignments]Index[[node]Name >>] - { - //TODO: Fix support for a named pipe with a block - outworker <- worker - }{ - If[[[node]Name >>] = ["~"]] - { - wires worker <- worker - [blocks]Peek - { - my index <- [~]Index >> - num <- [~]Output Number >> - }{ - //TODO: Propagate an error rather than printing it out - Print["Error, block reference symbol located outside of a block"] - } - }{ - If[[[node]Index >>] < [0]] - { - Print[[[["Error, reference to named pipe "]Append[[node]Name >>]]Append[" that was never assigned to in worker "]]Append[[parse worker]Name >>]] - }{ - my index <- [node]Index >> - num <- 0 - assignments worker <- Fold[Assignments Add Wires[?, ?, ?, parse worker, [node]Index >>], worker, [node]Assignments >>] - [blocks]Peek - { - wires worker <- [assignments worker]Add Wire[[~]Index >>, [~]Output Number >>, [node]Index >>, [0]-[1]] - }{ - wires worker <- Val[assignments worker] - } - } - } - } - index <- Val[my index] - - outworker <- Fold[Add Block Wire[?, ?, ?, my index, blocks, parse worker, assignments], wires worker, [node]Blocks >>] -} - -Check Worker Literals@Named Pipe Node[node,program:out] -{ - out <- [node]Blocks <<[ Map[[node]Blocks >>, Map[?, Check Worker Literals[?, program]]] ] -} - -Blueprint Global Node -{ - Store - Name - Assignments - Blocks - Index -} - -Global Node[store,name:out] -{ - out <- [[[[Build[Global Node()]]Store <<[store]]Name <<[name]]Assignments <<[()]]Blocks <<[()] -} - -Add to Worker@Global Node[node,worker,unused,parse worker,refs:out node,out worker,outrefs] -{ - out worker <- [worker]Add Global Get[[node]Store >>, [node]Name >>] {} - { - outrefs <- Fold[Assignment Save Reference[?, ?, ?, parse worker, ~], refs, [node]Assignments >>] - out node <- [node]Index <<[~] - } - outrefs <- refs -} - -Add Wires@Global Node[node,worker,blocks,parse worker,assignments:outworker,index,num,unused] -{ - outworker,index,num <- Add Wires Literal or Global[node, worker, blocks, parse worker, assignments] -} - -Has Block@Global Node[junk:out,unused] -{ - out <- Yes -} - -Check Worker Literals@Global Node[node,program:out] -{ - out <- [node]Blocks <<[ Map[[node]Blocks >>, Map[?, Check Worker Literals[?, program]]] ] -} - -Blueprint Literal Node -{ - Value - Assignments - Blocks - Index -} - -Has Block@Literal Node[junk:out,unused] -{ - out <- Yes -} - -Literal Node[value:out] -{ - out <- [[[Build[Literal Node()]]Value <<[value]]Assignments <<[()]]Blocks <<[()] -} - -Add to Worker@Literal Node[node,worker,unused,parse worker,refs:out node,out worker,out refs] -{ - out worker <- [worker]Add Constant[[node]Value >>] {} - { - out refs <- Fold[Assignment Save Reference[?, ?, ?, parse worker, ~], refs, [node]Assignments >>] - out node <- [node]Index <<[~] - } -} - -Add Wires@Literal Node[node,worker,blocks,parse worker,assignments:outworker,index,num,unused] -{ - outworker,index,num <- Add Wires Literal or Global[node, worker, blocks, parse worker, assignments] -} - -Check Worker Literals@Literal Node[node,program:out] -{ - out <- [node]Blocks <<[ Map[[node]Blocks >>, Map[?, Check Worker Literals[?, program]]] ] -} - -Add Wires Literal or Global[node,worker,blocks,parse worker,junk:outworker,index,num,unused] -{ - assignments worker <- Fold[Assignments Add Wires[?, ?, ?, parse worker, [node]Index >>], worker, [node]Assignments >>] - [blocks]Peek - { - outworker <- [assignments worker]Add Wire[[~]Index >>, [~]Output Number>>, [node]Index >>, [0]-[1]] - }{ - outworker <- Val[assignments worker] - } - index <- [node]Index >> - num <- 0 -} - -Blueprint Block Node -{ - Number -} - -Blueprint Parse Error -{ - Type - Text - Line Number -} - -Parse Error[type,text,number:out] -{ - out <- [[[Build[Parse Error()]]Type <<[type]]Text <<[text]]Line Number <<[number] -} - -Not Empty[string:out] -{ - If[[[string]Length] > [0]] - { - out <- Yes - }{ - out <- No - } -} - -Blueprint Blueprint Field -{ - Name - Type -} - -New Blueprint Field[name,type:out] -{ - out <- [[Build[Blueprint Field()]]Name <<[name]]Type <<[type] -} - -Process Blueprint Field[list,field,params:out] -{ - ,name <- [field]Get DString[[params]List Begin >>] - { - type info <- Parse List[~,params,()] - type <- [type info]Index[0] - { - If[[Blueprint Of[~]] = [Named Pipe Node()]] - { - before variant <- Type Instance[[type]Name >>] - }{ - before variant <- [type]Params <<[ Map[[type]Params >>, Remove Named Pipe Node[?]] ] - } - variant <- [type info]Index[1] - { - ,warn <- If[[Blueprint Of[~]] = [Named Pipe Node()]] - { - fieldtype,warn <- [before variant]Set Variant[[variant]Name >>] - } - Val[warn] - { - Print[[[["Warning: Invalid variant for type "]Append[[before variant]Name >>]]Append[" on field "]]Append[name]] - fieldtype <- Val[before variant] - } - }{ - fieldtype <- Val[before variant] - } - }{ - fieldtype <- Type Instance["Any Type"] - } - out <- [list]Append[New Blueprint Field[name, fieldtype]] - } {} {} { - out <- [list]Append[New Blueprint Field[name, Type Instance["Any Type"]]] - } -} - -Block Comment[string,begin comment,end comment,block count:out] -{ - If[[block count] > [0]] - { - after, before <- [string]Get DString[[[()]Append[begin comment]]Append[end comment]] {} {} - { - If[[~] = [begin comment]] - { - out <- Block Comment[after, begin comment, end comment, [block count]+[1]] - }{ - out <- Block Comment[after, begin comment, end comment, [block count]-[1]] - } - }{ - //No match - out <- "" - } - }{ - out <- string - } -} - -Line Comment[string:out] -{ - [string]Get DString["\n"] - { - out <- ["\n"]Append[~] - } {} {} { - out <- "" - } -} - -_Get Comment DString[string,delims,line comment,begin comment,end comment,prev before:rest,before,delim,nomatch] -{ - after,befored,used delim,nomatch <- [string]Get DString[delims] - { - If[[used delim] = [line comment]] - { - after comment <- Line Comment[after] - }{ - If[[used delim] = [begin comment]] - { - after comment <- Block Comment[after, begin comment, end comment, 1] - }{ - rest <- Val[after] - before <- [prev before]Append[befored] - delim <- Val[used delim] - } - } - } {} {} { - before <- [prev before]Append[befored] - } - - after comment - { - rest,more before,delim,nomatch <- _Get Comment DString[~, delims, line comment, begin comment, end comment, prev before] - before <- [before]Append[more before] - } - -} - -As List[val:out] -{ - [(List(),List Leaf())]Find[=[Blueprint Of[val], ?]] - { - out <- val - }{ - out <- [()]Append[val] - } -} - -Get Comment DString[string,delims,params:rest,before,delim,not found] -{ - line comment <- [params]Line Comment >> - begin comment <- [params]Comment Begin >> - end comment <- [params]Comment End >> - all delims <- [[[delims]As List]Append[begin comment]]Append[line comment] - rest, before, delim, not found <- _Get Comment DString[string, delims, line comment, begin comment, end comment, ""] -} - -Comment Left Trim[string,trim chars,params:out] -{ - line comment <- [params]Line Comment >> - - end comment <- [params]Comment End >> - trimmed <- Left Trim[string, trim chars] - If[[trimmed]Starts With[line comment]] - { - ,after delim <- [trimmed]Slice[[line comment]Length] - out <- Comment Left Trim[Line Comment[after delim], trim chars, params] - }{ - begin comment <- [params]Comment Begin >> - If[[trimmed]Starts With[begin comment]] - { - ,after delim <- [trimmed]Slice[[line comment]Length] - out <- Comment Left Trim[Block Comment[after delim, begin comment, end comment, 1], trim chars, params] - }{ - out <- Val[trimmed] - } - } -} - -PBlueprint[string,params,tree,lines:out] -{ - ,whitespace name <- [string]Get Comment DString[[params]Block Begin >>, params] - { - ,no blueprint <- [whitespace name]Slice[ [[params]Blueprint >>]Length ] - name <- Trim[no blueprint, "\r\n\t "] - name lines <- 0 - ,body <- [~]Get Comment DString[ [params]Block End >>, params] - { - body lines <- [body]Split["\n"] - more lines <- [[[body lines]Length] - [1]] + [name lines] - fields <- Fold[Process Blueprint Field[?, ?, params], (), Filter[Map[body lines, Trim[?,"\n\r\t "]], Not Empty[?]]] - new tree <- [tree]Blueprints << [ [[tree]Blueprints >>]Set[name, New Blueprint Definition[name, fields]] ] - out <- Null[~, params, new tree, [lines] + [more lines]] - } {} {} { - out <- [tree]Errors <<[ [[tree]Errors >>]Append[Parse Error["Error",[["Blueprint is missing an block close symbol \""]Append[[params]Block End >>]]Append["\""], lines]] ] - } - - } {} {} { - out <- [tree]Errors <<[ [[tree]Errors >>]Append[Parse Error["Error",[["Blueprint is missing an block open symbol \""]Append[[params]Block Begin >>]]Append["\""], lines]] ] - } -} - -Parse Import[string,params,tree,lines:out] -{ - [line]Slice[ [[params]Import >>]Length ] {} - { - filename <- Trim[~, " \n\r\t"] - } - - new tree <- [tree]Imports <<[[[tree]Imports >>]Set[filename, Yes]] - - ,line <- [string]Get Comment DString["\n", params] - { - out <- Null[~, params, new tree, [lines] + [1]] - } {} {} { - out <- Val[new tree] - } -} - -Get Expression Blocks[string,params,blocks:outblocks,after] -{ - check block <- Comment Left Trim[string, "\n\r\t ", params] - If[[check block]Starts With[[params]Block Begin >>]] - { - ,begin block <- [check block]Slice[[[params]Block Begin >>]Length] - trees, after block <- Worker Body[begin block, params, ()] - outblocks, after <- Get Expression Blocks[after block, params, [blocks]Append[trees]] - }{ - If[[check block]Starts With[[params]Empty Block >>]] - { - outblocks <- blocks - ,after <- [check block]Slice[[[params]Empty Block >>]Length] - }{ - outblocks <- blocks - after <- Val[check block] - } - } -} - -Parse Escape[string,params:char,after] -{ - code,rest <- [string]Slice[1] - If[[code] = [[params]Hex Escape >>]] - { - hex,after <- [rest]Slice[2] - char <- String[[Array[]]Append[Trunc UInt8[Abs UInt[Hex Int32[hex]]]]] - }{ - after <- Val[rest] - char <- [[params]Escape Map >>]Index[code] {} - { - char <- Val[code] - } - } -} - -Parse String[string,params,current:value,after] -{ - delims <- [[()]Append[[params]String End >>]]Append[[params]String Escape >>] - afters, before, delim <- [string]Get Comment DString[delims, params] - { - If[[delim] = [[params]String End >>]] - { - value <- [current]Append[before] - after <- Val[afters] - }{ - char,after escape <- Parse Escape[afters, params] - value,after <- Parse String[after escape, params, [[current]Append[before]]Append[char]] - } - } -} - -Parse List[string,params,list:value,after] -{ - trimmed <- Comment Left Trim[string, "\r\n\t ", params] - If[[trimmed]Starts With[[params]List End >>]] - { - value <- list - ,after <- [trimmed]Slice[[[params]List End >>]Length] - }{ - If[[trimmed]Starts With[[params]List Delim >>]] - { - ,el string <- [trimmed]Slice[[[params]List Delim >>]Length] - }{ - el string <- Val[trimmed] - } - element,after el <- Named Pipe or Literal[el string, params] - value,after <- Parse List[after el, params, [list]Append[[element]Get Value]] - } -} - -Get Value@Literal Node[node:out] -{ - out <- [node]Value >> -} - -Get Value@Named Pipe Node[node:out] -{ - out <- node -} - -Machine Integer[val, size, signed?:out] -{ - conv <- [[[[[[[[() - ]Append[UInt8[?]] - ]Append[Int8[?]] - ]Append[UInt16[?]] - ]Append[Int16[?]] - ]Append[UInt32[?]] - ]Append[Int32[?]] - ]Append[UInt64[?]] - ]Append[Int64[?]] - - base idx <- [[(8,16,32,64)]Find[=[size,?]]]*[2] - - If[signed?] - { - idx <- [base idx]+[1] - }{ - idx <- Val[base idx] - } - out <- [[conv]Index[idx]]Call[val] -} - -Parse Number[string,params:value,after] -{ - delims <- [[[[(" ","\t","\n","\r")]Append[[params]List Delim >>]]Append[[params]Block Begin >>]]Append[[params]Arg End >>]]Append[[params]List End >>] - after delim,valstring <- [string]Get Comment DString[delims, params] {} {} - { - after <- [~]Append[after delim] - }{ - after <- "" - } - first two,rest <- [valstring]Slice[2] - If[[first two] = ["0x"]] - { - value <- Hex Int32[rest] - }{ - If[[valstring]Contains["."]] - { - value <- Real64[valstring] - }{ - size, val, type <- [valstring]Get DString[("i","u")] - { - value <- Machine Integer[val, Int32[size], [type]=["i"]] - } {} {} { - value <- Int32[valstring] - } - } - } -} - -Parse Params@Type Instance[literal,params,string:out,after] -{ - plist,after <- Parse List[string,params,()] - out <- [literal]Params <<[plist] -} - -Named Pipe or Literal[string,params:out,after] -{ - name <- Comment Left Trim[string, "\n\r\t ", params] - If[[name]Starts With[[params]String Begin >>]] - { - ,string begin <- [name]Slice[[[params]String Begin >>]Length] - value,after <- Parse String[string begin, params, ""] - }{ - If[[name]Starts With[[params]List Begin >>]] - { - ,list start <- [name]Slice[[[params]List Begin >>]Length] - value,after <- Parse List[list start, params, ()] - }{ - If[[[name]Slice[1]]In["-0123456789"]] - { - value,after <- Parse Number[name, params] - }{ - delims <- [[[[[[[("\n")]Append[[params]Block Begin >>]]Append[[params]Block End >>]]Append[[params]Empty Block >>]]Append[[params]Arg End >>]]Append[[params]List Delim >>]]Append[[params]List End >>]]Append[[params]List Begin >>] - afterdelim,raw before,delim,nodelim <- [name]Get Comment DString[delims, params] {} {} {} - { delim <- "" } - - before <- Trim[raw before, "\r\n\t "] - If[[delim] = [[params]List Begin >>]] - { - value,after <- [Type Instance[before]]Parse Params[params,afterdelim] - }{ - Val[afterdelim] - { - after <- [delim]Append[~] - } - Val[nodelim] - { - after <- "" - } - If[[before] = ["Yes"]] - { - yesno <- Yes - }{ - If[[before] = ["No"]] - { - yesno <- No - }{ - If[[before] = [""]] - { - Print[[["Found "]Append[delim]]Append[" where a named pipe or literal was expected"]] - { Print[["Near: "]Append[ [afterdelim]Slice[80]]] } - }{ - If[[before]Contains[[params]Global Separator >>]] - { - parts <- [before]Split[[params]Global Separator >>] - out <- Global Node[Right Trim[[parts]Index[0],"\r\n\t "], Trim[[parts]Index[1], "\r\n\t "]] - }{ - out <- Named Pipe Node[Right Trim[before,"\r\n\t "]] - } - } - } - } - out <- Literal Node[yesno] - } - } - } - } - out <- Literal Node[value] -} - -Parse Arguments[string,params,arglist:args,after] -{ - targs <- Comment Left Trim[string, "\r\n\t ", params] - If[[targs]Starts With[[params]List Delim >>]] - { - [targs]Slice[[[params]List Delim >>]Length] {} - { - final args <- Comment Left Trim[~, "\r\n\t ", params] - } - }{ - If[[targs]Starts With[[params]Arg End >>]] - { - args <- arglist - ,after <- [targs]Slice[[[params]Arg End >>]Length] - }{ - final args <- Val[targs] - } - } - arg, after arg <- Parse Expression[final args, params] - args, after <- Parse Arguments[after arg, params, [arglist]Append[arg]] -} - -Worker or Field[name,args,params:out] -{ - get field <- [params]Get Field >> - If[[name]Ends With[get field]] - { - field <- Right Trim[[name]Slice[[[name]Length] - [[get field]Length]], "\n\r\t "] - out <- Field Node[field, args, No] - }{ - set field <- [params]Set Field >> - If[[name]Ends With[set field]] - { - field <- Right Trim[[name]Slice[[[name]Length] - [[set field]Length]], "\n\r\t "] - out <- Field Node[field, args, Yes] - }{ - out <- Worker Node[name, args] - } - } -} - -Prefix[string,params,name,existing args:expression,after] -{ - //Parse argument list - more args,after <- Parse Arguments[string, params, existing args] - expression <- Worker or Field[name, more args, params] -} - -Postfix or Infix[string,params:expression,after] -{ - args, after args <- Parse Arguments[string, params, ()] - delims <- [[[[[("\n")]Append[[params]Arg Begin >>]]Append[[params]Empty Block >>]]Append[[params]Block Begin >>]]Append[[params]Arg End >>]]Append[[params]List Delim >>] - aftere,before,delim <- [after args]Get Comment DString[delims, params] - { - If[[delim] = [[params]Arg Begin >>]] - { - expression, after <- Prefix[aftere, params, Trim[before,"\r\n\t "], args] - }{ - If[[delim] = [[params]Empty Block >>]] - { - after <- Val[aftere] - }{ - ,after <- [after args]Slice[[before]Length] - } - expression <- Worker or Field[Trim[before,"\r\n\t "], args, params] - } - } -} - -Parse Expression[trimmed,params:final expression,after blocks] -{ - delims <- [[[[[[[("\n")]Append[[params]Arg Begin >>]]Append[[params]Arg End >>]]Append[[params]Assign >>]]Append["\n"]]Append[[params]Empty Block >>]]Append[[params]Block End >>]]Append[[params]String Begin >>] - after, before, delim <- [trimmed]Get Comment DString[delims, params] - { - //If we find an arg begin token, we have a worker expression - If[[delim] = [[params]Arg Begin >>]] - { - maybe name <- Right Trim[before, "\r\t "] - //Prefix expressions will have the worker name before the first arg begin token - If[[maybe name] = [""]] - { - expression, after expression <- Postfix or Infix[after, params] - }{ - If[[maybe name]Contains[[params]List Delim >>]] - { - after expression <- [after literal]Append[[delim]Append[after]] - expression, after literal <- Named Pipe or Literal[Right Trim[before, "\r\n\t "], params] - }{ - expression, after expression <- Prefix[after, params, maybe name, ()] - } - } - }{ - If[[delim] = [[params]Assign >>]] - { - //Expressions starting with an assignment can be prefix, postfix or infix - //or they can be a simple literal or named pipe - assignments <- Map[[before]Split[[params]List Delim >>], Trim[?,"\n\r\t "]] - ,after blocks <- Parse Expression[Comment Left Trim[after, " \n\r\t", params], params] - { - final expression <- [~]Assignments <<[assignments] - } - }{ - //If[[delim] = [[params]String Begin >>]] - //{ - // If[[Trim[before, "\r\n\t "]] = [""]] - // { - // expression, after expression <- Named Pipe or Literal[[delim]Append[after], params] - // }{ - // after expression <- [after literal]Append[[delim]Append[after]] - // expression, after literal <- Named Pipe or Literal[Right Trim[before, "\r\n\t "], params] - // } - //}{ - // after expression <- [after literal]Append[[delim]Append[after]] - // expression, after literal <- Named Pipe or Literal[Right Trim[before, "\r\n\t "], params] - //} - expression, after expression <- Named Pipe or Literal[trimmed, params] - } - } - //Any expression can be followed by one or more blocks mapping the inputs of other expressions - //to the outputs of the current one - blocks,after blocks <- Get Expression Blocks[after expression, params, ()] - final expression <- [expression]Blocks <<[blocks] - } -} - -Worker Body[string,params,trees:outtrees,after end] -{ - trimmed <- Comment Left Trim[string, "\n\r\t ", params] - If[[trimmed]Starts With[[params]Block End >>]] - { - //We're done with this block, return - ,after end <- [trimmed]Slice[[[params]Block End >>]Length] - outtrees <- trees - }{ - expression, after expression <- Parse Expression[trimmed, params] - outtrees,after end <- Worker Body[after expression, params, [trees]Append[expression]] - } -} - -Process Modifiers[worker,params,modifiers:out] -{ - //Eventually this will need to be more sophisticated to handle more modifiers - trimmed <- Comment Left Trim[modifiers, "\n\r\t ", params] - If[[trimmed]Starts With[[params]Uses >>]] - { - ,after uses <- [trimmed]Slice[[[params]Uses >>]Length] - ,stores string <- [after uses]Get Comment DString["\n", params] - out <- [worker]Uses Stores <<[Map[[stores string]Split[[params]List Delim >>], Trim[?, "\r\n\t "]]] - }{ - out <- worker - } -} - -Remove Named Pipe Node[element:out] -{ - If[[Blueprint Of[element]] = [Named Pipe Node()]] - { - out <- [element]Name >> - }{ - If[[Blueprint Of[element]] = [Type Instance()]] - { - out <- [element]Params <<[ Map[[element]Params >>, Remove Named Pipe Node[?]] ] - }{ - out <- element - } - } -} - -Parse Param List[text,paramlist,typelist,params:out params,out types] -{ - delims <- [[()]Append[[params]List Begin >>]]Append[[params]List Delim >>] - after,param name <-[text]Get DString[delims] {} - { - tname <- Trim[~, "\r\n\t "] - If[[tname] = [""]] - { - nextlist <- Val[paramlist] - next types <- Val[typelist] - }{ - nextlist <- [paramlist]Append[tname] - next types <- [typelist]Append[paramtype] - } - }{ - If[[~] = [[params]List Begin >>]] - { - type info,after type <- Parse List[after,params,()] - type <- [type info]Index[0] - { - If[[Blueprint Of[~]] = [Named Pipe Node()]] - { - before variant <- Type Instance[[type]Name >>] - }{ - before variant <- <- [type]Params <<[ Map[[type]Params >>, Remove Named Pipe Node[?]] ] - } - variant <- [type info]Index[1] - { - ,warn <- If[[Blueprint Of[~]] = [Named Pipe Node()]] - { - before mutable,warn <- [before variant]Set Variant[[variant]Name >>] - } - Val[warn] - { - Print[[[["Warning: Invalid variant for type "]Append[[before variant]Name >>]]Append[" on input "]]Append[param name]] - before mutable <- Val[before variant] - } - }{ - before mutable <- Val[before variant] - } - [type info]Index[2] - { - paramtype <- [before mutable]Mutable? <<[ [[~]Name >>] = ["Mutable"] ] - }{ - paramtype <- Val[before mutable] - } - }{ - paramtype <- Type Instance["Any Type"] - } - [after type]Get DString[","] - { - out params,out types <- Parse Param List[~,nextlist,next types,params] - } {} {} { - out params <- Val[nextlist] - out types <- Val[next types] - } - }{ - paramtype <- Type Instance["Any Type"] - out params,out types <- Parse Param List[after,nextlist,next types,params] - } - - }{ - paramtype <- Type Instance["Any Type"] - out params <- Val[nextlist] - out types <- Val[next types] - } -} - -Worker Declaration[string,params:worker,rest,no match] -{ - ,whitespace name <- [string]Get Comment DString[[params]Arg Begin >>, params] - { - worker name <- Trim[whitespace name, "\n\r\t "] - in out <- [params]In Out Delim >> - arg end <- [params]Arg End >> - delims <- [[()]Append[in out]]Append[arg end] - after <- [~]Get Comment DString[delims, params] {} - { - arglist <- Trim[~,"\r\n\t "] - }{ - //check if there is an in/out separator - //if it isn't present, everything in the arglist is an input - If[[~] = [in out]] - { - rest <- [after]Get Comment DString[arg end, params] {} - { - outputs,output types <- Parse Param List[~, (), (), params] - } - }{ - rest <- Val[after] - outputs <- () - output types <- () - } - inputs,input types <- Parse Param List[arglist, (), (), params] - worker <- Parse Worker[worker name, inputs, outputs, input types, output types, 0] - } - }{}{}{ - no match <- string - } -} - -Worker Name[string,params,tree,lines:out] -{ - ,after arglist <- Worker Declaration[string, params] - { - worker name <- [~]Name >> - body text, modifiers <- [after arglist]Get Comment DString[[params]Block Begin >>, params] - modified <- Process Modifiers[~, params, modifiers] - expression trees, after body <- Worker Body[body text, params, ()] - worker <- [modified]Trees <<[expression trees] - new worker dict <- [[tree]Workers >>]Set[worker name, worker] - out <- Null[after body, params, [tree]Workers <<[new worker dict], 0] - } {} { - out <- tree - } -} - -Parse Foreign Worker[tree, string, lib, params:out] -{ - ,rest <- Worker Declaration[string, params] - { - foreign <- [~]Trees << [lib] - next <- [tree]Workers << [[[tree]Workers >>]Set[[foreign]Name >>, foreign]] - out <- Parse Foreign Worker[next, rest, lib, params] - } {} { - out <- tree - } -} - -Parse Foreign[string,params,tree,lines:out] -{ - ,after foreign <- [string]Slice[[[params]Foreign >>]Length] - [after foreign]Get Comment DString[[params]Blueprint Type Delim >>, params] - { - [~]Get Comment DString[[params]Block Begin >>, params] - { - rest, body <- [~]Get Comment DString[[params]Block End >>, params] - } - { lib <- Trim[~, "\r\n\t "] } - } - { language <- Trim[~, "\r\n\t "] } - Parse Foreign Worker[tree, body, New Foreign Lib[language, lib], params] - { - out <- Null[rest, params, ~, 0] - } -} - -Parse Global Vars[string,params,store:out] -{ - trimmed <- Left Trim[string, "\r\n\t "] - If[trimmed] - { - ,,after <- [trimmed]Partition[[params]Assign >>] - { - varname <- Right Trim[~, "\r\n\t "] - } {} { - valstring <- [~]Partition["\n"] {} {} - { - out <- Parse Global Vars[~,params,next store] - }{ - valstring <- Val[after] - out <- Val[next store] - } - Val[valstring] - { - Print[["Parsing initial value: "]Append[valstring]] - value <- [Named Pipe or Literal[Trim[~, "\r\n\t "], params]]Value >> - next store <- [store]Vars <<[ [[store]Vars >>]Set[varname, value] ] - } - }{ - Print[["Expected assignment operator in global var block, found "]Append[trimmed]] - } - }{ - out <- store - } -} - -Parse Globals[string,params,tree,lines:out] -{ - ,after globals <- [string]Slice[[[params]Globals >>]Length] - [after globals]Partition[[params]Block Begin >>] - { - store <- Global Store[Trim[~, "\r\n\t "]] - } {} { - - [~]Partition[[params]Block End >>] - { - next tree <- [tree]Add Global Store[Parse Global Vars[~, params, store]] - } {} { - out <- Null[~,params,next tree,lines] - }{ - Print["Error: Globals declaration missing block close symbol"] - out <- tree - } - } { - Print["Error: Globals declaration without block"] - out <- tree - } -} - - -Null[string,params,tree,lines:out] -{ - trimmed <- Comment Left Trim[string, " \n\r\t", params] - current line <- 0 - If[[trimmed]Starts With[ [params]Blueprint >> ]] - { - out <- PBlueprint[trimmed, params, tree, current line] - }{ - If[[trimmed]Starts With[ [params]Import >> ]] - { - out <- Parse Import[trimmed, params, tree, current line] - }{ - If[[trimmed]Starts With[ [params]Foreign >> ]] - { - out <- Parse Foreign[trimmed, params, tree, current line] - }{ - If[[trimmed]Starts With[[params]Globals >>]] - { - out <- Parse Globals[trimmed, params, tree, current line] - }{ - If[trimmed] - { - out <- Worker Name[trimmed, params, tree, current line] - }{ - out <- tree - } - } - } - } - } -} - -Check Worker Literals@Parse Worker[worker,program:out] -{ - [(List(),List Leaf())]Find[=[Blueprint Of[[worker]Trees >>], ?]] - { - out <- [worker]Trees <<[ Map[[worker]Trees >>, Check Worker Literals[?, program]] ] - }{ - out <- worker - } -} - -Register Workers Compile[prog, worker, name:out] -{ - //Print[["Registering "]Append[name]] - If[[ Blueprint Of[[worker]Trees >>] ] = [Foreign Lib()]] - { convention <- Val[[[worker]Trees >>]Language >>] } - { convention <- "rhope" } - out <- [prog]Register Worker[name, convention, [[worker]Inputs >>]Length, [[worker]Outputs >>]Length] -} - -Add Workers Compile[prog, worker, name:out] -{ - Print[["Transforming "]Append[name]] - If[[Blueprint Of[[worker]Trees >>]] = [Foreign Lib()]] - { - //TODO: Handle foreign func - final nworker <- [[[[[NWorker[[[worker]Trees >>]Language >>] - ]Inputs <<[ [worker]Inputs >> ] - ]Input Types <<[ [worker]Input Types >> ] - ]Outputs <<[ [worker]Outputs >> ] - ]Output Types <<[ [worker]Output Types >> ] - ]Library <<[ [[worker]Trees >>]Name >> ] - - }{ - assigned <- Fold[_Get Assigned Pipes[?], Dictionary[], [worker]Trees >>] - trees, nworker, refs <- Add List to Worker[[worker]Trees >>, [[NWorker["rhope"]]Uses[[worker]Uses Stores >>]]Outputs <<[ [worker]Outputs >> ], prog, [worker]Assigned <<[assigned], Dictionary[]] - { - final nworker <- Fold[Add Wires Helper[?, ?, ?, worker, refs], nworker, trees] - } - - } - out <- [prog]Bind Worker[name, final nworker] -} - -Add Wires Helper[worker,node,unused,parse worker,assignments:out] -{ - out <- [node]Add Wires[worker, (), parse worker, assignments] -} - -Add Blueprint Field[blueprint,field,unused:out] -{ - out <- [blueprint]Add Field[[field]Name >>, [field]Type >>] -} - -Add Blueprint Compile[prog,def:out] -{ - out <- [prog]Bind Blueprint[[def]Name >>, Fold[Add Blueprint Field[?], NBlueprint[], [def]Fields >>]] -} - -Tree to Program Native[parse tree,number types:out] -{ - registered <- Fold[Register Workers Compile[?], [Fold[Add Blueprint Compile[?], [[NProgram[]]Numtypes <<[number types]]Global Stores <<[[parse tree]Global Stores >>], [parse tree]Blueprints >>]]Register Builtins, [parse tree]Workers >>] - out <- Fold[Add Workers Compile[?], registered, [parse tree]Workers >>] - { Print["Transformed AST to dataflow graph "] } -} - -Needs Imports[needs import,not imported?,name:out] -{ - If[not imported?] - { - out <- [needs import]Append[name] - }{ - out <- needs import - } -} - -Do Import[tree,file name,unused,params:out] -{ - Print[["Parsing: "]Append[file name]] - file <- [File[file name]]Open["r"] - text <- String[[file]Read[[file]Length]] - after import <- Null[text, params, tree, 0] - - out <- [after import]Imports <<[[[after import]Imports >>]Set[file name, No]] -} - -Process Imports[parse tree,params:out] -{ - needs import <- Fold[Needs Imports[?], (), [parse tree]Imports >>] - If[[[needs import]Length] > [0]] - { - import tree <- Fold[Do Import[?, ?, ?, params], parse tree, needs import] - out <- Process Imports[import tree, params] - }{ - out <- parse tree - } -} - -Until End[text:out] -{ - line <- Get Input[] - If[[line] = ["End"]] - { - out <- [text]Append["\n"] - }{ - out <- Until End[[[text]Append["\n"]]Append[line]] - } -} - -Add If Store[stores,name,params:out] -{ - If[[name]Contains[[params]Global Separator >>]] - { - parts <- [name]Split[[params]Global Separator >>] - out <- [stores]Set[[parts]Index[0], Yes] - }{ - out <- stores - } -} - -Param Gather Stores[stores,node,params:out] -{ - out <- [node]Gather Stores[params, stores] -} - -Gather Stores@Named Pipe Node[node,params,stores:out] -{ - out <- Fold[Add If Store[?, ?, params], stores, [node]Assignments >>] -} - -Gather Stores@Global Node[node,params,stores:out] -{ - out <- [stores]Set[[node]Store >>, Yes] -} - -Gather Stores@Worker Node[node,params,stores:out] -{ - //TODO: Handle blocks - store list <- Fold[Param Gather Stores[?, ?, params], stores, [node]Params >>] - out <- Fold[Add If Store[?, ?, params], store list, [node]Assignments >>] -} - -Gather Stores@Field Node[node,params,stores:out] -{ - //TODO: Handle blocks - store list <- Fold[Param Gather Stores[?, ?, params], stores, [node]Params >>] - out <- Fold[Add If Store[?, ?, params], store list, [node]Assignments >>] -} - -Gather Stores@Literal Node[node,params,stores:out] -{ - out <- Fold[Add If Store[?, ?, params], stores, [node]Assignments >>] -} - - diff -r 24c6f8767190 -r c6ba9fe45910 testc.rhope --- a/testc.rhope Wed Jul 27 21:14:23 2011 -0700 +++ b/testc.rhope Wed Jul 27 21:28:43 2011 -0700 @@ -1,12 +1,41 @@ Import cbackend.rhope +Import number.rhope +Import boolean.rhope + +//Dummy versions of nworker methods so the code in number_c.rhope will compile +Register Worker[prog,name,convention,inputs,outputs:out] +{ + out <- prog +} + +Bind Worker[prog,name,worker:out] +{ + out <- prog +} + +Blueprint NWorker +{ + Inputs + Input Types + Outputs + Output Types + Builtin? +} + +NWorker[convention:out] +{ + out <- convention +} Main[] { - prog <- C Program[] - base <- [[[[[[[prog]Create Function["Fib",("n"),("out"),""] - ]Allocate Var["work1", "Any Type"] - ]Allocate Var["work2", "Any Type"] - ]Null["out"] + prog <- [[C Program[]]Generate Number Methods]Generate Boolean Methods + base <- [[[[[[[[[prog]Create Function["Fib",("n"),("out"),"rhope"] + ]Allocate Var["work1", Type Instance["Any Type"]] + ]Allocate Var["work2", Type Instance["Any Type"]] + ]Register Constant["const_1", 1] + ]Register Constant["const_2", 2] + ]Set Null["out"] ]Method Call["<", [[()]Append[AddRef["n"]]]Append[AddRef[Constant["const_2"]]]] ]Move[Result[0], "work1"] ]Method Call["If", [()]Append["work1"]] @@ -17,11 +46,9 @@ ]Move[AddRef[Constant["const_1"]], "out"] {Print["stream1 done"]} - stream3 <- [[[base]Instruction Stream - ]Release["n"] - ]Tail Method Call["+", ("work1","work2")] + - stream2 <- [[[[[[[[[[[base]Instruction Stream + [[[[[[[[[[base]Instruction Stream ]Release[Result[0]] ]Method Call["-", [[()]Append[AddRef["n"]]]Append[AddRef[Constant["const_1"]]]] ]Move[Result[0], "work1"] @@ -31,8 +58,14 @@ ]Move[Result[0], "work1"] ]Call["Fib", ("work2")] ]Move[Result[0], "work2"] - ]Do If[NotCond["out"], stream3] - {Print["stream2 done"]} + { + stream3 <- [[[~]Instruction Stream + ]Release["n"] + ]Method Call["+", ("work1","work2")] + stream2 <- [~]Do If[NotCond["out"], stream3] + {Print["stream2 done"]} + } + func <- [[[base ]Do If[Result[0], stream1] @@ -40,7 +73,15 @@ ]Release["n"] {Print["func done"] } - Print[[[prog]Store Function[func]]Text] - + main <- [[[[prog]Create Function["Main", (), ("out"), "rhope"] + ]Register Constant["const_30", 30] + ]Call["Fib", [()]Append[Constant["const_30"]]] + ]Move[Result[0], "out"] + + text <- [[[prog]Store Function[func] + ]Store Function[main] + ]Text + Print[[text]Length] + { Print[text] } } diff -r 24c6f8767190 -r c6ba9fe45910 testc_c.rhope --- a/testc_c.rhope Wed Jul 27 21:14:23 2011 -0700 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,87 +0,0 @@ -Import cbackend_c.rhope -Import number_c.rhope -Import boolean.rhope - -//Dummy versions of nworker methods so the code in number_c.rhope will compile -Register Worker[prog,name,convention,inputs,outputs:out] -{ - out <- prog -} - -Bind Worker[prog,name,worker:out] -{ - out <- prog -} - -Blueprint NWorker -{ - Inputs - Input Types - Outputs - Output Types - Builtin? -} - -NWorker[convention:out] -{ - out <- convention -} - -Main[] -{ - prog <- [[C Program[]]Generate Number Methods]Generate Boolean Methods - base <- [[[[[[[[[prog]Create Function["Fib",("n"),("out"),"rhope"] - ]Allocate Var["work1", Type Instance["Any Type"]] - ]Allocate Var["work2", Type Instance["Any Type"]] - ]Register Constant["const_1", 1] - ]Register Constant["const_2", 2] - ]Set Null["out"] - ]Method Call["<", [[()]Append[AddRef["n"]]]Append[AddRef[Constant["const_2"]]]] - ]Move[Result[0], "work1"] - ]Method Call["If", [()]Append["work1"]] - {Print["base done"] } - - stream1 <- [[[base]Instruction Stream - ]Release[Result[0]] - ]Move[AddRef[Constant["const_1"]], "out"] - {Print["stream1 done"]} - - - - [[[[[[[[[[base]Instruction Stream - ]Release[Result[0]] - ]Method Call["-", [[()]Append[AddRef["n"]]]Append[AddRef[Constant["const_1"]]]] - ]Move[Result[0], "work1"] - ]Method Call["-", [[()]Append[AddRef["n"]]]Append[AddRef[Constant["const_2"]]]] - ]Move[Result[0], "work2"] - ]Call["Fib", ("work1")] - ]Move[Result[0], "work1"] - ]Call["Fib", ("work2")] - ]Move[Result[0], "work2"] - { - stream3 <- [[[~]Instruction Stream - ]Release["n"] - ]Method Call["+", ("work1","work2")] - stream2 <- [~]Do If[NotCond["out"], stream3] - {Print["stream2 done"]} - } - - - func <- [[[base - ]Do If[Result[0], stream1] - ]Do If[Result[1], stream2] - ]Release["n"] - {Print["func done"] } - - main <- [[[[prog]Create Function["Main", (), ("out"), "rhope"] - ]Register Constant["const_30", 30] - ]Call["Fib", [()]Append[Constant["const_30"]]] - ]Move[Result[0], "out"] - - text <- [[[prog]Store Function[func] - ]Store Function[main] - ]Text - Print[[text]Length] - { Print[text] } -} - diff -r 24c6f8767190 -r c6ba9fe45910 testnworker.rhope --- a/testnworker.rhope Wed Jul 27 21:14:23 2011 -0700 +++ b/testnworker.rhope Wed Jul 27 21:28:43 2011 -0700 @@ -1,4 +1,4 @@ -Import nworker_c.rhope +Import nworker.rhope Test NWorker[:out] {