path
stringlengths
14
112
content
stringlengths
0
6.32M
size
int64
0
6.32M
max_lines
int64
1
100k
repo_name
stringclasses
2 values
autogenerated
bool
1 class
cosmopolitan/tool/net/demo/.reload.lua
-- special script called by main redbean process on invalidate
63
2
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/redbean-xhr.lua
-- redbean xhr handler demo hdr = GetHeader('x-custom-header') if hdr then SetHeader('Vary', 'X-Custom-Header') SetHeader('X-Custom-Header', 'hello ' .. hdr) else ServeError(400) end
192
9
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/binarytrees.lua
-- binary trees: benchmark game -- with resource limit tutorial -- by justine tunney local outofcpu = false local oldsigxcpufunc = nil local oldsigxcpuflags = nil local oldsigxcpumask = nil -- This is our signal handler. function OnSigxcpu(sig) -- Please note, it's dangerous to do complicated things from inside -- asynchronous signal handlers. Even Log() isn't async signal safe -- The best possible practice is to have them simply set a variable outofcpu = true end -- These two functions are what's being benchmarked. It's a popular -- torture test for interpreted languages since it generates a lot of -- garbage. Lua does well on this test, going faster than many other -- languages, e.g. Racket, Python. local function MakeTree(depth) if outofcpu then error({reason='MakeTree() caught SIGXCPU'}) end if depth > 0 then depth = depth - 1 left, right = MakeTree(depth), MakeTree(depth) return { left, right } else return { } end end local function CheckTree(tree) if outofcpu then error({reason='CheckTree() caught SIGXCPU'}) end if tree[1] then return 1 + CheckTree(tree[1]) + CheckTree(tree[2]) else return 1 end end -- Now for our redbean web server code... local function WriteForm(depth, suggestion) Write([[<!doctype html> <title>redbean binary trees</title> <style> body { padding: 1em; } h1 a { color: inherit; text-decoration: none; } h1 img { border: none; vertical-align: middle; } input { margin: 1em; padding: .5em; } p { word-break: break-word; max-width: 650px; } dt { font-weight: bold; } dd { margin-top: 1em; margin-bottom: 1em; } .hdr { text-indent: -1em; padding-left: 1em; } </style> <h1> <a href="/"><img src="/redbean.png"></a> <a href="fetch.lua">binary trees benchmark demo</a> </h1> <p> This demo is from the computer language benchmark game. It's a torture test for the Lua garbage collector. ProTip: Try loading this page while the terminal memory monitor feature is active, so you can see memory shuffle around in a dual screen display. We use setrlimit to set a 512mb memory limit. So if you specify a number higher than 23 (a good meaty benchmark) then the Lua GC should panic a bit trying to recover (due to malloc failure) and ultimately the worker process should die. However the server and your system will survive. </p> <form action="binarytrees.lua" method="post"> <input type="text" id="depth" name="depth" size="70" value="%s" placeholder="%d" onfocus="this.select()" autofocus> <input type="submit" value="run"> </form> ]] % {EscapeHtml(depth), suggestion}) end local function BinaryTreesDemo() if GetMethod() == 'GET' or GetMethod() == 'HEAD' then WriteForm("18", 18) elseif GetMethod() == 'POST' and not HasParam('depth') then ServeError(400) elseif GetMethod() == 'POST' then -- write out the page so user can submit again WriteForm(GetParam('depth'), 18) Write('<dl>\r\n') Write('<dt>Output\r\n') Write('<dd>\r\n') -- impose quotas to protect the server unix.setrlimit(unix.RLIMIT_AS, 1024 * 1024 * 1024) unix.setrlimit(unix.RLIMIT_CPU, 2, 4) -- when RLIMIT_AS (virtual address space) runs out of memory, then -- mmap() and malloc() start to fail, and lua reacts by trying to -- run the garbage collector over and over again. so we also place -- a limit on the number of "cpu time" seconds too. the behavior -- when we hit the soft limit, is the kernel gives us a friendly -- warning by sending the signal SIGXCPU which we must catch here -- once we catch it, we've got 2 seconds of grace time to clean up -- before we hit the "hard limit" and the kernel sends SIGKILL (9) oldsigxcpufunc, oldsigxcpuflags, oldsigxcpumask = unix.sigaction(unix.SIGXCPU, OnSigxcpu) -- get the user-supplied parameter depth = tonumber(GetParam('depth')) -- run the benchmark, recording how long it takes secs1, nanos1 = unix.clock_gettime() res = CheckTree(MakeTree(depth)) secs2, nanos2 = unix.clock_gettime() -- turn 128-bit timestamps into 64-bit nanosecond interval if secs2 == secs1 then nanos = nanos2 - nanos1 else nanos = (secs2 - secs1) * 1000000000 + (1000000000 - nanos1) + nanos2 end -- write out result of benchmark Write('0%o\r\n' % {res}) Write('<dt>Time Elapsed\r\n') Write('<dd>\r\n') Write('%g seconds, or<br>\r\n' % {nanos / 1e9}) Write('%g milliseconds, or<br>\r\n' % {nanos / 1e6}) Write('%g microseconds, or<br>\r\n' % {nanos / 1e6}) Write('%d nanoseconds\r\n' % {nanos}) Write('<dt>unix.clock_gettime() #1\r\n') Write('<dd>%d, %d\r\n' % {secs1, nanos1}) Write('<dt>unix.clock_gettime() #2\r\n') Write('<dd>%d, %d\r\n' % {secs2, nanos2}) Write('</dl>\r\n') else ServeError(405) SetHeader('Allow', 'GET, HEAD, POST') end end local function main() -- catch exceptions ok, err = pcall(BinaryTreesDemo) -- we don't need to restore the old handler -- but it's generally a good practice to clean up if oldsigxcpufunc then unix.sigaction(unix.SIGXCPU, oldsigxcpufunc, oldsigxcpuflags, oldsigxcpumask) end -- handle exceptions if not ok then -- whenever anything, at all, goes wrong, with anything -- always with few exceptions close the connection asap SetHeader('Connection', 'close') if err.reason then -- show our error message withoun internal code leaking out Write(err.reason) Write('\r\n') else -- just rethrow exception error('unexpected failure: ' .. tostring(err)) end end end main()
6,077
190
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/404.html
<!doctype html> <title>404 not found</title> <pre aria-label="404 not found"> _ _ ___ _ _ _ __ _ | || | / _ \| || | _ __ ___ | |_ / _| ___ _ _ _ __ __| | | || |_| | | | || |_ | '_ \ / _ \| __| | |_ / _ \| | | | '_ \ / _` | |__ _| |_| |__ _| | | | | (_) | |_ | _| (_) | |_| | | | | (_| | |_| \___/ |_| |_| |_|\___/ \__| |_| \___/ \__,_|_| |_|\__,_| </pre>
436
12
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/store-asset.lua
-- StoreAsset Demo -- -- Redbean is able to store files into its own executable structure. -- This is currently only supported on a Linux, Apple, and FreeBSD. -- -- By loading this page, your redbean will insert an immediate file into -- your redbean named `/hi`, which you can click the back button in the -- browser and view it on the listing page right afterwards! Write[[<!doctype html> <title>redbean store asset demo</title> <style> body { padding: 1em; } h1 a { color: inherit; text-decoration: none; } h1 img { border: none; vertical-align: middle; } input { margin: 1em; padding: .5em; } p { word-break: break-word; max-width: 650px; } dt { font-weight: bold; } dd { margin-top: 1em; margin-bottom: 1em; } .hdr { text-indent: -1em; padding-left: 1em; } </style> <h1> <a href="/"><img src="/redbean.png"></a> <a href="store-asset.lua">store asset demo</a> </h1> ]] if IsPublicIp(GetClientAddr()) then Write[[ <p> Bad request. </p> <p> This HTTP endpoint self-modifies the web server. You're communicating wtith this redbean over a public network. Therefore redbean won't service this request. </p> ]] elseif GetHostOs() == "WINDOWS" or GetHostOs() == "OPENBSD" or GetHostOs() == "NETBSD" then Write[[ <p> Unsupported </p> <p> Sorry! Redbean's Lua StoreAsset() function is only supported on Linux, Apple, and FreeBSD right now. </p> ]] else StoreAsset('/hi', [[ StoreAsset() worked! This file was inserted into your redbean by the Lua StoreAsset() API which was invoked by you browsing to the /store-asset.lua page. Enjoy your self-modifying web server! ]]) Write[[ <p> This Lua script has just stored a new file named <code>/hi</code> to your redbean zip executable. This was accomplished while the web server is running. It live updates, so if you click the back button in your browser, you should see <code>/hi</code> in the ZIP central directory listing, and you can send an HTTP message requesting it. </p> ]] end Write[[ <p> <a href="/">go back</a> </p> ]]
2,228
81
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/redbean-form.lua
-- redbean post request handler demo local function main() if GetMethod() ~= 'POST' then ServeError(405) SetHeader('Allow', 'POST') return end SetStatus(200) SetHeader('Content-Type', 'text/html; charset=utf-8') Write('<!doctype html>\r\n') Write('<title>redbean</title>\r\n') Write('<h3>POST Request HTML Form Handler Demo</h3>\r\n') Write('<p>') firstname = GetParam('firstname') lastname = GetParam('lastname') if firstname and lastname then Write('Hello ') Write(EscapeHtml(VisualizeControlCodes(firstname))) Write(' ') Write(EscapeHtml(VisualizeControlCodes(lastname))) Write('!<br>') Write('Thank you for using redbean.') end Write('<dl>\r\n') Write('<dt>Params\r\n') Write('<dd>\r\n') Write('<dl>\r\n') params = GetParams() for i = 1,#params do Write('<dt>') Write(EscapeHtml(VisualizeControlCodes(params[i][1]))) Write('\r\n') if params[i][2] then Write('<dd>') Write(EscapeHtml(VisualizeControlCodes(params[i][2]))) Write('\r\n') end end Write('</dl>\r\n') Write('<dt>Headers\r\n') Write('<dd>\r\n') Write('<dl>\r\n') for k,v in pairs(GetHeaders()) do Write('<dt>') Write(EscapeHtml(k)) Write('\r\n') Write('<dd>') Write(EscapeHtml(v)) Write('\r\n') end Write('</dl>\r\n') Write('<dt>Payload\r\n') Write('<dd><p>') Write(EscapeHtml(VisualizeControlCodes(GetBody()))) Write('\r\n') Write('</dl>\r\n') Write('<p>') Write('<a href="redbean.lua">Click here</a> ') Write('to return to the previous page.\r\n') end main()
1,683
71
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/call-lua-module.lua
-- Call Lua Module Demo -- -- Your Lua modules may be stored in the /.lua/ folder. -- -- In our /.init.lua global scope earlier, we ran the code: -- -- mymodule = require "mymodule" -- -- Which preloaded the /.lua/mymodule.lua module once into the server -- global memory template from which all request handlers are forked. -- Therefore, we can just immediately use that module from our Lua -- server pages. Write[[<!doctype html> <title>redbean call lua module demo</title> <style> body { padding: 1em; } h1 a { color: inherit; text-decoration: none; } h1 img { border: none; vertical-align: middle; } pre { margin-left: 2em; } p { word-break: break-word; max-width: 650px; } dt { font-weight: bold; } dd { margin-top: 1em; margin-bottom: 1em; } .hdr { text-indent: -1em; padding-left: 1em; } </style> <h1> <a href="/"><img src="/redbean.png"></a> <a href="call-lua-module.lua">call lua module demo</a> </h1> <p>Your Lua modules may be stored in the /.lua/ folder. <p>In our <code>/.init.lua</code> global scope earlier, we ran the code: <pre>mymodule = require "mymodule"</pre> <p>Which preloaded the <code>/.lua/mymodule.lua</code> module once into the server global memory template from which all request handlers are forked. Therefore, we can just immediately use that module from our Lua Server Pages. <p> Your <code>mymodule.hello()</code> output is as follows: <blockquote> ]] mymodule.hello() Write[[ </blockquote> <p> <a href="/">go back</a> </p> ]]
1,558
50
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/redbean.css
html { font-family: sans-serif; font-size: 14pt; } body { max-width: 700px; min-width: 700px; margin: 0 auto 0 auto; } pre, code { font-family: monospace; font-size: 12pt; } p { text-align: justify; } .indent { margin-left: 1em; } h1, h2 { margin: 1.5em 0 1.5em 0; } h1 strong { font-size: 14pt; } footer { margin-top: 12em; margin-bottom: 3em; font-size: 14pt; } .logo { float: right; }
426
44
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/printpayload.lua
local function main() if GetMethod() ~= 'POST' and GetMethod() ~= 'PUT' then ServeError(405) SetHeader('Allow', 'POST, PUT') return end SetStatus(200) SetHeader("Content-Type", GetHeader("Content-Type") or "text/plain") Write(GetBody()) end main()
282
13
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/fetch.lua
-- Fetch() API Demo local function WriteForm(url) Write([[<!doctype html> <title>redbean fetch demo</title> <style> body { padding: 1em; } h1 a { color: inherit; text-decoration: none; } h1 img { border: none; vertical-align: middle; } input { margin: 1em; padding: .5em; } pre { margin-left: 2em; } p { word-break: break-word; max-width: 650px; } dt { font-weight: bold; } dd { margin-top: 1em; margin-bottom: 1em; } .hdr { text-indent: -1em; padding-left: 1em; } </style> <h1> <a href="/"><img src="/redbean.png"></a> <a href="fetch.lua">redbean fetch demo</a> </h1> <p> Your redbean is able to function as an HTTP client too. Lua server pages can use the <code>Fetch()</code> API to to send outgoing HTTP and HTTPS requests to other web servers. All it takes is a line of code! </p> <form action="fetch.lua" method="post"> <input type="text" id="url" name="url" size="70" value="%s" placeholder="uri" autofocus> <input type="submit" value="fetch"> </form> ]] % {EscapeHtml(url)}) end local function main() if IsPublicIp(GetClientAddr()) then ServeError(403) elseif GetMethod() == 'GET' or GetMethod() == 'HEAD' then WriteForm("https://justine.lol") elseif GetMethod() == 'POST' then status, headers, payload = Fetch(GetParam('url')) if status then WriteForm(GetParam('url')) Write('<dl>\r\n') Write('<dt>Status\r\n') Write('<dd><p>%d %s\r\n' % {status, GetHttpReason(status)}) Write('<dt>Headers\r\n') Write('<dd>\r\n') for k,v in pairs(headers) do Write('<div class="hdr"><strong>') Write(EscapeHtml(k)) Write('</strong>: ') Write(EscapeHtml(v)) Write('</div>\r\n') end Write('<dt>Payload\r\n') Write('<dd><pre>') Write(EscapeHtml(VisualizeControlCodes(payload))) Write('</pre>\r\n') Write('</dl>\r\n') else err = headers WriteForm(GetParam('url')) Write('<h3>Error</h3>\n') Write('<p>') Write(EscapeHtml(VisualizeControlCodes(err))) end else ServeError(405) SetHeader('Allow', 'GET, HEAD, POST') end end main()
2,388
75
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/maxmind.lua
-- redbean maxmind demo -- by justine tunney local maxmind = require "maxmind" local kMetroCodes = { [500] = "Portland-Auburn ME", [501] = "New York NY", [502] = "Binghamton NY", [503] = "Macon GA", [504] = "Philadelphia PA", [505] = "Detroit MI", [506] = "Boston MA-Manchester NH", [507] = "Savannah GA", [508] = "Pittsburgh PA", [509] = "Ft. Wayne IN", [510] = "Cleveland-Akron (Canton) OH", [511] = "Washington DC (Hagerstown MD)", [512] = "Baltimore MD", [513] = "Flint-Saginaw-Bay City MI", [514] = "Buffalo NY", [515] = "Cincinnati OH", [516] = "Erie PA", [517] = "Charlotte NC", [518] = "Greensboro-High Point-Winston Salem NC", [519] = "Charleston SC", [520] = "Augusta GA", [521] = "Providence RI-New Bedford MA", [522] = "Columbus GA", [523] = "Burlington VT-Plattsburgh NY", [524] = "Atlanta GA", [525] = "Albany GA", [526] = "Utica NY", [527] = "Indianapolis IN", [528] = "Miami-Ft. Lauderdale FL", [529] = "Louisville KY", [530] = "Tallahassee FL-Thomasville GA", [531] = "Tri-Cities TN-VA", [532] = "Albany-Schenectady-Troy NY", [533] = "Hartford & New Haven CT", [534] = "Orlando-Daytona Beach-Melbourne FL", [535] = "Columbus OH", [536] = "Youngstown OH", [537] = "Bangor ME", [538] = "Rochester NY", [539] = "Tampa-St. Petersburg (Sarasota) FL", [540] = "Traverse City-Cadillac MI", [541] = "Lexington KY", [542] = "Dayton OH", [543] = "Springfield-Holyoke MA", [544] = "Norfolk-Portsmouth-Newport News VA", [545] = "Greenville-New Bern-Washington NC", [546] = "Columbia SC", [547] = "Toledo OH", [548] = "West Palm Beach-Ft. Pierce FL", [549] = "Watertown NY", [550] = "Wilmington NC", [551] = "Lansing MI", [552] = "Presque Isle ME", [553] = "Marquette MI", [554] = "Wheeling WV-Steubenville OH", [555] = "Syracuse NY", [556] = "Richmond-Petersburg VA", [557] = "Knoxville TN", [558] = "Lima OH", [559] = "Bluefield-Beckley-Oak Hill WV", [560] = "Raleigh-Durham (Fayetteville) NC", [561] = "Jacksonville FL", [563] = "Grand Rapids-Kalamazoo-Battle Creek MI", [564] = "Charleston-Huntington WV", [565] = "Elmira NY", [566] = "Harrisburg-Lancaster-Lebanon-York PA", [567] = "Greenville-Spartanburg SC-Asheville NC-Anderson SC", [569] = "Harrisonburg VA", [570] = "Florence-Myrtle Beach SC", [571] = "Ft. Myers-Naples FL", [573] = "Roanoke-Lynchburg VA", [574] = "Johnstown-Altoona PA", [575] = "Chattanooga TN", [576] = "Salisbury MD", [577] = "Wilkes Barre-Scranton PA", [581] = "Terre Haute IN", [582] = "Lafayette IN", [583] = "Alpena MI", [584] = "Charlottesville VA", [588] = "South Bend-Elkhart IN", [592] = "Gainesville FL", [596] = "Zanesville OH", [597] = "Parkersburg WV", [598] = "Clarksburg-Weston WV", [600] = "Corpus Christi TX", [602] = "Chicago IL", [603] = "Joplin MO-Pittsburg KS", [604] = "Columbia-Jefferson City MO", [605] = "Topeka KS", [606] = "Dothan AL", [609] = "St. Louis MO", [610] = "Rockford IL", [611] = "Rochester MN-Mason City IA-Austin MN", [612] = "Shreveport LA", [613] = "Minneapolis-St. Paul MN", [616] = "Kansas City MO", [617] = "Milwaukee WI", [618] = "Houston TX", [619] = "Springfield MO", [622] = "New Orleans LA", [623] = "Dallas-Ft. Worth TX", [624] = "Sioux City IA", [625] = "Waco-Temple-Bryan TX", [626] = "Victoria TX", [627] = "Wichita Falls TX & Lawton OK", [628] = "Monroe LA-El Dorado AR", [630] = "Birmingham AL", [631] = "Ottumwa IA-Kirksville MO", [632] = "Paducah KY-Cape Girardeau MO-Harrisburg-Mount Vernon IL", [633] = "Odessa-Midland TX", [634] = "Amarillo TX", [635] = "Austin TX", [636] = "Harlingen-Weslaco-Brownsville-McAllen TX", [637] = "Cedar Rapids-Waterloo-Iowa City & Dubuque IA", [638] = "St. Joseph MO", [639] = "Jackson TN", [640] = "Memphis TN", [641] = "San Antonio TX", [642] = "Lafayette LA", [643] = "Lake Charles LA", [644] = "Alexandria LA", [647] = "Greenwood-Greenville MS", [648] = "Champaign & Springfield-Decatur,IL", [649] = "Evansville IN", [650] = "Oklahoma City OK", [651] = "Lubbock TX", [652] = "Omaha NE", [656] = "Panama City FL", [657] = "Sherman TX-Ada OK", [658] = "Green Bay-Appleton WI", [659] = "Nashville TN", [661] = "San Angelo TX", [662] = "Abilene-Sweetwater TX", [669] = "Madison WI", [670] = "Ft. Smith-Fayetteville-Springdale-Rogers AR", [671] = "Tulsa OK", [673] = "Columbus-Tupelo-West Point MS", [675] = "Peoria-Bloomington IL", [676] = "Duluth MN-Superior WI", [678] = "Wichita-Hutchinson KS", [679] = "Des Moines-Ames IA", [682] = "Davenport IA-Rock Island-Moline IL", [686] = "Mobile AL-Pensacola (Ft. Walton Beach) FL", [687] = "Minot-Bismarck-Dickinson(Williston) ND", [691] = "Huntsville-Decatur (Florence) AL", [692] = "Beaumont-Port Arthur TX", [693] = "Little Rock-Pine Bluff AR", [698] = "Montgomery (Selma) AL", [702] = "La Crosse-Eau Claire WI", [705] = "Wausau-Rhinelander WI", [709] = "Tyler-Longview(Lufkin & Nacogdoches) TX", [710] = "Hattiesburg-Laurel MS", [711] = "Meridian MS", [716] = "Baton Rouge LA", [717] = "Quincy IL-Hannibal MO-Keokuk IA", [718] = "Jackson MS", [722] = "Lincoln & Hastings-Kearney NE", [724] = "Fargo-Valley City ND", [725] = "Sioux Falls(Mitchell) SD", [734] = "Jonesboro AR", [736] = "Bowling Green KY", [737] = "Mankato MN", [740] = "North Platte NE", [743] = "Anchorage AK", [744] = "Honolulu HI", [745] = "Fairbanks AK", [746] = "Biloxi-Gulfport MS", [747] = "Juneau AK", [749] = "Laredo TX", [751] = "Denver CO", [752] = "Colorado Springs-Pueblo CO", [753] = "Phoenix AZ", [754] = "Butte-Bozeman MT", [755] = "Great Falls MT", [756] = "Billings MT", [757] = "Boise ID", [758] = "Idaho Falls-Pocatello ID", [759] = "Cheyenne WY-Scottsbluff NE", [760] = "Twin Falls ID", [762] = "Missoula MT", [764] = "Rapid City SD", [765] = "El Paso TX", [766] = "Helena MT", [767] = "Casper-Riverton WY", [770] = "Salt Lake City UT", [771] = "Yuma AZ-El Centro CA", [773] = "Grand Junction-Montrose CO", [789] = "Tucson (Sierra Vista) AZ", [790] = "Albuquerque-Santa Fe NM", [798] = "Glendive MT", [800] = "Bakersfield CA", [801] = "Eugene OR", [802] = "Eureka CA", [803] = "Los Angeles CA", [804] = "Palm Springs CA", [807] = "San Francisco-Oakland-San Jose CA", [810] = "Yakima-Pasco-Richland-Kennewick WA", [811] = "Reno NV", [813] = "Medford-Klamath Falls OR", [819] = "Seattle-Tacoma WA", [820] = "Portland OR", [821] = "Bend OR", [825] = "San Diego CA", [828] = "Monterey-Salinas CA", [839] = "Las Vegas NV", [855] = "Santa Barbara-Santa Maria-San Luis Obispo CA", [862] = "Sacramento-Stockton-Modesto CA", [866] = "Fresno-Visalia CA", [868] = "Chico-Redding CA", [881] = "Spokane WA", } local function Dump(p) if type(p) == 'table' then local a = {} for k in pairs(p) do table.insert(a, k) end table.sort(a) Write('<dl>\n') for i = 1,#a do local k = a[i] local v = p[k] Write('<dt>') Dump(k) Write('\n') Write('<dd>') if k == 'iso_code' then Write('<img style="max-width:32px" src="//justine.lol/flags/' .. v:lower() .. '.png"> ') end Dump(v) if k == 'metro_code' then local metro = kMetroCodes[v] if metro then Write(' (' .. metro .. ')') end elseif k == 'accuracy_radius' then Write(' km') end Write('\n') end Write('</dl>\n') else Write(EscapeHtml(tostring(p))) end end local function main() if GetMethod() ~= 'GET' and GetMethod() ~= 'HEAD' then ServeError(405) SetHeader('Allow', 'GET, HEAD') return end local ip = nil local geo = nil local asn = nil local value = '8.8.8.8' if HasParam('ip') then local geodb = maxmind.open('/usr/local/share/maxmind/GeoLite2-City.mmdb') local asndb = maxmind.open('/usr/local/share/maxmind/GeoLite2-ASN.mmdb') ip = ParseIp(GetParam('ip')) if ip ~= -1 then value = FormatIp(ip) geo = geodb:lookup(ip) if geo then geo = geo:get() end asn = asndb:lookup(ip) if asn then asn = asn:get() end if not geo and not asn then SetStatus(404) end end end Write([[<!doctype html> <title>redbean maxmind demo</title> <style> body { padding: 1em; } h1 a { color: inherit; text-decoration: none; } h1 img { border: none; vertical-align: middle; } input { margin: 1em; padding: .5em; } pre { margin-left: 2em; } p { word-break: break-word; max-width: 650px; } dt { font-weight: bold; } dd { margin-top: 1em; margin-bottom: 1em; } .hdr { text-indent: -1em; padding-left: 1em; } </style> <h1> <a href="/"><img src="/redbean.png"></a> <a href="maxmind.lua">redbean maxmind demo</a> </h1> <p> Your redbean supports MaxMind GeoLite2 which is a free database you have to download separately, at their <a href="https://www.maxmind.com/en/geolite2/signup">website here</a>. It's worth doing because it lets you turn IP addresses into geographical coordinates, addresses, name it. Being able to Lua script this database is going to help you address things like online fraud and abuse. </p> <p> This script is hard coded to assume the database is at the following paths: <ul> <li><code>/usr/local/share/maxmind/GeoLite2-City.mmdb</code> <li><code>/usr/local/share/maxmind/GeoLite2-ASN.mmdb</code> </ul> <p> Which on Windows basically means the same thing as: </p> <ul> <li><code>C:\usr\local\share\maxmind\GeoLite2-City.mmdb</code> <li><code>C:\usr\local\share\maxmind\GeoLite2-ASN.mmdb</code> </ul> <p> Once you've placed it there, you can fill out the form below to have fun crawling all the information it provides! </p> <form action="maxmind.lua" method="get"> <input type="text" id="ip" name="ip" placeholder="8.8.8.8" value="%s" onfocus="this.select()" autofocus> <label for="ip">ip address</label> <br> <input type="submit" value="Lookup" autofocus> </form> ]] % {EscapeHtml(value)}) if ip then Write('<h3>Maxmind Geolite DB</h3>') if geo then Dump(geo) else Write('<p>Not found</p>\n') end Write('<h3>Maxmind ASN DB</h3>') if asn then Dump(asn) else Write('<p>Not found</p>\n') end end end main()
11,096
357
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/sql-backup.lua
if GetAssetSize("backup.sqlite3") == nil then Write("no backup exists. call <a href='sql-backupstore.lua'>sql-backupstore.lua</a> first.") return end backup = sqlite3.open_memory() buffer = LoadAsset("backup.sqlite3") backup:deserialize(buffer) -- insert more values for i = 1, 250 do backup:exec("INSERT INTO test (content) VALUES ('Hello more')") end -- See .init.lua for CREATE TABLE setup. for row in backup:nrows("SELECT * FROM test") do Write(row.id.." "..row.content.."<br>") end
503
19
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/unix-dir.lua
Write('<!doctype html>\r\n') Write('<title>redbean</title>\r\n') Write('<style>\r\n') Write('td,th { padding: 2px 5px; }\r\n') Write('td { white-space: nowrap; }\r\n') Write('.l { text-align: left; }\r\n') Write('.r { text-align: right; }\r\n') Write('</style>\r\n') Write('<h3>UNIX Directory Stream Demo</h3>\r\n') Write('<table>\r\n') Write('<thead>\r\n') Write('<tr>\r\n') Write('<th class=l>name\r\n') Write('<th>type\r\n') Write('<th class=r>ino\r\n') Write('<th class=r>off\r\n') Write('<th class=r>size\r\n') Write('<th class=r>blocks\r\n') Write('<th class=r>mode\r\n') Write('<th class=r>uid\r\n') Write('<th class=r>gid\r\n') Write('<th class=r>dev\r\n') Write('<th class=r>rdev\r\n') Write('<th class=r>nlink\r\n') Write('<th class=r>blksize\r\n') Write('<th class=r>gen\r\n') Write('<th class=r>flags\r\n') Write('<th class=r>birthtim\r\n') Write('<th class=r>mtim\r\n') Write('<th class=r>atim\r\n') Write('<th class=r>ctim\r\n') Write('<tbody>\r\n') dir = '.' for name, kind, ino, off in assert(unix.opendir(dir)) do Write('<tr>\r\n') Write('<td>') Write(EscapeHtml(name)) if kind == unix.DT_DIR then Write('/') end Write('\r\n') Write('<td>') if kind == unix.DT_REG then Write('DT_REG') elseif kind == unix.DT_DIR then Write('DT_DIR') elseif kind == unix.DT_FIFO then Write('DT_FIFO') elseif kind == unix.DT_CHR then Write('DT_CHR') elseif kind == unix.DT_BLK then Write('DT_BLK') elseif kind == unix.DT_LNK then Write('DT_LNK') elseif kind == unix.DT_SOCK then Write('DT_SOCK') else Write('DT_UNKNOWN') end Write('\r\n') Write('<td class=r>%d\r\n' % {ino}) Write('<td class=r>%d\r\n' % {off}) st,err = unix.stat(dir..'/'..name, unix.AT_SYMLINK_NOFOLLOW) if st then Write('<td class=r>%d\r\n' % {st:size()}) Write('<td class=r>%d\r\n' % {st:blocks()}) Write('<td class=r>%.7o\r\n' % {st:mode()}) Write('<td class=r>%d\r\n' % {st:uid()}) Write('<td class=r>%d\r\n' % {st:gid()}) Write('<td class=r>%d\r\n' % {st:dev()}) Write('<td class=r>%d,%d\r\n' % {unix.major(st:rdev()), unix.minor(st:rdev())}) Write('<td class=r>%d\r\n' % {st:nlink()}) Write('<td class=r>%d\r\n' % {st:blksize()}) Write('<td class=r>%d\r\n' % {st:gen()}) Write('<td class=r>%#x\r\n' % {st:flags()}) function WriteTime(unixsec,nanos) year,mon,mday,hour,min,sec,gmtoffsec = unix.localtime(unixsec) Write('<td class=r>%.4d-%.2d-%.2dT%.2d:%.2d:%.2d.%.9d%+.2d%.2d\r\n' % { year, mon, mday, hour, min, sec, nanos, gmtoffsec / (60 * 60), math.abs(gmtoffsec) % 60}) end WriteTime(st:birthtim()) WriteTime(st:mtim()) WriteTime(st:atim()) WriteTime(st:ctim()) else Write('<td class=l colspan=15>%s\r\n' % {err}) end end Write('</table>\r\n')
2,905
94
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/opensource.lua
Write('This Lua Server Page is stored in ZIP\r\n') Write('as normal Lua code that is compressed\r\n')
102
3
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/sql-backupstore.lua
buffer = db:serialize() StoreAsset("backup.sqlite3", buffer) Write("backup created. size: "..GetAssetSize("backup.sqlite3"))
125
4
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/unix-info.lua
local unix = require 'unix' Write('<!doctype html>\r\n') Write('<title>redbean</title>\r\n') Write('<h3>UNIX Information Demo</h3>\r\n') Write('<style>dt { margin: .5em 0; font-style:italic; }</style>\r\n') Write('<dl>\r\n') Write('<dt>unix.getuid()\r\n') Write('<dd>%d\r\n' % {unix.getuid()}) Write('<dt>unix.getgid()\r\n') Write('<dd>%d\r\n' % {unix.getgid()}) Write('<dt>unix.getpid()\r\n') Write('<dd>%d\r\n' % {unix.getpid()}) Write('<dt>unix.getppid()\r\n') Write('<dd>%d\r\n' % {unix.getppid()}) Write('<dt>unix.getpgrp()\r\n') Write('<dd>%d\r\n' % {unix.getpgrp()}) Write('<dt>unix.umask()\r\n') mask = unix.umask(027) unix.umask(mask) Write('<dd>%.4o\r\n' % {mask}) Write('<dt>unix.getsid(0)\r\n') sid, err = unix.getsid(0) if sid then Write('<dd>%d\r\n' % {sid}) else Write('<dd>%s\r\n' % {err}) end Write('<dt>unix.gethostname()\r\n') Write('<dd>%s\r\n' % {EscapeHtml(assert(unix.gethostname()))}) Write('<dt>unix.getcwd()\r\n') Write('<dd>%s\r\n' % {EscapeHtml(assert(unix.getcwd()))}) function PrintResourceLimit(name, id) soft, hard = unix.getrlimit(id) Write('<dt>getrlimit(%s)\r\n' % {name}) if soft then Write('<dd>') Write('soft ') if soft == -1 then Write('∞') else Write('%d' % {soft}) end Write('<br>\r\n') Write('hard ') if hard == -1 then Write('∞') else Write('%d' % {hard}) end Write('\r\n') else Write('<dd>%s\r\n' % {EscapeHtml(tostring(hard))}) end end PrintResourceLimit('RLIMIT_AS', unix.RLIMIT_AS) PrintResourceLimit('RLIMIT_RSS', unix.RLIMIT_RSS) PrintResourceLimit('RLIMIT_CPU', unix.RLIMIT_CPU) PrintResourceLimit('RLIMIT_FSIZE', unix.RLIMIT_FSIZE) PrintResourceLimit('RLIMIT_NPROC', unix.RLIMIT_NPROC) PrintResourceLimit('RLIMIT_NOFILE', unix.RLIMIT_NOFILE) Write('<dt>unix.siocgifconf()\r\n') Write('<dd>\r\n') ifs, err = unix.siocgifconf() if ifs then for i = 1,#ifs do if ifs[i].netmask ~= 0 then cidr = 32 - Bsf(ifs[i].netmask) else cidr = 0 end Write('%s %s/%d<br>\r\n' % {EscapeHtml(ifs[i].name), FormatIp(ifs[i].ip), cidr}) end else Write('%s\r\n' % {err}) end enabled, err = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_DEBUG) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_DEBUG)\r\n') if enabled then -- is nil on error Write('<dd>%d\r\n' % {enabled}) -- should be 0 or 1 else Write('<dd>%s\r\n' % {err}) end enabled, err = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_ACCEPTCONN) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_ACCEPTCONN)\r\n') if enabled then -- is nil on error Write('<dd>%d\r\n' % {enabled}) -- should be 0 or 1 else Write('<dd>%s\r\n' % {err}) end enabled, err = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_REUSEADDR) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_REUSEADDR)\r\n') if enabled then -- is nil on error Write('<dd>%d\r\n' % {enabled}) -- should be 0 or 1 else Write('<dd>%s\r\n' % {err}) end enabled, err = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_REUSEPORT) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_REUSEPORT)\r\n') if enabled then -- is nil on error Write('<dd>%d\r\n' % {enabled}) -- should be 0 or 1 else Write('<dd>%s\r\n' % {err}) end enabled, err = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_KEEPALIVE) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_KEEPALIVE)\r\n') if enabled then -- is nil on error Write('<dd>%s\r\n' % {enabled}) -- should be 0 or 1 else Write('<dd>%s\r\n' % {err}) end enabled, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_NODELAY) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_NODELAY)\r\n') if enabled then -- is nil on error Write('<dd>%s\r\n' % {enabled}) -- should be 0 or 1 else Write('<dd>%s\r\n' % {err}) end secs, nanos = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_RCVTIMEO) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_RCVTIMEO)\r\n') if secs then -- is nil on error Write('<dd>%d seconds + %d nanoseconds\r\n' % {secs, nanos}) else err = nanos Write('<dd>%s\r\n' % {err}) end secs, nanos = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_SNDTIMEO) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_SNDTIMEO)\r\n') if secs then -- is nil on error Write('<dd>%d seconds + %d nanoseconds\r\n' % {secs, nanos}) else err = nanos -- unix.Errno is always second result Write('<dd>%s\r\n' % {err}) end enabled, err = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_DONTROUTE) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_DONTROUTE)\r\n') if enabled then -- is nil if error Write('<dd>%d\r\n' % {enabled}) -- should be 0 or 1 else Write('<dd>%s\r\n' % {err}) end bytes, err = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_SNDBUF) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_SNDBUF)\r\n') if bytes then -- is nil if error Write('<dd>%d\r\n' % {bytes}) else Write('<dd>%s\r\n' % {err}) end bytes, err = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_RCVBUF) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_RCVBUF)\r\n') if bytes then -- is nil if error Write('<dd>%d\r\n' % {bytes}) else Write('<dd>%s\r\n' % {err}) end bytes, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_FASTOPEN) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_FASTOPEN)\r\n') if bytes then -- is nil if error Write('<dd>%d\r\n' % {bytes}) else Write('<dd>%s\r\n' % {err}) end enabled, err = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_BROADCAST) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_BROADCAST)\r\n') if enabled then -- is nil if error Write('<dd>%d\r\n' % {enabled}) -- should be 1 or 0 else Write('<dd>%s\r\n' % {err}) end enabled, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_CORK) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_CORK)\r\n') if enabled then -- is nil if error Write('<dd>%d\r\n' % {enabled}) -- should be 1 or 0 else Write('<dd>%s\r\n' % {err}) end enabled, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_QUICKACK) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_QUICKACK)\r\n') if enabled then Write('<dd>%d\r\n' % {enabled}) else Write('<dd>%s\r\n' % {err}) end enabled, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_DEFER_ACCEPT) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_DEFER_ACCEPT)\r\n') if enabled then Write('<dd>%s\r\n' % {enabled}) else Write('<dd>%s\r\n' % {err}) end enabled, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_FASTOPEN_CONNECT) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_FASTOPEN_CONNECT)\r\n') if err then Write('<dd>%s\r\n' % {err}) else Write('<dd>%s\r\n' % {enabled}) end bytes, err = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_SNDLOWAT) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_SNDLOWAT)\r\n') if bytes then Write('<dd>%d\r\n' % {bytes}) else Write('<dd>%s\r\n' % {err}) end bytes, err = unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_RCVLOWAT) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_SOCKET, unix.SO_RCVLOWAT)\r\n') if bytes then Write('<dd>%d\r\n' % {bytes}) else Write('<dd>%s\r\n' % {err}) end bytes, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_KEEPCNT) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_KEEPCNT)\r\n') if bytes then Write('<dd>%d\r\n' % {bytes}) else Write('<dd>%s\r\n' % {err}) end bytes, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_MAXSEG) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_MAXSEG)\r\n') if bytes then Write('<dd>%d\r\n' % {bytes}) else Write('<dd>%s\r\n' % {err}) end bytes, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_SYNCNT) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_SYNCNT)\r\n') if bytes then Write('<dd>%d\r\n' % {bytes}) else Write('<dd>%s\r\n' % {err}) end bytes, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_NOTSENT_LOWAT) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_NOTSENT_LOWAT)\r\n') if bytes then Write('<dd>%d\r\n' % {bytes}) else Write('<dd>%s\r\n' % {err}) end bytes, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_WINDOW_CLAMP) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_WINDOW_CLAMP)\r\n') if bytes then Write('<dd>%d\r\n' % {bytes}) else Write('<dd>%s\r\n' % {err}) end bytes, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_KEEPIDLE) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_KEEPIDLE)\r\n') if bytes then Write('<dd>%d\r\n' % {bytes}) else Write('<dd>%s\r\n' % {err}) end bytes, err = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_KEEPINTVL) Write('<dt>unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_KEEPINTVL)\r\n') if bytes then Write('<dd>%d\r\n' % {bytes}) else Write('<dd>%s\r\n' % {err}) end Write('<dt>unix.environ()\r\n') Write('<dd>\r\n') Write('<ul>\r\n') env = unix.environ() for i = 1,#env do Write('<li>%s\r\n' % {EscapeHtml(env[i])}) end Write('</ul>\r\n')
9,486
301
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/index.html
<!doctype html> <meta charset="utf-8"> <title>redbean</title> <link rel="stylesheet" href="redbean.css"> <img src="/redbean.png" class="logo" width="84" height="84"> <h2> <big>redbean</big><br> <small>distributable static web server</small> </h2> <p> Here's what you need to know about redbean: <ul> <li>million qps on modern pc <li>container is executable zip file <li>userspace filesystem w/o syscall overhead <li>kernelspace zero-copy gzip encoded responses <li>executable runs on linux, bsd, mac, and windows </ul> <p> redbean is based on <a href="https://justine.storage.googleapis.com/ape.html">αcτµαlly pδrταblε εxεcµταblε</a> and <a href="https://github.com/jart/cosmopolitan">cosmopolitan</a>. <br> redbean is authored by Justine Tunney who's on <a href="https://github.com/jart">GitHub</a> and <a href="https://twitter.com/JustineTunney">Twitter</a>.
897
30
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/gensvg.lua
local top = [[ <!DOCTYPE html> <html lang=en> <head> <link rel="icon" href="data:;base64,iVBORw0KGgo="> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="description"> <style> * {margin: 0;padding: 0;box-sizing: border-box;} body {margin: 0 auto;font-family: Roboto, Helvetica, Arial, sans-serif;color: #444444;line-height: 1;max-width: 960px;padding: 30px;} h1, h2, h3, h4 {color: #111111;font-weight: 400;} h1, h2, h3, h4, h5, p {margin-bottom: 24px;padding: 0;} h1 {font-size: 48px;} h2 {font-size: 36px;margin: 24px 0 6px;} .button {min-height:1rem;border: none;border-radius: 0.25rem;background: #1E88E5;color: white;font-family: sans-serif;font-size: 1rem;line-height: 1.2;white-space: nowrap;text-decoration: none;padding: 0.25rem 0.5rem;margin: 0.25rem;cursor: pointer;} body {height: 100vh;display: grid;place-items: center;background: hsl(0, 0%, 93%);} .canvas {width: 75vmin;height: 75vmin;background: hsl(350, 70%, 80%);} .shadow {filter: drop-shadow(1px 1px 0.5px rgba(0, 0, 0, .25));} </style> </head> <body> ]] local bottom = [[ <a href="https://github.com/jart/cosmopolitan/tree/master/tool/net/demo/gensvg.lua">Show The Code</a> </body> </html> ]] local nrows = 10 local ncols = 10 local sqsize = 20 local seed = math.random() local sat = 80 local light = 70 local function rect(x, y, w, h, rx) local style = string.format('class="shadow" fill="hsla(%s, %s%%, %s%%, %s)"', seed * 360 - 180, sat, light, math.random(100) / 100.0) return string.format( '<rect x="%s" y="%s" width="%s" height="%s" rx="%s" %s>', x, y, w, h, math.random(5, 12), style) end local function writeBlock(i, j) if math.random() < 0.45 then return end local cellsize = (math.random() > 0.25) and sqsize or math.random(1,4) * sqsize Write('<g class="draw-block">') Write(rect(i * sqsize - sqsize, j * sqsize - sqsize, cellsize, cellsize)) Write('</g>') end local function render() nrows = nrows * 3 ncols = ncols * 3 local xsize = nrows * sqsize local ysize = ncols * sqsize local style = string.format('style="background-color: hsl(%s,%s%%,%s%%);"', seed * 360, sat, light) Write('<svg class="canvas" ' .. style .. ' viewBox="0 0 ' .. xsize .. ' ' .. ysize .. '">') for i = 1, nrows, 1 do for j = 1, ncols, 1 do writeBlock(i, j) end end Write('</svg>') end Write(top) Write("<h2>Let's Generate Some SVG</h2>") Write("<p>If you don't like it, maybe refresh?</p>") render() Write('<div>') Write('<a class="button" href="/gensvg/1">Walk Through</a>') Write('</div>') Write(bottom)
2,933
78
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/unix-finger.lua
-- UNIX Finger Example local function WriteForm(host, user) Write([[<!doctype html> <title>redbean unix finger demo</title> <style> body { padding: 1em; } h1 a { color: inherit; text-decoration: none; } h1 img { border: none; vertical-align: middle; } input { margin: .5em; padding: .25em; } pre { margin-left: 2em; } p { word-break: break-word; max-width: 650px; } dt { font-weight: bold; } dd { margin-top: 1em; margin-bottom: 1em; } .hdr { text-indent: -1em; padding-left: 1em; } </style> <h1> <a href="/"><img src="/redbean.png"></a> <a href="unix-finger.lua">redbean unix finger demo</a> </h1> <p> Your redbean is able to function as an finger client. Lua server pages can use the <code>unix</code> module to implement protocols that your redbean wasn't originally intended to support. All it takes is few lines of code! </p> <form action="unix-finger.lua" method="post"> <input type="text" id="host" name="host" size="40" value="%s" placeholder="host" autofocus> <label for="host">host</label> <br> <input type="text" id="user" name="user" size="40" value="%s" placeholder="user"> <label for="user">user</label> <br> <input type="submit" value="finger"> </form> ]] % {EscapeHtml(host), EscapeHtml(user)}) end local function main() if IsPublicIp(GetClientAddr()) then ServeError(403) elseif GetMethod() == 'GET' or GetMethod() == 'HEAD' then WriteForm('graph.no', 'new_york') elseif GetMethod() == 'POST' then ip = assert(ResolveIp(GetParam('host'))) fd = assert(unix.socket()) assert(unix.connect(fd, ip, 79)) assert(unix.write(fd, GetParam('user') .. '\r\n')) response = '' while true do data = assert(unix.read(fd)) if data == '' then break end response = response .. data end assert(unix.close(fd)) WriteForm(GetParam('host'), GetParam('user')) Write('<pre>\r\n') Write(EscapeHtml(VisualizeControlCodes(response))) Write('</pre>\r\n') else ServeError(405) SetHeader('Allow', 'GET, HEAD, POST') end end main()
2,313
71
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/unix-unix.lua
-- UNIX Domain Sockets Example -- So we can detect that child died. died = false function OnSigchld(sig) died = true unix.wait() -- Prevent it from becoming a zombie end assert(unix.sigaction(unix.SIGCHLD, OnSigchld)) -- So keyboard interurpts only go to subprocess. oldint = assert(unix.sigaction(unix.SIGINT, unix.SIG_IGN)) oldquit = assert(unix.sigaction(unix.SIGQUIT, unix.SIG_IGN)) -- UNIX domain sockets need a file tmpdir = os.getenv('TMPDIR') or '/tmp' unixpath = '%s/redbean-unix.sock.%d' % {tmpdir, unix.getpid()} -- Create child process which is the server. child = assert(unix.fork()) if child == 0 then server = assert(unix.socket(unix.AF_UNIX, unix.SOCK_STREAM)) assert(unix.setsockopt(server, unix.SOL_SOCKET, unix.SO_RCVTIMEO, 2)) assert(unix.bind(server, unixpath)) assert(unix.listen(server)) client = assert(unix.accept(server)) data = assert(unix.read(client)) assert(data == 'ping!') assert(assert(unix.write(client, 'pong!')) == 5) assert(unix.close(client)) unix.exit(0) end -- Wait for the child to create the the socket file. function FileExists(path) st, err = unix.stat(path) return not err end expobackoff = 1 while not died do if FileExists(unixpath) then break else expobackoff = expobackoff << 1 unix.nanosleep(expobackoff // 1000000000, expobackoff % 1000000000) end end -- Now connect to the socket. if not died then client = assert(unix.socket(unix.AF_UNIX, unix.SOCK_STREAM)) assert(unix.connect(client, unixpath)) assert(assert(unix.write(client, 'ping!')) == 5) data = assert(unix.read(client)) assert(data == 'pong!') itworked = true else itworked = false end -- Wait for client to terminate. We don't check error here because if -- the child already died and the signal handler reaped it, then this -- returns a ECHILD error which is fine. unix.wait() assert(itworked) -- Now clean up the socket file. unix.unlink(unixpath) SetStatus(200) SetHeader('Connection', 'close') -- be lazy and let _Exit() clean up signal handlers SetHeader('Content-Type', 'text/html; charset=utf-8') Write('<!doctype html>\r\n') Write('<title>redbean unix domain sockets example</title>\r\n') Write('<h1>\r\n') Write('<img style="vertical-align:middle" src="data:image/png;base64,\r\n') Write(EncodeBase64(LoadAsset('/redbean.png'))) Write('">\r\n') Write('redbean unix domain sockets example\r\n') Write('</h1>\r\n') Write([[ <p> <strong>It worked!</strong> We successfully sent a ping pong via UNIX local sockets. Please check out the source code to this example inside your redbean at unix-unix.lua. </p> ]]) Write('</h1>\r\n')
2,684
90
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/redbean.lua
-- redbean lua server page demo local function main() -- This is the best way to print data to the console or log file. Log(kLogWarn, "hello from \e[1mlua\e[0m!") -- This check is pedantic but might be good to have. if GetMethod() ~= 'GET' and GetMethod() ~= 'HEAD' then ServeError(405) SetHeader('Allow', 'GET, HEAD') return end -- These two lines are optional. -- The default behavior is to do this if you don't. SetStatus(200) -- Shorthand for SetStatus(200, "OK") SetHeader('Content-Type', 'text/html; charset=utf-8') -- Response data is buffered until the script finishes running. -- Compression is applied automatically, based on your headers. Write('<!doctype html>\r\n') Write('<title>redbean</title>\r\n') Write('<h1>\r\n') Write('<img style="vertical-align:middle" src="data:image/png;base64,\r\n') Write(EncodeBase64(LoadAsset('/redbean.png'))) Write('">\r\n') Write('redbean lua server page demo\r\n') Write('</h1>\r\n') -- Prevent caching. -- We need this because we're doing things like putting the client's -- IP address in the response so we naturally don't want that cached SetHeader('Expires', FormatHttpDateTime(GetDate())) SetHeader('Cache-Control', 'no-cache, must-revalidate, max-age=0') -- GetUrl() is the resolved Request-URI (TODO: Maybe change API to return a URL object?) Write('<p>Thank you for visiting <code>') Write(GetUrl()) -- redbean encoded this value so it doesn't need html entity escaping Write('</code>\r\n') -- GetParam(NAME) is the fastest easiest way to get URL and FORM params -- If you want the RequestURL query params specifically in full do this Write('<h3>request url parameters</h3>\r\n') params = ParseUrl(GetUrl()).params -- like GetParams() but w/o form body if params and #params>0 then Write('<dl>\r\n') for i = 1,#params do Write('<dt>') Write(EscapeHtml(VisualizeControlCodes(params[i][1]))) Write('\r\n') if params[i][2] then Write('<dd>') Write(EscapeHtml(VisualizeControlCodes(params[i][2]))) Write('\r\n') end end Write('</dl>\r\n') Write("<p>Whatever you do, don't click on ") Write('<a href="') Write(EscapeHtml(EscapePath(GetPath()) .. '?magic')) Write('">') Write(EscapeHtml(VisualizeControlCodes(GetPath()))) Write('?magic</a>\r\n') else Write('<p>\r\n') Write('<em>none</em><br>\r\n') Write('ProTip: Try <a href="') Write(EscapeHtml(EscapePath(GetPath()) .. '?x=hi%20there%00%C0%80&y&z&z=' .. EscapeParam('&'))) Write('">clicking here</a>!\r\n') end -- redbean command line arguments -- these come *after* the c getopt server arguments Write('<h3>command line arguments</h3>\r\n') if #arg > 0 then Write('<ul>\r\n') for i = 1,#arg do Write('<li>') Write(EscapeHtml(VisualizeControlCodes(arg[i]))) Write('\r\n') end Write('</ul>\r\n') else Write('<p><em>none</em>\r\n') end Write([[ <h3>post request html form demo</h3> <form action="redbean-form.lua" method="post"> <input type="text" id="firstname" name="firstname"> <label for="firstname">first name</label> <br> <input type="text" id="lastname" name="lastname"> <label for="lastname">last name</label> <br> <input type="submit" value="Submit"> </form> ]]) Write([[ <h3>xmlhttprequest request demo</h3> <input id="x" value="lâtìn1"> <label for="x">X-Custom-Header</label><br> <button id="send">send</button><br> <div id="result"></div> <script> function OnSend() { var r = new XMLHttpRequest(); r.onload = function() { document.getElementById("result").innerText = this.getResponseHeader('X-Custom-Header'); }; r.open('POST', 'redbean-xhr.lua'); r.setRequestHeader('X-Custom-Header', document.getElementById('x').value); r.send(); } document.getElementById('send').onclick = OnSend; </script> ]]) -- fast redbean apis for accessing already parsed request data Write('<h3>extra information</h3>\r\n') Write('<dl>\r\n') Write('<dt>GetMethod()\r\n') Write('<dd>') Write(EscapeHtml(GetMethod())) -- & and ' are legal in http methods Write('\r\n') if GetUser() then Write('<dt>GetUser()\r\n') Write('<dd>') Write(EscapeHtml(VisualizeControlCodes(GetUser()))) Write('\r\n') end if GetScheme() then Write('<dt>GetScheme()\r\n') Write('<dd>') Write(GetScheme()) Write('\r\n') end if GetPass() then Write('<dt>GetPass()\r\n') Write('<dd>') Write(EscapeHtml(VisualizeControlCodes(GetPass()))) Write('\r\n') end Write('<dt>GetHost() <small>(from HTTP Request-URI or Host header or X-Forwarded-Host header or Berkeley Sockets)</small>\r\n') Write('<dd>') Write(EscapeHtml(VisualizeControlCodes(GetHost()))) Write('\r\n') Write('<dt>GetPort() <small>(from HTTP Request-URI or Host header or X-Forwarded-Host header or Berkeley Sockets)</small>\r\n') Write('<dd>') Write(tostring(GetPort())) Write('\r\n') Write('<dt>GetPath() <small>(from HTTP Request-URI)</small>\r\n') Write('<dd>') Write(EscapeHtml(VisualizeControlCodes(GetPath()))) Write('\r\n') Write('<dt>GetEffectivePath() <small>(actual path used internally to load the lua asset: routed depending on host, request path, and rewrites)</small>\r\n') Write('<dd>') Write(EscapeHtml(VisualizeControlCodes(GetEffectivePath()))) Write('\r\n') if GetFragment() then Write('<dt>GetFragment()\r\n') Write('<dd>') Write(EscapeHtml(VisualizeControlCodes(GetFragment()))) Write('\r\n') end Write('<dt>GetRemoteAddr() <small>(from Berkeley Sockets or X-Forwarded-For header)</small>\r\n') Write('<dd>') ip, port = GetRemoteAddr() Write('%s, %d' % {FormatIp(ip), port}) if CategorizeIp(ip) then Write('<br>\r\n') Write(CategorizeIp(ip)) end Write('\r\n') Write('<dt>GetClientAddr()\r\n') Write('<dd>') ip, port = GetClientAddr() Write('%s, %d' % {FormatIp(ip), port}) if CategorizeIp(ip) then Write('<br>\r\n') Write(CategorizeIp(ip)) end Write('\r\n') Write('<dt>GetServerIp()\r\n') Write('<dd>') ip, port = GetServerAddr() Write('%s, %d' % {FormatIp(ip), port}) if CategorizeIp(ip) then Write('<br>\r\n') Write(CategorizeIp(ip)) end Write('\r\n') Write('</dl>\r\n') -- redbean apis for generalized parsing and encoding referer = GetHeader('Referer') if referer then url = ParseUrl(referer) if url.scheme then url.scheme = string.upper(url.scheme) end Write('<h3>referer url</h3>\r\n') Write('<p>\r\n') Write(EscapeHtml(EncodeUrl(url))) Write('<dl>\r\n') if url.scheme then Write('<dt>scheme\r\n') Write('<dd>\r\n') Write(url.scheme) end if url.user then Write('<dt>user\r\n') Write('<dd>\r\n') Write(EscapeHtml(VisualizeControlCodes(url.user))) end if url.pass then Write('<dt>pass\r\n') Write('<dd>\r\n') Write(EscapeHtml(VisualizeControlCodes(url.pass))) end if url.host then Write('<dt>host\r\n') Write('<dd>\r\n') Write(EscapeHtml(VisualizeControlCodes(url.host))) end if url.port then Write('<dt>port\r\n') Write('<dd>\r\n') Write(EscapeHtml(VisualizeControlCodes(url.port))) end if url.path then Write('<dt>path\r\n') Write('<dd>\r\n') Write(EscapeHtml(VisualizeControlCodes(url.path))) end if url.params then Write('<dt>params\r\n') Write('<dd>\r\n') Write('<dl>\r\n') for i = 1,#url.params do Write('<dt>') Write(EscapeHtml(VisualizeControlCodes(url.params[i][1]))) Write('\r\n') if url.params[i][2] then Write('<dd>') Write(EscapeHtml(VisualizeControlCodes(url.params[i][2]))) Write('\r\n') end end Write('</dl>\r\n') end if url.fragment then Write('<dt>fragment\r\n') Write('<dd>\r\n') Write(EscapeHtml(VisualizeControlCodes(url.fragment))) end Write('</dl>\r\n') end Write('<h3>posix extended regular expressions</h3>\r\n') s = 'my ' .. FormatIp(GetRemoteAddr()) .. ' ip' -- traditional regular expressions m,a,b,c,d = re.search([[\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\)]], s, re.BASIC) -- easy api (~10x slower because compile is O(2ⁿ) and search is O(n)) m,a,b,c,d = re.search([[([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})]], s) -- proper api (especially if you put the re.compile() line in /.init.lua) pat = re.compile([[([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})]]) m,a,b,c,d = pat:search(s) -- m and rest are nil if match not found Write('<pre>\r\n') Write([[pat = re.compile('([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})')]]) Write('\r\nm,a,b,c,d = pat:search(%q)\r\n' % {s}) Write('</pre>\r\n') Write('<dl>\r\n') Write('<dt>m\r\n') Write('<dd>') Write("%q" % {m}) Write('\r\n') Write('<dt>a\r\n') Write('<dd>') Write("%q" % {a}) Write('\r\n') Write('<dt>b\r\n') Write('<dd>') Write("%q" % {b}) Write('\r\n') Write('<dt>c\r\n') Write('<dd>') Write("%q" % {c}) Write('\r\n') Write('<dt>d\r\n') Write('<dd>') Write("%q" % {d}) Write('\r\n') Write('</dl>\r\n') Write('<h3>source code to this page</h3>\r\n') Write('<pre>\r\n') Write(EscapeHtml(LoadAsset(GetEffectivePath()))) Write('</pre>\r\n') -- redbean zip assets Write('<h3>zip assets</h3>\r\n') paths = GetZipPaths() if #paths > 0 then Write('<ul>\r\n') for i = 1,#paths do Write('<li>\r\n') Write('<a href="') Write(EscapeHtml(EscapePath(paths[i]))) Write('">') Write(EscapeHtml(VisualizeControlCodes(paths[i]))) Write('</a>') if IsHiddenPath(paths[i]) then Write(' <small>[HIDDEN]</small>') end if not IsAcceptablePath(paths[i]) then Write(' <small>[BLOCKED]</small>') end if not IsAssetCompressed(paths[i]) then Write(' <small>[UNCOMPRESSED]</small>') end if (GetAssetMode(paths[i]) & 0xF000) == 0x4000 then Write(' <small>[DIRECTORY]</small>') end Write('<br>\r\n') Write('Modified: ') Write(FormatHttpDateTime(GetAssetLastModifiedTime(paths[i]))) Write('<br>\r\n') Write('Mode: ') Write("0%o" % {GetAssetMode(paths[i])}) Write('<br>\r\n') Write('Size: ') Write(tostring(GetAssetSize(paths[i]))) Write('<br>\r\n') if GetAssetComment(paths[i]) then Write('Comment: ') Write(EscapeHtml(VisualizeControlCodes(GetAssetComment(paths[i])))) Write('<br>\r\n') end Write('\r\n') end Write('</ul>\r\n') else Write('<p><em>none</em>\r\n') end end main()
11,486
351
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/hitcounter.lua
Write([[<!doctype html> <title>redbean mapshared demo</title> <style> body { padding: 1em; } h1 a { color: inherit; text-decoration: none; } h1 img { border: none; vertical-align: middle; } input { margin: 1em; padding: .5em; } pre { margin-left: 2em; } p { word-break: break-word; max-width: 650px; } dt { font-weight: bold; } dd { margin-top: 1em; margin-bottom: 1em; } .hdr { text-indent: -1em; padding-left: 1em; } </style> <h1> <a href="/"><img src="/redbean.png"></a> <a href="fetch.lua">redbean mapshared demo</a> </h1> <p> This page displays a <code>unix.mapshared()</code> hit counter of the <code>GetPath()</code>. </p> <dl> ]]) Lock() s = shm:read(SHM_JSON) if s == '' then s = '{}' end t = DecodeJson(s) Unlock() for k,v in pairs(t) do Write('<dt>%s<dd>%d\n' % {EscapeHtml(k), v}) end Write('</dl>')
845
36
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/unix-webserver.lua
-- webserver within a webserver demo -- we must go deeper! local unix = require 'unix' function OnTerm(sig) -- prevent redbean core from writing a response unix.write(mainfd, 'redbean is shutting down\r\n') unix.close(mainfd) end function main() if IsClientUsingSsl() then ServeError(400) return end mainfd = GetClientFd() mainip = GetRemoteAddr() unix.sigaction(unix.SIGTERM, OnTerm) unix.write(mainfd, 'HTTP/1.0 200 OK\r\n' .. 'Date: '.. FormatHttpDateTime(GetDate()) ..'\r\n' .. 'Content-Type: text/html; charset=utf-8\r\n' .. 'Connection: close\r\n' .. 'Server: redbean unix\r\n' .. '\r\n' .. '<!doctype html>\r\n' .. '<title>redbean</title>\r\n' .. '<h3>webserver within a webserver demo</h3>\r\n') addrs = {} servers = {} pollfds = {} pollfds[mainfd] = unix.POLLIN ifs = assert(unix.siocgifconf()) for i = 1,#ifs do if (IsLoopbackIp(mainip) and (IsPublicIp(ifs[i].ip) or IsPrivateIp(ifs[i].ip) or IsLoopbackIp(ifs[i].ip))) or (IsPrivateIp(mainip) and (IsPublicIp(ifs[i].ip) or IsPrivateIp(ifs[i].ip))) or (IsPublicIp(mainip) and IsPublicIp(ifs[i].ip)) then server = unix.socket() unix.bind(server, ifs[i].ip) unix.listen(server) ip, port = assert(unix.getsockname(server)) addr = '%s:%d' % {FormatIp(ip), port} url = 'http://%s' % {addr} Log(kLogInfo, 'listening on %s' % {addr}) unix.write(mainfd, 'listening on <a target="_blank" href="%s">%s</a><br>\r\n' % {url, url}) pollfds[server] = unix.POLLIN | unix.POLLHUP servers[server] = true addrs[server] = addr end end while true do evs, errno = unix.poll(pollfds) if not evs then break end for fd,revents in pairs(evs) do if fd == mainfd then data, errno = unix.read(mainfd) if not data then Log(kLogInfo, 'got %s from parent client' % {tostring(errno)}) -- prevent redbean core from writing a response unix.exit(1) end if #data == 0 then Log(kLogInfo, 'got hangup from parent client') Log(kLogInfo, 'closing server') -- prevent redbean core from writing a response unix.exit(0) end -- echo it back for fun unix.write(mainfd, data) elseif servers[fd] then unix.write(mainfd, 'preparing to accept from %d<br>\r\n' % {fd}) client, clientip, clientport = assert(unix.accept(fd)) addr = '%s:%d' % {FormatIp(clientip), clientport} addrs[client] = addr unix.write(mainfd, 'got client %s<br>\r\n' % {addr}) pollfds[client] = unix.POLLIN evs[server] = nil else unix.write(mainfd, 'preparing to read from %d<br>\r\n' % {fd}) data = unix.read(fd) unix.write(mainfd, 'done reading from %d<br>\r\n' % {fd}) if data and #data ~= 0 then unix.write(mainfd, 'got %d bytes from %s<br>\r\n' % {#data, addrs[fd]}) unix.write(fd, 'HTTP/1.0 200 OK\r\n' .. 'Date: '.. FormatHttpDateTime(GetDate()) ..'\r\n' .. 'Content-Type: text/html; charset=utf-8\r\n' .. 'Connection: close\r\n' .. 'Server: redbean unix\r\n' .. '\r\n' .. '<!doctype html>\r\n' .. '<title>redbean</title>\r\n' .. '<h3>embedded webserver demo</h3>\r\n' .. 'hello! this is a web server embedded in a web server!\r\n') end unix.close(fd) pollfds[fd] = nil end end end end main()
4,104
113
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/unix-raise.lua
#!/home/jart/bin/redbean -i assert(unix.sigaction(unix.SIGUSR1, function(sig) gotsigusr1 = true end)) gotsigusr1 = false assert(unix.raise(unix.SIGUSR1)) if gotsigusr1 then print('hooray the signal was delivered') else print('oh no some other signal was handled') end
277
12
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/script.lua
#!/usr/bin/redbean -i print('hello world')
43
3
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/.init.lua
mymodule = require "mymodule" sqlite3 = require "lsqlite3" -- ddos protection ProgramTokenBucket() -- /.init.lua is loaded at startup in redbean's main process HidePath('/usr/share/zoneinfo/') HidePath('/usr/share/ssl/') -- open a browser tab using explorer/open/xdg-open LaunchBrowser('/tool/net/demo/index.html') -- sql database (see sql.lua) db = sqlite3.open_memory() db:exec[[ CREATE TABLE test ( id INTEGER PRIMARY KEY, content TEXT ); INSERT INTO test (content) VALUES ('Hello World'); INSERT INTO test (content) VALUES ('Hello Lua'); INSERT INTO test (content) VALUES ('Hello Sqlite3'); ]] -- shared memory hit counter SHM_LOCK = 0 -- index zero (first eight bytes) will hold mutex SHM_JSON = 8 -- store json payload starting at the index eight shm = unix.mapshared(65520) function Lock() local ok, old = shm:cmpxchg(SHM_LOCK, 0, 1) if not ok then if old == 1 then old = shm:xchg(SHM_LOCK, 2) end while old > 0 do shm:wait(SHM_LOCK, 2) old = shm:xchg(SHM_LOCK, 2) end end end function Unlock() old = shm:fetch_add(SHM_LOCK, -1) if old == 2 then shm:store(SHM_LOCK, 0) shm:wake(SHM_LOCK, 1) end end function OnServerListen(fd, ip, port) unix.setsockopt(fd, unix.SOL_TCP, unix.TCP_SAVE_SYN, true) return false end function OnClientConnection(ip, port, serverip, serverport) syn, synerr = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_SAVED_SYN) end function UpdateHitCounter() local s, t, k Lock() s = shm:read(SHM_JSON) if s == '' then s = '{}' end t = DecodeJson(s) k = GetPath() if not t[k] then t[k] = 0 end t[k] = t[k] + 1 shm:write(SHM_JSON, EncodeJson(t)) Unlock() end -- this intercepts all requests if it's defined function OnHttpRequest() UpdateHitCounter() if GetHeader('User-Agent') then Log(kLogInfo, "client is running %s and reports %s" % { finger.GetSynFingerOs(finger.FingerSyn(syn)), VisualizeControlCodes(GetHeader('User-Agent'))}) end if HasParam('magic') then Write('<p>\r\n') Write('OnHttpRequest() has intercepted your request<br>\r\n') Write('because you specified the magic parameter\r\n') Write('<pre>\r\n') Write(EscapeHtml(LoadAsset('/.init.lua'))) Write('</pre>\r\n') else Route() -- this asks redbean to do the default thing end SetHeader('Server', 'redbean!') end function Adder(x, y) return x + y end
2,565
96
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/crashreport.lua
globalvar1 = 31337 globalvar2 = { hello = 'world', } function dosomething(param1, x) local res local y y = 0 SetStatus(200) SetHeader('Content-Type', 'text/plain; charset=utf-8') Write('preprae to crash... now\r\n') res = x / y Write('42 / 0 is %d\r\n' % {res}) end function start(param1) local x = 42 dosomething(s, x) end function main() local s = 'hello' start(s) end main()
422
29
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/unix-subprocess.lua
-- example of how to run the ls command -- and pipe its output to the http user local unix = require "unix" function main() if GetHostOs() == 'WINDOWS' then cmd = 'dir' else cmd = 'ls' end ls = assert(unix.commandv(cmd)) reader, writer = assert(unix.pipe(unix.O_CLOEXEC)) oldint = assert(unix.sigaction(unix.SIGINT, unix.SIG_IGN)) oldquit = assert(unix.sigaction(unix.SIGQUIT, unix.SIG_IGN)) oldmask = assert(unix.sigprocmask(unix.SIG_BLOCK, unix.Sigset(unix.SIGCHLD))) child = assert(unix.fork()) if child == 0 then unix.close(0) unix.open("/dev/null", unix.O_RDONLY) unix.close(1) unix.dup(writer) unix.close(2) unix.open("/dev/null", unix.O_RDONLY) unix.sigaction(unix.SIGINT, oldint) unix.sigaction(unix.SIGQUIT, oldquit) unix.sigprocmask(unix.SIG_SETMASK, oldmask) unix.execve(ls, {ls, '-Shal'}) unix.exit(127) else unix.close(writer) SetStatus(200) SetHeader('Content-Type', 'text/plain') while true do data, err = unix.read(reader) if data then if data ~= '' then Write(data) else break end elseif err:errno() ~= unix.EINTR then Log(kLogWarn, 'read() failed: %s' % {tostring(err)}) break end end unix.close(reader) Log(kLogWarn, 'wait() begin') unix.wait(-1) Log(kLogWarn, 'wait() end') unix.sigaction(unix.SIGINT, oldint) unix.sigaction(unix.SIGQUIT, oldquit) unix.sigprocmask(unix.SIG_SETMASK, oldmask) return end end main()
1,652
56
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/unix-rawsocket.lua
local unix = require 'unix' local function main() if GetMethod() ~= 'GET' and GetMethod() ~= 'HEAD' then ServeError(405) SetHeader('Allow', 'GET, HEAD') return end if IsClientUsingSsl() then SetStatus(400) SetHeader('Content-Type', 'text/html; charset=utf-8') Write('<!doctype html>\r\n') Write('<title>redbean unix module</title>\r\n') Write('<h1>\r\n') Write('<img style="vertical-align:middle" src="data:image/png;base64,\r\n') Write(EncodeBase64(LoadAsset('/redbean.png'))) Write('">\r\n') Write('redbean unix demo\r\n') Write('<span style="color:red">&nbsp;error</span>\r\n') Write('</h1>\r\n') Write([[ <p> The redbean unix module demo needs to intercept a raw unix socket. It's hard to do that if your file descriptor is encrypted with TLS. Please reload this page using http:// rather than https://. </p> ]]) Write('</h1>\r\n') return end -- steal client from redbean fd = GetClientFd() -- this function returns twice pid, errno = unix.fork() if errno then SetStatus(400) SetHeader('Content-Type', 'text/html; charset=utf-8') Write('<!doctype html>\r\n') Write('<title>redbean unix module</title>\r\n') Write('<h1>\r\n') Write('<img style="vertical-align:middle" src="data:image/png;base64,\r\n') Write(EncodeBase64(LoadAsset('/redbean.png'))) Write('">\r\n') Write('redbean unix demo\r\n') Write('<span style="color:red">&nbsp;%s</span>\r\n' % {EscapeHtml(tostring(errno))}) Write('</h1>\r\n') Write([[ <p> Your redbean doesn't have the ability to fork. Most likely because you enabled sandboxing and fork() isn't in your bpf policy. </p> ]]) Write('</h1>\r\n') return end -- the parent process gets the pid if pid ~= 0 then unix.close(fd) return end -- if pid is zero then we're the child -- turn into a daemon unix.umask(0) unix.setsid() if unix.fork() > 0 then unix.exit(0) end unix.close(0) unix.open('/dev/null', unix.O_RDONLY) unix.close(1) unix.open('/dev/null', unix.O_WRONLY) efd = unix.open('/tmp/redbean-unix.log', unix.O_WRONLY | unix.O_CREAT | unix.O_TRUNC, 0600) unix.dup(efd, 2) unix.close(efd) unix.sigaction(unix.SIGHUP, unix.SIG_DFL) unix.sigaction(unix.SIGINT, unix.SIG_DFL) unix.sigaction(unix.SIGQUIT, unix.SIG_DFL) unix.sigaction(unix.SIGTERM, unix.SIG_DFL) unix.sigaction(unix.SIGUSR1, unix.SIG_DFL) unix.sigaction(unix.SIGUSR2, unix.SIG_DFL) unix.sigaction(unix.SIGCHLD, unix.SIG_DFL) -- communicate with client unix.write(fd, 'HTTP/1.0 200 OK\r\n' .. 'Connection: close\r\n' .. 'Date: '.. FormatHttpDateTime(GetDate()) ..'\r\n' .. 'Content-Type: text/html; charset=utf-8\r\n' .. 'Server: redbean unix\r\n' .. '\r\n') unix.write(fd, '<!doctype html>\n') unix.write(fd, '<title>redbean unix module</title>') unix.write(fd, '<h1>\r\n') unix.write(fd, '<img style="vertical-align:middle" src="data:image/png;base64,\r\n') unix.write(fd, EncodeBase64(LoadAsset('/redbean.png'))) unix.write(fd, '">\r\n') unix.write(fd, 'redbean unix demo\r\n') unix.write(fd, '<span style="color:green">&nbsp;success</span>\r\n') unix.write(fd, '</h1>\r\n') unix.write(fd, '<p>\r\n') unix.write(fd, 'your lua code just stole control of your http client\r\n') unix.write(fd, 'socket file descriptor from redbean server, and then\r\n') unix.write(fd, 'became an autonomous daemon reparented on your init!\r\n') unix.write(fd, '</p>\r\n') -- terminate unix.close(fd) unix.exit(0) end main()
3,843
115
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/closedsource.lua
Write('This Lua Server Page is stored in ZIP\r\n') Write('as compressed byte code, see luac.com and net.mk\r\n')
113
3
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/finger.lua
-- fingerprinting example Write[[<!doctype html> <title>redbean binary trees</title> <style> body { padding: 1em; } h1 a { color: inherit; text-decoration: none; } h1 img { border: none; vertical-align: middle; } input { margin: 1em; padding: .5em; } p { word-break: break-word; max-width: 650px; } dt { font-family: monospace; } dd { margin-top: 1em; margin-bottom: 1em; } .hdr { text-indent: -1em; padding-left: 1em; } </style> <h1> <a href="/"><img src="/redbean.png"></a> <a href="finger.lua">redbean finger demo</a> </h1> ]] Write[[ <h2>Your TCP SYN Packet</h2> ]] -- See .init.lua hooks which set SYN and SYNERR globals. if syn then if syn ~= '' then Write('<dl>\r\n') Write('<dt>syn = unix.getsockopt(GetClientFd(), unix.SOL_TCP, unix.TCP_SAVED_SYN)\r\n') Write('<dd>') Write(EscapeHtml(EncodeLua(syn))) Write('\r\n') Write('<dt>finger.FingerSyn(syn)\r\n') Write('<dd>') Write(EscapeHtml(EncodeLua(finger.FingerSyn(syn)))) Write('\r\n') Write('<dt>finger.DescribeSyn(syn)\r\n') Write('<dd>') Write(EscapeHtml(EncodeLua(finger.DescribeSyn(syn)))) Write('\r\n') Write('<dt>finger.GetSynFingerOs(finger.FingerSyn(syn))\r\n') Write('<dd>') Write(EscapeHtml(EncodeLua(finger.GetSynFingerOs(finger.FingerSyn(syn))))) Write('\r\n') Write('</dl>\r\n') else Write([[ <p> your operating system returned an empty string as the syn packet! did you remember to use setsockopt(TCP_SAVE_SYN)? did you call getsockopt(TCP_SAVED_SYN) more than once? </p> ]]) end else Write([[ <p> your operating system most likely doesn't support TCP_SAVED_SYN because getsockopt() returned %s. </p> ]] % {EscapeHtml(tostring(synerr))}) end
1,848
66
jart/cosmopolitan
false
cosmopolitan/tool/net/demo/.lua/mymodule.lua
local mymodule = {} function mymodule.hello() Write("<b>Hello World!</b>\r\n") end return mymodule
104
8
jart/cosmopolitan
false
cosmopolitan/tool/net/tiny/help.txt
SYNOPSIS redbean.com [-hvduzmbagf] [-p PORT] [-D DIR] DESCRIPTION redbean - single-file distributable web server DOCUMENTATION This binary was built in MODE=tiny or MODE=tinylinux You can view documentation online at https://redbean.dev/
251
13
jart/cosmopolitan
false
cosmopolitan/tool/hash/hash.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ PKGS += TOOL_HASH TOOL_HASH_SRCS := $(wildcard tool/hash/*.c) TOOL_HASH_OBJS = \ $(TOOL_HASH_SRCS:%.c=o/$(MODE)/%.o) TOOL_HASH_COMS = \ $(TOOL_HASH_SRCS:%.c=o/$(MODE)/%.com) TOOL_HASH_BINS = \ $(TOOL_HASH_COMS) \ $(TOOL_HASH_COMS:%=%.dbg) TOOL_HASH_DIRECTDEPS = \ LIBC_FMT \ LIBC_INTRIN \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_STDIO \ LIBC_STR \ LIBC_MEM \ LIBC_STUBS TOOL_HASH_DEPS := \ $(call uniq,$(foreach x,$(TOOL_HASH_DIRECTDEPS),$($(x)))) o/$(MODE)/tool/hash/hash.pkg: \ $(TOOL_HASH_OBJS) \ $(foreach x,$(TOOL_HASH_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/tool/hash/%.com.dbg: \ $(TOOL_HASH_DEPS) \ o/$(MODE)/tool/hash/%.o \ o/$(MODE)/tool/hash/hash.pkg \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) $(TOOL_HASH_OBJS): \ $(BUILD_FILES) \ tool/hash/hash.mk .PHONY: o/$(MODE)/tool/hash o/$(MODE)/tool/hash: $(TOOL_HASH_BINS) $(TOOL_HASH_CHECKS)
1,140
49
jart/cosmopolitan
false
cosmopolitan/tool/hash/crctab.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2020 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/fmt/conv.h" #include "libc/intrin/bits.h" #include "libc/macros.internal.h" #include "libc/nexgen32e/crc32.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" /** * @fileoverview CRC Lookup Table Generator * @see http://reveng.sourceforge.net/crc-catalogue/17plus.htm */ int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s POLYNOMIAL\n", argv[0]); exit(1); } static uint32_t tab[256]; crc32init(tab, strtol(argv[1], NULL, 0)); for (unsigned i = 0; i < ARRAYLEN(tab); ++i) { if (i > 0) { printf(","); if (i % 6 == 0) { printf("\n"); } } printf("0x%08x", tab[i]); } printf("\n"); return 0; }
2,550
50
jart/cosmopolitan
false
cosmopolitan/tool/plinko/plinko.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ ifeq ($(ARCH), x86_64) PKGS += TOOL_PLINKO TOOL_PLINKO_SRCS := $(wildcard tool/plinko/*.c) TOOL_PLINKO_OBJS = \ $(TOOL_PLINKO_SRCS:%.c=o/$(MODE)/%.o) TOOL_PLINKO_COMS = \ $(TOOL_PLINKO_SRCS:%.c=o/$(MODE)/%.com) TOOL_PLINKO_BINS = \ $(TOOL_PLINKO_COMS) \ $(TOOL_PLINKO_COMS:%=%.dbg) TOOL_PLINKO_DIRECTDEPS = \ LIBC_INTRIN \ LIBC_LOG \ LIBC_MEM \ LIBC_CALLS \ LIBC_RUNTIME \ LIBC_SYSV \ LIBC_STDIO \ LIBC_X \ LIBC_STUBS \ LIBC_NEXGEN32E \ LIBC_ZIPOS \ TOOL_PLINKO_LIB TOOL_PLINKO_DEPS := \ $(call uniq,$(foreach x,$(TOOL_PLINKO_DIRECTDEPS),$($(x)))) o/$(MODE)/tool/plinko/plinko.pkg: \ $(TOOL_PLINKO_OBJS) \ $(foreach x,$(TOOL_PLINKO_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/tool/plinko/%.com.dbg: \ $(TOOL_PLINKO_DEPS) \ o/$(MODE)/tool/plinko/%.o \ o/$(MODE)/tool/plinko/plinko.pkg \ o/$(MODE)/tool/plinko/lib/library.lisp.zip.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/tool/plinko/plinko.com: \ o/$(MODE)/tool/plinko/plinko.com.dbg \ o/$(MODE)/third_party/zip/zip.com \ o/$(MODE)/tool/build/symtab.com @$(MAKE_OBJCOPY) @$(MAKE_SYMTAB_CREATE) @$(MAKE_SYMTAB_ZIP) o/$(MODE)/tool/plinko/plinko.com.zip.o: \ o/$(MODE)/tool/plinko/plinko.com o/$(MODE)/tool/plinko/plinko.com.zip.o \ o/$(MODE)/tool/plinko/lib/library.lisp.zip.o \ o/$(MODE)/tool/plinko/lib/binarytrees.lisp.zip.o \ o/$(MODE)/tool/plinko/lib/algebra.lisp.zip.o \ o/$(MODE)/tool/plinko/lib/infix.lisp.zip.o \ o/$(MODE)/tool/plinko/lib/ok.lisp.zip.o: \ ZIPOBJ_FLAGS += \ -B endif .PHONY: o/$(MODE)/tool/plinko o/$(MODE)/tool/plinko: $(TOOL_PLINKO_BINS) $(TOOL_PLINKO_CHECKS)
1,936
74
jart/cosmopolitan
false
cosmopolitan/tool/plinko/README.txt
DESCRIPTION plinko is a simple lisp interpreter that takes advantage of advanced operating system features irrespective of their practicality such as using the nsa instruction popcount for mark sweep garbage collection overcommit memory, segment registers, and other dirty hacks that the popular interpreters cannot do; this lets plinko gain a considerable performance edge while retaining an event greater edge in simplicity We hope you find these sources informative, educational, and possibly useful too. Lisp source code, written in its dialect is included too under //tool/plinko/lib and unit tests which clarify their usage can be found in //test/tool/plinko. BENCHMARK binary trees (n=21) - sbcl: 200 ms (native jit; simulated arithmetic) - plinko: 400 ms (interpreted; simulated arithmetic) - python3: 800 ms (interpreted; native arithmetic) - racket: 1200 ms (interpreted; simulated arithmetic) AUTHOR Justine Alexandra Roberts Tunney <jtunney@gmail.com> LICENSE ISC SEE ALSO SectorLISP SectorLambda
1,078
36
jart/cosmopolitan
false
cosmopolitan/tool/plinko/plinko.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/plinko.h" #include "libc/thread/tls.h" STATIC_YOINK("__zipos_get"); int main(int argc, char *argv[]) { __tls_enabled = false; Plinko(argc, argv); return 0; }
2,028
29
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/iswide.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/midpoint.h" #include "libc/macros.internal.h" #include "tool/plinko/lib/char.h" static const unsigned short kWides[][2] = { {0x1100, 0x115F}, // HANGUL CHOSEONG KIYEOK..HANGUL CHOSEONG FILLER {0x231A, 0x231B}, // WATCH..HOURGLASS {0x2329, 0x2329}, // LEFT-POINTING ANGLE BRACKET {0x232A, 0x232A}, // RIGHT-POINTING ANGLE BRACKET {0x23E9, 0x23EC}, // BLACK RIGHT-POINTING DOUBLE TRIANGLE... {0x23F0, 0x23F0}, // ALARM CLOCK {0x23F3, 0x23F3}, // HOURGLASS WITH FLOWING SAND {0x25FD, 0x25FE}, // WHITE MEDIUM SMALL SQUARE..BLACK MEDIUM SMALL SQUARE {0x2614, 0x2615}, // UMBRELLA WITH RAIN DROPS..HOT BEVERAGE {0x2648, 0x2653}, // ARIES..PISCES {0x267F, 0x267F}, // WHEELCHAIR SYMBOL {0x2693, 0x2693}, // ANCHOR {0x26A1, 0x26A1}, // HIGH VOLTAGE SIGN {0x26AA, 0x26AB}, // MEDIUM WHITE CIRCLE..MEDIUM BLACK CIRCLE {0x26BD, 0x26BE}, // SOCCER BALL..BASEBALL {0x26C4, 0x26C5}, // SNOWMAN WITHOUT SNOW..SUN BEHIND CLOUD {0x26CE, 0x26CE}, // OPHIUCHUS {0x26D4, 0x26D4}, // NO ENTRY {0x26EA, 0x26EA}, // CHURCH {0x26F2, 0x26F3}, // FOUNTAIN..FLAG IN HOLE {0x26F5, 0x26F5}, // SAILBOAT {0x26FA, 0x26FA}, // TENT {0x26FD, 0x26FD}, // FUEL PUMP {0x2705, 0x2705}, // WHITE HEAVY CHECK MARK {0x270A, 0x270B}, // RaiseD FIST..RaiseD HAND {0x2728, 0x2728}, // SPARKLES {0x274C, 0x274C}, // CROSS MARK {0x274E, 0x274E}, // NEGATIVE SQUARED CROSS MARK {0x2753, 0x2755}, // BLACK QUESTION MARK ORNAMENT..WHITE EXCLAMATION MARK {0x2757, 0x2757}, // HEAVY EXCLAMATION MARK SYMBOL {0x2795, 0x2797}, // HEAVY PLUS SIGN..HEAVY DIVISION SIGN {0x27B0, 0x27B0}, // CURLY LOOP {0x27BF, 0x27BF}, // DOUBLE CURLY LOOP {0x2B1B, 0x2B1C}, // BLACK LARGE SQUARE..WHITE LARGE SQUARE {0x2B50, 0x2B50}, // WHITE MEDIUM STAR {0x2B55, 0x2B55}, // HEAVY LARGE CIRCLE {0x2E80, 0x2E99}, // CJK RADICAL REPEAT..CJK RADICAL RAP {0x2E9B, 0x2EF3}, // CJK RADICAL CHOKE..CJK RADICAL C-SIMPLIFIED TURTLE {0x2F00, 0x2FD5}, // KANGXI RADICAL ONE..KANGXI RADICAL FLUTE {0x2FF0, 0x2FFB}, // IDEOGRAPHIC DESCRIPTION CHARACTER LTR..OVERLAID {0x3000, 0x3000}, // IDEOGRAPHIC SPACE {0x3001, 0x3003}, // IDEOGRAPHIC COMMA..DITTO MARK {0x3004, 0x3004}, // JAPANESE INDUSTRIAL STANDARD SYMBOL {0x3005, 0x3005}, // IDEOGRAPHIC ITERATION MARK {0x3006, 0x3006}, // IDEOGRAPHIC CLOSING MARK {0x3007, 0x3007}, // IDEOGRAPHIC NUMBER ZERO {0x3008, 0x3008}, // LEFT ANGLE BRACKET {0x3009, 0x3009}, // RIGHT ANGLE BRACKET {0x300A, 0x300A}, // LEFT DOUBLE ANGLE BRACKET {0x300B, 0x300B}, // RIGHT DOUBLE ANGLE BRACKET {0x300C, 0x300C}, // LEFT CORNER BRACKET {0x300D, 0x300D}, // RIGHT CORNER BRACKET {0x300E, 0x300E}, // LEFT WHITE CORNER BRACKET {0x300F, 0x300F}, // RIGHT WHITE CORNER BRACKET {0x3010, 0x3010}, // LEFT BLACK LENTICULAR BRACKET {0x3011, 0x3011}, // RIGHT BLACK LENTICULAR BRACKET {0x3012, 0x3013}, // POSTAL MARK..GETA MARK {0x3014, 0x3014}, // LEFT TORTOISE SHELL BRACKET {0x3015, 0x3015}, // RIGHT TORTOISE SHELL BRACKET {0x3016, 0x3016}, // LEFT WHITE LENTICULAR BRACKET {0x3017, 0x3017}, // RIGHT WHITE LENTICULAR BRACKET {0x3018, 0x3018}, // LEFT WHITE TORTOISE SHELL BRACKET {0x3019, 0x3019}, // RIGHT WHITE TORTOISE SHELL BRACKET {0x301A, 0x301A}, // LEFT WHITE SQUARE BRACKET {0x301B, 0x301B}, // RIGHT WHITE SQUARE BRACKET {0x301C, 0x301C}, // WAVE DASH {0x301D, 0x301D}, // REVERSED DOUBLE PRIME QUOTATION MARK {0x301E, 0x301F}, // DOUBLE PRIME QUOTATION MARK..LOW DOUBLE PRIME {0x3020, 0x3020}, // POSTAL MARK FACE {0x3021, 0x3029}, // HANGZHOU NUMERAL ONE..HANGZHOU NUMERAL NINE {0x302A, 0x302D}, // IDEOGRAPHIC LEVEL TONE MARK..ENTERING TONE MARK {0x302E, 0x302F}, // HANGUL SINGLE DOT TONE MARK..DOUBLE DOT TONE MARK {0x3030, 0x3030}, // WAVY DASH {0x3031, 0x3035}, // VERTICAL KANA REPEAT MARK..KANA REPEAT MARK LOWER {0x3036, 0x3037}, // CIRCLED POSTAL MARK..IDEOGRAPHIC TELEGRAPH LF SYMBOL {0x3038, 0x303A}, // HANGZHOU NUMERAL TEN..HANGZHOU NUMERAL THIRTY {0x303B, 0x303B}, // VERTICAL IDEOGRAPHIC ITERATION MARK {0x303C, 0x303C}, // MASU MARK {0x303D, 0x303D}, // PART ALTERNATION MARK {0x303E, 0x303E}, // IDEOGRAPHIC VARIATION INDICATOR {0x3041, 0x3096}, // HIRAGANA LETTER SMALL A..HIRAGANA LETTER SMALL KE {0x3099, 0x309A}, // COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK... {0x309B, 0x309C}, // KATAKANA-HIRAGANA VOICED SOUND MARK... {0x309D, 0x309E}, // HIRAGANA ITERATION MARK..VOICED ITERATION MARK {0x309F, 0x309F}, // HIRAGANA DIGRAPH YORI {0x30A0, 0x30A0}, // KATAKANA-HIRAGANA DOUBLE HYPHEN {0x30A1, 0x30FA}, // KATAKANA LETTER SMALL A..KATAKANA LETTER VO {0x30FB, 0x30FB}, // KATAKANA MIDDLE DOT {0x30FC, 0x30FE}, // KATAKANA-HIRAGANA PROLONGED SOUND MARK..ITERATION {0x30FF, 0x30FF}, // KATAKANA DIGRAPH KOTO {0x3105, 0x312F}, // BOPOMOFO LETTER B..BOPOMOFO LETTER NN {0x3131, 0x318E}, // HANGUL LETTER KIYEOK..HANGUL LETTER ARAEAE {0x3190, 0x3191}, // IDEOGRAPHIC ANNOTATION LINKING MARK..REVERSE {0x3192, 0x3195}, // IDEOGRAPHIC ANNOTATION ONE MARK..FOUR {0x3196, 0x319F}, // IDEOGRAPHIC ANNOTATION TOP MARK..MAN {0x31A0, 0x31BF}, // BOPOMOFO LETTER BU..BOPOMOFO LETTER AH {0x31C0, 0x31E3}, // CJK STROKE T..CJK STROKE Q {0x31F0, 0x31FF}, // KATAKANA LETTER SMALL KU..KATAKANA LETTER SMALL RO {0x3200, 0x321E}, // PARENTHESIZED HANGUL KIYEOK..CHARACTER O HU {0x3220, 0x3229}, // PARENTHESIZED IDEOGRAPH ONE..TEN {0x322A, 0x3247}, // PARENTHESIZED IDEOGRAPH MOON..CIRCLED IDEOGRAPH KOTO {0x3250, 0x3250}, // PARTNERSHIP SIGN {0x3251, 0x325F}, // CIRCLED NUMBER TWENTY ONE..CIRCLED 35 {0x3260, 0x327F}, // CIRCLED HANGUL KIYEOK..KOREAN STANDARD SYMBOL {0x3280, 0x3289}, // CIRCLED IDEOGRAPH ONE..CIRCLED IDEOGRAPH TEN {0x328A, 0x32B0}, // CIRCLED IDEOGRAPH MOON..CIRCLED IDEOGRAPH NIGHT {0x32B1, 0x32BF}, // CIRCLED NUMBER THIRTY SIX..CIRCLED NUMBER FIFTY {0x32C0, 0x32FF}, // TELEGRAPH SYMBOL FOR JANUARY..SQUARE ERA NAME REIWA {0x3300, 0x33FF}, // SQUARE APAATO..SQUARE GAL {0x3400, 0x4DBF}, // CJK UNIFIED IDEOGRAPH {0x4E00, 0x9FFF}, // CJK UNIFIED IDEOGRAPH {0xA000, 0xA014}, // YI SYLLABLE IT..YI SYLLABLE E {0xA015, 0xA015}, // YI SYLLABLE WU {0xA016, 0xA48C}, // YI SYLLABLE BIT..YI SYLLABLE YYR {0xA490, 0xA4C6}, // YI RADICAL QOT..YI RADICAL KE {0xA960, 0xA97C}, // HANGUL CHOSEONG TIKEUT-MIEUM..SSANGYEORINHIEUH {0xAC00, 0xD7A3}, // HANGUL SYLLABLE GA..HANGUL SYLLABLE HIH {0xF900, 0xFA6D}, // CJK COMPATIBILITY IDEOGRAPH {0xFA6E, 0xFA6F}, // RESERVED {0xFA70, 0xFAD9}, // CJK COMPATIBILITY IDEOGRAPH {0xFADA, 0xFAFF}, // RESERVED {0xFE10, 0xFE16}, // PRESENTATION FORM FOR VERTICAL COMMA..QUESTION {0xFE17, 0xFE17}, // VERTICAL LEFT WHITE LENTICULAR BRACKET {0xFE18, 0xFE18}, // VERTICAL RIGHT WHITE LENTICULAR BRAKCET {0xFE19, 0xFE19}, // PRESENTATION FORM FOR VERTICAL HORIZONTAL ELLIPSIS {0xFE30, 0xFE30}, // PRESENTATION FORM FOR VERTICAL TWO DOT LEADER {0xFE31, 0xFE32}, // VERTICAL EM DASH..VERTICAL EN DASH {0xFE33, 0xFE34}, // VERTICAL LOW LINE..VERTICAL WAVY LOW LINE {0xFE35, 0xFE35}, // PRESENTATION FORM FOR VERTICAL LEFT PARENTHESIS {0xFE36, 0xFE36}, // PRESENTATION FORM FOR VERTICAL RIGHT PARENTHESIS {0xFE37, 0xFE37}, // PRESENTATION FORM FOR VERTICAL LEFT CURLY BRACKET {0xFE38, 0xFE38}, // PRESENTATION FORM FOR VERTICAL RIGHT CURLY BRACKET {0xFE39, 0xFE39}, // VERTICAL LEFT TORTOISE SHELL BRACKET {0xFE3A, 0xFE3A}, // VERTICAL RIGHT TORTOISE SHELL BRACKET {0xFE3B, 0xFE3B}, // VERTICAL LEFT BLACK LENTICULAR BRACKET {0xFE3C, 0xFE3C}, // VERTICAL RIGHT BLACK LENTICULAR BRACKET {0xFE3D, 0xFE3D}, // VERTICAL LEFT DOUBLE ANGLE BRACKET {0xFE3E, 0xFE3E}, // VERTICAL RIGHT DOUBLE ANGLE BRACKET {0xFE3F, 0xFE3F}, // VERTICAL LEFT ANGLE BRACKET {0xFE40, 0xFE40}, // VERTICAL RIGHT ANGLE BRACKET {0xFE41, 0xFE41}, // VERTICAL LEFT CORNER BRACKET {0xFE42, 0xFE42}, // VERTICAL RIGHT CORNER BRACKET {0xFE43, 0xFE43}, // VERTICAL LEFT WHITE CORNER BRACKET {0xFE44, 0xFE44}, // VERTICAL RIGHT WHITE CORNER BRACKET {0xFE45, 0xFE46}, // SESAME DOT..WHITE SESAME DOT {0xFE47, 0xFE47}, // VERTICAL LEFT SQUARE BRACKET {0xFE48, 0xFE48}, // VERTICAL RIGHT SQUARE BRACKET {0xFE49, 0xFE4C}, // DASHED OVERLINE..DOUBLE WAVY OVERLINE {0xFE4D, 0xFE4F}, // DASHED LOW LINE..WAVY LOW LINE {0xFE50, 0xFE52}, // SMALL COMMA..SMALL FULL STOP {0xFE54, 0xFE57}, // SMALL SEMICOLON..SMALL EXCLAMATION MARK {0xFE58, 0xFE58}, // SMALL EM DASH {0xFE59, 0xFE59}, // SMALL LEFT PARENTHESIS {0xFE5A, 0xFE5A}, // SMALL RIGHT PARENTHESIS {0xFE5B, 0xFE5B}, // SMALL LEFT CURLY BRACKET {0xFE5C, 0xFE5C}, // SMALL RIGHT CURLY BRACKET {0xFE5D, 0xFE5D}, // SMALL LEFT TORTOISE SHELL BRACKET {0xFE5E, 0xFE5E}, // SMALL RIGHT TORTOISE SHELL BRACKET {0xFE5F, 0xFE61}, // SMALL NUMBER SIGN..SMALL ASTERISK {0xFE62, 0xFE62}, // SMALL PLUS SIGN {0xFE63, 0xFE63}, // SMALL HYPHEN-MINUS {0xFE64, 0xFE66}, // SMALL LESS-THAN SIGN..SMALL EQUALS SIGN {0xFE68, 0xFE68}, // SMALL REVERSE SOLIDUS {0xFE69, 0xFE69}, // SMALL DOLLAR SIGN {0xFE6A, 0xFE6B}, // SMALL PERCENT SIGN..SMALL COMMERCIAL AT {0xFF01, 0xFF03}, // EXCLAMATION MARK..NUMBER SIGN {0xFF04, 0xFF04}, // DOLLAR SIGN {0xFF05, 0xFF07}, // PERCENT SIGN..APOSTROPHE {0xFF08, 0xFF08}, // LEFT PARENTHESIS {0xFF09, 0xFF09}, // RIGHT PARENTHESIS {0xFF0A, 0xFF0A}, // ASTERISK {0xFF0B, 0xFF0B}, // PLUS SIGN {0xFF0C, 0xFF0C}, // COMMA {0xFF0D, 0xFF0D}, // HYPHEN-MINUS {0xFF0E, 0xFF0F}, // FULL STOP..SOLIDUS {0xFF10, 0xFF19}, // DIGIT ZERO..DIGIT NINE {0xFF1A, 0xFF1B}, // COLON..SEMICOLON {0xFF1C, 0xFF1E}, // LESS-THAN..GREATER-THAN {0xFF1F, 0xFF20}, // QUESTION MARK..COMMERCIAL AT {0xFF21, 0xFF3A}, // LATIN CAPITAL LETTER A..Z {0xFF3B, 0xFF3B}, // LEFT SQUARE BRACKET {0xFF3C, 0xFF3C}, // REVERSE SOLIDUS {0xFF3D, 0xFF3D}, // RIGHT SQUARE BRACKET {0xFF3E, 0xFF3E}, // CIRCUMFLEX ACCENT {0xFF3F, 0xFF3F}, // LOW LINE {0xFF40, 0xFF40}, // GRAVE ACCENT {0xFF41, 0xFF5A}, // LATIN SMALL LETTER A..Z {0xFF5B, 0xFF5B}, // LEFT CURLY BRACKET {0xFF5C, 0xFF5C}, // VERTICAL LINE {0xFF5D, 0xFF5D}, // RIGHT CURLY BRACKET {0xFF5E, 0xFF5E}, // TILDE {0xFF5F, 0xFF5F}, // LEFT WHITE PARENTHESIS {0xFF60, 0xFF60}, // RIGHT WHITE PARENTHESIS {0xFFE0, 0xFFE1}, // CENT SIGN..POUND SIGN {0xFFE2, 0xFFE2}, // NOT SIGN {0xFFE3, 0xFFE3}, // MACRON {0xFFE4, 0xFFE4}, // BROKEN BAR {0xFFE5, 0xFFE6}, // YEN SIGN..WON SIGN }; static const int kAstralWides[][2] = { {0x16FE0, 0x16FE1}, // TANGUT ITERATION MARK..NUSHU ITERATION MARK {0x16FE2, 0x16FE2}, // OLD CHINESE HOOK MARK {0x16FE3, 0x16FE3}, // OLD CHINESE ITERATION MARK {0x16FE4, 0x16FE4}, // KHITAN SMALL SCRIPT FILLER {0x16FF0, 0x16FF1}, // VIETNAMESE ALTERNATE READING MARK CA..NHAY {0x17000, 0x187F7}, // TANGUT IDEOGRAPH {0x18800, 0x18AFF}, // TANGUT COMPONENT {0x18B00, 0x18CD5}, // KHITAN SMALL SCRIPT CHARACTER {0x18D00, 0x18D08}, // TANGUT IDEOGRAPH {0x1AFF0, 0x1AFF3}, // KATAKANA LETTER MINNAN TONE-2..5 {0x1AFF5, 0x1AFFB}, // KATAKANA LETTER MINNAN TONE-7..5 {0x1AFFD, 0x1AFFE}, // KATAKANA LETTER MINNAN NASALIZED TONE-7..8 {0x1B000, 0x1B0FF}, // KATAKANA LETTER ARCHAIC E..HENTAIGANA LETTER RE-2 {0x1B100, 0x1B122}, // HENTAIGANA LETTER RE-3..KATAKANA LETTER ARCHAIC WU {0x1B150, 0x1B152}, // HIRAGANA LETTER SMALL WI..HIRAGANA LETTER SMALL WO {0x1B164, 0x1B167}, // KATAKANA LETTER SMALL WI..KATAKANA LETTER SMALL N {0x1B170, 0x1B2FB}, // NUSHU CHARACTER-1B170..NUSHU CHARACTER-1B2FB {0x1F004, 0x1F004}, // MAHJONG TILE RED DRAGON {0x1F0CF, 0x1F0CF}, // PLAYING CARD BLACK JOKER {0x1F18E, 0x1F18E}, // NEGATIVE SQUARED AB {0x1F191, 0x1F19A}, // SQUARED CL..SQUARED VS {0x1F200, 0x1F202}, // SQUARE HIRAGANA HOKA..SQUARED KATAKANA SA {0x1F210, 0x1F23B}, // SQUARED CJK UNIFIED IDEOGRAPH {0x1F240, 0x1F248}, // TORTOISE SHELL BRACKETED CJK UNIFIED IDEOGRAPH {0x1F250, 0x1F251}, // CIRCLED IDEOGRAPH ADVANTAGE..ACCEPT {0x1F260, 0x1F265}, // ROUNDED SYMBOL FOR FU..ROUNDED SYMBOL FOR CAI {0x1F300, 0x1F320}, // CYCLONE..SHOOTING STAR {0x1F32D, 0x1F335}, // HOT DOG..CACTUS {0x1F337, 0x1F37C}, // TULIP..BABY BOTTLE {0x1F37E, 0x1F393}, // BOTTLE WITH POPPING CORK..GRADUATION CAP {0x1F3A0, 0x1F3CA}, // CAROUSEL HORSE..SWIMMER {0x1F3CF, 0x1F3D3}, // CRICKET BAT AND BALL..TABLE TENNIS PADDLE AND BALL {0x1F3E0, 0x1F3F0}, // HOUSE BUILDING..EUROPEAN CASTLE {0x1F3F4, 0x1F3F4}, // WAVING BLACK FLAG {0x1F3F8, 0x1F3FA}, // BADMINTON RACQUET AND SHUTTLECOCK..AMPHORA {0x1F3FB, 0x1F3FF}, // EMOJI MODIFIER FITZPATRICK TYPE-1-2..6 {0x1F400, 0x1F43E}, // RAT..PAW PRINTS {0x1F440, 0x1F440}, // EYES {0x1F442, 0x1F4FC}, // EAR..VIDEOCASSETTE {0x1F4FF, 0x1F53D}, // PRAYER BEADS..DOWN-POINTING SMALL RED TRIANGLE {0x1F54B, 0x1F54E}, // KAABA..MENORAH WITH NINE BRANCHES {0x1F550, 0x1F567}, // CLOCK FACE ONE OCLOCK..CLOCK FACE TWELVE-THIRTY {0x1F57A, 0x1F57A}, // MAN DANCING {0x1F595, 0x1F596}, // REVERSED HAND WITH MIDDLE FINGER EXTENDED..FINGERS {0x1F5A4, 0x1F5A4}, // BLACK HEART {0x1F5FB, 0x1F5FF}, // MOUNT FUJI..MOYAI {0x1F600, 0x1F64F}, // GRINNING FACE..PERSON WITH FOLDED HANDS {0x1F680, 0x1F6C5}, // ROCKET..LEFT LUGGAGE {0x1F6CC, 0x1F6CC}, // SLEEPING ACCOMMODATION {0x1F6D0, 0x1F6D2}, // PLACE OF WORSHIP..SHOPPING TROLLEY {0x1F6D5, 0x1F6D7}, // HINDU TEMPLE..ELEVATOR {0x1F6DD, 0x1F6DF}, // PLAYGROUND SLIDE..RING BUOY {0x1F6EB, 0x1F6EC}, // AIRPLANE DEPARTURE..AIRPLANE ARRIVING {0x1F6F4, 0x1F6FC}, // SCOOTER..ROLLER SKATE {0x1F7E0, 0x1F7EB}, // LARGE ORANGE CIRCLE..LARGE BROWN SQUARE {0x1F7F0, 0x1F7F0}, // HEAVY EQUALS SIGN {0x1F90C, 0x1F93A}, // PINCHED FINGERS..FENCER {0x1F93C, 0x1F945}, // WRESTLERS..GOAL NET {0x1F947, 0x1F9FF}, // FIRST PLACE MEDAL..NAZAR AMULET {0x1FA70, 0x1FA74}, // BALLET SHOES..THONG SANDAL {0x1FA78, 0x1FA7C}, // DROP OF BLOOD..CRUTCH {0x1FA80, 0x1FA86}, // YO-YO..NESTING DOLLS {0x1FA90, 0x1FAAC}, // RINGED PLANET..HAMSA {0x1FAB0, 0x1FABA}, // FLY..NEST WITH EGGS {0x1FAC0, 0x1FAC5}, // ANATOMICAL HEART..PERSON WITH CROWN {0x1FAD0, 0x1FAD9}, // BLUEBERRIES..JAR {0x1FAE0, 0x1FAE7}, // MELTING FACE..BUBBLES {0x1FAF0, 0x1FAF6}, // HAND WITH INDEX FINGER THUMB CROSSED..HEART HANDS {0x20000, 0x2A6DF}, // CJK UNIFIED IDEOGRAPH {0x2A6E0, 0x2A6FF}, // RESERVED {0x2A700, 0x2B738}, // CJK UNIFIED IDEOGRAPH {0x2B739, 0x2B73F}, // RESERVED {0x2B740, 0x2B81D}, // CJK UNIFIED IDEOGRAPH {0x2B81E, 0x2B81F}, // RESERVED {0x2B820, 0x2CEA1}, // CJK UNIFIED IDEOGRAPH {0x2CEA2, 0x2CEAF}, // RESERVED {0x2CEB0, 0x2EBE0}, // CJK UNIFIED IDEOGRAPH {0x2EBE1, 0x2F7FF}, // RESERVED {0x2F800, 0x2FA1D}, // CJK COMPATIBILITY IDEOGRAPH {0x2FA1E, 0x2FA1F}, // RESERVED {0x2FA20, 0x2FFFD}, // RESERVED {0x30000, 0x3134A}, // CJK UNIFIED IDEOGRAPH {0x3134B, 0x3FFFD}, // RESERVED }; pureconst bool IsWide(int c) { int m, l, r, n; if (c < 0x1100) { return false; } else if (c < 0x10000) { l = 0; r = n = sizeof(kWides) / sizeof(kWides[0]); while (l < r) { m = _midpoint(l, r); if (kWides[m][1] < c) { l = m + 1; } else { r = m; } } return l < n && kWides[l][0] <= c && c <= kWides[l][1]; } else { l = 0; r = n = sizeof(kAstralWides) / sizeof(kAstralWides[0]); while (l < r) { m = _midpoint(l, r); if (kAstralWides[m][1] < c) { l = m + 1; } else { r = m; } } return l < n && kAstralWides[l][0] <= c && c <= kAstralWides[l][1]; } } pureconst int GetMonospaceCharacterWidth(int c) { return !IsControl(c) + IsWide(c); }
18,302
344
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/ok.lisp
#| plinko - a really fast lisp tarpit | Copyright 2022 Justine Alexandra Roberts Tunney | | Permission to use, copy, modify, and/or distribute this software for | any purpose with or without fee is hereby granted, provided that the | above copyright notice and this permission notice appear in all copies. | | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL | WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED | WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE | AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL | DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR | PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER | TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | PERFORMANCE OF THIS SOFTWARE. |# (QUOTE OKCOMPUTER)
848
19
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/infix.lisp
#| plinko - a really fast lisp tarpit | Copyright 2022 Justine Alexandra Roberts Tunney | | Permission to use, copy, modify, and/or distribute this software for | any purpose with or without fee is hereby granted, provided that the | above copyright notice and this permission notice appear in all copies. | | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL | WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED | WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE | AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL | DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR | PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER | TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | PERFORMANCE OF THIS SOFTWARE. |# (DEFUN UNARY-INFIX (INFIX I) (COND ((ATOM (CAR I)) (COND ((EQ (CAR I) "+") (UNARY-INFIX INFIX (CDR I))) ((EQ (CAR I) "-") (LET ((X (UNARY-INFIX INFIX (CDR I)))) (CONS (LIST 'SUB '0 (CAR X)) (CDR X)))) ((EQ (CAR I) "~") (LET ((X (UNARY-INFIX INFIX (CDR I)))) (CONS (LIST 'NOT (CAR X)) (CDR X)))) ((EQ (CAR I) "!") (LET ((X (UNARY-INFIX INFIX (CDR I)))) (CONS (LIST 'NOT (LIST 'EQ '0 (CAR X))) (CDR X)))) (I))) ((CONS (INFIX (CAR I)) (CDR I))))) (DEFUN POW-INFIX (INFIX I) (LET ((X (UNARY-INFIX INFIX I))) (COND ((EQ (CADR X) "**") (LET ((Y (POW-INFIX INFIX (CDDR X)))) (CONS (LIST 'POW (CAR X) (CAR Y)) (CDR Y)))) (X)))) (DEFUN -MUL-INFIX (INFIX X) (COND ((EQ (CADR X) "*") (LET ((Y (POW-INFIX INFIX (CDDR X)))) (-MUL-INFIX INFIX (CONS (LIST 'MUL (CAR X) (CAR Y)) (CDR Y))))) ((EQ (CADR X) "/") (LET ((Y (POW-INFIX INFIX (CDDR X)))) (-MUL-INFIX INFIX (CONS (LIST 'DIV (CAR X) (CAR Y)) (CDR Y))))) ((EQ (CADR X) "%") (LET ((Y (POW-INFIX INFIX (CDDR X)))) (-MUL-INFIX INFIX (CONS (LIST 'REM (CAR X) (CAR Y)) (CDR Y))))) (X))) (DEFUN MUL-INFIX (INFIX I) (-MUL-INFIX INFIX (POW-INFIX INFIX I))) (DEFUN -ADD-INFIX (INFIX X) (COND ((EQ (CADR X) "+") (LET ((Y (MUL-INFIX INFIX (CDDR X)))) (-ADD-INFIX INFIX (CONS (LIST 'ADD (CAR X) (CAR Y)) (CDR Y))))) ((EQ (CADR X) "-") (LET ((Y (MUL-INFIX INFIX (CDDR X)))) (-ADD-INFIX INFIX (CONS (LIST 'SUB (CAR X) (CAR Y)) (CDR Y))))) (X))) (DEFUN ADD-INFIX (INFIX I) (-ADD-INFIX INFIX (MUL-INFIX INFIX I))) (DEFUN -SHIFT-INFIX (INFIX X) (COND ((EQ (CADR X) "<<") (LET ((Y (ADD-INFIX INFIX (CDDR X)))) (-SHIFT-INFIX INFIX (CONS (LIST 'SHL (CAR X) (CAR Y)) (CDR Y))))) ((EQ (CADR X) ">>") (LET ((Y (ADD-INFIX INFIX (CDDR X)))) (-SHIFT-INFIX INFIX (CONS (LIST 'SAR (CAR X) (CAR Y)) (CDR Y))))) ((EQ (CADR X) ">>>") (LET ((Y (ADD-INFIX INFIX (CDDR X)))) (-SHIFT-INFIX INFIX (CONS (LIST 'SHR (CAR X) (CAR Y)) (CDR Y))))) (X))) (DEFUN SHIFT-INFIX (INFIX I) (-SHIFT-INFIX INFIX (ADD-INFIX INFIX I))) (DEFUN -RELATIONAL-INFIX (INFIX X) (COND ((EQ (CADR X) "<") (LET ((Y (SHIFT-INFIX INFIX (CDDR X)))) (-RELATIONAL-INFIX INFIX (CONS (LIST 'LT (CAR X) (CAR Y)) (CDR Y))))) ((EQ (CADR X) ">") (LET ((Y (SHIFT-INFIX INFIX (CDDR X)))) (-RELATIONAL-INFIX INFIX (CONS (LIST 'GT (CAR X) (CAR Y)) (CDR Y))))) ((EQ (CADR X) ">=") (LET ((Y (SHIFT-INFIX INFIX (CDDR X)))) (-RELATIONAL-INFIX INFIX (CONS (LIST 'GE (CAR X) (CAR Y)) (CDR Y))))) ((EQ (CADR X) "<=") (LET ((Y (SHIFT-INFIX INFIX (CDDR X)))) (-RELATIONAL-INFIX INFIX (CONS (LIST 'LE (CAR X) (CAR Y)) (CDR Y))))) (X))) (DEFUN RELATIONAL-INFIX (INFIX I) (-RELATIONAL-INFIX INFIX (SHIFT-INFIX INFIX I))) (DEFUN -EQUALITY-INFIX (INFIX X) (COND ((EQ (CADR X) "==") (LET ((Y (RELATIONAL-INFIX INFIX (CDDR X)))) (-EQUALITY-INFIX INFIX (CONS (LIST 'EQ (CAR X) (CAR Y)) (CDR Y))))) ((EQ (CADR X) "!=") (LET ((Y (RELATIONAL-INFIX INFIX (CDDR X)))) (-EQUALITY-INFIX INFIX (CONS (LIST 'NOT (LIST 'EQ (CAR X) (CAR Y))) (CDR Y))))) (X))) (DEFUN EQUALITY-INFIX (INFIX I) (-EQUALITY-INFIX INFIX (RELATIONAL-INFIX INFIX I))) (DEFUN -AND-INFIX (INFIX X) (COND ((EQ (CADR X) "&") (LET ((Y (EQUALITY-INFIX INFIX (CDDR X)))) (-AND-INFIX INFIX (CONS (LIST 'AND (CAR X) (CAR Y)) (CDR Y))))) (X))) (DEFUN AND-INFIX (INFIX I) (-AND-INFIX INFIX (EQUALITY-INFIX INFIX I))) (DEFUN -XOR-INFIX (INFIX X) (COND ((EQ (CADR X) "^") (LET ((Y (AND-INFIX INFIX (CDDR X)))) (-XOR-INFIX INFIX (CONS (LIST 'XOR (CAR X) (CAR Y)) (CDR Y))))) (X))) (DEFUN XOR-INFIX (INFIX I) (-XOR-INFIX INFIX (AND-INFIX INFIX I))) (DEFUN -OR-INFIX (INFIX X) (COND ((EQ (CADR X) "|") (LET ((Y (XOR-INFIX INFIX (CDDR X)))) (-OR-INFIX INFIX (CONS (LIST 'OR (CAR X) (CAR Y)) (CDR Y))))) (X))) (DEFUN OR-INFIX (INFIX I) (-OR-INFIX INFIX (XOR-INFIX INFIX I))) (DEFUN -LOGAND-INFIX (INFIX X) (COND ((EQ (CADR X) "&&") (LET ((Y (OR-INFIX INFIX (CDDR X)))) (-LOGAND-INFIX INFIX (CONS (LIST 'AND (LIST 'NOT (LIST 'EQ '0 (CAR X))) (LIST 'NOT (LIST 'EQ '0 (CAR Y)))) (CDR Y))))) (X))) (DEFUN LOGAND-INFIX (INFIX I) (-LOGAND-INFIX INFIX (OR-INFIX INFIX I))) (DEFUN -LOGOR-INFIX (INFIX X) (COND ((EQ (CADR X) "||") (LET ((Y (LOGAND-INFIX INFIX (CDDR X)))) (-LOGOR-INFIX INFIX (CONS (LIST 'OR (LIST 'NOT (LIST 'EQ '0 (CAR X))) (LIST 'NOT (LIST 'EQ '0 (CAR Y)))) (CDR Y))))) (X))) (DEFUN LOGOR-INFIX (INFIX I) (-LOGOR-INFIX INFIX (LOGAND-INFIX INFIX I))) (DEFUN CONDITIONAL-INFIX (INFIX I) (LET ((X (LOGOR-INFIX INFIX I))) (COND ((EQ (CADR X) "?") (LET ((Y (LOGOR-INFIX INFIX (CDDR X)))) (COND ((EQ (CADR Y) ":") (LET ((Z (CONDITIONAL-INFIX INFIX (CDDR Y)))) (CONS (LIST 'IF (CAR X) (CAR Y) (CAR Z)) (CDR Z)))) (X)))) (X)))) (DEFUN INFIX (I) (LET ((X (CONDITIONAL-INFIX INFIX I))) (IF (CDR X) (ERROR 'UNINFIXD (CDR X)) (CAR X))))
6,603
181
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/isdelegate.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/plinko.h" /** * Matches * * (λ V (F . V) . Q) * * @return F on success, or 0 on mismatch * @note Q is ignored * @note V must be a non-nil atom * @note λ means LAMBDA */ int IsDelegate(int x_) { dword w_; if (x_ >= 0) return 0; w_ = Get(x_); // (λ V (F . V) . Q) int ax_ = LO(w_); int dx_ = HI(w_); if (ax_ != kLambda) return 0; if (dx_ >= 0) return 0; w_ = Get(dx_); // (V (F . V) . Q) int adx_ = LO(w_); int ddx_ = HI(w_); int V = adx_; if (V <= 0) return 0; if (ddx_ >= 0) return 0; w_ = Get(ddx_); // ((F . V) . Q) int addx_ = LO(w_); int dddx_ = HI(w_); if (addx_ >= 0) return 0; w_ = Get(addx_); // (F . V) int aaddx_ = LO(w_); int daddx_ = HI(w_); int F = aaddx_; if (daddx_ != V) return 0; return F; }
2,638
56
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/setup.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/plinko.h" static void SetInput(const char *s) { bp[0] = 0; dx = L' '; strcpy(stpcpy(g_buffer[0], s), " "); } static void Programme(int i, DispatchFn *f, int x) { SetShadow(i, MAKE(EncodeDispatchFn(f), x)); } static void Program(int i, DispatchFn *f) { Programme(i, f, 0); } static void ProgramPrecious(int i) { Program(i, DispatchPrecious); } static void ProgramLookup(int i) { Program(i, DispatchLookup); } static void ProgramIgnore0(int i) { Program(i, DispatchIgnore0); } static void ProgramPlan(int i) { Program(i, DispatchPlan); } void Setup(void) { int i; char buf[4] = "(A)"; SetShadow(-1, DF(DispatchPlan)); SetShadow(0, DF(DispatchPrecious)); SetShadow(+1, DF(DispatchPrecious)); PROG(ProgramPrecious, kEq, "EQ"); PROG(ProgramPrecious, kGc, "GC"); PROG(ProgramPrecious, kCmp, "CMP"); PROG(ProgramPrecious, kCar, "CAR"); PROG(ProgramPrecious, kCdr, "CDR"); PROG(ProgramPrecious, kBeta, "BETA"); PROG(ProgramPrecious, kAtom, "ATOM"); PROG(ProgramPrecious, kCond, "COND"); PROG(ProgramPrecious, kCons, "CONS"); PROG(ProgramPrecious, kRead, "READ"); PROG(ProgramPrecious, kDump, "DUMP"); PROG(ProgramPrecious, kExit, "EXIT"); PROG(ProgramPrecious, kFork, "FORK"); PROG(ProgramPrecious, kQuote, "QUOTE"); PROG(ProgramPrecious, kProgn, "PROGN"); PROG(ProgramPrecious, kMacro, "MACRO"); PROG(ProgramPrecious, kQuiet, "QUIET"); PROG(ProgramPrecious, kError, "ERROR"); PROG(ProgramPrecious, kTrace, "TRACE"); PROG(ProgramPrecious, kPrint, "PRINT"); PROG(ProgramPrecious, kPrinc, "PRINC"); PROG(ProgramPrecious, kFlush, "FLUSH"); PROG(ProgramPrecious, kOrder, "ORDER"); PROG(ProgramPrecious, kGensym, "GENSYM"); PROG(ProgramPrecious, kPprint, "PPRINT"); PROG(ProgramPrecious, kIgnore, "IGNORE"); PROG(ProgramPrecious, kMtrace, "MTRACE"); PROG(ProgramPrecious, kFtrace, "FTRACE"); PROG(ProgramPrecious, kGtrace, "GTRACE"); PROG(ProgramPrecious, kLambda, "LAMBDA"); PROG(ProgramPrecious, kDefine, "DEFINE"); PROG(ProgramPrecious, kExpand, "EXPAND"); PROG(ProgramPrecious, kClosure, "CLOSURE"); PROG(ProgramPrecious, kPartial, "PARTIAL"); PROG(ProgramPrecious, kFunction, "FUNCTION"); PROG(ProgramPrecious, kIntegrate, "INTEGRATE"); PROG(ProgramPrecious, kPrintheap, "PRINTHEAP"); PROG(ProgramPrecious, kImpossible, "IMPOSSIBLE"); PROG(ProgramLookup, kComma, "COMMA_"); PROG(ProgramLookup, kSplice, "SPLICE_"); PROG(ProgramLookup, kBackquote, "BACKQUOTE_"); PROG(ProgramLookup, kString, "STRING_"); PROG(ProgramLookup, kSquare, "SQUARE_"); PROG(ProgramLookup, kCurly, "CURLY_"); PROG(ProgramLookup, kDefun, "DEFUN"); PROG(ProgramLookup, kDefmacro, "DEFMACRO"); PROG(ProgramLookup, kAppend, "APPEND"); PROG(ProgramLookup, kOr, "OR"); PROG(ProgramLookup, kAnd, "AND"); PROG(ProgramLookup, kIntersection, "INTERSECTION"); PROG(ProgramLookup, kList, "LIST"); PROG(ProgramLookup, kMember, "MEMBER"); PROG(ProgramLookup, kNot, "NOT"); PROG(ProgramLookup, kReverse, "REVERSE"); PROG(ProgramLookup, kSqrt, "SQRT"); PROG(ProgramLookup, kSubset, "SUBSET"); PROG(ProgramLookup, kSuperset, "SUPERSET"); PROG(ProgramLookup, kBecause, "BECAUSE"); PROG(ProgramLookup, kTherefore, "THEREFORE"); PROG(ProgramLookup, kUnion, "UNION"); PROG(ProgramLookup, kImplies, "IMPLIES"); PROG(ProgramLookup, kYcombinator, "YCOMBINATOR"); PROG(ProgramLookup, kNand, "NAND"); PROG(ProgramLookup, kNor, "NOR"); PROG(ProgramLookup, kXor, "XOR"); PROG(ProgramLookup, kIff, "IFF"); PROG(ProgramLookup, kCycle, "CYCLE"); PROG(ProgramLookup, kTrench, "𝕋ℝ𝔼ℕℂℍ"); PROG(ProgramLookup, kUnchanged, "ⁿ/ₐ"); PROG(ProgramIgnore0, kIgnore0, "(IGNORE)"); for (i = 0; i < 26; ++i, ++buf[1]) { PROG(ProgramPlan, kConsAlphabet[i], buf); } for (buf[0] = L'A', buf[1] = 0, i = 0; i < 26; ++i, ++buf[0]) { if (buf[0] != 'T') { PROG(ProgramLookup, kAlphabet[i], buf); } else { kAlphabet[i] = 1; } } }
5,896
140
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/histo.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_HISTO_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_HISTO_H_ #include "libc/intrin/bsr.h" #include "libc/macros.internal.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define HISTO(H, X) \ do { \ uint64_t x_ = X; \ x_ = x_ ? _bsrl(x_) + 1 : x_; \ ++H[MIN(x_, ARRAYLEN(H) - 1)]; \ } while (0) void PrintHistogram(int, const char *, const long *, size_t); long GetLongSum(const long *, size_t); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_HISTO_H_ */
636
21
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/binarytrees.lisp
#| plinko - a really fast lisp tarpit | Copyright 2022 Justine Alexandra Roberts Tunney | | Permission to use, copy, modify, and/or distribute this software for | any purpose with or without fee is hereby granted, provided that the | above copyright notice and this permission notice appear in all copies. | | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL | WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED | WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE | AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL | DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR | PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER | TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | PERFORMANCE OF THIS SOFTWARE. |# (DEFUN OCT (X R) (COND (X (OCT (CDR (CDR (CDR X))) (COND ((CAR (CDR (CDR X))) (COND ((CAR (CDR X)) (COND ((CAR X) (CONS '7 R)) ((CONS '6 R)))) ((CAR X) (CONS '5 R)) ((CONS '4 R)))) ((CAR (CDR X)) (COND ((CAR X) (CONS '3 R)) ((CONS '2 R)))) ((CAR X) (CONS '1 R)) ((CDR (CDR (CDR X))) (CONS '0 R)) (R)))) ((CONS '0 R)))) (DEFUN + (A B C) (COND (C (COND (A (COND (B (COND ((CAR A) (COND ((CAR B) (CONS T (+ (CDR A) (CDR B) T))) ((CONS NIL (+ (CDR A) (CDR B) T))))) ((CAR B) (CONS NIL (+ (CDR A) (CDR B) T))) ((CONS T (+ (CDR A) (CDR B)))))) ((CAR A) (CONS NIL (+ (CDR A) NIL T))) ((CONS T (CDR A))))) (B (COND ((CAR B) (CONS NIL (+ NIL (CDR B) T))) ((CONS T (CDR B))))) ((CONS C)))) (A (COND (B (COND ((CAR A) (COND ((CAR B) (CONS NIL (+ (CDR A) (CDR B) T))) ((CONS T (+ (CDR A) (CDR B)))))) ((CAR B) (CONS T (+ (CDR A) (CDR B)))) ((CONS NIL (+ (CDR A) (CDR B)))))) (A))) (B))) (DEFUN ++ (A) (COND ((CAR A) (CONS NIL (++ (CDR A)))) ((CONS T (CDR A))))) (DEFUN MAKE-TREE (DEPTH) (COND (DEPTH (LET ((D (CDR DEPTH))) (CONS (MAKE-TREE D) (MAKE-TREE D)))) ('(NIL NIL)))) (DEFUN CHECK-TREE (N R) (COND ((CAR N) (CHECK-TREE (CDR N) (CHECK-TREE (CAR N) (++ R)))) ((++ R)))) ;; ;; binary trees benchmark game ;; ;; goes 2x faster than python even though it rolls its own arithmetic. ;; ;; goes 2x faster than racket but not sbcl since, since plinko is an ;; ;; interpreter and doesn't jit native instructions currently. ;; (TEST ;; '(0 1 7 7 7 7 7 7 7) ;; (OCT ;; (CHECK-TREE ;; (MAKE-TREE ;; '(NIL NIL NIL NIL NIL NIL NIL ;; NIL NIL NIL NIL NIL NIL NIL ;; NIL NIL NIL NIL NIL NIL NIL))))) ;; use reasonably small size so tests go fast (TEST '(0 3 7 7 7 7 7 7) (OCT (CHECK-TREE (MAKE-TREE '(NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL)))))
3,471
94
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/lib.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ ifeq ($(ARCH), x86_64) PKGS += TOOL_PLINKO_LIB TOOL_PLINKO_LIB_ARTIFACTS += TOOL_PLINKO_LIB_A TOOL_PLINKO_LIB = $(TOOL_PLINKO_LIB_A_DEPS) $(TOOL_PLINKO_LIB_A) TOOL_PLINKO_LIB_A = o/$(MODE)/tool/plinko/lib/plinkolib.a TOOL_PLINKO_LIB_A_FILES := $(filter-out %/.%,$(wildcard tool/plinko/lib/*)) TOOL_PLINKO_LIB_A_HDRS = $(filter %.h,$(TOOL_PLINKO_LIB_A_FILES)) TOOL_PLINKO_LIB_A_SRCS_S = $(filter %.S,$(TOOL_PLINKO_LIB_A_FILES)) TOOL_PLINKO_LIB_A_SRCS_C = $(filter %.c,$(TOOL_PLINKO_LIB_A_FILES)) TOOL_PLINKO_LIB_A_CHECKS = \ $(TOOL_PLINKO_LIB_A_HDRS:%=o/$(MODE)/%.ok) \ $(TOOL_PLINKO_LIB_A).pkg TOOL_PLINKO_LIB_A_SRCS = \ $(TOOL_PLINKO_LIB_A_SRCS_S) \ $(TOOL_PLINKO_LIB_A_SRCS_C) TOOL_PLINKO_LIB_A_OBJS = \ $(TOOL_PLINKO_LIB_A_SRCS_S:%.S=o/$(MODE)/%.o) \ $(TOOL_PLINKO_LIB_A_SRCS_C:%.c=o/$(MODE)/%.o) TOOL_PLINKO_LIB_A_DIRECTDEPS = \ LIBC_CALLS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_LOG \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_SOCK \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ THIRD_PARTY_COMPILER_RT \ THIRD_PARTY_GETOPT TOOL_PLINKO_LIB_A_DEPS := \ $(call uniq,$(foreach x,$(TOOL_PLINKO_LIB_A_DIRECTDEPS),$($(x)))) $(TOOL_PLINKO_LIB_A): \ $(TOOL_PLINKO_LIB_A).pkg \ $(TOOL_PLINKO_LIB_A_OBJS) $(TOOL_PLINKO_LIB_A).pkg: \ $(TOOL_PLINKO_LIB_A_OBJS) \ $(foreach x,$(TOOL_PLINKO_LIB_A_DIRECTDEPS),$($(x)_A).pkg) ifeq ($(MODE),) $(TOOL_PLINKO_LIB_A_OBJS): private OVERRIDE_CFLAGS += -fno-inline endif ifeq ($(MODE),dbg) $(TOOL_PLINKO_LIB_A_OBJS): private OVERRIDE_CFLAGS += -fno-inline endif $(TOOL_PLINKO_LIB_A_OBJS): private OVERRIDE_CFLAGS += -ffast-math -foptimize-sibling-calls -O2 TOOL_PLINKO_LIB_LIBS = $(foreach x,$(TOOL_PLINKO_LIB_ARTIFACTS),$($(x))) TOOL_PLINKO_LIB_SRCS = $(foreach x,$(TOOL_PLINKO_LIB_ARTIFACTS),$($(x)_SRCS)) TOOL_PLINKO_LIB_HDRS = $(foreach x,$(TOOL_PLINKO_LIB_ARTIFACTS),$($(x)_HDRS)) TOOL_PLINKO_LIB_BINS = $(foreach x,$(TOOL_PLINKO_LIB_ARTIFACTS),$($(x)_BINS)) TOOL_PLINKO_LIB_CHECKS = $(foreach x,$(TOOL_PLINKO_LIB_ARTIFACTS),$($(x)_CHECKS)) TOOL_PLINKO_LIB_OBJS = $(foreach x,$(TOOL_PLINKO_LIB_ARTIFACTS),$($(x)_OBJS)) TOOL_PLINKO_LIB_TESTS = $(foreach x,$(TOOL_PLINKO_LIB_ARTIFACTS),$($(x)_TESTS)) endif .PHONY: o/$(MODE)/tool/plinko/lib o/$(MODE)/tool/plinko/lib: $(TOOL_PLINKO_LIB_CHECKS)
2,553
77
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/char.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_CHAR_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_CHAR_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ static inline pureconst bool IsC0(int c) { return (0 <= c && c < 32) || c == 0177; } static inline pureconst bool IsDigit(int c) { return L'0' <= c && c <= L'9'; } static inline pureconst bool IsUpper(int c) { return L'A' <= c && c <= L'Z'; } static inline pureconst bool IsLower(int c) { return L'a' <= c && c <= L'z'; } static inline pureconst bool IsMathAlnum(int c) { return 0x1d400 <= c && c <= 0x1d7ff; } static inline pureconst bool IsControl(int c) { return (0 <= c && c <= 0x1F) || (0x7F <= c && c <= 0x9F); } static noinstrument pureconst inline int ToUpper(int c) { return 'a' <= c && c <= 'z' ? 'A' - 'a' + c : c; } int GetDiglet(int) pureconst; bool IsHex(int) pureconst; bool IsParen(int) pureconst; bool IsSpace(int) pureconst; int GetMonospaceCharacterWidth(int) pureconst; bool IsWide(int) pureconst; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_CHAR_H_ */
1,108
44
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/isycombinator.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/plinko.h" /** * Matches * * (⅄ (λ (N) ((λ (W) (W W)) (λ (V) (N (λ M ((V V) . M)))))) . Q) * * @return true if matches, otherwise false * @note M must be a non-nil atom * @note N must be a non-nil atom * @note Q is ignored * @note V must be a non-nil atom * @note W must be a non-nil atom * @note λ means LAMBDA * @note ⅄ means CLOSURE */ bool IsYcombinator(int x_) { dword w_; if (x_ >= 0) return false; w_ = Get(x_); int ax_ = LO(w_); int dx_ = HI(w_); if (ax_ != kClosure) return false; if (dx_ >= 0) return false; w_ = Get(dx_); // ((λ (N) ((λ (W) (W W)) (λ (V) (N (λ M ((V V) . M)))))) . Q) int adx_ = LO(w_); int ddx_ = HI(w_); if (adx_ >= 0) return false; w_ = Get(adx_); // (λ (N) ((λ (W) (W W)) (λ (V) (N (λ M ((V V) . M)))))) int aadx_ = LO(w_); int dadx_ = HI(w_); if (aadx_ != kLambda) return false; if (dadx_ >= 0) return false; w_ = Get(dadx_); // ((N) ((λ (W) (W W)) (λ (V) (N (λ M ((V V) . M)))))) int adadx_ = LO(w_); int ddadx_ = HI(w_); if (adadx_ >= 0) return false; w_ = Get(adadx_); // (N) int aadadx_ = LO(w_); int dadadx_ = HI(w_); if (ddadx_ >= 0) return false; w_ = Get(ddadx_); // (((λ (W) (W W)) (λ (V) (N (λ M ((V V) . M)))))) int addadx_ = LO(w_); int dddadx_ = HI(w_); int N = aadadx_; if (N <= 0) return false; if (addadx_ >= 0) return false; w_ = Get(addadx_); // ((λ (W) (W W)) (λ (V) (N (λ M ((V V) . M))))) int aaddadx_ = LO(w_); int daddadx_ = HI(w_); if (dadadx_) return false; if (dddadx_) return false; if (aaddadx_ >= 0) return false; w_ = Get(aaddadx_); // (λ (W) (W W)) int aaaddadx_ = LO(w_); int daaddadx_ = HI(w_); if (daddadx_ >= 0) return false; w_ = Get(daddadx_); // ((λ (V) (N (λ M ((V V) . M))))) int adaddadx_ = LO(w_); int ddaddadx_ = HI(w_); if (aaaddadx_ != kLambda) return false; if (adaddadx_ >= 0) return false; w_ = Get(adaddadx_); // (λ (V) (N (λ M ((V V) . M)))) int aadaddadx_ = LO(w_); int dadaddadx_ = HI(w_); if (daaddadx_ >= 0) return false; w_ = Get(daaddadx_); // ((W) (W W)) int adaaddadx_ = LO(w_); int ddaaddadx_ = HI(w_); if (ddaddadx_) return false; if (adaaddadx_ >= 0) return false; w_ = Get(adaaddadx_); // (W) int aadaaddadx_ = LO(w_); int dadaaddadx_ = HI(w_); if (aadaddadx_ != kLambda) return false; if (ddaaddadx_ >= 0) return false; w_ = Get(ddaaddadx_); // ((W W)) int addaaddadx_ = LO(w_); int dddaaddadx_ = HI(w_); if (dadaddadx_ >= 0) return false; w_ = Get(dadaddadx_); // ((V) (N (λ M ((V V) . M)))) int adadaddadx_ = LO(w_); int ddadaddadx_ = HI(w_); int W = aadaaddadx_; if (W <= 0) return false; if (adadaddadx_ >= 0) return false; w_ = Get(adadaddadx_); // (V) int aadadaddadx_ = LO(w_); int dadadaddadx_ = HI(w_); if (addaaddadx_ >= 0) return false; w_ = Get(addaaddadx_); // (W W) int aaddaaddadx_ = LO(w_); int daddaaddadx_ = HI(w_); if (ddadaddadx_ >= 0) return false; w_ = Get(ddadaddadx_); // ((N (λ M ((V V) . M)))) int addadaddadx_ = LO(w_); int dddadaddadx_ = HI(w_); if (dadaaddadx_) return false; int V = aadadaddadx_; if (V <= 0) return false; if (dddaaddadx_) return false; if (addadaddadx_ >= 0) return false; w_ = Get(addadaddadx_); // (N (λ M ((V V) . M))) int aaddadaddadx_ = LO(w_); int daddadaddadx_ = HI(w_); if (aaddaaddadx_ != W) return false; if (dadadaddadx_) return false; if (daddaaddadx_ >= 0) return false; w_ = Get(daddaaddadx_); // (W) int adaddaaddadx_ = LO(w_); int ddaddaaddadx_ = HI(w_); if (dddadaddadx_) return false; if (adaddaaddadx_ != W) return false; if (aaddadaddadx_ != N) return false; if (ddaddaaddadx_) return false; if (daddadaddadx_ >= 0) return false; w_ = Get(daddadaddadx_); // ((λ M ((V V) . M))) int adaddadaddadx_ = LO(w_); int ddaddadaddadx_ = HI(w_); if (adaddadaddadx_ >= 0) return false; w_ = Get(adaddadaddadx_); // (λ M ((V V) . M)) int aadaddadaddadx_ = LO(w_); int dadaddadaddadx_ = HI(w_); if (ddaddadaddadx_) return false; if (aadaddadaddadx_ != kLambda) return false; if (dadaddadaddadx_ >= 0) return false; w_ = Get(dadaddadaddadx_); // (M ((V V) . M)) int adadaddadaddadx_ = LO(w_); int ddadaddadaddadx_ = HI(w_); int M = adadaddadaddadx_; if (M <= 0) return false; if (ddadaddadaddadx_ >= 0) return false; w_ = Get(ddadaddadaddadx_); // (((V V) . M)) int addadaddadaddadx_ = LO(w_); int dddadaddadaddadx_ = HI(w_); if (addadaddadaddadx_ >= 0) return false; w_ = Get(addadaddadaddadx_); // ((V V) . M) int aaddadaddadaddadx_ = LO(w_); int daddadaddadaddadx_ = HI(w_); if (dddadaddadaddadx_) return false; if (aaddadaddadaddadx_ >= 0) return false; w_ = Get(aaddadaddadaddadx_); // (V V) int aaaddadaddadaddadx_ = LO(w_); int daaddadaddadaddadx_ = HI(w_); if (daddadaddadaddadx_ != M) return false; if (aaaddadaddadaddadx_ != V) return false; if (daaddadaddadaddadx_ >= 0) return false; w_ = Get(daaddadaddadaddadx_); // (V) int adaaddadaddadaddadx_ = LO(w_); int ddaaddadaddadaddadx_ = HI(w_); if (adaaddadaddadaddadx_ != V) return false; if (ddaaddadaddadaddadx_) return false; return true; }
7,066
173
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/printchar.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/bsr.h" #include "tool/plinko/lib/char.h" #include "tool/plinko/lib/ktpenc.h" #include "tool/plinko/lib/plinko.h" int PrintChar(int fd, int s) { unsigned c; int d, e, i, n; c = s & 0xffffffff; if (bp[fd] + 6 > sizeof(g_buffer[fd])) Flush(fd); if (c < 0200) { g_buffer[fd][bp[fd]++] = c; if (c == L'\n') Flush(fd); } else { d = c; e = kTpEnc[_bsrl(d) - 7]; i = n = e & 255; do g_buffer[fd][bp[fd] + i--] = 0200 | (d & 077); while (d >>= 6, i); g_buffer[fd][bp[fd]] = d | e >> 8; bp[fd] += n + 1; } return GetMonospaceCharacterWidth(c); }
2,447
43
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/getlongsum.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/limits.h" #include "tool/plinko/lib/histo.h" long GetLongSum(const long *h, size_t n) { long t; size_t i; for (t = i = 0; i < n; ++i) { if (__builtin_add_overflow(t, h[i], &t)) { t = LONG_MAX; break; } } return t; }
2,098
33
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/preplan.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/countbranch.h" #include "libc/runtime/runtime.h" #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/index.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/printf.h" static int CopyTree(int x) { int a, b; if (x >= 0) return x; b = CopyTree(Cdr(x)); a = CopyTree(Car(x)); return Cons(a, b); } static int PreplanCond(int e, int a, int s) { int f, g; if (!(e = Cdr(e))) return 0; if ((f = Car(e)) < 0) { if ((g = Cdr(f)) < 0) { f = List(Preplan(Car(f), a, s), Preplan(Car(g), a, s)); } else { f = Cons(Preplan(Car(f), a, s), 0); } } return Cons(f, PreplanCond(e, a, s)); } static int PreplanList(int e, int a, int s) { if (e >= 0) return e; return Cons(Preplan(Car(e), a, s), PreplanList(Cdr(e), a, s)); } int Preplan(int e, int a, int s) { int f, x; struct qword q; if (e >= 0) return e; f = Car(e); if (f != kQuote) { if (f == kClosure) { /* * (CLOSURE (LAMBDA (X Y) Z) . A) * -1 = ( Z, -0) c[6] * -2 = ( Y, -0) c[5] * -3 = ( X, -2) c[4] * -4 = ( -3, -1) c[3] * -5 = (LAMB, -4) c[2] * -6 = ( -5, A) c[1] * -7 = (CLOS, -5) c[0] */ e = Cons(kClosure, Cons(Preplan(Cadr(e), Cddr(e), 0), Cddr(e))); } else if (f == kCond) { e = Cons(kCond, PreplanCond(e, a, s)); } else if (f == kLambda || f == kMacro) { /* * (LAMBDA (X Y) Z) * -1 = ( Z, -0) l[4] * -2 = ( Y, -0) l[3] * -3 = ( X, -2) l[2] * -4 = ( -3, -1) l[1] * -5 = (LAMB, -4) l[0] */ x = Preplan(Caddr(e), a, Shadow(Cadr(e), s)); x = Cons(x, 0); x = Cons(CopyTree(Cadr(e)), x); e = Cons(f, x); } else { e = PreplanList(e, a, s); } } if (LO(GetShadow(e)) == EncodeDispatchFn(DispatchPlan)) { if ((q = IsIf(e)).ax) { /* x = Cons(LO(q.ax), Cons(HI(q.ax), LO(q.dx))); */ /* * guarantees this order * -1 = ( Z, -0) if[5] * -2 = ( Y, -0) if[4] * -3 = ( X, -2) if[3] * -4 = ( -1, -0) if[2] * -5 = ( -3, -4) if[1] * -6 = (COND, -5) if[0] */ e = Cons(LO(q.dx), 0); e = List3(kCond, List(LO(q.ax), HI(q.ax)), e); SetShadow(e, MAKE(DF(DispatchIf), 0)); } else { SetShadow(e, Plan(e, a, s)); } } return e; }
4,208
110
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/cmp.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/plinko.h" /** * Compares LISP data structures * * (≷ 𝑥 𝑦) ⟹ (⊥) | ⊥ | ⊤ * * Where * * (⊥) means less than a.k.a. -1 * ⊥ means equal a.k.a. 0 * ⊤ means greater than a.k.a. +1 * * The comparison is performed as follows: * * (≷ 𝑥 𝑥) ⟹ ⊥ everything's equal to itself * (≡ 𝑥 𝑦) ⟶ (≡ (≷ 𝑥 𝑦) ⊥) (eq) and (cmp) agree if (eq) returns t * (≡ (≷ 𝑥 𝑦) ⊥) ⟺ (equal 𝑥 𝑦) (cmp) returns eq iff (equal) returns t * (≷ (ℶ x 𝑦) (ℶ x 𝑦)) ⟹ ⊥ i.e. this does deep comparisons * (≷ ⊥ 𝑥) ⟹ (⊥) nil is less than everything non-nil * (≷ 𝑥 ⊥) ⟹ ⊤ comparisons are always symmetric * (≷ 𝑖 𝑗) ⟹ (⊥) atom vs. atom compares unicodes * (≷ 𝑖𝑗 𝑘𝑙) ⟺ (≷ (𝑖 𝑗) (𝑘 𝑙)) atom characters treated like lists * (≷ 𝑖 (x . 𝑦)) ⟹ (⊥) atom vs. cons is always less than * (≷ (x . 𝑦) (x . 𝑦)) ⟹ ⊥ cons vs. cons just recurses * (≷ (𝑥) (⊥ 𝑦)) ⟹ ⊤ e.g. cmp returns gt because 𝑥 > ⊥ * (≷ (𝑥) (𝑧 𝑦)) ⟹ (⊥) e.g. cmp returns lt because ⊥ < (𝑦) * (≷ (x . 𝑦) (x 𝑦)) ⟹ (⊥) e.g. cmp returns lt because 𝑦 < (𝑦) * * @return -1, 0, +1 */ int Cmp(int x, int y) { int c; dword t, u; if (x == y) return 0; if (x > 1 && y > 1) { if (LO(Get(x)) < LO(Get(x))) return -1; if (LO(Get(x)) > LO(Get(x))) return +1; } for (;; x = Cdr(x), y = Cdr(y)) { if (x == y) return 0; if (!x) return -1; if (!y) return +1; if (x < 0) { if (y >= 0) return +1; if ((c = Cmp(Car(x), Car(y)))) return c; } else { if (y < 0) return -1; for (;;) { t = x != 1 ? Get(x) : MAKE(L'T', TERM); u = y != 1 ? Get(y) : MAKE(L'T', TERM); if (LO(t) != LO(u)) { return LO(t) < LO(u) ? -1 : +1; } x = HI(t); y = HI(u); if (x == y) return 0; if (x == TERM) return -1; if (y == TERM) return +1; } if (Car(x) != Car(y)) { return Car(x) < Car(y) ? -1 : +1; } } } }
4,184
85
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/stack.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_STACK_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_STACK_H_ #include "libc/log/check.h" #include "tool/plinko/lib/error.h" #include "tool/plinko/lib/plinko.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define SetFrame(r, x) \ do { \ if (r & NEED_POP) { \ Repush(x); \ } else { \ r |= NEED_POP; \ Push(x); \ } \ } while (0) forceinline dword GetCurrentFrame(void) { DCHECK_GT(sp, 0); return g_stack[(sp - 1) & 0xffffffff]; } forceinline void Push(int x) { unsigned short s = sp; g_stack[s] = MAKE(x, ~cx); if (!__builtin_add_overflow(s, 1, &s)) { sp = s; } else { StackOverflow(); } } forceinline dword Pop(void) { DCHECK_GT(sp, 0); return g_stack[--sp & 0xffffffff]; } forceinline void Repush(int x) { int i; DCHECK_GT(sp, 0); i = (sp - 1) & MASK(STACK); g_stack[i & 0xffffffff] = MAKE(x, HI(g_stack[i & 0xffffffff])); } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_STACK_H_ */
1,129
49
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/pairlis.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/error.h" #include "tool/plinko/lib/plinko.h" int Pairlis(int x, int y, int a) { if (!x) return a; if (x > 0) return Alist(x, y, a); if (y <= 0) { a = pairlis(Cdr(x), Cdr(y), a); return Car(x) ? pairlis(Car(x), Car(y), a) : a; } else { Error("argument structure%n" " want: %S%n" " got: %S", x, y); } }
2,251
36
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/tree.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_TREE_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_TREE_H_ #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/plinko.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int PutTree(int, int, int); int GetTree(int, int); int GetTreeCount(int, int, int *); int Nod(int, int, int, int); forceinline pureconst int Key(int E) { return E < 0 ? Car(E) : E; } forceinline pureconst int Val(int E) { return E < 0 ? Cdr(E) : E; } forceinline pureconst int Ent(int N) { return Car(Car(N)); } forceinline pureconst int Chl(int N) { return Cdr(Car(N)); } forceinline pureconst int Lit(int N) { return Car(Chl(N)); } forceinline pureconst int Rit(int N) { return Cdr(Chl(N)); } forceinline pureconst int Red(int N) { return Cdr(N); } forceinline int Bkn(int N) { return Red(N) ? Cons(Car(N), 0) : N; } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_TREE_H_ */
982
48
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/enclose.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/config.h" #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/error.h" #include "tool/plinko/lib/gc.h" #include "tool/plinko/lib/index.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/printf.h" #include "tool/plinko/lib/stack.h" static void CheckClosureFullyDefined(int e, int a, int s) { int f; Push(e); if (e >= 0) { if (!IsPrecious(e) && !HasAtom(e, s) && !Assoc(e, a)) { Error("crash binding in closure"); } } else if ((f = Car(e)) != kQuote && f != kClosure) { if (f == kLambda || f == kMacro) { CheckClosureFullyDefined(Caddr(e), a, Cons(Cadr(e), s)); } else if (f == kCond) { while ((e = Cdr(e)) < 0) { if ((f = Car(e)) < 0) { CheckClosureFullyDefined(Car(f), a, s); if ((f = Cdr(f)) < 0) { CheckClosureFullyDefined(Car(f), a, s); } } } } else { do { if (e < 0) { CheckClosureFullyDefined(Car(e), a, s); e = Cdr(e); } else { CheckClosureFullyDefined(e, a, s); e = 0; } } while (e); } } Pop(); } static void CheckClosure(int e, int a) { int A; if (DEBUG_CLOSURE && logc) { A = cx; CheckClosureFullyDefined(e, a, 0); MarkSweep(A, 0); } } int Enclose(int e, int a) { int x; dword w; CheckClosure(e, a); return Cons(kClosure, Cons(e, a)); }
3,253
77
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/printint.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "tool/plinko/lib/print.h" #include "tool/plinko/lib/types.h" int PrintInt(int fd, long x, int cols, char quot, char zero, int base, bool issigned) { dword y; char z[32]; int i, j, k, n; DCHECK_LE(base, 36); i = j = 0; y = x < 0 && issigned ? -x : x; do { if (quot && j == 3) z[i++ & 31] = quot, j = 0; z[i++ & 31] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[y % base]; } while (++j, (y /= base)); k = i + (x < 0 && issigned); if (zero) { n = PrintZeroes(fd, +cols - k); } else { n = PrintIndent(fd, +cols - k); } if (x < 0 && issigned) n += PrintChar(fd, L'-'); while (i) n += PrintChar(fd, z[--i & 31]); PrintIndent(fd, -cols - n); return n; }
2,577
46
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/library.lisp
#| plinko - a really fast lisp tarpit | Copyright 2022 Justine Alexandra Roberts Tunney | | Permission to use, copy, modify, and/or distribute this software for | any purpose with or without fee is hereby granted, provided that the | above copyright notice and this permission notice appear in all copies. | | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL | WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED | WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE | AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL | DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR | PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER | TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | PERFORMANCE OF THIS SOFTWARE. |# (DEFINE YCOMBINATOR (LAMBDA (F) ((LAMBDA (G) (G G)) (LAMBDA (G) (F (LAMBDA A ((G G) . A))))))) (DEFINE REVERSE (YCOMBINATOR (LAMBDA (REVERSE) (LAMBDA (X Y) (COND (X (REVERSE (CDR X) (CONS (CAR X) Y))) (Y)))))) (DEFINE COPY (YCOMBINATOR (LAMBDA (COPY) (LAMBDA (X R) (COND ((ATOM X) X) ((CONS (COPY (CAR X)) (COPY (CDR X))))))))) (DEFINE ISPRECIOUS (LAMBDA (X) (COND ((EQ X NIL)) ((EQ X T)) ((EQ X EQ)) ((EQ X CMP)) ((EQ X CAR)) ((EQ X CDR)) ((EQ X BETA)) ((EQ X ATOM)) ((EQ X COND)) ((EQ X CONS)) ((EQ X FORK)) ((EQ X QUOTE)) ((EQ X MACRO)) ((EQ X LAMBDA)) ((EQ X DEFINE)) ((EQ X EXPAND)) ((EQ X CLOSURE)) ((EQ X PARTIAL)) ((EQ X FUNCTION)) ((EQ X INTEGRATE)) ((EQ X GC)) ((EQ X READ)) ((EQ X DUMP)) ((EQ X EXIT)) ((EQ X PROGN)) ((EQ X QUIET)) ((EQ X ERROR)) ((EQ X TRACE)) ((EQ X PRINT)) ((EQ X PRINC)) ((EQ X FLUSH)) ((EQ X GENSYM)) ((EQ X PPRINT)) ((EQ X IGNORE)) ((EQ X MTRACE)) ((EQ X FTRACE)) ((EQ X GTRACE)) ((EQ X PRINTHEAP)) ((EQ X IMPOSSIBLE))))) (DEFINE QUOTH (MACRO (X) (CONS QUOTE (CONS X)))) (DEFINE ISQUOTE (LAMBDA (X) (COND (X (COND ((ATOM X) NIL) ((EQ (CAR X) QUOTE)))) (T)))) (DEFINE QUOTECONS (LAMBDA (A B) (COND ((COND ((ISQUOTE A) (ISQUOTE B))) (CONS QUOTE (CONS (CONS (CAR (CDR A)) (CAR (CDR B)))))) ((CONS CONS (CONS A (COND (B (CONS B))))))))) (DEFINE BACKQUOTER (YCOMBINATOR (LAMBDA (BACKQUOTER) (LAMBDA (X) (COND ((ATOM X) (COND ((ISPRECIOUS X) X) ((CONS QUOTE (CONS X NIL))))) ((EQ (CAR X) 'COMMA_) (CAR (CDR X))) ((COND ((ATOM (CAR X)) NIL) ((EQ (CAR (CAR X)) 'SPLICE_))) (CAR (CDR (CAR X)))) ((QUOTECONS (BACKQUOTER (CAR X)) (BACKQUOTER (CDR X))))))))) (DEFINE CURLY_ QUOTH) (DEFINE STRING_ QUOTH) (DEFINE SQUARE_ QUOTH) (DEFINE BACKQUOTE_ (MACRO (X) (BACKQUOTER X))) (DEFINE > (MACRO (X Y) `(EQ (CMP ,X ,Y) T))) (DEFINE <= (MACRO (X Y) `(EQ (EQ (CMP ,X ,Y) T)))) (DEFINE >= (MACRO (X Y) `(ATOM (CMP ,X ,Y)))) (DEFINE < (MACRO (X Y) `(EQ (ATOM (CMP ,X ,Y))))) (DEFINE NOT (MACRO (P) `(EQ ,P))) (DEFINE IMPLIES ((LAMBDA (IMPLIES) (MACRO A (IMPLIES A))) (YCOMBINATOR (LAMBDA (IMPLIES) (LAMBDA (A) (COND (A `(COND (,(CAR A) ,(COND ((CDR (CDR A)) (IMPLIES (CDR A))) ((CAR (CDR A))))) (T))) (T))))))) (DEFINE AND ((LAMBDA (AND) (MACRO A (IMPLIES A (AND A)))) (YCOMBINATOR (LAMBDA (AND) (LAMBDA (A) (COND ((CDR A) (CONS COND (CONS (CONS (CAR A) (CONS (AND (CDR A))))))) ((CAR A)))))))) (DEFINE OR ((LAMBDA (OR) (MACRO A (COND (A (COND ((CDR A) (CONS COND (OR A))) ((CAR A))))))) (YCOMBINATOR (LAMBDA (OR) (LAMBDA (A) (COND (A (CONS (CONS (CAR A)) (OR (CDR A)))))))))) (DEFINE IFF (MACRO (P Q) ((LAMBDA (S) `((LAMBDA (,S) (COND (,P ,S) (,S NIL) (T))) ,Q)) (GENSYM)))) (DEFINE ISUPPER (AND (>= 'A) (<= 'Z))) (DEFINE ISLOWER (AND (>= "A") (<= "Z"))) (DEFINE CONDISTRIVIAL (YCOMBINATOR (LAMBDA (CONDISTRIVIAL) (LAMBDA (ISTRIVIAL) (LAMBDA (X) (OR (EQ X) (AND (AND (ISTRIVIAL (CAR (CAR X))) (OR (EQ (CDR (CAR X))) (ISTRIVIAL (CAR (CDR (CAR X)))))) ((CONDISTRIVIAL ISTRIVIAL) (CDR X))))))))) (DEFINE ISTRIVIAL (YCOMBINATOR (LAMBDA (ISTRIVIAL) (LAMBDA (X) (COND ((ATOM X)) ((EQ (CAR X) QUOTE)) ((OR (EQ (CAR X) CAR) (EQ (CAR X) CDR) (EQ (CAR X) ATOM)) (ISTRIVIAL (CAR (CDR X)))) ((OR (EQ (CAR X) EQ) (EQ (CAR X) CMP)) (AND (ISTRIVIAL (CAR (CDR X))) (ISTRIVIAL (CAR (CDR (CDR X)))))) ((EQ (CAR X) COND) ((CONDISTRIVIAL ISTRIVIAL) (CDR X)))))))) (DEFINE EQUAL ((LAMBDA (EQUAL) (MACRO X (COND ((NOT X) (ERROR '(NEED ARGUMENTS))) ((NOT (CDR X)) `(EQ ,(CAR X))) ((NOT (CDR (CDR X))) `(EQ (CMP ,(CAR X) ,(CAR (CDR X))))) ((ATOM (CAR X)) (EQUAL (CAR X) (CDR X))) (((LAMBDA (S) `((LAMBDA (,S) ,(EQUAL S (CDR X))) ,(CAR X))) (GENSYM)))))) (YCOMBINATOR (LAMBDA (EQUAL) (LAMBDA (S X) (COND ((CDR X) `(COND ((EQ (CMP ,S ,(CAR X))) ,(EQUAL S (CDR X))))) (`(EQ (CMP ,S ,(CAR X)))))))))) (DEFINE LIST (LAMBDA A A)) (DEFINE IF (MACRO (X A B) (COND (B `(COND (,X ,A) (,B))) ((ERROR (LIST (LIST 'CONSIDER (LIST 'AND X A)) (LIST 'INSTEAD 'OF (LIST 'IF X A)))))))) (DEFINE CURRY (LAMBDA (F X) (LAMBDA A (F X . A)))) (DEFINE APPEND (LAMBDA (X Y) (COND (Y ((LAMBDA (F) (F F X)) (LAMBDA (F X) (COND (X (CONS (CAR X) (F F (CDR X)))) (Y))))) (X)))) (DEFINE -APPEND (YCOMBINATOR (LAMBDA (-APPEND) (LAMBDA (Y X) (COND (X (CONS (CAR X) (-APPEND Y (CDR X)))) (Y)))))) (DEFINE APPEND (LAMBDA (X Y) (COND (Y (-APPEND Y X)) (X)))) (DEFINE KEEP (LAMBDA (X Y) (COND ((EQUAL X Y) X) (Y)))) (DEFINE PEEL (LAMBDA (X Y) (COND ((EQUAL X (CAR Y)) Y) ((CONS X Y))))) (DEFINE AKEYS (YCOMBINATOR (LAMBDA (AKEYS) (LAMBDA (X) (COND (X (CONS (CAR (CAR X)) (AKEYS (CDR X))))))))) (DEFINE EVAL (LAMBDA (X A) ((CONS CLOSURE (CONS (CONS LAMBDA (CONS () (CONS X))) A))))) (DEFINE HASATOM (YCOMBINATOR (LAMBDA (HASATOM) (LAMBDA (V Z) (COND ((EQ V Z)) ((ATOM Z) NIL) ((HASATOM V (CAR Z))) ((HASATOM V (CDR Z)))))))) (DEFINE COND-FREEVARS (YCOMBINATOR (LAMBDA (COND-FREEVARS) (LAMBDA (FREEVARS X R S) (COND ((ATOM X) R) ((COND-FREEVARS FREEVARS (CDR X) (FREEVARS (CAR (CAR X)) (COND ((CDR (CAR X)) (FREEVARS (CAR (CDR (CAR X))) R S)) (R)) S) S))))))) (DEFINE LIST-FREEVARS (YCOMBINATOR (LAMBDA (LIST-FREEVARS) (LAMBDA (FREEVARS X R S) (COND ((ATOM X) (FREEVARS X R S)) (((LAMBDA (Y) (LIST-FREEVARS FREEVARS (CDR X) Y S)) (FREEVARS (CAR X) R S)))))))) (DEFINE FREEVARS (YCOMBINATOR (LAMBDA (FREEVARS) (LAMBDA (X R S) (COND ((ATOM X) (COND ((ISPRECIOUS X) R) ((HASATOM X S) R) ((CONS X R)))) ((EQ (CAR X) QUOTE) R) ((EQ (CAR X) CLOSURE) R) ((EQ (CAR X) LAMBDA) (FREEVARS (CAR (CDR (CDR X))) R (CONS (CAR (CDR X)) S))) ((EQ (CAR X) COND) (COND-FREEVARS FREEVARS (CDR X) R S)) ((LIST-FREEVARS FREEVARS X R S))))))) (DEFINE DEFUN (MACRO (F A B) (COND ((HASATOM F (FREEVARS B)) `(DEFINE ,F (YCOMBINATOR (LAMBDA (,F) (LAMBDA ,A ,B))))) (`(DEFINE ,F (LAMBDA ,A ,B)))))) (DEFINE DEFMACRO (MACRO (F A B) (COND ((HASATOM F (FREEVARS B)) `(DEFINE ,F (MACRO A ((YCOMBINATOR (LAMBDA (,F) (LAMBDA ,A ,B))) . A)))) (`(DEFINE ,F (MACRO ,A ,B)))))) (DEFUN -REQUIRED (XS) (ERROR 'PARAMETER (LIST XS) 'IS 'REQUIRED)) (DEFMACRO REQUIRED (X) `(COND (,X) ((-REQUIRED ',X)))) (DEFUN -TEST1 (X XS) (OR (EQ X T) (ERROR (LIST (LIST 'ERROR (LIST 'TEST XS)) (LIST 'WANT T) (LIST 'GOT X))))) (DEFUN -TEST2 (X XS Y YS) (OR (EQUAL X Y) (IF (EQUAL X XS) (ERROR (LIST (LIST 'ERROR 'FAILED (LIST 'TEST XS YS)) (LIST 'WANT X) (LIST 'GOT Y))) (ERROR (LIST (LIST 'ERROR 'FAILED (LIST 'TEST XS YS)) (LIST 'GOT Y)))))) (DEFMACRO TEST A (COND ((EQ A) (ERROR '(NEED ARGUMENTS))) ((EQ (CDR A)) `(IGNORE (-TEST1 (QUIET ,(CAR A)) ',(CAR A)))) ((EQ (CDR (CDR A))) `(IGNORE (-TEST2 (QUIET ,(CAR A)) ',(CAR A) (QUIET ,(CAR (CDR A))) ',(CAR (CDR A))))) ((EQ A) (ERROR '(TOO MANY ARGUMENTS))))) (DEFMACRO ASSERT (A) `(PROGN (-TEST T ,A T ',A) NIL)) (DEFUN MEMBER (X Y) (COND (Y (COND ((EQUAL X (CAR Y)) Y) ((MEMBER X (CDR Y))))))) (DEFUN SUBSET (X Y) (IMPLIES X (AND (MEMBER (CAR X) Y) (SUBSET (CDR X) Y)))) (DEFUN INTERSECTION (X Y) (AND X (OR (AND (CAR X) (MEMBER (CAR X) Y) (INTERSECTION (CDR X) Y)) (INTERSECTION (CDR X) Y)))) (DEFUN UNION (X Y) (COND (X (COND ((MEMBER (CAR X) Y) (UNION (CDR X) Y)) ((CONS (CAR X) (UNION (CDR X) Y))))) (Y))) (DEFUN AKEYS (X) (COND (X (CONS (CAR (CAR X)) (AKEYS (CDR X)))))) (DEFUN AVALS (X) (COND (X (CONS (CAR (CDR (CAR X))) (AVALS (CDR X)))))) (DEFMACRO CAAR (X) `(CAR (CAR ,X))) (DEFMACRO CADR (X) `(CAR (CDR ,X))) (DEFMACRO CDAR (X) `(CDR (CAR ,X))) (DEFMACRO CDDR (X) `(CDR (CDR ,X))) (DEFMACRO CAAAR (X) `(CAR (CAR (CAR ,X)))) (DEFMACRO CAADR (X) `(CAR (CAR (CDR ,X)))) (DEFMACRO CADAR (X) `(CAR (CDR (CAR ,X)))) (DEFMACRO CADDR (X) `(CAR (CDR (CDR ,X)))) (DEFMACRO CDAAR (X) `(CDR (CAR (CAR ,X)))) (DEFMACRO CDADR (X) `(CDR (CAR (CDR ,X)))) (DEFMACRO CDDAR (X) `(CDR (CDR (CAR ,X)))) (DEFMACRO CDDDR (X) `(CDR (CDR (CDR ,X)))) (DEFMACRO CAAAAR (X) `(CAR (CAR (CAR (CAR ,X))))) (DEFMACRO CAAADR (X) `(CAR (CAR (CAR (CDR ,X))))) (DEFMACRO CAADAR (X) `(CAR (CAR (CDR (CAR ,X))))) (DEFMACRO CAADDR (X) `(CAR (CAR (CDR (CDR ,X))))) (DEFMACRO CADAAR (X) `(CAR (CDR (CAR (CAR ,X))))) (DEFMACRO CADADR (X) `(CAR (CDR (CAR (CDR ,X))))) (DEFMACRO CADDAR (X) `(CAR (CDR (CDR (CAR ,X))))) (DEFMACRO CADDDR (X) `(CAR (CDR (CDR (CDR ,X))))) (DEFMACRO CDAAAR (X) `(CDR (CAR (CAR (CAR ,X))))) (DEFMACRO CDAADR (X) `(CDR (CAR (CAR (CDR ,X))))) (DEFMACRO CDADAR (X) `(CDR (CAR (CDR (CAR ,X))))) (DEFMACRO CDADDR (X) `(CDR (CAR (CDR (CDR ,X))))) (DEFMACRO CDDAAR (X) `(CDR (CDR (CAR (CAR ,X))))) (DEFMACRO CDDADR (X) `(CDR (CDR (CAR (CDR ,X))))) (DEFMACRO CDDDAR (X) `(CDR (CDR (CDR (CAR ,X))))) (DEFMACRO CDDDDR (X) `(CDR (CDR (CDR (CDR ,X))))) (DEFMACRO CADDDDR (X) `(CAR (CDR (CDR (CDR (CDR ,X)))))) (DEFUN ISCONST (P) (COND ((EQ P NIL)) ((EQ P T)))) (DEFMACRO NAND (P Q) (COND ((COND ((ISCONST P) (ISCONST Q))) (IMPLIES P (IMPLIES Q NIL))) (`(IMPLIES ,P (IMPLIES ,Q NIL))))) (DEFMACRO XOR (P Q) (COND ((COND ((ISCONST P) (ISCONST Q))) (COND (P (NOT Q)) (Q))) (P `((LAMBDA (A B) (COND (A (COND (B NIL) (A))) (B (COND (A NIL) (B))))) ,P ,Q)))) (DEFMACRO LET (VARS EXPR) `((LAMBDA ,(AKEYS VARS) ,EXPR) ,@(AVALS VARS))) (DEFMACRO LET* (((A B) . C) E) (IF A `((LAMBDA (,A) ,(LET* C E)) ,B) E)) (DEFUN LAST (X R) (IF X (LAST (CDR X) (CAR X)) R)) (DEFUN ASSOC (X Y D) (AND Y (IF (EQUAL X (CAR (CAR Y))) (CAR Y) (ASSOC X (CDR Y))))) (DEFUN ADDSET (X Y) (IF (MEMBER X Y) Y (CONS X Y))) (DEFUN REVERSE-MAPCAR (F X C R) (IF X (REVERSE-MAPCAR F (CDR X) C ((OR C CONS) (F (CAR X)) R)) R)) (DEFUN MAPCAR (F X) (AND X (CONS (F (CAR X)) (MAPCAR F (CDR X))))) (DEFUN MAPSET (F X R) (IF X (MAPSET F (CDR X) (ADDSET (F (CAR X)) R)) (REVERSE R))) (DEFINE REDUCE ((LAMBDA (G) (LAMBDA (F X) (IF (CDR X) (G F (CDR X) (CAR X)) (CAR X)))) (YCOMBINATOR (LAMBDA (G) (LAMBDA (F X A) (IF X (G F (CDR X) (F A (CAR X))) A)))))) (DEFUN ALL (X) (IMPLIES X (REDUCE AND X))) (DEFUN ANY (X) (REDUCE OR X)) (DEFUN PAIRWISE (X R) (IF X (PAIRWISE (CDDR X) (CONS (CONS (CAR X) (CADR X)) R)) (REVERSE R))) (DEFMACRO DOLIST ((A B) F) `(MAPCAR (LAMBDA (,A) ,F) ,B)) (DEFMACRO REVERSE-DOLIST ((A B C R) F) `(REVERSE-MAPCAR (LAMBDA (,A) ,F) ,B ,C ,R)) (DEFUN PAIRLIS (X Y A) (COND ((EQ X) A) ((ATOM X) (CONS (CONS X (CONS Y)) A)) ((ATOM Y) (ERROR '(ARGUMENT STRUCTURE) X Y)) ((LET ((A (PAIRLIS (CDR X) (CDR Y) A))) (COND ((CAR X) (PAIRLIS (CAR X) (CAR Y) A)) (A)))))) (DEFUN JOIN (S X) (COND ((EQ X) NIL) ((EQ (CDR X) NIL) (CONS (CAR X))) ((CONS (CAR X) (CONS S (JOIN S (CDR X))))))) (DEFUN GETVAR (V A) (AND A (COND ((EQ V (CAAR A)) (CAR A)) ((GETVAR V (CDR A)))))) (DEFUN GROUPBY (F X K G R) (IF X (LET ((J (F (CAR X)))) (IF (EQUAL J K) (GROUPBY F (CDR X) K (CONS (CAR X) G) R) (GROUPBY F (CDR X) J (CONS (CAR X)) (OR (AND G (CONS (CONS K (REVERSE G)) R)) R)))) (REVERSE (OR (AND G (CONS (CONS K (REVERSE G)) R)) R))))
15,327
571
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/makesclosures.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/plinko.h" bool MakesClosures(int x) { int h; if (x < 0 && (h = Car(x)) != kQuote && h != kClosure) { if (h == kMacro) return true; if (h == kLambda) return true; if (h == kCond) { while ((x = Cdr(x)) < 0) { if ((h = Car(x)) < 0) { if (MakesClosures(Car(h))) return true; if ((h = Cdr(h)) < 0) { if (MakesClosures(Car(h))) return true; } } } } else { while (x) { if (x < 0) { h = Car(x); x = Cdr(x); } else { h = x; x = 0; } MakesClosures(h); } } } return false; }
2,509
50
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/evlis.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/plinko.h" int Evlis(int x, int a, dword p1, dword p2) { if (!x) return x; if (x > 0) return FasterRecurse(x, a, p1, p2); int y = FasterRecurse(Car(x), a, p1, p2); return Cons(y, Evlis(Cdr(x), a, p1, p2)); }
2,112
28
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/index.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_INDEX_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_INDEX_H_ #include "tool/plinko/lib/error.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/stack.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ forceinline nosideeffect int Head(int x) { if (x <= 0) return LO(Get(x)); Push(x); Raise(kCar); } forceinline nosideeffect int Tail(int x) { if (x <= 0) return HI(Get(x)); Push(x); Raise(kCdr); } forceinline nosideeffect int Cadr(int x) { return Head(Tail(x)); } forceinline nosideeffect int Caddr(int x) { return Head(Tail(Tail(x))); } static inline nosideeffect int Caar(int X) { return Head(Head(X)); } static inline nosideeffect int Cdar(int X) { return Tail(Head(X)); } static inline nosideeffect int Cddr(int X) { return Tail(Tail(X)); } static inline nosideeffect int Caaar(int X) { return Head(Head(Head(X))); } static inline nosideeffect int Caadr(int X) { return Head(Head(Tail(X))); } static inline nosideeffect int Cadar(int X) { return Head(Tail(Head(X))); } static inline nosideeffect int Cdaar(int X) { return Tail(Head(Head(X))); } static inline nosideeffect int Cdadr(int X) { return Tail(Head(Tail(X))); } static inline nosideeffect int Cddar(int X) { return Tail(Tail(Head(X))); } static inline nosideeffect int Cdddr(int X) { return Tail(Tail(Tail(X))); } static inline nosideeffect int Caaaar(int X) { return Head(Head(Head(Head(X)))); } static inline nosideeffect int Caaadr(int X) { return Head(Head(Head(Tail(X)))); } static inline nosideeffect int Caadar(int X) { return Head(Head(Tail(Head(X)))); } static inline nosideeffect int Caaddr(int X) { return Head(Head(Tail(Tail(X)))); } static inline nosideeffect int Cadaar(int X) { return Head(Tail(Head(Head(X)))); } static inline nosideeffect int Cadadr(int X) { return Head(Tail(Head(Tail(X)))); } static inline nosideeffect int Caddar(int X) { return Head(Tail(Tail(Head(X)))); } static inline nosideeffect int Cadddr(int X) { return Head(Tail(Tail(Tail(X)))); } static inline nosideeffect int Cdaaar(int X) { return Tail(Head(Head(Head(X)))); } static inline nosideeffect int Cdaadr(int X) { return Tail(Head(Head(Tail(X)))); } static inline nosideeffect int Cdadar(int X) { return Tail(Head(Tail(Head(X)))); } static inline nosideeffect int Cdaddr(int X) { return Tail(Head(Tail(Tail(X)))); } static inline nosideeffect int Cddaar(int X) { return Tail(Tail(Head(Head(X)))); } static inline nosideeffect int Cddadr(int X) { return Tail(Tail(Head(Tail(X)))); } static inline nosideeffect int Cdddar(int X) { return Tail(Tail(Tail(Head(X)))); } static inline nosideeffect int Cddddr(int X) { return Tail(Tail(Tail(Tail(X)))); } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_INDEX_H_ */
2,879
136
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/readstring.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/build/lib/case.h" #include "tool/plinko/lib/char.h" #include "tool/plinko/lib/plinko.h" int ReadString(int fd, unsigned x) { int i, n, y, z; ax = y = TERM; if (x == L'"') { dx = ReadByte(fd); return ax; } else { z = ReadByte(fd); if (x == L'\\') { x = z; z = ReadByte(fd); switch (x) { CASE(L'a', x = L'\a'); CASE(L'b', x = L'\b'); CASE(L'e', x = 00033); CASE(L'f', x = L'\f'); CASE(L'n', x = L'\n'); CASE(L'r', x = L'\r'); CASE(L't', x = L'\t'); CASE(L'v', x = L'\v'); case L'x': n = 2; goto ReadHexEscape; case L'u': n = 4; goto ReadHexEscape; case L'U': n = 8; goto ReadHexEscape; default: if (IsDigit(x)) { x = GetDiglet(x); for (i = 0; IsDigit(z) && i < 2; ++i) { x *= 8; x += GetDiglet(z); z = ReadByte(fd); } } break; ReadHexEscape: for (x = i = 0; IsHex(z) && i < n; ++i) { x *= 16; x += GetDiglet(z); z = ReadByte(fd); } break; } } y = ReadString(fd, z); } return Intern(x, y); }
3,139
75
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/desymbolize.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/build/lib/case.h" #include "tool/plinko/lib/plinko.h" pureconst int Desymbolize(int c) { return -1; switch (c) { CASE(L'⊥', return 0); CASE(L'⊤', return 1); CASE(L'≡', return kEq); CASE(L'⍅', return kCar); CASE(L'⊷', return kCar); CASE(L'⍆', return kCdr); CASE(L'⊶', return kCdr); CASE(L'α', return kAtom); CASE(L'ζ', return kCond); CASE(L'ℶ', return kCons); CASE(L'β', return kBeta); CASE(L'ψ', return kMacro); CASE(L'λ', return kLambda); CASE(L'⅄', return kClosure); CASE(L'∂', return kPartial); CASE(L'║', return kAppend); CASE(L'≷', return kCmp); CASE(L'∧', return kAnd); CASE(L'∨', return kOr); CASE(L'⋔', return kFork); CASE(L'Λ', return kDefun); CASE(L'≝', return kDefine); CASE(L'ə', return kExpand); CASE(L'Ψ', return kDefmacro); CASE(L'𝑓', return kFunction); CASE(L'∫', return kIntegrate); CASE(L'∅', return kImpossible); CASE(L'𝕐', return kYcombinator); CASE(L'∩', return kIntersection); CASE(L'ℒ', return kList); CASE(L'∊', return kMember); CASE(L'¬', return kNot); CASE(L'Ω', return kQuote); CASE(L'Я', return kReverse); CASE(L'√', return kSqrt); CASE(L'⊂', return kSubset); CASE(L'⊃', return kSuperset); CASE(L'∵', return kBecause); CASE(L'∴', return kTherefore); CASE(L'∪', return kUnion); CASE(L'⟶', return kImplies); CASE(L'⊼', return kNand); CASE(L'⊽', return kNor); CASE(L'⊻', return kXor); CASE(L'⟺', return kIff); CASE(L'⟳', return kCycle); CASE(L'⊙', return kOrder); default: return -1; } }
3,555
76
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/trace.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_TRACE_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_TRACE_H_ #include "libc/str/str.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define START_TRACE \ bool t; \ PairFn *pf; \ BindFn *bf; \ EvlisFn *ef; \ RecurseFn *rf; \ unsigned char mo; \ TailFn *tails[8]; \ EvalFn *ev, *ex; \ memcpy(tails, kTail, sizeof(kTail)); \ ev = eval; \ bf = bind_; \ ef = evlis; \ ex = expand; \ pf = pairlis; \ rf = recurse; \ EnableTracing(); \ t = trace; \ trace = true #define END_TRACE \ trace = t; \ eval = ev; \ bind_ = bf; \ evlis = ef; \ expand = ex; \ pairlis = pf; \ recurse = rf; \ memcpy(kTail, tails, sizeof(kTail)) void EnableTracing(void); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_TRACE_H_ */
1,277
42
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/plinko.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_PLINKO_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_PLINKO_H_ #include "libc/limits.h" #include "libc/log/check.h" #include "libc/runtime/runtime.h" #include "tool/plinko/lib/config.h" #include "tool/plinko/lib/types.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #define LO(x) (int)(x) #define HI(x) (int)((x) >> 32) #define MASK(x) ((x)-1u) #define ROR(x, k) ((unsigned)(x) >> k | ((unsigned)(x) << (32 - k))) #define MAKE(l, h) (((unsigned)(l)) | (dword)(h) << 32) #define SHAD(i) g_dispatch[(i) & (BANE | MASK(BANE))] #define DF(f) EncodeDispatchFn(f) #define CAR(x) LO(Get(x)) #define CDR(x) HI(Get(x)) #define ARG1(e) Cadr(e) #define __(c) (assert(IsUpper(c)), kAlphabet[c - 'A']) #define _(s) __(STRINGIFY(s)[0]) #define ZERO4 MAKE4(0, 0, 0, 0) #define MAKE4(a, b, c, d) \ (struct qword) { \ MAKE(a, b), MAKE(c, d) \ } #define Equal(x, y) !Cmp(x, y) #define RESTORE(s) s = save_##s #define SAVE(s, x) \ typeof(s) save_##s = s; \ s = x #define PROG(d, k, s) \ SetInput(s); \ k = Read(0); \ d(k) #define GetFrameCx() ~HI(GetCurrentFrame()) #define GetDispatchFn(x) DecodeDispatchFn(GetShadow(x)) #define DecodeDispatchFn(x) ((DispatchFn *)(uintptr_t)(unsigned)(x)) #define GetShadow(i) \ ((__seg_fs const dword *)((uintptr_t)g_mem))[(i) & (BANE | MASK(BANE))] struct T { int res; }; struct Binding { int u; dword p1; }; typedef int EvalFn(int, int); typedef int PairFn(int, int, int); typedef int RecurseFn(dword, dword, dword); typedef struct T RetFn(dword, dword, dword); typedef int EvlisFn(int, int, dword, dword); typedef struct Binding BindFn(int, int, int, int, dword, dword); typedef struct T TailFn(dword, dword, dword, dword, dword); typedef struct T DispatchFn(dword, dword, dword, dword, dword, dword); typedef int ForceIntTailDispatchFn(dword, dword, dword, dword, dword, dword); BindFn Bind, BindTrace; RecurseFn RecurseTrace; EvlisFn Evlis, EvlisTrace; PairFn Pairlis, PairlisTrace; EvalFn Eval, EvalTrace, ExpandTrace, Exlis; TailFn DispatchTail, DispatchTailGc, DispatchTailTmcGc; TailFn DispatchTailTrace, DispatchTailGcTrace, DispatchTailTmcGcTrace; DispatchFn DispatchNil, DispatchTrue, DispatchPlan, DispatchQuote, DispatchLookup, DispatchBuiltin, DispatchFuncall, DispatchRecursive, DispatchYcombine, DispatchPrecious, DispatchIgnore0, DispatchAdd, DispatchShortcut, DispatchCar, DispatchCdr, DispatchAtom, DispatchEq, DispatchCmp, DispatchOrder, DispatchLambda, DispatchCond, DispatchCons, DispatchProgn, DispatchQuiet, DispatchTrace, DispatchFtrace, DispatchFunction, DispatchBeta, DispatchGensym, DispatchPrinc, DispatchPrintheap, DispatchGc, DispatchFlush, DispatchError, DispatchExit, DispatchRead, DispatchIdentity, DispatchLet, DispatchLet1, DispatchLet2, DispatchIgnore1, DispatchExpand, DispatchPprint, DispatchPrint, DispatchEnclosedLetegatinator, DispatchEnclosedLetegate, DispatchIf, DispatchCall1, DispatchCall2; DispatchFn DispatchEnclosedLet, DispatchCaar, DispatchCadr, DispatchCdar, DispatchCddr, DispatchCaaar, DispatchCaadr, DispatchCadar, DispatchCaddr, DispatchCdaar, DispatchCdadr, DispatchCddar, DispatchCdddr, DispatchCaaaar, DispatchCaaadr, DispatchCaadar, DispatchCaaddr, DispatchCadaar, DispatchCadadr, DispatchCaddar, DispatchCadddr, DispatchCdaaar, DispatchCdaadr, DispatchCdadar, DispatchCdaddr, DispatchCddaar, DispatchCddadr, DispatchCdddar, DispatchCddddr; #ifndef __llvm__ register dword cGets asm("r12"); register dword *g_mem asm("rbx"); #else extern dword cGets; extern dword *g_mem; #endif extern unsigned short sp; extern bool loga; extern bool logc; extern bool dump; extern bool quiet; extern bool stats; extern bool simpler; extern bool trace; extern bool ftrace; extern bool mtrace; extern bool gtrace; extern bool noname; extern bool literally; extern bool symbolism; extern int cHeap; extern int cAtoms; extern int cFrost; extern int globals; extern int revglob; extern int ordglob; extern int ax; extern int cx; extern int dx; extern int ex; extern int pdp; extern int bp[4]; extern int fails; extern int depth; extern int kTrace; extern int kMtrace; extern int kFtrace; extern int kGtrace; extern int kEq; extern int kGc; extern int kCmp; extern int kCar; extern int kBackquote; extern int kDefun; extern int kDefmacro; extern int kAppend; extern int kBeta; extern int kAnd; extern int kCdr; extern int kRead; extern int kDump; extern int kQuote; extern int kProgn; extern int kLambda; extern int kDefine; extern int kMacro; extern int kQuiet; extern int kSplice; extern int kPrinc; extern int kPrint; extern int kPprint; extern int kIgnore; extern int kExpand; extern int kCond; extern int kAtom; extern int kOr; extern int kCons; extern int kIntegrate; extern int kString; extern int kSquare; extern int kCurly; extern int kFork; extern int kGensym; extern int kTrench; extern int kYcombinator; extern int kBecause; extern int kTherefore; extern int kUnion; extern int kImplies; extern int kNand; extern int kNor; extern int kXor; extern int kIff; extern int kPartial; extern int kError; extern int kExit; extern int kClosure; extern int kFunction; extern int kCycle; extern int kFlush; extern int kIgnore0; extern int kComma; extern int kIntersection; extern int kList; extern int kMember; extern int kNot; extern int kReverse; extern int kSqrt; extern int kSubset; extern int kSuperset; extern int kPrintheap; extern int kImpossible; extern int kUnchanged; extern int kOrder; extern jmp_buf crash; extern jmp_buf exiter; extern RetFn *const kRet[8]; extern char g_buffer[4][512]; extern unsigned short g_depths[128][3]; extern dword tick; extern dword cSets; extern dword *g_dis; extern EvalFn *eval; extern BindFn *bind_; extern char **inputs; extern EvalFn *expand; extern EvlisFn *evlis; extern PairFn *pairlis; extern TailFn *kTail[8]; extern RecurseFn *recurse; extern int g_copy[256]; extern int g_print[256]; extern int kAlphabet[26]; extern dword g_stack[STACK]; extern int kConsAlphabet[26]; extern long g_assoc_histogram[12]; extern long g_gc_lop_histogram[30]; extern long g_gc_marks_histogram[30]; extern long g_gc_dense_histogram[30]; extern long g_gc_sparse_histogram[30]; extern long g_gc_discards_histogram[30]; bool HasAtom(int, int) nosideeffect; bool IsConstant(int) pureconst; bool IsYcombinator(int); bool MakesClosures(int); dword Plan(int, int, int); int Assoc(int, int); int Cmp(int, int); int CountAtoms(int, int, int) nosideeffect; int CountReferences(int, int, int); int CountSimpleArguments(int) nosideeffect; int CountSimpleParameters(int) nosideeffect; int Define(int, int); int DumpDefines(int, int, int); int Desymbolize(int) pureconst; int Enclose(int, int); int Expand(int, int); int FindFreeVariables(int, int, int); int Intern(int, int); int IsCar(int); int IsCdr(int); int IsDelegate(int); int Plinko(int, char *[]); int Preplan(int, int, int); int Read(int); int ReadByte(int); int ReadChar(int); int ReadSpaces(int); int ReadString(int, unsigned); int Reverse(int, int); int Symbolize(int) pureconst; struct qword IsIf(int); void Flush(int); void PlanFuncalls(int, dword, int); void Setup(void); forceinline dword Get(int i) { #ifndef NDEBUG DCHECK_LT(i, TERM); #endif ++cGets; return g_mem[i & (BANE | MASK(BANE))]; } forceinline int Car(int i) { #ifndef NDEBUG DCHECK_LE(i, 0); #endif return LO(Get(i)); } forceinline int Cdr(int i) { #ifndef NDEBUG DCHECK_LE(i, 0); #endif return HI(Get(i)); } forceinline unsigned EncodeDispatchFn(DispatchFn *f) { DCHECK_LE((uintptr_t)f, UINT_MAX); return (uintptr_t)f; } forceinline pureconst bool IsPrecious(int x) { return LO(GetShadow(x)) == EncodeDispatchFn(DispatchPrecious); } forceinline pureconst bool IsVariable(int x) { return LO(GetShadow(x)) == EncodeDispatchFn(DispatchLookup); } forceinline nosideeffect void *Addr(int i) { return g_mem + (i & (BANE | MASK(BANE))); } forceinline struct T Ret(dword ea, dword tm, dword r) { return kRet[r](ea, tm, r); } static inline int FasterRecurse(int v, int a, dword p1, dword p2) { if (v == LO(p1)) return HI(p1); if (v == LO(p2)) return HI(p2); /* if (IsPrecious(v)) return v; */ /* if (v < 0 && Car(v) == kQuote) return Car(Cdr(v)); */ return recurse(MAKE(v, a), p1, p2); } forceinline int Recurse(dword ea, dword p1, dword p2) { return ((ForceIntTailDispatchFn *)GetDispatchFn(LO(ea)))(ea, 0, 0, p1, p2, GetShadow(LO(ea))); } forceinline struct T TailCall(dword ea, dword tm, dword r, dword p1, dword p2) { return kTail[r](ea, tm, r, p1, p2); } static inline int Keep(int x, int y) { return Equal(x, y) ? x : y; } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_PLINKO_H_ */
8,906
338
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/gc.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/intrin/bsf.h" #include "libc/intrin/popcnt.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/log/countbranch.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/str/str.h" #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/gc.h" #include "tool/plinko/lib/histo.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/print.h" #include "tool/plinko/lib/printf.h" #include "tool/plinko/lib/stack.h" forceinline void SetBit(dword M[], unsigned i) { M[i / DWBITS] |= (dword)1 << (i % DWBITS); } forceinline nosideeffect bool HasBit(const dword M[], unsigned i) { return (M[i / DWBITS] >> (i % DWBITS)) & 1; } struct Gc *NewGc(int A) { int B = cx; unsigned n; struct Gc *G; DCHECK_LE(B, A); DCHECK_LE(A, 0); if (B < cHeap) cHeap = B; n = ROUNDUP(A - B, DWBITS) / DWBITS; G = Addr(BANE); bzero(G->M, n * sizeof(G->M[0])); G->n = n; G->A = A; G->B = B; G->P = (unsigned *)(G->M + n); *G->P++ = 0; return G; } void Marker(const dword M[], int A, int x) { int i; dword t; do { i = ~(x - A); if (HasBit(M, i)) return; SetBit(M, i); if (HI(GetShadow(x)) < A) { Marker(M, A, HI(GetShadow(x))); } t = Get(x); if (LO(t) < A) { Marker(M, A, LO(t)); } } while ((x = HI(t)) < A); } int Census(struct Gc *G) { int n, t, l; unsigned i, j; i = G->A - G->B; n = i / DWBITS; for (j = t = 0; j < n; ++j) { G->P[j] = t += popcnt(G->M[j]); } if (i % DWBITS) { t += popcnt(G->M[j]); } G->noop = t == i; for (l = j = 0; j < G->n; ++j) { if (!~G->M[j]) { l += DWBITS; } else { l += _bsfl(~G->M[j]); break; } } G->C = G->A - l; #if HISTO_GARBAGE HISTO(g_gc_marks_histogram, t); HISTO(g_gc_discards_histogram, i - t); HISTO(g_gc_lop_histogram, l); #endif return t; } int Relocater(const dword M[], const unsigned P[], int A, int x) { long n; unsigned i, r; i = ~(x - A); n = i / DWBITS; r = i % DWBITS; return A + ~(P[n - 1] + popcnt(M[n] & (((dword)1 << r) - 1))); } void Sweep(struct Gc *G) { dword m; int a, b, d, i, j; if (G->noop) return; i = 0; b = d = G->A; for (; i < G->n; ++i) { m = G->M[i]; if (~m) { j = _bsfl(~m); m >>= j; m <<= j; d -= j; break; } else { b -= DWBITS; d -= DWBITS; } } for (; i < G->n; b -= DWBITS, m = G->M[++i]) { for (; m; m &= ~((dword)1 << j)) { a = b + ~(j = _bsfl(m)); Set(--d, MAKE(Relocate(G, LO(Get(a))), Relocate(G, HI(Get(a))))); SetShadow(d, MAKE(LO(GetShadow(a)), Relocate(G, HI(GetShadow(a))))); } } cx = d; } int MarkSweep(int A, int x) { struct Gc *G; if (x >= A) return cx = A, x; G = NewGc(A); Mark(G, x); Census(G); x = Relocate(G, x); Sweep(G); return x; }
4,741
157
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/prettyprint.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "libc/nt/struct/size.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/print.h" #include "tool/plinko/lib/tree.h" static void PrettyPrintList(int fd, int x, int n) { int i, y, once, func, mode, argwidth, funcwidth, forcedot; DCHECK_GE(n, 0); DCHECK_LE(x, 0); if (x < cx) { n += PrintChar(fd, L'!'); n += PrintInt(fd, x, 0, 0, 0, 10, true); } else { if (ShouldConcealClosure(x)) { x = Car(Cdr(x)); } PrintChar(fd, L'('); if (x < 0) { func = Car(x); funcwidth = PrettyPrint(fd, func, ++n); if (func == kDefine) { PrintSpace(fd); PrettyPrint(fd, Car(Cdr(x)), n); forcedot = 0; x = Cdr(x); mode = Cdr(x) < 0; once = 1; n += 1; } else if ((func == kLambda || func == kMacro) && (Cdr(x) < 0 && Cdr(Cdr(x)) < 0)) { PrintSpace(fd); if (!Car(Cdr(x))) { PrintChar(fd, L'('); PrintChar(fd, L')'); } else { PrettyPrint(fd, Car(Cdr(x)), n); } x = Cdr(x); mode = 1; forcedot = 0; once = 1; n += 1; } else { if (func >= 0) { n += funcwidth + 1; } mode = func < 0 && Car(func) != kQuote; once = mode; forcedot = 0; } if (!forcedot && ShouldForceDot(x)) { forcedot = true; n += 2; } while ((x = Cdr(x))) { y = x; argwidth = 0; if (y < 0 && !forcedot) { y = Car(y); } else { argwidth += PrintSpace(fd); argwidth += PrintDot(fd); mode = y < 0; x = 0; } if (y >= 0) { argwidth += PrintSpace(fd); argwidth += PrintAtom(fd, y); if (!once) n += argwidth; } else { if (once && (y < 0 || mode)) { mode = 1; PrintNewline(fd); if (depth >= 0) PrintDepth(fd, depth); PrintIndent(fd, n); } else { if (y < 0) mode = 1; PrintSpace(fd); } once = 1; PrettyPrint(fd, y, n); } forcedot = 0; } } PrintChar(fd, L')'); } } /** * Prints LISP data structure with style. * * @param fd is where i/o goes * @param x is thing to print * @param n is indent level */ int PrettyPrint(int fd, int x, int n) { DCHECK_GE(n, 0); if (!noname) { GetName(&x); } x = EnterPrint(x); if (1. / x < 0) { PrettyPrintList(fd, x, n); n = 0; } else { n = PrintAtom(fd, x); } LeavePrint(x); return n; }
4,494
131
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/plinko.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/sigaction.h" #include "libc/errno.h" #include "libc/intrin/likely.h" #include "libc/intrin/strace.internal.h" #include "libc/log/countbranch.h" #include "libc/log/countexpr.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/runtime/runtime.h" #include "libc/runtime/stack.h" #include "libc/runtime/symbols.internal.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/sig.h" #include "libc/time/clockstonanos.internal.h" #include "third_party/getopt/getopt.h" #include "tool/build/lib/case.h" #include "tool/plinko/lib/char.h" #include "tool/plinko/lib/error.h" #include "tool/plinko/lib/gc.h" #include "tool/plinko/lib/histo.h" #include "tool/plinko/lib/index.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/print.h" #include "tool/plinko/lib/printf.h" #include "tool/plinko/lib/stack.h" #include "tool/plinko/lib/trace.h" #include "tool/plinko/lib/tree.h" STATIC_STACK_SIZE(0x100000); #define PUTS(f, s) write(f, s, strlen(s)) #define DISPATCH(ea, tm, r, p1, p2) \ GetDispatchFn(LO(ea))(ea, tm, r, p1, p2, GetShadow(LO(ea))) static void Unwind(int S) { int s; dword t; while (sp > S) { s = --sp & MASK(STACK); if ((t = g_stack[s])) { g_stack[s] = 0; cx = ~HI(t); } } } static void Backtrace(int S) { int i; dword f; for (i = 0; sp > S && i < STACK; ++i) { f = Pop(); Fprintf(2, "%d %p%n", ~HI(f), LO(f)); g_stack[sp & MASK(STACK)] = 0; } } forceinline bool ShouldIgnoreGarbage(int A) { static unsigned cadence; if (DEBUG_GARBAGE) return false; if (!(++cadence & AVERSIVENESS)) return false; return true; } static inline bool ShouldPanicAboutGarbage(int A) { return false; } static inline bool ShouldAbort(int A) { return cx <= A + BANE / STACK * 3; // hacked thrice permitted memory } static relegated dontinline int ErrorExpr(void) { Raise(kError); } static int Order(int x, int y) { if (x < y) return -1; if (x > y) return +1; return 0; } static int Append(int x, int y) { if (!x) return y; return Cons(Car(x), Append(Cdr(x), y)); } static int ReconstructAlist(int a) { int r; for (r = 0; a < 0; a = Cdr(a)) { if (Car(a) == kClosure) { return Reverse(r, a); } if (Caar(a) < 0) { r = Reverse(r, a); } else if (!Assoc(Caar(a), r)) { r = Cons(Car(a), r); } } return Reverse(r, 0); } static bool AtomEquals(int x, const char *s) { dword t; do { if (!*s) return false; t = Get(x); if (LO(t) != *s++) return false; // xxx: ascii } while ((x = HI(t)) != TERM); return !*s; } static pureconst int LastCons(int x) { while (Cdr(x)) x = Cdr(x); return x; } static pureconst int LastChar(int x) { dword e; do e = Get(x); while ((x = HI(e)) != TERM); return LO(e); } forceinline pureconst bool IsClosure(int x) { return x < 0 && Car(x) == kClosure; } forceinline pureconst bool IsQuote(int x) { return x < 0 && Car(x) == kQuote; } static int Quote(int x) { if (IsClosure(x)) return x; if (IsPrecious(x)) return x; return List(kQuote, x); } static int QuoteList(int x) { if (!x) return x; return Cons(Quote(Car(x)), QuoteList(Cdr(x))); } static int GetAtom(const char *s) { int x, y, t, u; ax = y = TERM; x = *s++ & 255; if (*s) y = GetAtom(s); return Intern(x, y); } static int Gensym(void) { char B[16], t; static unsigned g; unsigned a, b, x, n; n = 0; x = g++; B[n++] = L'G'; do B[n++] = L'0' + (x & 7); while ((x >>= 3)); B[n] = 0; for (a = 1, b = n - 1; a < b; ++a, --b) { t = B[a]; B[a] = B[b]; B[b] = t; } return GetAtom(B); } static nosideeffect bool Member(int v, int x) { while (x) { if (x > 0) return v == x; if (v == Car(x)) return true; x = Cdr(x); } return false; } static int GetBindings(int x, int a) { int r, b; for (r = 0; x < 0; x = Cdr(x)) { if ((b = Assoc(Car(x), a))) { r = Cons(b, r); } else { Error("could not find dependency %S in %p", Car(x), a); } } return r; } static int Lambda(int e, int a, dword p1, dword p2) { int u; if (p1) a = Alist(LO(p1), HI(p1), a); if (p2) a = Alist(LO(p2), HI(p2), a); if (DEBUG_CLOSURE || logc) { u = FindFreeVariables(e, 0, 0); a = GetBindings(u, a); } return Enclose(e, a); } static int Function(int e, int a, dword p1, dword p2) { int u; if (e < 0 && Car(e) == kLambda) e = Lambda(e, a, p1, p2); if (e >= 0 || Car(e) != kClosure) Error("not a closure"); a = Cddr(e); e = Cadr(e); u = FindFreeVariables(e, 0, 0); a = GetBindings(u, a); return Enclose(e, a); } static int Simplify(int e, int a) { return Function(e, a, 0, 0); } static int PrintFn(int x) { int y; DCHECK_LT(x, TERM); y = Car(x); while ((x = Cdr(x))) { if (!quiet) { Print(1, y); PrintSpace(1); } y = Car(x); } if (!quiet) { Print(1, y); PrintNewline(1); } return y; } static int PprintFn(int x) { int y, n; DCHECK_LT(x, TERM); n = 0; y = Car(x); while ((x = Cdr(x))) { if (!quiet) { n += Print(1, y); n += PrintSpace(1); } y = Car(x); } if (!quiet) { PrettyPrint(1, y, n); PrintNewline(1); } Flush(1); return y; } static relegated struct T DispatchRetImpossible(dword ea, dword tm, dword r) { Fprintf(2, "ERROR: \e[7;31mIMPOSSIBLE RETURN\e[0m NO %d%n"); Raise(LO(ea)); } static relegated struct T DispatchTailImpossible(dword ea, dword tm, dword r, dword p1, dword p2) { Fprintf(2, "ERROR: \e[7;31mIMPOSSIBLE TAIL\e[0m NO %d%n"); Raise(LO(ea)); } static struct T DispatchRet(dword ea, dword tm, dword r) { return (struct T){LO(ea)}; } static struct T DispatchLeave(dword ea, dword tm, dword r) { Pop(); return (struct T){LO(ea)}; } static struct T DispatchLeaveGc(dword ea, dword tm, dword r) { int A, e; e = LO(ea); A = GetFrameCx(); if (e < A && cx < A && UNLIKELY(!ShouldIgnoreGarbage(A))) { e = MarkSweep(A, e); } Pop(); return (struct T){e}; } static struct T DispatchLeaveTmcGc(dword ea, dword tm, dword r) { int A, e; A = GetFrameCx(); e = Reverse(LO(tm), LO(ea)); if (!ShouldIgnoreGarbage(A)) { e = MarkSweep(A, e); } Pop(); return (struct T){e}; } RetFn *const kRet[] = { DispatchRet, // DispatchRetImpossible, // DispatchRetImpossible, // DispatchRetImpossible, // DispatchLeave, // DispatchLeaveGc, // DispatchRetImpossible, // DispatchLeaveTmcGc, // }; struct T DispatchTail(dword ea, dword tm, dword r, dword p1, dword p2) { return DISPATCH(ea, tm, r, p1, p2); } struct T DispatchTailGc(dword ea, dword tm, dword r, dword p1, dword p2) { int A; struct Gc *G; A = GetFrameCx(); if (cx < A && UNLIKELY(!ShouldIgnoreGarbage(A))) { if (ShouldPanicAboutGarbage(A)) { if (!ShouldAbort(A)) { ea = MAKE(LO(ea), ReconstructAlist(HI(ea))); } else { Raise(kCycle); } } G = NewGc(A); Mark(G, LO(ea)); Mark(G, HI(ea)); Mark(G, HI(p1)); Mark(G, HI(p2)); Census(G); p1 = MAKE(LO(p1), Relocate(G, HI(p1))); p2 = MAKE(LO(p2), Relocate(G, HI(p2))); ea = MAKE(Relocate(G, LO(ea)), Relocate(G, HI(ea))); Sweep(G); } return DISPATCH(ea, tm, r, p1, p2); } struct T DispatchTailTmcGc(dword ea, dword tm, dword r, dword p1, dword p2) { int A; struct Gc *G; A = GetFrameCx(); if (UNLIKELY(!ShouldIgnoreGarbage(A))) { if (ShouldPanicAboutGarbage(A)) { if (!ShouldAbort(A)) { ea = MAKE(LO(ea), ReconstructAlist(HI(ea))); } else { Raise(kCycle); } } G = NewGc(A); Mark(G, LO(tm)); Mark(G, LO(ea)); Mark(G, HI(ea)); Mark(G, HI(p1)); Mark(G, HI(p2)); Census(G); p1 = MAKE(LO(p1), Relocate(G, HI(p1))); p2 = MAKE(LO(p2), Relocate(G, HI(p2))); ea = MAKE(Relocate(G, LO(ea)), Relocate(G, HI(ea))); tm = MAKE(Relocate(G, LO(tm)), Relocate(G, HI(tm))); Sweep(G); } return DISPATCH(ea, tm, r, p1, p2); } struct T DispatchNil(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { return Ret(0, tm, r); // 𝑥 ⟹ ⊥ } struct T DispatchTrue(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { return Ret(1, tm, r); // 𝑥 ⟹ ⊤ } struct T DispatchPrecious(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { return Ret(ea, tm, r); // 𝑘 ⟹ 𝑘 } struct T DispatchIdentity(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { return Ret(ea, tm, r); // e.g. (⅄ (λ 𝑥 𝑦) 𝑎) ⟹ (⅄ (λ 𝑥 𝑦) 𝑎) } struct T DispatchShortcut(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { return Ret(MAKE(HI(d), 0), tm, r); } struct T DispatchLookup(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int e, a, kv; e = LO(ea); a = HI(ea); DCHECK(!IsPrecious(e)); DCHECK_GT(e, 0); DCHECK_LE(a, 0); if (LO(p1) == LO(ea)) return Ret(MAKE(HI(p1), 0), tm, r); if (LO(p2) == LO(ea)) return Ret(MAKE(HI(p2), 0), tm, r); if ((kv = Assoc(e, a))) { return Ret(MAKE(Cdr(kv), 0), tm, r); // (eval 𝑘 (…(𝑘 𝑣)…)) ⟹ 𝑣 } else { Error("crash variable %S%n", e); } } struct T DispatchQuote(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { return Ret(MAKE(HI(d), 0), tm, r); // (Ω 𝑥) ⟹ 𝑥 } struct T DispatchAtom(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int x = FasterRecurse(HI(d), HI(ea), p1, p2); return Ret(MAKE(x >= 0, 0), tm, r); // (α (𝑥 . 𝑦)) ⟹ ⊥, (α 𝑘) ⟹ ⊤ } struct T DispatchCar(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int x = FasterRecurse(HI(d), HI(ea), p1, p2); return Ret(MAKE(Head(x), 0), tm, r); // (⍅ (𝑥 . 𝑦)) ⟹ 𝑥 } struct T DispatchCdr(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int x = FasterRecurse(HI(d), HI(ea), p1, p2); return Ret(MAKE(Tail(x), 0), tm, r); // (⍆ (𝑥 . 𝑦)) ⟹ 𝑦 } struct T DispatchEq(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int x = FasterRecurse(ARG1(LO(ea)), HI(ea), p1, p2); int y = FasterRecurse(HI(d), HI(ea), p1, p2); return Ret(MAKE(x == y, 0), tm, r); // (≡ 𝑥 𝑥) ⟹ ⊤, (≡ 𝑥 𝑦) ⟹ ⊥ } struct T DispatchCmp(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int x = FasterRecurse(ARG1(LO(ea)), HI(ea), p1, p2); int y = FasterRecurse(HI(d), HI(ea), p1, p2); return Ret(MAKE(Cmp(x, y), 0), tm, r); // (≷ 𝑥 𝑦) ⟹ (⊥) | ⊥ | ⊤ } struct T DispatchOrder(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int x = FasterRecurse(ARG1(LO(ea)), HI(ea), p1, p2); int y = FasterRecurse(HI(d), HI(ea), p1, p2); return Ret(MAKE(Order(x, y), 0), tm, r); // (⊙ 𝑥 𝑦) ⟹ (⊥) | ⊥ | ⊤ } struct T DispatchCons(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int x; if (cx < cHeap) cHeap = cx; x = Car(Cdr(LO(ea))); x = FasterRecurse(x, HI(ea), p1, p2); if (!HI(d)) return Ret(MAKE(Cons(x, 0), 0), tm, r); if (~r & NEED_POP) { r |= NEED_POP; Push(LO(ea)); } r |= NEED_GC | NEED_TMC; tm = MAKE(Cons(x, LO(tm)), 0); return TailCall(MAKE(HI(d), HI(ea)), tm, r, p1, p2); // (ℶ x 𝑦) ↩ (tm 𝑥′ . 𝑦) } struct T DispatchLambda(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { // (eval (𝑘 𝑥 𝑦) 𝑎) ⟹ (⅄ (𝑘 𝑥 𝑦) . 𝑎) SetFrame(r, LO(ea)); r |= NEED_GC; return Ret(MAKE(Lambda(LO(ea), HI(ea), p1, p2), 0), tm, r); } struct T DispatchCond(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int y, z, c = HI(d); if (r & NEED_POP) { Repush(LO(ea)); } do { if (!Cdr(c) && !Cdr(Car(c))) { // (ζ …(𝑝)) ↩ 𝑝 return TailCall(MAKE(Car(Car(c)), HI(ea)), tm, r, p1, p2); } if (~r & NEED_POP) { r |= NEED_POP; Push(LO(ea)); } if ((y = FasterRecurse(Car(Car(c)), HI(ea), p1, p2))) { if ((z = Cdr(Car(c))) < 0) { // (ζ …(𝑝 𝑏)…) ↩ 𝑏 if 𝑝′ return TailCall(MAKE(Car(z), HI(ea)), tm, r, p1, p2); } else { // (ζ …(𝑝)…) ⟹ 𝑝′ if 𝑝′ return Ret(MAKE(y, 0), tm, r); } } } while ((c = Cdr(c))); return Ret(MAKE(c, 0), tm, r); // (ζ) ⟹ ⊥ } struct T DispatchIf(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { return TailCall( MAKE(Get(LO(ea) + 4 + !FasterRecurse(Get(LO(ea) + 3), HI(ea), p1, p2)), HI(ea)), tm, r, p1, p2); } struct T DispatchPrinc(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { bool b; int x, e, A; e = LO(ea); SetFrame(r, e); b = literally; literally = true; e = recurse(MAKE(Head(Tail(e)), HI(ea)), p1, p2); Print(1, e); literally = b; return Ret(MAKE(e, 0), tm, r); } struct T DispatchFlush(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int x, A; SetFrame(r, LO(ea)); Flush(1); return Ret(MAKE(kIgnore0, 0), tm, r); } struct T DispatchPrint(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int a, f, x, A; f = LO(ea); a = HI(ea); SetFrame(r, f); for (;;) { f = Cdr(f); if (!Cdr(f)) { if (quiet) { return TailCall(MAKE(Car(f), a), tm, r, p1, p2); } else { x = recurse(MAKE(Car(f), a), p1, p2); Print(1, x); PrintNewline(1); return Ret(MAKE(x, 0), tm, r); } } if (!quiet) { A = cx; x = recurse(MAKE(Car(f), a), p1, p2); Print(1, x); PrintSpace(1); MarkSweep(A, 0); } } } struct T DispatchPprint(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int a, f, x, n, A; f = LO(ea); a = HI(ea); SetFrame(r, f); for (n = 0;;) { f = Cdr(f); if (!Cdr(f)) { if (quiet) { return TailCall(MAKE(Car(f), a), tm, r, p1, p2); } else { x = recurse(MAKE(Car(f), a), p1, p2); PrettyPrint(1, x, n); PrintNewline(1); return Ret(MAKE(x, 0), tm, r); } } if (!quiet) { A = cx; x = recurse(MAKE(Car(f), a), p1, p2); n += Print(1, x); n += PrintSpace(1); MarkSweep(A, 0); } } } struct T DispatchPrintheap(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int x, A; SetFrame(r, LO(ea)); if (Cdr(LO(ea))) { A = cx; x = recurse(MAKE(Cadr(LO(ea)), HI(ea)), p1, p2); PrintHeap(A); } else { PrintHeap(0); x = 0; } return Ret(x, tm, r); } struct T DispatchGc(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int A, e; SetFrame(r, LO(ea)); A = GetFrameCx(); e = recurse(MAKE(HI(d), HI(ea)), p1, p2); if (e < A && cx < A && !ShouldIgnoreGarbage(A)) { e = MarkSweep(A, e); } return Ret(MAKE(e, 0), tm, r); } struct T DispatchProgn(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int A, y, x = HI(d); for (;;) { y = Car(x); x = Cdr(x); if (!x) { if (r & NEED_POP) { Repush(y); } return TailCall(MAKE(y, HI(ea)), tm, r, p1, p2); // (progn ⋯ 𝑥) ↩ 𝑥 } A = cx; recurse(MAKE(y, HI(ea)), p1, p2); // evaluate for effect MarkSweep(A, 0); } } struct T DispatchGensym(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { return Ret(MAKE(Gensym(), 0), tm, r); } struct T DispatchQuiet(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { SAVE(quiet, true); ea = MAKE(recurse(MAKE(Cadr(LO(ea)), HI(ea)), p1, p2), 0); RESTORE(quiet); return Ret(ea, tm, r); } struct T DispatchTrace(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { START_TRACE; ea = MAKE(recurse(MAKE(Cadr(LO(ea)), HI(ea)), p1, p2), 0); END_TRACE; return Ret(ea, tm, r); } struct T DispatchFtrace(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { ftrace_install(); ftrace_enabled(+1); ea = MAKE(recurse(MAKE(Cadr(LO(ea)), HI(ea)), p1, p2), 0); ftrace_enabled(-1); return Ret(ea, tm, r); } struct T DispatchBeta(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { SetFrame(r, LO(ea)); r |= NEED_GC; return Ret(MAKE(Simplify(recurse(MAKE(HI(d), HI(ea)), p1, p2), HI(ea)), 0), tm, r); } struct T DispatchFunction(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { // (eval (𝑓 (𝑘 𝑥 𝑦)) 𝑎) ⟹ (⅄ (𝑘 𝑥 𝑦) . prune 𝑎 wrt (𝑘 𝑥 𝑦)) SetFrame(r, LO(ea)); r |= NEED_GC; return Ret( MAKE(Function(recurse(MAKE(HI(d), HI(ea)), p1, p2), HI(ea), p1, p2), 0), tm, r); } struct T DispatchIgnore0(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { return Ret(MAKE(kIgnore0, 0), tm, r); } struct T DispatchIgnore1(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int x = recurse(MAKE(Car(Cdr(LO(ea))), HI(ea)), p1, p2); return Ret(MAKE(List(kIgnore, x), 0), tm, r); } struct T DispatchExpand(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int x; SetFrame(r, LO(ea)); r |= NEED_GC; x = HI(d); x = recurse(MAKE(x, HI(ea)), p1, p2); return Ret(MAKE(expand(x, HI(ea)), 0), tm, r); } static int GrabArgs(int x, int a, dword p1, dword p2) { if (x >= 0) return x; return Cons(recurse(MAKE(Car(x), a), p1, p2), GrabArgs(Cdr(x), a, p1, p2)); } struct T DispatchError(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int e, x; e = LO(ea); SetFrame(r, e); r |= NEED_GC; x = GrabArgs(Cdr(e), HI(ea), p1, p2); Raise(Cons(Car(e), x)); } struct T DispatchExit(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { longjmp(exiter, 1); } struct T DispatchRead(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { return Ret(MAKE(Read(0), 0), tm, r); } struct T DispatchFuncall(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int a, b, e, f, t, u, y, p, z; e = LO(ea); a = HI(ea); DCHECK_LT(e, 0); SetFrame(r, e); r |= NEED_GC; f = Car(e); z = Cdr(e); y = HI(d) ? HI(d) : FasterRecurse(f, a, p1, p2); Delegate: if (y < 0) { t = Car(y); if (t == kClosure) { // (eval ((⅄ (λ 𝑥 𝑦) 𝑏) 𝑧) 𝑎) ↩ (eval ((λ 𝑥 𝑦) 𝑧) 𝑏) y = Cdr(y); // ((λ 𝑥 𝑦) 𝑏) u = Cdr(y); // 𝑏 y = Car(y); // (λ 𝑥 𝑦) t = Car(y); // λ } else { u = a; } p = Car(Cdr(y)); b = Car(Cdr(Cdr(y))); if (t == kLambda) { if (!(p > 0 && b < 0 && Cdr(b) == p)) { struct Binding bz = bind_(p, z, a, u, p1, p2); return TailCall(MAKE(b, bz.u), tm, r, bz.p1, 0); } else { // fast path ((lambda 𝑣 (𝑦 . 𝑣)) 𝑧) ↩ (𝑦′ 𝑧) y = recurse(MAKE(Car(b), u), 0, 0); goto Delegate; } } else if (t == kMacro) { // (eval ((ψ 𝑥 𝑦) 𝑥) 𝑎) ↩ (eval (eval 𝑦 ((𝑥ᵢ 𝑥ᵢ) 𝑎)) 𝑎) return TailCall(MAKE(eval(b, pairlis(p, Exlis(z, a), u)), a), tm, r, 0, 0); } } else if (y > 1 && y != f && IsPrecious(y)) { // unplanned builtin calls // e.g. ((cond (p car) (cdr)) x) return TailCall(MAKE(Cons(y, z), a), tm, r, p1, p2); } React(e, y, kFunction); } struct T DispatchCall1(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int a, b, e, f, t, u, y, p, z; e = LO(ea); a = HI(ea); DCHECK_LT(e, 0); SetFrame(r, e); f = Car(e); z = Cdr(e); y = HI(d); t = Car(y); // (eval ((⅄ (λ 𝑥 𝑦) 𝑏) 𝑧) 𝑎) ↩ (eval ((λ 𝑥 𝑦) 𝑧) 𝑏) y = Cdr(y); // ((λ 𝑥 𝑦) 𝑏) u = Cdr(y); // 𝑏 y = Car(y); // (λ 𝑥 𝑦) p = Car(Cdr(y)); b = Car(Cdr(Cdr(y))); return TailCall(MAKE(b, u), tm, r, MAKE(Car(p), FasterRecurse(Car(Cdr(LO(ea))), HI(ea), p1, p2)), 0); } struct T DispatchCall2(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int a, b, e, f, t, u, y, p, z; e = LO(ea); a = HI(ea); DCHECK_LT(e, 0); SetFrame(r, e); f = Car(e); z = Cdr(e); y = HI(d); t = Car(y); // (eval ((⅄ (λ 𝑥 𝑦) 𝑏) 𝑧) 𝑎) ↩ (eval ((λ 𝑥 𝑦) 𝑧) 𝑏) y = Cdr(y); // ((λ 𝑥 𝑦) 𝑏) u = Cdr(y); // 𝑏 y = Car(y); // (λ 𝑥 𝑦) p = Car(Cdr(y)); b = Car(Cdr(Cdr(y))); return TailCall( MAKE(b, u), tm, r, MAKE(Car(p), FasterRecurse(Car(Cdr(LO(ea))), HI(ea), p1, p2)), MAKE(Car(Cdr(p)), FasterRecurse(Car(Cdr(Cdr(LO(ea)))), HI(ea), p1, p2))); } struct T DispatchLet1(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { // Fast path DispatchFuncall() for ((λ (𝑣) 𝑦) 𝑧₀) expressions // HI(d) contains ((𝑣) 𝑦) if (UNLIKELY(trace)) Fprintf(2, "%J╟─%s[%p @ %d] δ %'Rns%n", "DispatchLet1", LO(ea), LO(ea)); int v = Car(Car(HI(d))); int y = Car(Cdr(HI(d))); int z = FasterRecurse(Car(Cdr(LO(ea))), HI(ea), p1, p2); int a = HI(ea); if (!LO(p1) || LO(p1) == v) { p1 = MAKE(v, z); } else if (!LO(p2) || LO(p2) == v) { p2 = MAKE(v, z); } else { a = Alist(LO(p2), HI(p2), a); p2 = p1; p1 = MAKE(v, z); } return TailCall(MAKE(y, a), tm, r, p1, p2); } int Eval(int e, int a) { return ((ForceIntTailDispatchFn *)GetDispatchFn(e))(MAKE(e, a), 0, 0, 0, 0, GetShadow(e)); } static void ResetStats(void) { cHeap = cx; cGets = 0; cSets = 0; } static void PrintStats(long usec) { Fprintf(2, ";; heap %'16ld nsec %'16ld%n" ";; gets %'16ld sets %'16ld%n" ";; atom %'16ld frez %'16ld%n", -cHeap - -cFrost, usec, cGets, cSets, cAtoms, -cFrost); } static wontreturn Exit(void) { exit(0 <= fails && fails <= 255 ? fails : 255); } static wontreturn void PrintUsage(void) { PUTS(!!fails + 1, "Usage: "); PUTS(!!fails + 1, program_invocation_name); PUTS(!!fails + 1, " [-MNSacdfgqstz?h] <input.lisp >errput.lisp\n\ -d dump global defines, on success\n\ -s print statistics upon each eval\n\ -z uses alternative unicode glyphs\n\ -f print log of all function calls\n\ -S avoid pretty printing most case\n\ -c dont conceal transitive closure\n\ -a log name bindings in the traces\n\ -t hyper verbose jump table traces\n\ -M enable tracing of macro expands\n\ -N disable define name substitutes\n\ -g will log garbage collector pass\n\ -q makes (print) and (pprint) noop\n\ "); Exit(); } int Plinko(int argc, char *argv[]) { long *p; bool trace; int S, x, u, j; uint64_t t1, t2; tick = kStartTsc; #ifndef NDEBUG ShowCrashReports(); #endif signal(SIGPIPE, SIG_DFL); depth = -1; trace = false; while ((x = getopt(argc, argv, "MNSacdfgqstz?h")) != -1) { switch (x) { CASE(L'd', dump = true); CASE(L's', stats = true); CASE(L'z', symbolism = true); CASE(L'f', ftrace = true); CASE(L'S', simpler = true); CASE(L'c', logc = true); CASE(L'a', loga = true); CASE(L't', trace = true); CASE(L'g', gtrace = true); CASE(L'q', quiet = true); CASE(L'M', mtrace = true); CASE(L'N', noname = true); CASE(L'?', PrintUsage()); CASE(L'h', PrintUsage()); default: ++fails; PrintUsage(); } } if (arch_prctl(ARCH_SET_FS, 0x200000000000) == -1 || arch_prctl(ARCH_SET_GS, (intptr_t)DispatchPlan) == -1) { fputs("error: ", stderr); fputs(strerror(errno), stderr); fputs("\nyour operating system doesn't allow you change both " "the %fs and %gs registers\nin your processor. that's a shame, " "since they're crucial for performance.\n", stderr); exit(1); } if (mmap((void *)0x200000000000, ROUNDUP((TERM + 1) * sizeof(g_mem[0]), FRAMESIZE), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, -1, 0) == MAP_FAILED || mmap((void *)(0x200000000000 + (BANE & (BANE | MASK(BANE))) * sizeof(g_mem[0])), (BANE & (BANE | MASK(BANE))) * sizeof(g_mem[0]), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, -1, 0) == MAP_FAILED || mmap((void *)0x400000000000, ROUNDUP((TERM + 1) * sizeof(g_mem[0]), FRAMESIZE), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, -1, 0) == MAP_FAILED || mmap((void *)(0x400000000000 + (BANE & (BANE | MASK(BANE))) * sizeof(g_mem[0])), (BANE & (BANE | MASK(BANE))) * sizeof(g_mem[0]), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, -1, 0) == MAP_FAILED) { fputs("error: ", stderr); fputs(strerror(errno), stderr); fputs("\nyour operating system doesn't allow you to allocate\n" "outrageous amounts of overcommit memory, which is a shame, since\n" "the pml4t feature in your processor was intended to give you that\n" "power since it's crucial for sparse data applications and lisp.\n" "for instance, the way racket works around this problem is by\n" "triggering thousands of segmentation faults as part of normal\n" "operation\n", stderr); exit(1); } g_mem = (void *)0x200000000000; inputs = argv + optind; if (*inputs) { close(0); DCHECK_NE(-1, open(*inputs++, O_RDONLY)); } eval = Eval; bind_ = Bind; evlis = Evlis; expand = Expand; recurse = Recurse; pairlis = Pairlis; kTail[0] = DispatchTail; kTail[1] = DispatchTailImpossible; kTail[2] = DispatchTailImpossible; kTail[3] = DispatchTailImpossible; kTail[4] = DispatchTail; kTail[5] = DispatchTailGc; kTail[6] = DispatchTailImpossible; kTail[7] = DispatchTailTmcGc; if (trace) EnableTracing(); cx = -1; cFrost = cx; Setup(); cFrost = cx; if (!setjmp(exiter)) { for (;;) { S = sp; DCHECK_EQ(0, S); DCHECK_EQ(cx, cFrost); if (!(x = setjmp(crash))) { x = Read(0); x = expand(x, globals); if (stats) ResetStats(); if (x < 0 && Car(x) == kDefine) { globals = Define(x, globals); cFrost = cx; } else { t1 = rdtsc(); x = eval(x, globals); if (x < 0 && Car(x) == kIgnore) { MarkSweep(cFrost, 0); } else { Fprintf(1, "%p%n", x); MarkSweep(cFrost, 0); if (stats) { t2 = rdtsc(); PrintStats(ClocksToNanos(t1, t2)); } } } } else { x = ~x; ++fails; eval = Eval; expand = Expand; Fprintf(2, "?%p%s%n", x, cx == BANE ? " [HEAP OVERFLOW]" : ""); Backtrace(S); Exit(); Unwind(S); MarkSweep(cFrost, 0); } } } #if HISTO_ASSOC PrintHistogram(2, "COMPARES PER ASSOC", g_assoc_histogram, ARRAYLEN(g_assoc_histogram)); #endif #if HISTO_GARBAGE PrintHistogram(2, "GC MARKS PER COLLECTION", g_gc_marks_histogram, ARRAYLEN(g_gc_marks_histogram)); PrintHistogram(2, "GC DISCARDS PER COLLECTION", g_gc_discards_histogram, ARRAYLEN(g_gc_discards_histogram)); PrintHistogram(2, "GC MARKS / DISCARDS FOR DENSE COLLECTIONS", g_gc_dense_histogram, ARRAYLEN(g_gc_dense_histogram)); PrintHistogram(2, "GC DISCARDS / MARKS FOR SPARSE COLLECTIONS", g_gc_sparse_histogram, ARRAYLEN(g_gc_sparse_histogram)); PrintHistogram(2, "GC LOP", g_gc_lop_histogram, ARRAYLEN(g_gc_lop_histogram)); #endif if (dump && !fails) { DumpDefines(kDefine, globals, Reverse(ordglob, 0)); } Exit(); }
30,475
1,070
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/cons.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_CONS_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_CONS_H_ #include "tool/plinko/lib/error.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/types.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ forceinline void Set(int i, dword t) { #ifndef NDEBUG DCHECK_NE(0, i); DCHECK_LT(i, TERM); DCHECK_LT(LO(t), TERM); DCHECK_LE(HI(t), TERM); if (i < 0) { DCHECK_LT(i, LO(t), "topology compromised"); DCHECK_LT(i, HI(t), "topology compromised"); } else { DCHECK_GE(LO(t), 0); DCHECK_GE(HI(t), 0); } #endif g_mem[i & (BANE | MASK(BANE))] = t; ++cSets; } forceinline int Alloc(dword t) { int c = cx; if (!__builtin_sub_overflow(c, 1, &c)) { Set(c, t); return cx = c; } OutOfMemory(); } forceinline void SetShadow(int i, dword t) { #ifndef NDEBUG DCHECK_GE(i, cx); DCHECK_LT(i, TERM); DCHECK_GE(LO(t), 0); /* if (i < 0) DCHECK_GE(HI(t), i, "topology compromised"); */ #endif ((__seg_fs dword *)((uintptr_t)g_mem))[i & (BANE | MASK(BANE))] = t; } forceinline int Cons(int x, int y) { int c; c = Alloc(MAKE(x, y)); SetShadow(c, DF(DispatchPlan)); return c; } forceinline int Alist(int x, int y, int z) { return Cons(Cons(x, y), z); } int List(int, int); int List3(int, int, int); int List4(int, int, int, int); int Shadow(int, int); int GetCommonCons(int, int); int ShareCons(int, int); int ShareList(int, int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_CONS_H_ */
1,553
68
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/printf.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_PRINTF_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_PRINTF_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int Printf(const char *, ...); int Fprintf(int, const char *, ...); int Fnprintf(int, int, const char *, ...); int Vfprintf(const char *, va_list, int); int Vfnprintf(const char *, va_list, int, int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_PRINTF_H_ */
476
15
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/algebra.lisp
#| plinko - a really fast lisp tarpit | Copyright 2022 Justine Alexandra Roberts Tunney | | Permission to use, copy, modify, and/or distribute this software for | any purpose with or without fee is hereby granted, provided that the | above copyright notice and this permission notice appear in all copies. | | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL | WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED | WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE | AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL | DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR | PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER | TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | PERFORMANCE OF THIS SOFTWARE. |# (DEFINE EXPLAIN NIL) (DEFUN SUBST (X A) (AND X (IF (ATOM X) (LET ((R (ASSOC X A))) (IF R (CDR R) X)) (CONS (SUBST (CAR X) A) (SUBST (CDR X) A))))) (DEFUN ISCONSTANT (X) (EQ X 'K)) (DEFUN ISVARIABLE (X) (OR (EQ X 'A) (EQ X 'B) (EQ X 'C) (EQ X 'TODO))) (DEFUN ISDIGLET (X) (AND (>= X '0) (<= X '9))) (DEFUN ISCOMMUTATIVE (X) (OR (EQ X 'ADD) (EQ X '*) (EQ X 'XOR) (EQ X 'OR) (EQ X 'AND) (EQ X 'NAND) (EQ X 'EQ) (EQ X 'EQUAL) (EQ X 'MIN) (EQ X 'MAX))) (DEFUN RIGHTEN (X) (IF (ATOM X) X (KEEP X (CONS (CAR X) (LET ((A (RIGHTEN (CADR X)))) (IF (CDDR X) (LET ((B (RIGHTEN (CADDR X)))) (IF (AND (ISCOMMUTATIVE (CAR X)) (< B A)) (LIST B A) (LIST A B))) (LIST A))))))) (DEFUN MATCHES (X P A) (COND ((ATOM P) (IF (AND P (OR (ISVARIABLE P) (AND (ISCONSTANT P) (ISDIGLET X)))) (LET ((Y (ASSOC P A))) (IF Y (AND (EQUAL X (CDR Y)) A) (CONS (CONS P X) A))) (AND (EQ P X) A))) ((NOT (ATOM X)) (LET ((R (MATCHES (CAR X) (CAR P) A))) (AND R (MATCHES (CDR X) (CDR P) R)))))) (DEFUN -SIMPNODE (X P) (AND P (LET ((R (MATCHES X (CAAR P) '(NIL)))) (IF R (IF EXPLAIN (PRINT 'REDUCE X 'BECAUSE (CAAR P) 'IS (CADAR P) 'THEREFORE (RIGHTEN (SUBST (CADAR P) R))) (SUBST (CADAR P) R)) (-SIMPNODE X (CDR P)))))) (DEFUN SIMPNODE (X P) (AND P (LET ((R (AND (EQ (CAR X) (CAAR P)) (-SIMPNODE X (CDAR P))))) (OR R (SIMPNODE X (CDR P)))))) (DEFUN SIMPTREE (X P H) (IF (ATOM X) X (IF (NOT (MEMBER X H)) (LET* ((H (CONS X H)) (B (SIMPTREE (CADDR X) P H)) (C (CONS (CAR X) (CONS (SIMPTREE (CADR X) P H) (AND B (CONS B))))) (D (SIMPNODE C P))) (IF D (SIMPTREE D P H) (KEEP X C))) (ERROR 'SIMPTREE 'CYCLE X 'HISTORY H)))) (DEFUN PERMCOMB (OP ARG1 ARG2 RES) (IF ARG2 (PERMCOMB OP ARG1 (CDR ARG2) (PEEL (LIST OP (CAR ARG2) ARG1) (PEEL (LIST OP ARG1 (CAR ARG2)) RES))) RES)) (DEFUN PERMCOMA (OP ARG1 ARG2 RES) (IF ARG1 (PERMCOMA OP (CDR ARG1) ARG2 (PERMCOMB OP (CAR ARG1) ARG2 RES)) RES)) (DEFUN PERMCOMM (X) (IF (AND (NOT (ATOM X)) (ISCOMMUTATIVE (CAR X))) (PERMCOMA (CAR X) (PERMCOMM (CADR X)) (PERMCOMM (CADDR X))) (CONS X))) (DEFUN -RULES (((A B) . P) R) (IF A (-RULES P (CONS (REVERSE-DOLIST (E (PERMCOMM (RIGHTEN A))) (LIST E B)) R)) (REDUCE APPEND (REVERSE R)))) (DEFUN RULES (L R) (GROUPBY (LAMBDA (X) (CAAR X)) (-RULES L R))) (DEFINE LOLGEBRA (RULES '(((ADD 1 2) 3) ((ADD 1 3) 4) ((ADD 1 4) 5) ((ADD A 0) A) ((ADD (SUB A B) B) A) ;; COMMUTATIVE PROPERTY ((ADD A A) (* 2 A)) ((ADD A (SUB B A)) B) ((ADD (SUB A B) B) A) ((ADD (ADD A B) (SUB C A)) (ADD C B)) ((ADD (SUB A B) (SUB C A)) (SUB C B)) ((ADD (* A B) (* A B)) (* 2 (* A B))) ((ADD (* A B) (* B (ADD A C))) (* B (ADD (* 2 A) C))) ((ADD (POW A 2) (* (POW A 2) B)) (* (POW A 2) (ADD B 1))) ((ADD A (* A K)) (* A (ADD K 1))) ((ADD A (ADD K B)) (ADD K (ADD A B))) ((ADD A (SUB K B)) (ADD K (SUB A B))) ((ADD (* B A) (* C A)) (* A (ADD B C))) ((ADD (SUB 0 A) B) (SUB B A)) ((ADD A (SUB 0 B)) (SUB A B)) ((ADD (NOT A) 1) (SUB 0 A)) ((ADD (* (SUB 0 B) C) A) (SUB A (* B C))) ((ADD (XOR A (NOT B)) (* 2 (OR A B))) (SUB (ADD A B) 1)) ((ADD (ADD (ADD A B) 1) (NOT (OR A B))) (OR A B)) ((ADD (SUB A B) (AND (NOT (* 2 A)) (* 2 B))) (XOR A B)) ((ADD (SUB 0 B) (AND (NOT (* 2 A)) (* 2 B))) (SUB (XOR A B) A)) ((ADD (SUB 0 B) (* 2 (AND (NOT A) B))) (SUB (XOR A B) A)) ((ADD (SUB A B) (* 2 (AND (NOT A) B))) (XOR A B)) ((ADD (AND A B) (OR A B)) (ADD A B)) ((ADD (XOR A B) (* 2 (AND A B))) (ADD A B)) ((ADD (SUB (SUB 0 A) B) (* 2 (OR A B))) (XOR A B)) ((ADD (* (SUB 0 2) (AND (NOT A) B)) B) (ADD (SUB 0 (XOR A B)) A)) ((ADD (ADD A B) (NOT (AND A B))) (SUB (AND A B) 1)) ((ADD (ADD A B) (* 2 (NOT (OR A B)))) (SUB (XOR A B) 2)) ((ADD (DIV A C) (DIV B C)) (DIV (ADD A B) C)) ((ADD (AND A B) (XOR A B)) (OR A B)) ((ADD (AND A B) (OR A B)) (ADD A B)) ((ADD (SUB (ADD A B) (* 2 (OR A B))) (XOR A B)) 0) ((ADD (NOT A) A) (SUB 0 1)) ((ADD (AND A (NOT B)) (AND (NOT A) B)) (XOR A B)) ((ADD (SUB (AND A (NOT B)) (AND (NOT A) B)) C) (ADD (SUB A B) C)) ((ADD (POW A 2) (ADD (* 2 (* A B)) (POW B 2))) (POW (ADD A B) 2)) ;; BINOMIAL THEOREM ((ADD (ADD (POW A 3) (ADD (* 3 (* B (POW A 2))) (* 3 (* A (POW B 2))))) (POW B 3)) (POW (ADD A B) 3)) ;; BINOMIAL THEOREM ((SUB 1 1) 0) ((SUB 2 1) 1) ((SUB 3 1) 2) ((SUB 4 1) 3) ((SUB 5 1) 4) ((SUB 1 2) (SUB 0 1)) ((SUB 2 2) 0) ((SUB 3 2) 1) ((SUB 4 2) 2) ((SUB 5 2) 3) ((SUB A A) 0) ;; UNSAFE WITH NANS ((SUB A 0) A) ((SUB (ADD A B) B) A) ;; COMMUTATIVE PROPERTY ((SUB 0 (ADD A 1)) (NOT A)) ((SUB (POW A 2) (POW B 2)) (* (ADD A B) (SUB A B))) ;; DIFFERENCE OF TWO SQUARES ((SUB (SUB (* A (ADD B A)) (* A B)) (POW B 2)) (* (ADD A B) (SUB A B))) ;; DIFFERENCE OF TWO SQUARES ((SUB (ADD A B) A) B) ((SUB (ADD A B) B) A) ((SUB A (SUB A B)) B) ((SUB A (ADD B A)) (SUB 0 B)) ((SUB A (ADD A B)) (SUB 0 B)) ((SUB (SUB A B) A) (SUB 0 B)) ((SUB (SUB A B) A) (SUB 0 B)) ((SUB (ADD A B) (SUB A C)) (ADD B C)) ((SUB (DIV 1 2) 1) (SUB 0 (DIV 1 2))) ;; SQRT DERIVATIVE HACK ((SUB A (SUB K B)) (SUB (ADD A B) K)) ((SUB (ADD K A) B) (ADD K (SUB A B))) ((SUB (DIV (LOG A) (LOG C)) (DIV (LOG B) (LOG C))) (DIV (LOG (DIV A B)) (LOG C))) ;; DOMAIN IS 0<C<1 ∨ C>1 ((SUB 0 (NOT A)) (ADD A 1)) ((SUB 0 (SUB A B)) (SUB B A)) ((SUB A (XOR 0 1)) (SUB A 1)) ((SUB (SUB 0 1) A) (NOT A)) ((SUB (OR A B) (AND A (NOT B))) B) ((SUB (SUB 0 (XOR A (NOT B))) (* 2 (OR A B))) (ADD (SUB (SUB 0 A) B) 1)) ((SUB (SUB 0 A) (AND (NOT (* 2 A)) (* 2 B))) (SUB (SUB 0 (XOR A B)) B)) ((SUB (ADD A B) (* 2 (AND A B))) (XOR A B)) ((SUB (ADD A B) (OR A B)) (AND A B)) ((SUB (AND A B) (OR (NOT A) B)) (ADD A 1)) ((SUB (OR A B) (AND A B)) (XOR A B)) ((SUB (AND (* 2 (NOT A)) (* 2 B)) B) (SUB (XOR A B) A)) ((SUB (DIV A C) (DIV B C)) (DIV (SUB A B) C)) ;; ((SUB A (* (DIV A B) B)) (REM A B)) ;; ONLY FOR INTEGER ARITHMETIC ((SUB (ADD A B) (OR A B)) (AND A B)) ((SUB (ADD A B) (AND A B)) (OR A B)) ((SUB (OR A B) (XOR A B)) (AND A B)) ((SUB (OR A B) (AND A B)) (XOR A B)) ((SUB B (AND A B)) (AND (NOT A) B)) ((SUB A (AND A B)) (AND A (NOT B))) ((SUB (SUB 0 (AND A B)) 1) (NOT (AND A B))) ((SUB (SUB (AND A B) A) 1) (OR (NOT A) B)) ((SUB (SUB (AND A B) B) 1) (OR A (NOT B))) ((SUB (ADD (SUB (SUB 0 A) B) (AND A B)) 1) (NOT (OR A B))) ((SUB (ADD (SUB (SUB 0 A) B) (* 2 (AND A B))) 1) (NOT (XOR A B))) ((SUB (SUB 0 A) 1) (NOT A)) ((SUB (AND A (NOT B)) (AND A B)) (SUB (XOR A B) B)) ((SUB (AND A B) (AND A (NOT B))) (SUB B (XOR A B))) ((SUB (AND A B) (AND A (NOT B))) (SUB B (XOR A B))) ((POW A 0) 1) ((POW 0 A) 0) ((POW 1 A) 1) ((POW A 1) A) ((POW 2 2) 4) ((POW 3 2) 9) ((POW 4 (DIV 1 2)) 2) ((POW 8 (DIV 1 3)) 2) ((POW A (SUB 0 1)) (DIV 1 A)) ((POW (ABS A) B) (POW A B)) ((POW A (SUB 0 B) 1) (DIV 1 (POW A B))) ;; THIS NORMALIZATION ((POW (POW K A) (DIV 1 B)) (POW (POW K (DIV 1 B)) A)) ;; COMES BEFORE NEXT ((POW (POW A B) C) (POW A (* B C))) ;; COMES AFTER PREV ((POW B (DIV (LOG A) (LOG B))) A) ((POW (* K K) (DIV 1 2)) K) ((POW (POW A 2) (DIV 1 2)) (ABS A)) ((POW (* K (POW A 2)) (DIV 1 2)) (* (ABS A) (POW K (DIV 1 2)))) ;; DOMAIN K≥0 ((DIV A 0) :DBZERO) ((DIV A A) 1) ((DIV A 1) A) ((DIV 0 (- 0 K)) (- 0 0)) ;; SIGNED ZERO LOL ((DIV 0 A) 0) ((DIV (SUB 0 A) A) (SUB 0 1)) ((DIV A (SUB 0 1)) (SUB 0 A)) ((DIV (DIV A B) C) (DIV A (* B C))) ((DIV A (DIV B C)) (* (DIV A B) C)) ((DIV A (SUB 0 B)) (DIV (SUB 0 A) B)) ;; SHOULD WE? ((DIV (* A 2) 2) A) ((DIV (SIN A) (TAN A)) (COS A)) ((DIV (SIN A) (COS A)) (TAN A)) ((DIV (COS A) (SIN A)) (DIV 1 (TAN A))) ((DIV (TAN A) (SIN A)) (DIV 1 (COS A))) ((DIV (POW A C) (POW A B)) (POW A (SUB C B))) ;; EXPONENT RULE ((DIV (POW A B) (POW A C)) (POW A (SUB C B))) ;; EXPONENT RULE ((DIV (* B (POW A (SUB B 1))) (POW A B)) (DIV B A)) ;; UGLY ;; ((DIV A (POW B C)) (* A (POW B (SUB 0 C)))) ;; EXPONENT RULE [CYCLIC] ((DIV (POW A B) (POW C B)) (POW (DIV A C) B)) ;; DOMAIN IS APPROXIMATELY ABC≥1 ((DIV (LOG (POW B A)) (LOG B)) A) ((DIV (LOG (POW A B)) (LOG C)) (* B (DIV (LOG A) (LOG C)))) ((DIV (* A B) (* A C)) (DIV B C)) ;; CANCELLATION ((DIV (POW A (DIV 1 2)) (POW B (DIV 1 2))) (POW (DIV A B) (DIV 1 2))) ;; DOMAIN >0 ((* A 0) 0) ;; UNSAFE WITH NANS ((* A 1) A) ((* A A) (POW A 2)) ((* A (SUB 0 1)) (SUB 0 A)) ((* A (DIV 1 B)) (DIV A B)) ((* (POW A 2) A) (POW A 3)) ((* (* K A) (* K B)) (* (* 2 K) (* A B))) ((* (* B A) A) (* (POW A 2) B)) ;; SHOULD NOT BE NEEDED ((* (* (POW A 2) B) A) (* (* (POW A 2) A) B)) ;; ((* B (* K (POW A 2))) (* K (* B (POW A 2)))) ((* (* C (* A B)) A) (* (* C (POW A 2)) B)) ((* (POW A B) (POW A C)) (POW A (ADD B C))) ;; EXPONENT RULE ((* (* TODO (POW A B)) (POW A C)) (* TODO (POW A (ADD B C)))) ;; EXPONENT RULE ((* (POW A B) (POW C B)) (POW (* A C) B)) ;; DOMAIN IS APPROXIMATELY ABC≥0 ((* A (POW A K)) (POW A (ADD K 1))) ;; NOTE: A=0∧K<0 IS DIVIDE ERROR ((* (DIV A B) (DIV B C)) (DIV A C)) ;; CANCELLATION ((* (DIV B A) A) B) ;; CANCELLATION ((* (POW A (DIV 1 2)) (POW A (DIV 1 2))) A) ((* (POW A (DIV 1 2)) (POW B (DIV 1 2))) (POW (* A B) (DIV 1 2))) ;; DOMAIN ≥0 ((* (POW C A) (POW C B)) (POW C (ADD A B))) ;; ((* (DIV A 2) 2) (AND A (NOT 1))) ;; ONLY FOR UNSIGNED INTEGER ARITHMETIC ;; ((* (DIV A B) C) (DIV (* A C) B)) ;; EVIL ((REM 0 A) 0) ((REM A A) 0) ((REM A 1) 0) ;; INTEGER ONLY ((REM A (SUB 0 1)) 0) ((REM (REM A B) B) (REM A B)) ((REM A (SUB 0 B)) (REM A B)) ;; REMAINDER ONLY; NOT MODULUS ((AND A A) A) ((AND (LT A B) (LT B C)) (LT A C)) ;; TRANSITIVE PROPERTY ((AND A 0) 0) ((AND A (NOT A)) 0) ((AND (ADD (* 2 A) 1) (* 2 B)) (AND (* 2 A) (* B 2))) ((AND (NOT A) (NOT B)) (NOT (AND A B))) ;; DE MORGAN'S LAW ((AND A (NOT 0)) A) ((AND A (NOT (AND A B))) (AND A (NOT B))) ((AND (OR A B) (NOT A)) (AND B (NOT A))) ((AND (OR A B) (NOT (AND A B))) (XOR A B)) ((AND (OR A B) (XOR (NOT A) B)) (AND A B)) ((AND (OR (NOT A) B) (OR A (NOT B))) (NOT (XOR A B))) ((AND (NOT A) (NOT B)) (NOT (OR A B))) ((AND (XOR A B) B) (AND (NOT A) B)) ((AND (AND A B) B) (AND A B)) ((AND (AND A B) (AND A C)) (AND (AND A B) C)) ((AND (OR A B) (NOT (XOR A B))) (AND A B)) ((OR A A) A) ((OR A 0) A) ((OR (NOT A) (NOT B)) (NOT (OR A B))) ;; DE MORGAN'S LAW ((OR A (NOT (OR A B))) (OR A (NOT B))) ((OR (AND (NOT A) B) (NOT (OR A B))) (NOT A)) ((OR (AND A B) (NOT (OR A B))) (NOT (XOR A B))) ((OR (XOR A B) (NOT (OR A B))) (NOT (AND A B))) ((OR (AND A B) (NOT A)) (OR B (NOT A))) ((OR (AND A B) (XOR A B)) (OR A B)) ((OR (NOT A) (NOT B)) (NOT (AND A B))) ((OR (OR A B) B) (OR A B)) ((OR (OR A B) (OR A C)) (OR (OR A B) C)) ((OR (NOT A) A) (SUB 0 1)) ((OR A (NOT 0)) (NOT 0)) ((OR (AND A (NOT B)) (AND (NOT A) B)) (XOR A B)) ((OR (XOR A B) A) (OR A B)) ((OR A (NOT (XOR A B))) (OR A (NOT B))) ((OR (AND A B) (NOT (XOR A B))) (NOT (XOR A B))) ((OR (OR A B) (AND A B)) (OR A B)) ((OR (OR A B) (XOR A B)) (OR A B)) ((XOR A A) 0) ((XOR (OR A B) (OR A (NOT B))) (NOT A)) ((XOR (OR (NOT A) B) (XOR A B)) (OR A (NOT B))) ((XOR (XOR A B) (OR A B)) (AND A B)) ((XOR (AND A B) (XOR A B)) (OR A B)) ((XOR (AND A B) (OR A B)) (XOR A B)) ((XOR (OR (NOT A) B) (OR A (NOT B))) (XOR A B)) ((XOR (OR A B) A) (AND B (NOT A))) ((XOR (NOT A) (NOT B)) (XOR A B)) ((XOR (NOT A) B) (XOR A (NOT B))) ((XOR (AND A B) B) (AND (NOT A) B)) ((XOR (XOR A B) B) A) ((XOR (XOR A B) (XOR A C)) (XOR B C)) ((XOR A (NOT 0)) (NOT A)) ((XOR (NOT A) A) (SUB 0 1)) ((XOR (AND A (NOT B)) (AND (NOT A) B)) (XOR A B)) ((XOR (AND A (NOT B)) (NOT A)) (NOT (AND A B))) ((NOT (SAR (NOT A) B)) (SAR A B)) ((NOT (SUB 0 A)) (SUB A 1)) ((NOT (ADD A (SUB 0 1))) (SUB 0 A)) ((NOT (ADD (NOT A) B)) (SUB A B)) ((NOT (AND (NOT A) B)) (OR A (NOT B))) ((NOT (OR (NOT A) B)) (AND A (NOT B))) ((NOT (ROR (NOT A) B)) (ROR A B)) ((NOT (ROL (NOT A) B)) (ROL A B)) ((MIN A A) A) ((MIN (MAX A B) B) B) ((MIN A (SUB 0 A)) (SUB 0 (ABS A))) ((MIN (NOT A) (NOT B)) (NOT (MAX A B))) ((MAX A A) A) ((MAX (MIN A B) B) B) ((MAX A (SUB 0 A)) (ABS A)) ((MAX (NOT A) (NOT B)) (NOT (MIN A B))) ((SIN (ATAN A)) (DIV A (POW (ADD (POW A 2) 1) (DIV 1 2)))) ((SIN (ASIN A)) A) ((COS (SUB 0 A)) (COS A)) ((COS (ABS A)) (COS A)) ((COS (ABS A)) (COS A)) ((COS (ATAN A)) (DIV 1 (POW (ADD (POW A 2) 1) (DIV 1 2)))) ((COS (ACOS A)) A) ((COS (ASIN A)) (POW (SUB 1 (POW A 2)) (DIV 1 2))) ((TAN (ATAN A)) A) ((SINH (ATANH A)) (DIV A (POW (* (SUB 1 A) (ADD 1 A)) (DIV 1 2)))) ((COSH (ATANH A)) (DIV 1 (POW (* (SUB 1 A) (ADD 1 A)) (DIV 1 2)))) ((CONJ (CONJ A)) A) ((ABS K) K) ((LOG 1) 0) ((SHL A 0) A) ((SAR A 0) A) ((SHR A 0) A) ((ROR A 0) A) ((ROL A 0) A) ((NEG A) (SUB 0 A)) ((PLUS A B) (ADD A B)) ((TIMES A B) (* A B)) ((SQR A) (POW A 2)) ((EXP A) (POW E A)) ((EXP2 A) (POW 2 A)) ((EXPT A B) (POW A B)) ((LN A) (LOG A)) ((LOG2 A) (DIV (LOG A) (LOG 2))) ((LOG10 A) (DIV (LOG A) (LOG 10))) ((LOGN A B) (DIV (LOG A) (LOG B))) ((HYPOT A B) (POW (ADD (POW A 2) (POW B 2)) (DIV 1 2))) ((ACOSH A) (DIV (LOG (ADD A (POW (SUB (POW A 2) 1) (DIV 1 2)))) (LOG E))) ((ASINH A) (DIV (LOG (ADD A (POW (ADD (POW A 2) 1) (DIV 1 2)))) (LOG E))) ((ACOSH A) (DIV (LOG (ADD A (POW (SUB (POW A 2) 1) (DIV 1 2)))) (LOG E))) ;; DOMAIN A≥1 ;; ((ATANH A) (LOGN (* (DIV 1 2) (LOGN (DIV (ADD 1 A) (SUB 1 A)) E)))) ;; ((DIV A (SHL 1 B)) (SAR A B)) ;; ONLY FOR UNSIGNED INTEGER A ((SQRT A) (POW A (DIV 1 2))) ((CBRT A) (POW A (DIV 1 3))) ((ROOT A B) (POW A (DIV 1 B)))))) (DEFUN SIMPLIFY (X RULES) (RIGHTEN (SIMPTREE (IF EXPLAIN (PRINT 'SIMPLIFY (RIGHTEN X)) (RIGHTEN X)) (OR RULES LOLGEBRA)))) (DEFUN DERIV (X WRT) (COND ((EQ X WRT) '1) ((ATOM X) '0) ((LET ((OP (CAR X)) (X (CADR X)) (Y (CADDR X))) (COND ((OR (EQ OP 'ADD) (EQ OP 'SUB)) `(,OP ,(DERIV X WRT) ,(DERIV Y WRT))) ((EQ OP '*) `(ADD (* ,X ,(DERIV Y WRT)) (* ,(DERIV X WRT) ,Y))) ((EQ OP 'DIV) `(SUB (DIV ,(DERIV X WRT) ,Y) (DIV (* ,X ,(DERIV Y WRT)) (POW ,Y 2)))) ((EQ OP 'POW) `(ADD (* (POW ,X ,Y) (* (LOG ,X) ,(DERIV Y WRT))) (* ,Y (* (POW ,X (SUB ,Y 1)) ,(DERIV X WRT))))) ((EQ OP 'LOG) `(DIV ,(DERIV X WRT) ,X)) ((EQ OP 'SIN) `(* ,(DERIV X WRT) (COS ,X))) ((EQ OP 'COS) `(SUB 0 (* ,(DERIV X WRT) (SIN ,X)))) ((EQ OP 'ABS) `(DIV (* ,X ,(DERIV X WRT)) (ABS ,X))) ((ERROR 'HOW (LIST 'DERIV (LIST OP X Y) WRT)))))))) (DEFUN DERIVATIVE (X Y RULES) (SIMPLIFY (LET ((X (SIMPLIFY X))) (IF EXPLAIN (PRINT 'DIFFERENTIATE X 'WRT Y 'IS (DERIV X Y)) (DERIV X Y))) RULES))
17,776
484
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/char.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/char.h" pureconst bool IsHex(int c) { return ((L'0' <= c && c <= L'9') || (L'A' <= c && c <= L'F') || (L'a' <= c && c <= L'f')); } pureconst int GetDiglet(int c) { if (IsDigit(c)) return c - L'0'; if (IsUpper(c)) return c - L'A' + 10; if (IsLower(c)) return c - L'a' + 10; return -1; } pureconst bool IsSpace(int c) { switch (c) { case L' ': case L'\t': case L'\n': case L'\f': case L'\v': case L'\r': return true; default: return false; } } pureconst bool IsParen(int c) { switch (c) { case L'(': case L')': case L'[': case L']': case L'{': case L'}': return true; default: return false; } }
2,567
60
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/error.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "tool/plinko/lib/error.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/printf.h" #include "tool/plinko/lib/stack.h" relegated wontreturn void Raise(int x) { Flush(1); Flush(2); longjmp(crash, ~x); } relegated wontreturn void Error(const char *f, ...) { int n; va_list va; Flush(1); Flush(2); va_start(va, f); n = Fprintf(2, "\e[1;31merror\e[0m: "); n = Vfnprintf(f, va, 2, n); Fprintf(2, "%n"); va_end(va); Raise(kError); } relegated wontreturn void OutOfMemory(void) { Error("out of memory"); } relegated wontreturn void StackOverflow(void) { Error("stack overflow"); } relegated wontreturn void React(int e, int x, int k) { if (!sp || e != LO(GetCurrentFrame())) Push(e); Push(x); Raise(k); }
2,658
58
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/iscar.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/plinko.h" /** * Matches * * (⍅ X) * * @return X on success, or 0 on mismatch * @note ⍅ means CAR */ int IsCar(int x_) { dword w_; if (x_ >= 0) return 0; w_ = Get(x_); // (⍅ X) int ax_ = LO(w_); int dx_ = HI(w_); if (ax_ != kCar) return 0; if (dx_ >= 0) return 0; w_ = Get(dx_); // (X) int adx_ = LO(w_); int ddx_ = HI(w_); int X = adx_; if (ddx_) return 0; return X; }
2,277
44
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/ktpenc.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_KTPENC_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_KTPENC_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ extern const short kTpEnc[25]; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_KTPENC_H_ */
306
11
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/index.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/index.h" #define INDEXER(NAME, EVAL) \ struct T NAME(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { \ return Ret(MAKE(EVAL(FasterRecurse(HI(d), HI(ea), p1, p2)), 0), tm, r); \ } INDEXER(DispatchCaar, Caar); INDEXER(DispatchCadr, Cadr); INDEXER(DispatchCdar, Cdar); INDEXER(DispatchCddr, Cddr); INDEXER(DispatchCaaar, Caaar); INDEXER(DispatchCaadr, Caadr); INDEXER(DispatchCadar, Cadar); INDEXER(DispatchCaddr, Caddr); INDEXER(DispatchCdaar, Cdaar); INDEXER(DispatchCdadr, Cdadr); INDEXER(DispatchCddar, Cddar); INDEXER(DispatchCdddr, Cdddr); INDEXER(DispatchCaaaar, Caaaar); INDEXER(DispatchCaaadr, Caaadr); INDEXER(DispatchCaadar, Caadar); INDEXER(DispatchCaaddr, Caaddr); INDEXER(DispatchCadaar, Cadaar); INDEXER(DispatchCadadr, Cadadr); INDEXER(DispatchCaddar, Caddar); INDEXER(DispatchCadddr, Cadddr); INDEXER(DispatchCdaaar, Cdaaar); INDEXER(DispatchCdaadr, Cdaadr); INDEXER(DispatchCdadar, Cdadar); INDEXER(DispatchCdaddr, Cdaddr); INDEXER(DispatchCddaar, Cddaar); INDEXER(DispatchCddadr, Cddadr); INDEXER(DispatchCdddar, Cdddar); INDEXER(DispatchCddddr, Cddddr);
3,003
54
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/types.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_TYPES_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_TYPES_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ typedef unsigned long dword; struct qword { dword ax; dword dx; }; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_TYPES_H_ */
344
16
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/countatoms.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/plinko.h" nosideeffect int CountAtoms(int x, int max, int res) { if (!x || res >= max) return res; if (x > 0) return res + 1; return CountAtoms(Cdr(x), max, CountAtoms(Car(x), max, res)); }
2,059
26
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/vars.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/runtime/runtime.h" #include "tool/plinko/lib/plinko.h" #ifdef __llvm__ dword cGets; dword *g_mem; #endif unsigned short sp; bool ftrace; bool mtrace; bool gtrace; bool noname; bool literally; bool symbolism; bool dump; // -d causes globals to be printed at exit bool trace; // -t causes evaluator to print explanations bool loga; // -a flag causes -t to print massive environment bool logc; // -c flag causes -t to print jupiterian closures bool quiet; // tracks (quiet) state which suppresses (print) bool stats; // -s causes statistics to be printed after each evaluation bool simpler; // -S usually disables pretty printing so you can | cut -c-80 int cx; // cons stack pointer int ax; // used by read atom interner int dx; // used by read for lookahead int bp[4]; // buffer pointers for file descriptors int pdp; // used by print to prevent stack overflow int depth; // when tracing is enabled tracks trace depth int fails; // failure count to influence process exit code int cHeap; // statistical approximate of minimum cx during work int cAtoms; // statistical count of characters in atom hash tree int cFrost; // monotonic frostline of defined permanent cons cells int globals; // cons[rbtree;bool 0] of globally scoped definitions i.e. 𝑎 int revglob; // reverse mapped rbtree of globals (informational printing) int ordglob; // the original defined order for all global definition keys int kTrace; int kMtrace; int kFtrace; int kGtrace; int kEq; int kGc; int kCmp; int kCar; int kBackquote; int kDefun; int kDefmacro; int kAppend; int kBeta; int kAnd; int kCdr; int kRead; int kDump; int kQuote; int kProgn; int kLambda; int kDefine; int kMacro; int kQuiet; int kSplice; int kPrinc; int kPrint; int kPprint; int kIgnore; int kExpand; int kCond; int kAtom; int kOr; int kCons; int kIntegrate; int kString; int kSquare; int kCurly; int kFork; int kGensym; int kTrench; int kYcombinator; int kBecause; int kTherefore; int kUnion; int kImplies; int kNand; int kNor; int kXor; int kIff; int kPartial; int kError; int kExit; int kClosure; int kFunction; int kCycle; int kFlush; int kIgnore0; int kComma; int kIntersection; int kList; int kMember; int kNot; int kReverse; int kSqrt; int kSubset; int kSuperset; int kPrintheap; int kImpossible; int kUnchanged; int kOrder; jmp_buf crash; jmp_buf exiter; char g_buffer[4][512]; unsigned short g_depths[128][3]; dword tick; dword cSets; dword *g_dis; EvalFn *eval; BindFn *bind_; char **inputs; EvalFn *expand; EvlisFn *evlis; PairFn *pairlis; TailFn *kTail[8]; RecurseFn *recurse; int g_copy[256]; int g_print[256]; int kAlphabet[26]; dword g_stack[STACK]; int kConsAlphabet[26]; long g_assoc_histogram[12]; long g_gc_lop_histogram[30]; long g_gc_marks_histogram[30]; long g_gc_dense_histogram[30]; long g_gc_sparse_histogram[30]; long g_gc_discards_histogram[30];
4,743
159
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/hasatom.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/plinko.h" nosideeffect bool HasAtom(int v, int x) { if (!x) return false; if (x > 0) return v == x; return HasAtom(v, Car(x)) || HasAtom(v, Cdr(x)); }
2,020
26
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/symbolize.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/plinko.h" pureconst int Symbolize(int x) { if (literally) return -1; if (x == TERM) return -1; DCHECK_LT(x, TERM); switch (LO(Get(x))) { case L'A': if (x == kAtom) return L'α'; if (x == kAnd) return L'∧'; if (x == kAppend) return L'║'; return -1; case L'B': if (x == kBeta) return L'β'; if (x == kBecause) return L'∵'; return -1; case L'C': if (x == kCar) return L'⍅'; if (x == kCdr) return L'⍆'; if (x == kClosure) return L'⅄'; if (x == kCond) return L'ζ'; if (x == kCons) return L'ℶ'; if (x == kCmp) return L'≷'; if (x == kCycle) return L'⟳'; return -1; case L'D': if (x == kDefine) return L'≝'; if (x == kDefmacro) return L'Ψ'; if (x == kDefun) return L'Λ'; return -1; case L'E': if (x == kEq) return L'≡'; if (x == kExpand) return L'ə'; return -1; case L'F': if (x == kFunction) return L'𝑓'; if (x == kFork) return L'⋔'; return -1; case L'P': if (x == kPartial) return L'∂'; return -1; case L'I': if (x == kIff) return L'⟺'; if (x == kImplies) return L'⟶'; if (x == kIntegrate) return L'∫'; if (x == kIntersection) return L'∩'; return -1; case L'L': if (x == kLambda) return L'λ'; if (x == kList) return L'ℒ'; return -1; case L'M': if (x == kMacro) return L'ψ'; if (x == kMember) return L'∊'; return -1; case L'N': if (!x) return L'⊥'; if (x == kNand) return L'⊼'; if (x == kNor) return L'⊽'; if (x == kNot) return L'¬'; return -1; case L'O': if (x == kOr) return L'∨'; if (x == kOrder) return L'⊙'; return -1; case L'Q': if (x == kQuote) return L'Ω'; return -1; case L'R': if (x == kReverse) return L'Я'; return -1; case L'S': if (x == kSqrt) return L'√'; if (x == kSubset) return L'⊂'; if (x == kSuperset) return L'⊃'; return -1; case L'T': if (x == 1) return L'⊤'; if (x == kTherefore) return L'∴'; return -1; case L'U': if (x == kUnion) return L'∪'; if (x == kImpossible) return L'∅'; return -1; case L'X': if (x == kXor) return L'⊻'; return -1; case L'Y': if (x == kYcombinator) return L'𝕐'; return -1; default: return -1; } }
4,361
113
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/printheap.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/fmt/itoa.h" #include "libc/runtime/symbols.internal.h" #include "libc/str/str.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/printf.h" static const char *GetElfSymbol(uintptr_t funcaddr) { int s; static char buf[19]; struct SymbolTable *t; if ((t = GetSymbolTable())) { if ((s = __get_symbol(t, funcaddr)) != -1) { return t->name_base + t->names[s]; } } buf[0] = '0'; buf[1] = 'x'; uint64toarray_radix16(funcaddr, buf + 2); return buf; } static const char *GetDispatchName(int x) { const char *s; s = GetElfSymbol(LO(GetShadow(x))); if (_startswith(s, "Dispatch")) s += 8; return s; } void PrintHeap(int i) { for (; i-- > cx;) { Printf("%10d (%10d . %10d) %10s[%10d] %p%n", i, LO(Get(i)), HI(Get(i)), GetDispatchName(i), HI(GetShadow(i)), i); } }
2,678
53
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/plan.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/countbranch.h" #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/error.h" #include "tool/plinko/lib/index.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/printf.h" #include "tool/plinko/lib/stack.h" #include "tool/plinko/lib/types.h" nosideeffect int CountSimpleParameters(int x) { int i; for (i = 0; x; ++i, x = Cdr(x)) { if (x > 0) return -1; // variadic args aren't simple if (!Car(x)) return -1; // nil parameters aren't simple if (Car(x) < 0) return -1; // destructured parameters aren't simple } return i; } nosideeffect int CountSimpleArguments(int x) { int i; for (i = 0; x; ++i, x = Cdr(x)) { if (x > 0) return -1; // apply isn't simple } return i; } static dword PlanQuote(int e, int a, int s) { if (Cdr(e) >= 0) React(e, e, kQuote); // one normal parameter required return MAKE(DF(DispatchQuote), Cadr(e)); // >1 prms is sectorlisp comment } static dword PlanCar(int e, int a, int s) { if (!Cdr(e)) return DF(DispatchNil); // (⍅) ⟺ (⍅ ⊥) if (Cddr(e)) React(e, e, kCar); // too many args if (!Cadr(e)) return DF(DispatchNil); return MAKE(DF(DispatchCar), Cadr(e)); } static dword PlanCdr(int e, int a, int s) { if (!Cdr(e)) return DF(DispatchNil); // (⍆) ⟺ (⍆ ⊥) if (Cddr(e)) React(e, e, kCdr); // too many args if (!ARG1(e)) return DF(DispatchNil); return MAKE(DF(DispatchCdr), Cadr(e)); } static dword PlanAtom(int e, int a, int s) { if (CountSimpleArguments(Cdr(e)) != 1) React(e, e, kAtom); return MAKE(DF(DispatchAtom), Cadr(e)); } static dword PlanEq(int e, int a, int s) { int n = CountSimpleArguments(Cdr(e)); if (n != 2 && n != 1) React(e, e, kAtom); // (≡ 𝑥) is our (null 𝑥) return MAKE(DF(DispatchEq), Caddr(e)); } static dword PlanCmp(int e, int a, int s) { if (CountSimpleArguments(Cdr(e)) != 2) React(e, e, kCmp); return MAKE(DF(DispatchCmp), Caddr(e)); } static dword PlanOrder(int e, int a, int s) { if (CountSimpleArguments(Cdr(e)) != 2) React(e, e, kOrder); return MAKE(DF(DispatchOrder), Caddr(e)); } static dword PlanCons(int e, int a, int s) { int p = CountSimpleArguments(Cdr(e)); if (p == -1) Error("cons dot arg"); if (p > 2) Error("too many args"); return MAKE(DF(DispatchCons), Caddr(e)); } static dword PlanLambda(int e, int a, int s) { if (CountSimpleArguments(Cdr(e)) == -1) Error("bad lambda: %S", e); return DF(DispatchLambda); } static dword PlanCond(int e, int a, int s) { int x, b; if (!Cdr(e)) return DF(DispatchNil); // (ζ) ⟺ ⊥ for (x = e; (x = Cdr(x));) { if (x > 0) React(e, e, kCond); // (ζ . 𝑣) not allowed if (Car(x) >= 0) React(e, e, kCond); // (ζ 𝑣) not allowed if (Cdr(Car(x)) > 0) React(e, e, kCond); // (ζ (𝑥 . 𝑣)) not allowed } return MAKE(DF(DispatchCond), Cdr(e)); } static dword PlanProgn(int e, int a, int s) { int x; if (!Cdr(e)) return DF(DispatchNil); // (progn) ⟺ ⊥ if (CountSimpleArguments(Cdr(e)) == -1) React(e, e, kProgn); return MAKE(DF(DispatchProgn), Cdr(e)); } static dword PlanQuiet(int e, int a, int s) { if (Cdr(e) > 0) React(e, e, kQuiet); // apply not allowed if (!Cdr(e)) React(e, e, kQuiet); // zero args not allowed if (Cdr(Cdr(e))) React(e, e, kQuiet); // >1 args not allowed return DF(DispatchQuiet); } static dword PlanTrace(int e, int a, int s) { if (Cdr(e) > 0) React(e, e, kTrace); // apply not allowed if (!Cdr(e)) React(e, e, kTrace); // zero args not allowed if (Cdr(Cdr(e))) React(e, e, kTrace); // >1 args not allowed return DF(DispatchTrace); } static dword PlanFtrace(int e, int a, int s) { if (Cdr(e) > 0) React(e, e, kFtrace); // apply not allowed if (!Cdr(e)) React(e, e, kFtrace); // zero args not allowed if (Cdr(Cdr(e))) React(e, e, kFtrace); // >1 args not allowed return DF(DispatchFtrace); } static dword PlanFunction(int e, int a, int s) { if (CountSimpleArguments(Cdr(e)) != 1) Raise(kFunction); return MAKE(DF(DispatchFunction), Cadr(e)); } static dword PlanBeta(int e, int a, int s) { if (CountSimpleArguments(Cdr(e)) != 1) Raise(kBeta); return MAKE(DF(DispatchBeta), Cadr(e)); } static dword PlanIgnore(int e, int a, int s) { if (!Cdr(e)) return DF(DispatchIgnore0); if (Cdr(e) > 0) React(e, e, kIgnore); // apply not allowed if (!Cdr(e)) React(e, e, kIgnore); // zero args not allowed if (Cdr(Cdr(e))) React(e, e, kIgnore); // >1 args not allowed return DF(DispatchIgnore1); } static dword PlanExpand(int e, int a, int s) { if (CountSimpleArguments(Cdr(e)) != 1) React(e, e, kExpand); return MAKE(DF(DispatchExpand), Cadr(e)); } static dword PlanPrint(int e, int a, int s) { if (CountSimpleArguments(Cdr(e)) == -1) React(e, e, kPrint); return DF(DispatchPrint); } static dword PlanGensym(int e, int a, int s) { if (CountSimpleArguments(Cdr(e))) React(e, e, kGensym); return DF(DispatchGensym); } static dword PlanPprint(int e, int a, int s) { if (CountSimpleArguments(Cdr(e)) == -1) React(e, e, kPprint); return DF(DispatchPprint); } static dword PlanPrintheap(int e, int a, int s) { int p = CountSimpleArguments(Cdr(e)); if (p != 0 && p != 1) React(e, e, kPrintheap); return DF(DispatchPrintheap); } static dword PlanGc(int e, int a, int s) { if (CountSimpleArguments(Cdr(e)) != 1) React(e, e, kGc); return MAKE(DF(DispatchGc), Cadr(e)); } static dword PlanPrinc(int e, int a, int s) { if (CountSimpleArguments(Cdr(e)) == -1) React(e, e, kPrinc); return DF(DispatchPrinc); } static dword PlanFlush(int e, int a, int s) { if (CountSimpleArguments(Cdr(e)) == -1) React(e, e, kFlush); return DF(DispatchFlush); } static dword PlanError(int e, int a, int s) { return DF(DispatchError); } static dword PlanExit(int e, int a, int s) { if (Cdr(e)) React(e, e, kExit); return DF(DispatchExit); } static dword PlanRead(int e, int a, int s) { if (Cdr(e)) React(e, e, kRead); return DF(DispatchRead); } static dword PlanDefine(int e, int a, int s) { return DF(DispatchIdentity); } static dword PlanClosure(int e, int a, int s) { return DF(DispatchIdentity); } static dword PlanLet(int e, int a, int s) { int p, n; if ((n = CountSimpleArguments(Cdr(e))) == -1) return DF(DispatchFuncall); if (CountSimpleArguments(Car(e)) < 3) React(e, e, kLambda); // need (λ 𝑥 𝑦) switch (CountSimpleParameters(Cadr(Car(e)))) { case -1: return DF(DispatchFuncall); case 0: if (n != 0) Error("let argument count mismatch: %S", e); return MAKE(DF(DispatchShortcut), Caddr(Car(e))); // ((λ ⊥ 𝑦)) becomes 𝑦 case 1: if (n != 1) Error("let argument count mismatch: %S", e); return MAKE(DF(DispatchLet1), Cdar(e)); default: return MAKE(DF(DispatchFuncall), 0); } } static dontinline dword PlanPrecious(int e, int a, int s, int f) { int x; DCHECK_GT(f, 0); if (f == kCar) return PlanCar(e, a, s); if (f == kCdr) return PlanCdr(e, a, s); if (f == kGc) return PlanGc(e, a, s); if (f == kEq) return PlanEq(e, a, s); if (f == kCmp) return PlanCmp(e, a, s); if (f == kBeta) return PlanBeta(e, a, s); if (f == kCond) return PlanCond(e, a, s); if (f == kAtom) return PlanAtom(e, a, s); if (f == kCons) return PlanCons(e, a, s); if (f == kExit) return PlanExit(e, a, s); if (f == kRead) return PlanRead(e, a, s); if (f == kOrder) return PlanOrder(e, a, s); if (f == kQuote) return PlanQuote(e, a, s); if (f == kProgn) return PlanProgn(e, a, s); if (f == kQuiet) return PlanQuiet(e, a, s); if (f == kTrace) return PlanTrace(e, a, s); if (f == kPrint) return PlanPrint(e, a, s); if (f == kPrinc) return PlanPrinc(e, a, s); if (f == kFlush) return PlanFlush(e, a, s); if (f == kError) return PlanError(e, a, s); if (f == kMacro) return PlanLambda(e, a, s); if (f == kFtrace) return PlanFtrace(e, a, s); if (f == kLambda) return PlanLambda(e, a, s); if (f == kGensym) return PlanGensym(e, a, s); if (f == kPprint) return PlanPprint(e, a, s); if (f == kIgnore) return PlanIgnore(e, a, s); if (f == kExpand) return PlanExpand(e, a, s); if (f == kDefine) return PlanDefine(e, a, s); if (f == kClosure) return PlanClosure(e, a, s); if (f == kFunction) return PlanFunction(e, a, s); if (f == kPrintheap) return PlanPrintheap(e, a, s); if (!a) { Push(e); Push(f); Raise(kFunction); } return DF(DispatchFuncall); } dontinline dword Plan(int e, int a, int s) { int c, f, p, x1, x2, x3, x4; DCHECK_LT(e, 0); if ((x1 = IsCar(e))) { if ((x2 = IsCar(x1))) { if ((x3 = IsCar(x2))) { if ((x4 = IsCar(x3))) return MAKE(DF(DispatchCaaaar), x4); if ((x4 = IsCdr(x3))) return MAKE(DF(DispatchCaaadr), x4); return MAKE(DF(DispatchCaaar), x3); } if ((x3 = IsCdr(x2))) { if ((x4 = IsCar(x3))) return MAKE(DF(DispatchCaadar), x4); if ((x4 = IsCdr(x3))) return MAKE(DF(DispatchCaaddr), x4); return MAKE(DF(DispatchCaaar), x3); } return MAKE(DF(DispatchCaar), x2); } if ((x2 = IsCdr(x1))) { if ((x3 = IsCar(x2))) { if ((x4 = IsCar(x3))) return MAKE(DF(DispatchCadaar), x4); if ((x4 = IsCdr(x3))) return MAKE(DF(DispatchCadadr), x4); return MAKE(DF(DispatchCadar), x3); } if ((x3 = IsCdr(x2))) { if ((x4 = IsCar(x3))) return MAKE(DF(DispatchCaddar), x4); if ((x4 = IsCdr(x3))) return MAKE(DF(DispatchCadddr), x4); return MAKE(DF(DispatchCaddr), x3); } return MAKE(DF(DispatchCadr), x2); } return MAKE(DF(DispatchCar), x1); } if ((x1 = IsCdr(e))) { if ((x2 = IsCar(x1))) { if ((x3 = IsCar(x2))) { if ((x4 = IsCar(x3))) return MAKE(DF(DispatchCdaaar), x4); if ((x4 = IsCdr(x3))) return MAKE(DF(DispatchCdaadr), x4); return MAKE(DF(DispatchCdaar), x3); } if ((x3 = IsCdr(x2))) { if ((x4 = IsCar(x3))) return MAKE(DF(DispatchCdadar), x4); if ((x4 = IsCdr(x3))) return MAKE(DF(DispatchCdaddr), x4); return MAKE(DF(DispatchCdadr), x3); } return MAKE(DF(DispatchCdar), x2); } if ((x2 = IsCdr(x1))) { if ((x3 = IsCar(x2))) { if ((x4 = IsCar(x3))) return MAKE(DF(DispatchCddaar), x4); if ((x4 = IsCdr(x3))) return MAKE(DF(DispatchCddadr), x4); return MAKE(DF(DispatchCddar), x3); } if ((x3 = IsCdr(x2))) { if ((x4 = IsCar(x3))) return MAKE(DF(DispatchCdddar), x4); if ((x4 = IsCdr(x3))) return MAKE(DF(DispatchCddddr), x4); return MAKE(DF(DispatchCdddr), x3); } return MAKE(DF(DispatchCddr), x2); } return MAKE(DF(DispatchCdr), x1); } if ((f = Car(e)) > 0) { if (LO(GetShadow(f)) == EncodeDispatchFn(DispatchPrecious)) { return PlanPrecious(e, a, s, f); } if (!HasAtom(f, s) && (f = Assoc(f, a))) { f = Cdr(f); if (IsYcombinator(f)) { return DF(DispatchYcombine); } else if (f < 0 && Car(f) == kClosure && f > e) { if (Car(Cadr(f)) == kLambda) { c = CountSimpleArguments(Cdr(e)); p = CountSimpleParameters(Cadr(Cadr(f))); if (c == 1 && p == 1) { return MAKE(DF(DispatchCall1), f); } else if (c == 2 && p == 2) { return MAKE(DF(DispatchCall2), f); } } return MAKE(DF(DispatchFuncall), f); } } } else if (Car(f) == kLambda) { return PlanLet(e, a, s); } return DF(DispatchFuncall); } struct T DispatchPlan(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { SetShadow(LO(ea), (d = Plan(LO(ea), HI(ea), 0))); return DecodeDispatchFn(d)(ea, tm, r, p1, p2, d); }
13,566
375
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/flush.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/errno.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/printf.h" void Flush(int fd) { int n, i = 0; while (i < bp[fd]) { if ((n = write(fd, g_buffer[fd] + i, bp[fd] - i)) > 0) { i += n; } else if (errno != EINTR) { ++fails; Fprintf(2, "error: write() %s%n", strerror(errno)); longjmp(exiter, 1); } } bp[fd] = 0; }
2,316
39
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/dispatchycombine.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/index.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/stack.h" struct T DispatchRecur(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { struct Binding bz; bz = bind_(Car(Car(HI(d))), Cdr(LO(ea)), HI(ea), Cdr(HI(d)), p1, p2); return TailCall(MAKE(Cdr(Car(HI(d))), bz.u), tm, r, bz.p1, 0); } struct T DispatchRecur1(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { return TailCall( MAKE(Car(HI(d) + 5), Cdr(HI(d) + 1)), tm, r, MAKE(Car(HI(d) + 4), FasterRecurse(Car(Cdr(LO(ea))), HI(ea), p1, p2)), 0); } struct T DispatchRecur2(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { return TailCall( MAKE(Car(HI(d) + 6), Cdr(HI(d))), tm, r, MAKE(Car(HI(d) + 4), FasterRecurse(Car(Cdr(LO(ea))), HI(ea), p1, p2)), MAKE(Car(HI(d) + 5), FasterRecurse(Car(Cdr(Cdr(LO(ea)))), HI(ea), p1, p2))); } struct T DispatchYcombine(dword ea, dword tm, dword r, dword p1, dword p2, dword d) { int ycomb, z, u, t, p, b, name, lambda, closure; SetFrame(r, LO(ea)); r |= NEED_GC; ycomb = recurse(MAKE(Car(LO(ea)), HI(ea)), p1, p2); DCHECK(IsYcombinator(ycomb)); ycomb = Cadr(ycomb); lambda = recurse(MAKE(Cadr(ea), HI(ea)), p1, p2); closure = recurse(MAKE(Caddr(ycomb), Alist(Car(Cadr(ycomb)), lambda, 0)), 0, 0); if (Car(lambda) == kClosure) lambda = Car(Cdr(lambda)); DCHECK_EQ(kClosure, Car(closure)); DCHECK_EQ(kLambda, Car(lambda)); DCHECK_EQ(kLambda, Car(Car(Cdr(closure)))); name = Car(Cadr(lambda)); lambda = Cadr(closure); closure = Enclose(lambda, Cddr(closure)); closure = Preplan(closure, Cddr(closure), 0); lambda = Cadr(closure); if ((p = CountSimpleParameters(Cadr(lambda))) == 1 || p == 2) { if (p == 1) { PlanFuncalls(name, MAKE(DF(DispatchRecur1), closure), Caddr(lambda)); } else { PlanFuncalls(name, MAKE(DF(DispatchRecur2), closure), Caddr(lambda)); } } else { PlanFuncalls(name, MAKE(DF(DispatchRecur), Cons(Cons(Cadr(Cadr(closure)), Caddr(Cadr(closure))), Cddr(closure))), Caddr(lambda)); } return Ret(MAKE(closure, 0), tm, r); }
4,182
82
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/read.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/errno.h" #include "libc/intrin/strace.internal.h" #include "libc/log/check.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/o.h" #include "tool/plinko/lib/char.h" #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/error.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/printf.h" static int Read1(int); static int Read2(int); noinstrument int ReadSpaces(int fd) { size_t n; ssize_t rc; for (;;) { rc = read(fd, g_buffer[fd], sizeof(g_buffer[fd]) - 1); if (rc != -1) { if ((n = rc)) { g_buffer[fd][n] = 0; bp[fd] = 1; return g_buffer[fd][0] & 255; } else if (fd == 0 && *inputs) { close(0); if (open(*inputs++, O_RDONLY) == -1) { ++fails; Flush(1); Fprintf(2, "error: open(%s) %s%n", inputs[-1], strerror(errno)); longjmp(exiter, 1); } } else { Flush(1); Flush(2); longjmp(exiter, 1); } } else if (errno != EINTR) { ++fails; Flush(1); Fprintf(2, "error: read(%d) %s%n", fd, strerror(errno)); longjmp(exiter, 1); } } } noinstrument int ReadByte(int fd) { int c; if ((c = g_buffer[fd][bp[fd]++] & 255)) return c; return ReadSpaces(fd); } noinstrument int ReadChar(int fd) { int b, a = dx; for (;;) { dx = ReadByte(fd); if (dx != ';') { break; } else { do b = ReadByte(fd); while ((b != '\n')); } } if (a >= 0300) { for (b = 0200; a & b; b >>= 1) { a ^= b; } while ((dx & 0300) == 0200) { a <<= 6; a |= dx & 0177; dx = ReadByte(fd); } } if (0 < a && a < TERM) { return ToUpper(a); } Error("thompson-pike varint outside permitted range"); } static int ReadListItem(int fd, int closer, int f(int)) { int i, n, x, y; dword t; if ((x = f(fd)) > 0) { if (Get(x) == MAKE(closer, TERM)) return -0; if (Get(x) == MAKE(L'.', TERM)) { x = f(fd); if ((y = ReadListItem(fd, closer, Read1))) { Error("multiple list items after dot: %S", y); } return x; } } return ShareCons(x, ReadListItem(fd, closer, Read1)); } static int ReadList(int fd, int closer) { int t; ++fails; t = ReadListItem(fd, closer, Read2); --fails; return t; } static int TokenizeInteger(int fd, int b) { dword a; int c, i, x, y; for (i = a = 0;; ++i) { if ((c = GetDiglet(ToUpper(dx))) != -1 && c < b) { a = (a * b) + c; ReadChar(fd); } else { ax = TERM; return Intern(a, TERM); } } } static void ConsumeComment(int fd) { int c, t = 1; for (;;) { c = ReadChar(fd); if (c == '#' && dx == '|') ++t; if (!t) return; if (c == '|' && dx == '#') --t; } } static int ReadAtomRest(int fd, int x) { int y, t, u; ax = y = TERM; if (x == L'\\') x = ReadChar(fd); if (!IsSpace(dx) && !IsParen(dx) && !IsMathAlnum(x) && !IsMathAlnum(dx)) { y = ReadAtomRest(fd, ReadChar(fd)); } return Intern(x, y); } static int ReadAtom(int fd) { int a, s, x; x = ReadChar(fd); if ((s = Desymbolize(x)) != -1) return s; a = ReadAtomRest(fd, x); if (LO(Get(a)) == L'T' && HI(Get(a)) == TERM) { a = 1; } else if (LO(Get(a)) == L'N' && HI(Get(a)) != TERM && LO(Get(HI(Get(a)))) == L'I' && HI(Get(HI(Get(a)))) != TERM && LO(Get(HI(Get(HI(Get(a)))))) == L'L' && HI(Get(HI(Get(HI(Get(a)))))) == TERM) { a = 0; } return a; } static int TokenizeComplicated(int fd) { int c; ReadChar(fd); switch ((c = ReadChar(fd))) { case L'\'': return List(kFunction, Read(fd)); case L'B': return TokenizeInteger(fd, 2); case L'X': return TokenizeInteger(fd, 16); case L'Z': return TokenizeInteger(fd, 36); case L'O': return TokenizeInteger(fd, 8); case L'|': ConsumeComment(fd); return Read(fd); default: Error("unsuppported complicated syntax #%c [0x%x]", c, c); } } static int Read2(int fd) { int r, f, t, l; while (IsSpace((l = dx))) ReadChar(fd); switch (dx) { case L'#': r = TokenizeComplicated(fd); break; case L'\'': ReadChar(fd); r = ShareList(kQuote, Read(fd)); break; case L'`': ReadChar(fd); r = ShareList(kBackquote, Read(fd)); break; case L',': ReadChar(fd); if (dx == L'@') { ReadChar(fd); r = ShareList(kSplice, Read(fd)); } else { r = ShareList(kComma, Read(fd)); } break; case L'"': r = ShareList(kString, ReadString(fd, ReadByte(fd))); break; case L'(': ReadChar(fd); r = ReadList(fd, L')'); break; case L'[': ReadChar(fd); r = ShareList(kSquare, ReadList(fd, L']')); break; case L'{': ReadChar(fd); r = ShareList(kCurly, ReadList(fd, L'}')); break; default: r = ReadAtom(fd); break; } return r; } static int ReadLambda(int fd, int n) { int a, c, r, q = 0; do { c = ReadChar(fd); if (c == L'λ') { for (a = 0; (c = ReadChar(fd)) != '.';) { a = Cons(Intern(c, TERM), a); } for (r = ReadLambda(fd, n); a; a = Cdr(a)) { r = List3(kLambda, Cons(Car(a), 0), r); } } else if (c == L'(') { r = ReadLambda(fd, n + 1); } else if (c == L')') { break; } else if (IsSpace(c)) { Raise(kRead); } else { r = Intern(c, TERM); } if (!q) { q = r; } else { q = List(q, r); } if (!n && dx == L')') break; } while (!IsSpace(dx)); return q; } static int Read1(int fd) { while (IsSpace(dx)) ReadChar(fd); // todo: fix horrible i/o if (dx == 0xCE && (g_buffer[fd][bp[fd]] & 255) == 0xbb) { return ReadLambda(fd, 0); } return Read2(fd); } int Read(int fd) { int r; ftrace_enabled(-1); strace_enabled(-1); r = Read1(fd); strace_enabled(+1); ftrace_enabled(+1); return r; }
7,886
290
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/planfuncalls.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/index.h" #include "tool/plinko/lib/plinko.h" void PlanFuncalls(int n, dword p, int x) { int h; if (x < 0 && (h = Car(x)) != kQuote && h != kClosure && h != kMacro) { if (h == kLambda) { if (!HasAtom(n, Cadr(x))) { PlanFuncalls(n, p, Caddr(x)); } } else if (h == kCond) { while ((x = Cdr(x)) < 0) { if ((h = Car(x)) < 0) { PlanFuncalls(n, p, Car(h)); if ((h = Cdr(h)) < 0) { PlanFuncalls(n, p, Car(h)); } } } } else { if (h == n) { SetShadow(x, p); } while (x) { if (x < 0) { h = Car(x); x = Cdr(x); } else { h = x; x = 0; } PlanFuncalls(n, p, h); } } } }
2,668
56
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/printtree.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/print.h" #include "tool/plinko/lib/printf.h" #include "tool/plinko/lib/tree.h" void PrintTree(int fd, int N, int n) { if (N >= 0) { Print(fd, N); } else { Fnprintf(fd, n, "%s %S%n%I", Red(N) ? "RED" : "BLK", Key(Ent(N))); PrintIndent(fd, n); Fnprintf(fd, n + 2, "%I- %T%n%I", Lit(N)); PrintIndent(fd, n); Fnprintf(fd, n + 2, "%I- %T", Rit(N)); } }
2,241
34
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/gc.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_GC_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_GC_H_ #include "tool/plinko/lib/types.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ struct Gc { int A, B, C; unsigned n; unsigned noop; unsigned *P; dword M[]; }; int MarkSweep(int, int); struct Gc *NewGc(int); int Census(struct Gc *); void Sweep(struct Gc *); void Marker(const dword[], int, int); int Relocater(const dword[], const unsigned[], int, int); forceinline int Relocate(const struct Gc *G, int x) { if (x >= G->C) return x; return Relocater(G->M, G->P, G->A, x); } forceinline void Mark(struct Gc *G, int x) { if (x >= G->A) return; Marker(G->M, G->A, x); } COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_GC_H_ */
805
35
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/isconstant.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/plinko.h" pureconst bool IsConstant(int e) { unsigned f = LO(GetShadow(e)); if (f == EncodeDispatchFn(DispatchNil)) return true; if (f == EncodeDispatchFn(DispatchTrue)) return true; if (f == EncodeDispatchFn(DispatchPrecious)) return true; if (f == EncodeDispatchFn(DispatchQuote)) return true; return false; }
2,187
29
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/bind.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/plinko.h" struct Binding Bind(int x, int y, int a, int u, dword p1, dword p2) { int k, v, w; dword a1 = 0; while (x) { if (x < 0) { if (y <= 0) { k = Car(x), x = Cdr(x); v = Car(y), y = Cdr(y); if (k) { if (k > 0) { if (!a1) { a1 = MAKE(k, FasterRecurse(v, a, p1, p2)); } else { u = Alist(k, FasterRecurse(v, a, p1, p2), u); } } else { u = pairlis(k, FasterRecurse(v, a, p1, p2), u); } } } else { u = pairlis(x, FasterRecurse(y, a, p1, p2), u); y = 0; break; } } else { u = Alist(x, evlis(y, a, p1, p2), u); y = 0; break; } } if (y < 0) { Error("bind: too many arguments x=%S y=%S", x, y); } return (struct Binding){u, a1}; }
2,751
57
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/reverse.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/plinko.h" int Reverse(int x, int y) { dword t; while (x < 0) { t = Get(x); x = HI(t); y = Cons(LO(t), y); } return y; }
2,037
31
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/printf.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/strace.internal.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/time/clockstonanos.internal.h" #include "tool/plinko/lib/char.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/print.h" #include "tool/plinko/lib/printf.h" static inline long GetVarInt(va_list va, signed char t) { if (t <= 0) return va_arg(va, int); return va_arg(va, long); } static int PrintStr(int fd, const char *s, int cols) { int n, j, k = 0, i = 0; n = strlen(s); k += PrintIndent(fd, +cols - n); while (i < n) k += PrintChar(fd, s[i++]); k += PrintIndent(fd, -cols - n); return k; } int Printf(const char *f, ...) { int n; va_list va; va_start(va, f); n = Vfnprintf(f, va, 1, 0); va_end(va); return n; } int Fprintf(int fd, const char *f, ...) { int n; va_list va; va_start(va, f); n = Vfnprintf(f, va, fd, 0); va_end(va); return n; } int Fnprintf(int fd, int n, const char *f, ...) { va_list va; va_start(va, f); n = Vfnprintf(f, va, fd, n); va_end(va); return n; } int Vfprintf(const char *f, va_list va, int fd) { return Vfnprintf(f, va, fd, 0); } int Vfnprintf(const char *f, va_list va, int fd, int n) { enum { kPlain, kEsc, kCsi }; static int recursive; dword t, u; const char *s; signed char type; char quot, ansi, gotr, pdot, zero; int b, c, i, x, y, si, prec, cols, sign; gotr = false; t = rdtsc(); ftrace_enabled(-1); strace_enabled(-1); ++recursive; for (ansi = 0;;) { for (;;) { if (!(c = *f++ & 0377) || c == L'%') break; if (c >= 0300) { for (b = 0200; c & b; b >>= 1) { c ^= b; } while ((*f & 0300) == 0200) { c <<= 6; c |= *f++ & 0177; } } switch (ansi) { case kPlain: if (c == 033) { ansi = kEsc; } else if (c != L'\n' && c != L'\r') { n += GetMonospaceCharacterWidth(c); } else { n = 0; } break; case kEsc: if (c == '[') { ansi = kCsi; } else { ansi = kPlain; } break; case kCsi: if (0x40 <= c && c <= 0x7e) { ansi = kPlain; } break; default: unreachable; } EmitFormatByte: PrintChar(fd, c); } if (!c) break; prec = 0; pdot = 0; cols = 0; quot = 0; type = 0; zero = 0; sign = 1; for (;;) { switch ((c = *f++)) { default: goto EmitFormatByte; case L'n': PrintNewline(fd); n = 0; break; case L'l': ++type; continue; case L'0': case L'1': case L'2': case L'3': case L'4': case L'5': case L'6': case L'7': case L'8': case L'9': si = pdot ? prec : cols; si *= 10; si += c - '0'; goto UpdateCols; case L'*': si = va_arg(va, int); UpdateCols: if (pdot) { prec = si; } else { if (si < 0) { si = -si; sign = -1; } else if (!si) { zero = 1; } cols = si; } continue; case L'-': sign = -1; continue; case L'.': pdot = 1; continue; case L'_': case L',': case L'\'': quot = c; continue; case L'I': if (depth >= 0) { n += PrintDepth(fd, depth); } else { n += PrintIndent(fd, sp * 2); } break; case L'J': if (depth >= 0) { n += PrintDepth(fd, depth - 1); } else { n += PrintIndent(fd, (sp - 1) * 2); } break; case L'V': y = depth >= 0 ? depth : sp; if (y) { n += PrintIndent(fd, (y - 1) * 2); n += PrintChar(fd, L'├'); n += PrintChar(fd, L'─'); } break; case L'W': y = depth >= 0 ? depth : sp; if (y) { n += PrintIndent(fd, (y - 1) * 2); n += PrintChar(fd, L'│'); n += PrintChar(fd, L' '); } break; case L'X': y = depth >= 0 ? depth : sp; if (y) { n += PrintIndent(fd, (y - 1) * 2); n += PrintChar(fd, L'└'); n += PrintChar(fd, L'─'); } break; case L'p': if (simpler) goto SimplePrint; // fallthrough case L'P': n += PrettyPrint(fd, va_arg(va, int), MAX(0, depth > 0 ? n - depth * 3 : n)); break; case L'T': PrintTree(fd, va_arg(va, int), n); break; case L'R': gotr = true; n += PrintInt(fd, ClocksToNanos(tick, t), cols * sign, quot, zero, 10, true); break; case L'S': SimplePrint: n += Print(fd, va_arg(va, int)); break; case L'A': y = va_arg(va, int); x = va_arg(va, int); n += PrintChar(fd, L'['); n += PrintArgs(fd, y, x, 0); n += PrintChar(fd, L']'); break; case L'K': if ((b = va_arg(va, int)) < 0) { PrintChar(fd, L'('); for (;;) { n += Print(fd, Car(Car(b))); if ((b = Cdr(b)) >= 0) break; PrintChar(fd, L' '); } PrintChar(fd, L')'); } else { n += Print(fd, b); } break; case L'd': n += PrintInt(fd, GetVarInt(va, type), cols * sign, quot, zero, 10, true); break; case L'u': n += PrintInt(fd, GetVarInt(va, type), cols * sign, quot, zero, 10, 0); break; case L'b': n += PrintInt(fd, GetVarInt(va, type), cols * sign, quot, zero, 2, 0); break; case L'o': n += PrintInt(fd, GetVarInt(va, type), cols * sign, quot, zero, 8, 0); break; case L'x': n += PrintInt(fd, GetVarInt(va, type), cols * sign, quot, zero, 16, 0); break; case L's': s = va_arg(va, const char *); if (!s) s = "NULL"; n += PrintStr(fd, s, cols * sign); break; case L'c': n += PrintChar(fd, va_arg(va, int)); break; } break; } } --recursive; ftrace_enabled(+1); strace_enabled(+1); if (!recursive) { u = rdtsc(); if (gotr) { tick = u; } else { tick -= u >= t ? u - t : ~t + u + 1; } } return n; }
8,784
305
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/expand.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "tool/plinko/lib/config.h" #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/gc.h" #include "tool/plinko/lib/index.h" #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/trace.h" int Exlis(int x, int a) { int y; if (!x) return x; if (x > 0) return expand(x, a); y = expand(Car(x), a); return Keep(x, Cons(y, Exlis(Cdr(x), a))); } static int Expander(int e, int a) { int f, u, x, y, s; for (s = 0;;) { DCHECK_LT(e, TERM); DCHECK_LE(a, 0); if (e >= 0) return e; if ((f = Car(e)) > 0) { if (f == kQuote) return e; if (f == kClosure) return e; if (f == kTrace) { START_TRACE; x = Cadr(e); y = expand(x, a); e = x == y ? e : List(Car(e), y); END_TRACE; return e; } if (HasAtom(f, s)) return e; s = Cons(f, s); } e = Exlis(e, a); if (f >= 0) { if (!(f = Assoc(f, a))) return e; f = Cdr(f); if (f >= 0) return e; } if (Car(f) == kClosure) { u = Cddr(f); f = Cadr(f); } else { u = a; } if (Head(f) != kMacro) return e; e = eval(Caddr(f), pairlis(Cadr(f), Cdr(e), u)); } } int Expand(int e, int a) { int r, A; A = cx; Push(List(kExpand, e)); r = Keep(e, Expander(e, a)); Pop(); r = MarkSweep(A, r); return r; }
3,200
81
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/intern.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/cons.h" #include "tool/plinko/lib/plinko.h" static inline int Probe(unsigned h, unsigned p) { return (h + p * p) & MASK(TERM); } static inline int Hash(unsigned h, unsigned x) { return MAX(2, ((h * 0xdeaadead) ^ x) & MASK(TERM)); } static int Interner(dword t, int h, int p) { dword u; if ((u = Get(h))) { if (u != t) { h = Interner(t, Probe(h, p), p + 1); } return h; } else if (++cAtoms < TERM / 2) { Set(h, t); SetShadow(h, DF(DispatchLookup)); return h; } else { Error("too many atoms"); } } int Intern(int x, int y) { return Interner(MAKE(x, y), (ax = Hash(x, ax)), 1); }
2,493
49
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/printvars.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "tool/plinko/lib/plinko.h" #include "tool/plinko/lib/print.h" int PrintArgs(int fd, int keys, int vals, int n) { if (!keys) return n; if (keys > 0) { if (!(vals < 0 && Car(vals) == kClosure)) { if (n) { n += PrintChar(fd, L';'); n += PrintChar(fd, L' '); } n += Print(fd, keys); n += PrintChar(fd, L'='); n += Print(fd, vals); } return n; } if (vals > 0) { if (n) { n += PrintChar(fd, L';'); n += PrintChar(fd, L' '); } n += Print(fd, Car(keys)); n += PrintChar(fd, L'='); n += PrintChar(fd, L'!'); n += Print(fd, vals); vals = 0; } else { n += PrintArgs(fd, Car(keys), Car(vals), n); } if (!Cdr(keys)) return n; return PrintArgs(fd, Cdr(keys), Cdr(vals), n); }
2,626
52
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/countreferences.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/check.h" #include "tool/plinko/lib/index.h" #include "tool/plinko/lib/plinko.h" /** * Counts references to variable. * * @param v is atom name of variable * @param m is count after which we should stop counting * @param e is expression * @return number of counted references greater than zero * @note this produces garbage when recursing into let */ int CountReferences(int v, int m, int e) { int f, r; DCHECK_GT(v, 0); if (e >= 0) { r = e == v; } else { f = Car(e); if (f == kQuote || f == kClosure) { r = 0; } else if (f == kLambda || f == kMacro) { if (m > 0 && !HasAtom(v, Cadr(e))) { r = CountReferences(v, m, Caddr(e)); } else { r = 0; } } else if (f == kCond) { for (r = 0; (e = Cdr(e)) < 0 && r < m;) { if ((f = Car(e)) < 0) { r += CountReferences(v, m - r, Car(f)); if ((f = Cdr(f)) < 0) { r += CountReferences(v, m - r, Car(f)); } } } } else { for (r = 0; e && r < m;) { if (e < 0) { f = Car(e); e = Cdr(e); } else { f = e; e = 0; } r += CountReferences(v, m - r, f); } } } DCHECK_GE(r, 0); return r; }
3,113
72
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/print.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_PRINT_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_PRINT_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int Print(int, int); int PrettyPrint(int, int, int); bool ShouldForceDot(int); bool ShouldConcealClosure(int); int EnterPrint(int); int PrintArgs(int, int, int, int); int PrintAtom(int, int); int PrintChar(int, int); int PrintDepth(int, int); int PrintDot(int); int PrintIndent(int, int); int PrintInt(int, long, int, char, char, int, bool); int PrintListDot(int, int); int PrintSpace(int); int PrintZeroes(int, int); void GetName(int *); void LeavePrint(int); void PrintHeap(int); void PrintNewline(int); void PrintTree(int, int, int); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_PRINT_H_ */
811
32
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/config.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_CONFIG_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_CONFIG_H_ #include "libc/dce.h" #define HISTO_ASSOC 0 #define HISTO_GARBAGE 0 #define DEBUG_TREE 0 #define DEBUG_CLOSURE 0 #define DEBUG_GARBAGE 0 #define DEBUG_MATCHER 0 #define EXPLAIN_GARBAGE 0 #define AVERSIVENESS 15 #define NEED_GC 1 #define NEED_TMC 2 #define NEED_POP 4 #define STACK 65536 // we want a two power that's large enough for emoji but not // not so large that we're drowning in virtual memory pages! #define TERM 0x20000 #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ #if IsModeDbg() #define inline dontinline #undef forceinline #define forceinline static dontinline #endif #define BANE INT_MIN #define DWBITS (sizeof(dword) * CHAR_BIT) COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_CONFIG_H_ */
903
39
jart/cosmopolitan
false
cosmopolitan/tool/plinko/lib/error.h
#ifndef COSMOPOLITAN_TOOL_PLINKO_LIB_ERROR_H_ #define COSMOPOLITAN_TOOL_PLINKO_LIB_ERROR_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ void Raise(int) relegated wontreturn; void Error(const char *, ...) relegated wontreturn; void OutOfMemory(void) relegated wontreturn; void StackOverflow(void) relegated wontreturn; void React(int, int, int) relegated wontreturn; COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_TOOL_PLINKO_LIB_ERROR_H_ */
502
15
jart/cosmopolitan
false